Autonomy Software C++ 24.5.1
Welcome to the Autonomy Software repository of the Mars Rover Design Team (MRDT) at Missouri University of Science and Technology (Missouri S&T)! API reference contains the source code and other resources for the development of the autonomy software for our Mars rover. The Autonomy Software project aims to compete in the University Rover Challenge (URC) by demonstrating advanced autonomous capabilities and robust navigation algorithms.
Loading...
Searching...
No Matches
duckdb::BufferPool Class Reference
Collaboration diagram for duckdb::BufferPool:

Classes

struct  EvictionResult
struct  MemoryUsage

Public Member Functions

 BufferPool (BlockAllocator &block_allocator, idx_t maximum_memory, bool track_eviction_timestamps, idx_t allocator_bulk_deallocation_flush_threshold)
void SetLimit (idx_t limit, const char *exception_postscript)
void SetAllocatorBulkDeallocationFlushThreshold (idx_t threshold)
 If bulk deallocation larger than this occurs, flush outstanding allocations.
idx_t GetAllocatorBulkDeallocationFlushThreshold ()
void UpdateUsedMemory (MemoryTag tag, int64_t size)
idx_t GetUsedMemory (bool flush=true) const
idx_t GetMaxMemory () const
virtual idx_t GetQueryMaxMemory () const
TemporaryMemoryManager & GetTemporaryMemoryManager ()
void SetObjectCache (ObjectCache *object_cache_p)

Protected Types

enum class  MemoryUsageCaches { FLUSH , NO_FLUSH }

Protected Member Functions

virtual EvictionResult EvictBlocks (MemoryTag tag, idx_t extra_memory, idx_t memory_limit, unique_ptr< FileBuffer > *buffer=nullptr)
virtual EvictionResult EvictBlocksInternal (EvictionQueue &queue, MemoryTag tag, idx_t extra_memory, idx_t memory_limit, unique_ptr< FileBuffer > *buffer=nullptr)
EvictionResult EvictObjectCacheEntries (MemoryTag tag, idx_t extra_memory, idx_t memory_limit)
 Evict object cache entries if needed.
idx_t PurgeAgedBlocks (uint32_t max_age_sec)
 Purge all blocks that haven't been pinned within the last N seconds.
idx_t PurgeAgedBlocksInternal (EvictionQueue &queue, uint32_t max_age_sec, int64_t now, int64_t limit)
void PurgeQueue (const BlockHandle &handle)
 Garbage collect dead nodes in the eviction queue.
bool AddToEvictionQueue (shared_ptr< BlockHandle > &handle)
EvictionQueue & GetEvictionQueueForBlockMemory (const BlockMemory &memory)
 Gets the eviction queue for the specified type.
void IncrementDeadNodes (const BlockMemory &memory)
 Increments the dead nodes for the queue with specified type.

Protected Attributes

const array< idx_t, EVICTION_QUEUE_TYPES > eviction_queue_sizes
 Mapping and priority order for the eviction queues.
mutex limit_lock
 The lock for changing the memory limit.
atomic< idx_t > maximum_memory
 The maximum amount of memory that the buffer manager can keep (in bytes).
atomic< idx_t > allocator_bulk_deallocation_flush_threshold
 If bulk deallocation larger than this occurs, flush outstanding allocations.
bool track_eviction_timestamps
 Record timestamps of buffer manager unpin() events. Usable by custom eviction policies.
vector< unique_ptr< EvictionQueue > > queues
 Eviction queues.
unique_ptr< TemporaryMemoryManager > temporary_memory_manager
 Memory manager for concurrently used temporary memory, e.g., for physical operators.
MemoryUsage memory_usage
BlockAllocator & block_allocator
 The block allocator.
optional_ptr< ObjectCache > object_cache = nullptr
 Per-database singleton object cache managed by buffer pool.

Static Protected Attributes

static constexpr idx_t EVICTION_QUEUE_TYPES = FILE_BUFFER_TYPE_COUNT - 1
 How many eviction queue types we have (BLOCK and EXTERNAL_FILE go into same queue).
static constexpr idx_t BLOCK_AND_EXTERNAL_FILE_QUEUE_SIZE = 1
 How many eviction queues we have for the different FileBufferTypes.
static constexpr idx_t MANAGED_BUFFER_QUEUE_SIZE = 6
static constexpr idx_t TINY_BUFFER_QUEUE_SIZE = 1

Friends

class BlockMemory
class BlockHandle
class BlockManager
class BufferManager
class StandardBufferManager

Detailed Description

The BufferPool is in charge of handling memory management for one or more databases. It defines memory limits and implements priority eviction among all users of the pool.

Member Enumeration Documentation

◆ MemoryUsageCaches

enum class duckdb::BufferPool::MemoryUsageCaches
strongprotected
113996 {
113997 FLUSH,
113998 NO_FLUSH,
113999 };

Constructor & Destructor Documentation

◆ BufferPool()

duckdb::BufferPool::BufferPool ( BlockAllocator & block_allocator,
idx_t maximum_memory,
bool track_eviction_timestamps,
idx_t allocator_bulk_deallocation_flush_threshold )
387458 : eviction_queue_sizes({BLOCK_AND_EXTERNAL_FILE_QUEUE_SIZE, MANAGED_BUFFER_QUEUE_SIZE, TINY_BUFFER_QUEUE_SIZE}),
387462 temporary_memory_manager(make_uniq<TemporaryMemoryManager>()), block_allocator(block_allocator) {
387463 for (idx_t queue_type_idx = 0; queue_type_idx < EVICTION_QUEUE_TYPES; queue_type_idx++) {
387464 const auto types = EvictionQueueTypeIdxToFileBufferTypes(queue_type_idx);
387465 const auto &type_queue_size = eviction_queue_sizes[queue_type_idx];
387466 for (idx_t queue_idx = 0; queue_idx < type_queue_size; queue_idx++) {
387467 queues.push_back(make_uniq<EvictionQueue>(types));
387468 }
387469 }
387470}
BlockAllocator & block_allocator
The block allocator.
Definition duckdb.cpp:114056
static constexpr idx_t BLOCK_AND_EXTERNAL_FILE_QUEUE_SIZE
How many eviction queues we have for the different FileBufferTypes.
Definition duckdb.cpp:113989
atomic< idx_t > allocator_bulk_deallocation_flush_threshold
If bulk deallocation larger than this occurs, flush outstanding allocations.
Definition duckdb.cpp:114044
static constexpr idx_t EVICTION_QUEUE_TYPES
How many eviction queue types we have (BLOCK and EXTERNAL_FILE go into same queue).
Definition duckdb.cpp:113987
const array< idx_t, EVICTION_QUEUE_TYPES > eviction_queue_sizes
Mapping and priority order for the eviction queues.
Definition duckdb.cpp:113993
unique_ptr< TemporaryMemoryManager > temporary_memory_manager
Memory manager for concurrently used temporary memory, e.g., for physical operators.
Definition duckdb.cpp:114050
vector< unique_ptr< EvictionQueue > > queues
Eviction queues.
Definition duckdb.cpp:114048
bool track_eviction_timestamps
Record timestamps of buffer manager unpin() events. Usable by custom eviction policies.
Definition duckdb.cpp:114046
atomic< idx_t > maximum_memory
The maximum amount of memory that the buffer manager can keep (in bytes).
Definition duckdb.cpp:114042
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237

◆ ~BufferPool()

duckdb::BufferPool::~BufferPool ( )
virtual
387471 {
387472}

Member Function Documentation

◆ SetLimit()

void duckdb::BufferPool::SetLimit ( idx_t limit,
const char * exception_postscript )

Set a new memory limit to the buffer pool, throws an exception if the new limit is too low and not enough blocks can be evicted

387711 {
387712 lock_guard<mutex> l_lock(limit_lock);
387713 // try to evict until the limit is reached
387714 if (!EvictBlocks(MemoryTag::EXTENSION, 0, limit).success) {
387715 throw OutOfMemoryException(
387716 "Failed to change memory limit to %lld: could not free up enough memory for the new limit%s", limit,
387717 exception_postscript);
387718 }
387719 idx_t old_limit = maximum_memory;
387720 // set the global maximum memory to the new limit if successful
387721 maximum_memory = limit;
387722 // evict again
387723 if (!EvictBlocks(MemoryTag::EXTENSION, 0, limit).success) {
387724 // failed: go back to old limit
387725 maximum_memory = old_limit;
387726 throw OutOfMemoryException(
387727 "Failed to change memory limit to %lld: could not free up enough memory for the new limit%s", limit,
387728 exception_postscript);
387729 }
387730 block_allocator.FlushAll();
387731}
mutex limit_lock
The lock for changing the memory limit.
Definition duckdb.cpp:114040

◆ SetAllocatorBulkDeallocationFlushThreshold()

void duckdb::BufferPool::SetAllocatorBulkDeallocationFlushThreshold ( idx_t threshold)

If bulk deallocation larger than this occurs, flush outstanding allocations.

387733 {
387735}
GMat threshold(const GMat &src, const GScalar &thresh, const GScalar &maxval, int type)

◆ GetAllocatorBulkDeallocationFlushThreshold()

idx_t duckdb::BufferPool::GetAllocatorBulkDeallocationFlushThreshold ( )
387737 {
387739}

◆ UpdateUsedMemory()

void duckdb::BufferPool::UpdateUsedMemory ( MemoryTag tag,
int64_t size )
387523 {
387524 memory_usage.UpdateUsedMemory(tag, size);
387525}
MemoryUsage memory_usage
Definition duckdb.cpp:114054

◆ GetUsedMemory()

idx_t duckdb::BufferPool::GetUsedMemory ( bool flush = true) const
387527 {
387528 return memory_usage.GetUsedMemory(flush ? MemoryUsageCaches::FLUSH : MemoryUsageCaches::NO_FLUSH);
387529}

◆ GetMaxMemory()

idx_t duckdb::BufferPool::GetMaxMemory ( ) const
387531 {
387532 return maximum_memory;
387533}

◆ GetQueryMaxMemory()

idx_t duckdb::BufferPool::GetQueryMaxMemory ( ) const
virtual
387535 {
387536 return GetMaxMemory();
387537}

◆ GetTemporaryMemoryManager()

TemporaryMemoryManager & duckdb::BufferPool::GetTemporaryMemoryManager ( )
387539 {
387540 return *temporary_memory_manager;
387541}

◆ SetObjectCache()

void duckdb::BufferPool::SetObjectCache ( ObjectCache * object_cache_p)
inline

Take per-database ObjectCache under buffer pool's memory management. Notice, object cache should be registered for at most once, otherwise InvalidInput exception is thrown.

113946 {
113947 if (object_cache != nullptr) {
113948 throw InvalidInputException("Object cache has already been registered in buffer pool, cannot re-register!");
113949 }
113950 object_cache = object_cache_p;
113951 }
optional_ptr< ObjectCache > object_cache
Per-database singleton object cache managed by buffer pool.
Definition duckdb.cpp:114058

◆ EvictBlocks()

BufferPool::EvictionResult duckdb::BufferPool::EvictBlocks ( MemoryTag tag,
idx_t extra_memory,
idx_t memory_limit,
unique_ptr< FileBuffer > * buffer = nullptr )
protectedvirtual
387576 {
387577 for (auto &queue : queues) {
387578 auto block_result = EvictBlocksInternal(*queue, tag, extra_memory, memory_limit, buffer);
387579 if (block_result.success) {
387580 return block_result;
387581 }
387582 }
387583
387584 // Evict object cache, which is usually used to cache metadata and configs, when flushing buffer blocks alone is not
387585 // enough to limit overall memory consumption.
387586 return EvictObjectCacheEntries(tag, extra_memory, memory_limit);
387587}
EvictionResult EvictObjectCacheEntries(MemoryTag tag, idx_t extra_memory, idx_t memory_limit)
Evict object cache entries if needed.
Definition duckdb.cpp:387543

◆ EvictBlocksInternal()

BufferPool::EvictionResult duckdb::BufferPool::EvictBlocksInternal ( EvictionQueue & queue,
MemoryTag tag,
idx_t extra_memory,
idx_t memory_limit,
unique_ptr< FileBuffer > * buffer = nullptr )
protectedvirtual
387590 {
387591 TempBufferPoolReservation r(tag, *this, extra_memory);
387592 bool found = false;
387593
387594 if (memory_usage.GetUsedMemory(MemoryUsageCaches::NO_FLUSH) <= memory_limit) {
387595 if (extra_memory > allocator_bulk_deallocation_flush_threshold) {
387596 block_allocator.FlushAll(extra_memory);
387597 }
387598 return {true, std::move(r)};
387599 }
387600
387601 queue.IterateUnloadableBlocks([&](BufferEvictionNode &, const shared_ptr<BlockMemory> &handle, BlockLock &lock) {
387602 // hooray, we can unload the block
387603 if (buffer && handle->GetBuffer(lock)->AllocSize() == extra_memory) {
387604 // we can re-use the memory directly
387605 *buffer = handle->UnloadAndTakeBlock(lock);
387606 found = true;
387607 return false;
387608 }
387609
387610 // release the memory and mark the block as unloaded
387611 handle->Unload(lock);
387612
387613 if (memory_usage.GetUsedMemory(MemoryUsageCaches::NO_FLUSH) <= memory_limit) {
387614 found = true;
387615 return false;
387616 }
387617
387618 // Continue iteration
387619 return true;
387620 });
387621
387622 if (!found) {
387623 r.Resize(0);
387624 } else if (extra_memory > allocator_bulk_deallocation_flush_threshold) {
387625 block_allocator.FlushAll(extra_memory);
387626 }
387627
387628 return {found, std::move(r)};
387629}

◆ EvictObjectCacheEntries()

BufferPool::EvictionResult duckdb::BufferPool::EvictObjectCacheEntries ( MemoryTag tag,
idx_t extra_memory,
idx_t memory_limit )
protected

Evict object cache entries if needed.

387543 {
387544 TempBufferPoolReservation r(tag, *this, extra_memory);
387545
387546 if (memory_usage.GetUsedMemory(MemoryUsageCaches::NO_FLUSH) <= memory_limit) {
387547 if (extra_memory > allocator_bulk_deallocation_flush_threshold) {
387548 block_allocator.FlushAll(extra_memory);
387549 }
387550 return {true, std::move(r)};
387551 }
387552
387553 bool success = false;
387554 while (!object_cache->IsEmpty()) {
387555 const idx_t freed_mem = object_cache->EvictToReduceMemory(extra_memory);
387556 // Break if all entries cannot be evicted.
387557 if (freed_mem == 0) {
387558 break;
387559 }
387560
387561 if (memory_usage.GetUsedMemory(MemoryUsageCaches::NO_FLUSH) <= memory_limit) {
387562 success = true;
387563 break;
387564 }
387565 }
387566 if (!success) {
387567 r.Resize(0);
387568 } else if (extra_memory > allocator_bulk_deallocation_flush_threshold) {
387569 block_allocator.FlushAll(extra_memory);
387570 }
387571
387572 return {success, std::move(r)};
387573}

◆ PurgeAgedBlocks()

idx_t duckdb::BufferPool::PurgeAgedBlocks ( uint32_t max_age_sec)
protected

Purge all blocks that haven't been pinned within the last N seconds.

Do not remove this method. There are extensions that rely on time-based purging of blocks, that uses the method.

387633 {
387634 int64_t now = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now())
387635 .time_since_epoch()
387636 .count();
387637 int64_t limit = now - (static_cast<int64_t>(max_age_sec) * 1000);
387638 idx_t purged_bytes = 0;
387639 for (auto &queue : queues) {
387640 purged_bytes += PurgeAgedBlocksInternal(*queue, max_age_sec, now, limit);
387641 }
387642 return purged_bytes;
387643}
::int64_t int64_t

◆ PurgeAgedBlocksInternal()

idx_t duckdb::BufferPool::PurgeAgedBlocksInternal ( EvictionQueue & queue,
uint32_t max_age_sec,
int64_t now,
int64_t limit )
protected
387645 {
387646 idx_t purged_bytes = 0;
387647 queue.IterateUnloadableBlocks(
387648 [&](BufferEvictionNode &node, const shared_ptr<BlockMemory> &handle, BlockLock &lock) {
387649 // We will unload this block regardless. But stop the iteration immediately afterward if this
387650 // block is younger than the age threshold.
387651 auto lru_timestamp_msec = handle->GetLRUTimestamp();
387652 bool is_fresh = lru_timestamp_msec >= limit && lru_timestamp_msec <= now;
387653 purged_bytes += handle->GetMemoryUsage();
387654 handle->Unload(lock);
387655 // Return false to stop iterating if the current block is_fresh
387656 return !is_fresh;
387657 });
387658 return purged_bytes;
387659}

◆ PurgeQueue()

void duckdb::BufferPool::PurgeQueue ( const BlockHandle & handle)
protected

Garbage collect dead nodes in the eviction queue.

387701 {
387702 const auto &memory = block.GetMemory();
387703 const auto &buffer_manager = memory.GetBufferManager();
387704 auto &eviction_queue = GetEvictionQueueForBlockMemory(memory);
387705 const auto queue_sleep_micros =
387706 Settings::Get<DebugEvictionQueueSleepMicroSecondsSetting>(buffer_manager.GetDatabase());
387707 eviction_queue.debug_eviction_queue_sleep = queue_sleep_micros;
387708 eviction_queue.Purge();
387709}
EvictionQueue & GetEvictionQueueForBlockMemory(const BlockMemory &memory)
Gets the eviction queue for the specified type.
Definition duckdb.cpp:387498
Here is the call graph for this function:

◆ AddToEvictionQueue()

bool duckdb::BufferPool::AddToEvictionQueue ( shared_ptr< BlockHandle > & handle)
protected

Add a buffer handle to the eviction queue. Returns true, if the queue is ready to be purged, and false otherwise.

387474 {
387475 auto &memory = handle->GetMemory();
387476 auto &queue = GetEvictionQueueForBlockMemory(memory);
387477
387478 // The block handle is locked during this operation (Unpin),
387479 // or the block handle is still a local variable (ConvertToPersistent)
387480 D_ASSERT(memory.GetReaders() == 0);
387481 auto ts = memory.NextEvictionSequenceNumber();
387483 memory.SetLRUTimestamp(std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now())
387484 .time_since_epoch()
387485 .count());
387486 }
387487
387488 if (ts != 1) {
387489 // we add a newer version, i.e., we kill exactly one previous version
387490 queue.IncrementDeadNodes();
387491 }
387492
387493 // Get the eviction queue for the block and add it
387494 BufferEvictionNode node(handle->GetMemoryWeak(), ts);
387495 return queue.AddToEvictionQueue(std::move(node));
387496}
Here is the call graph for this function:

◆ GetEvictionQueueForBlockMemory()

EvictionQueue & duckdb::BufferPool::GetEvictionQueueForBlockMemory ( const BlockMemory & memory)
protected

Gets the eviction queue for the specified type.

387498 {
387499 const auto &handle_buffer_type = memory.GetBufferType();
387500
387501 // Get offset into eviction queues for this FileBufferType
387502 idx_t queue_index = 0;
387503 const auto handle_queue_type_idx = FileBufferTypeToEvictionQueueTypeIdx(handle_buffer_type);
387504 for (idx_t type_idx = 0; type_idx < handle_queue_type_idx; type_idx++) {
387505 queue_index += eviction_queue_sizes[type_idx];
387506 }
387507
387508 const auto &queue_size = eviction_queue_sizes[handle_queue_type_idx];
387509 // Adjust if eviction_queue_idx is set (idx == 0 -> add at back, idx >= queue_size -> add at front)
387510 auto eviction_queue_idx = memory.GetEvictionQueueIndex();
387511 if (eviction_queue_idx < queue_size) {
387512 queue_index += queue_size - eviction_queue_idx - 1;
387513 }
387514
387515 D_ASSERT(queues[queue_index]->HasFileBufferType(handle_buffer_type));
387516 return *queues[queue_index];
387517}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ IncrementDeadNodes()

void duckdb::BufferPool::IncrementDeadNodes ( const BlockMemory & memory)
protected

Increments the dead nodes for the queue with specified type.

387519 {
387521}
void IncrementDeadNodes()
Increment the dead node counter in the purge queue.
Definition duckdb.cpp:387304
Here is the call graph for this function:

Member Data Documentation

◆ memory_usage

MemoryUsage duckdb::BufferPool::memory_usage
mutableprotected

To improve performance, MemoryUsage maintains counter caches based on current cpu or thread id, and only updates the global counter when the cache value exceeds a threshold. Therefore, the statistics may have slight differences from the actual memory usage.


The documentation for this class was generated from the following file: