Overview / System & concurrency

cache

In-memory cache with a Robin Hood table over a preallocated block, and a sharded variant for multiple threads.

Always compiled: part of the core build.Include #include <ethereal/cpp/cache/cache_inc.hpp>C layer

cache_inc.hpp

#include <ethereal/cpp/cache/cache_inc.hpp>

Umbrella header of the Cache module.

Includes the shared types, the single thread cache and the sharded cache.

cache.hpp

#include <ethereal/cpp/cache/cache.hpp>

Single thread cache of the Cache module, with a preallocated slab and an open addressing table.

Open addressing with Robin Hood probing, power of two capacity, mask instead of modulo. The spec asks for it in these words: "No chained buckets, no per-entry allocation, no pointer chasing." A chained table makes every lookup chase pointers across different cache lines. In a cache that is the whole cost: the hash is one multiplication, and a cache miss is two hundred cycles. The remainder of a division costs more than twenty cycles and a mask costs one, so the capacity is always a power of two.

What Robin Hood solves: in plain linear probing the unlucky keys end up far from their slot and the lucky ones sit on it, and the worst lookup gets worse as the table fills. Robin Hood takes from the rich and gives to the poor: whoever has been probing longer pushes whoever has been probing less. The result is not a better mean but a much smaller variance. The median lookup stays the same and the worst one stops being a disaster.

The bucket keeps the hash, which saves the chase. Each bucket has eight bytes: thirty two bits of hash and thirty two of slab index, eight buckets per cache line. Comparing the short hash first resolves almost every probe without touching the slab. Only when it matches does the lookup go to the slab to compare the key, and then the cache miss was worth it.

class

CCache

Ethereal::Cache#

A single thread cache, with a preallocated slab.

template< typename TKey, typename TValue, typename THash = SDefaultHash< TKey > > class CCache final
Not thread safe. For many threads use CShardedCache, which splits this one into shards, each with its own lock.
alias

void

#
using EvictFn = void ( * )( void * pCtx, const TKey & Key, const TValue & Value, EEvictReason eReason );

Called when an entry leaves. Runs outside any lock.

alias

EStatus

#
using LoaderFn = EStatus ( * )( void * pCtx, const TKey & Key, TValue * pOut );

Produces the value of a key that missed.

constructor

CCache

#
CCache() = default;

Default constructor. Call Init before use.

function

Init

#
EStatus Init( const SCacheParams & Params )

Sizes the slab and the table. All the memory is reserved here.

Params
Cache parameters.
eOk, or eInvalidArgument when uMaxEntries is zero. Also eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
function

SetEvictCallback

#
void SetEvictCallback( const EvictFn pFn, void * const pCtx ) noexcept

Sets the function called when an entry leaves.

pFn
The callback. Null disables it.
pCtx
Context passed back to the callback.
function

Get

#
bool Get( const TKey & Key, TValue * const pOut )

Looks up a key and copies the value.

Zero allocations, always, on a hit or a miss.

Key
The key.
pOut
Receives the value. May be null.
false when the key is missing, expired, or of another generation.
function

GetRef

#
bool GetRef( const TKey & Key, const TValue ** const ppOut )

Looks up a key and lends the value without copying it.

The loan is valid until the next operation that changes the cache. A 'Put' can evict this entry, and then the pointer points to something else.

It does not exist in the concurrent variant, and the spec says why: returning a pointer into a cache that another thread can evict is a use after free waiting to happen.

Key
The key.
ppOut
Receives a pointer to the value. May be null.
false when the key is missing, expired, or of another generation.
function

Contains

#
bool Contains( const TKey & Key )

The key is in the cache. Does not change the recency order.

function

Put

#
EStatus Put( const TKey & Key, const TValue & Value, const ETL_UINT64 uTtlMs = 0u, const std::size_t uCost = 1u )

Stores a value, replacing the one with the same key.

Key
The key.
Value
The value.
uTtlMs
Time to live. Zero uses uDefaultTtlMs.
uCost
Cost of the entry, counted against uMaxCostBytes.
eOk, eNotInitialized, eRejected (admission filter) or eOutOfMemory.
function

Remove

#
bool Remove( const TKey & Key )

Removes a key. The eviction callback is called with eExplicit.

false when the key was not there.
function

Clear

#
void Clear()

Removes everything. The callback is called for each live entry.

function

InvalidateAll

#
void InvalidateAll() noexcept

Invalidates everything in O(1). This is the recommended way.

function

Generation

#
ETL_UINT32 Generation() const noexcept

Current generation.

function

GetOrLoad

#
EStatus GetOrLoad( const TKey & Key, TValue * const pOut, void * const pCtx, const LoaderFn pLoader )

Looks up a key and, on a miss, calls the loader and stores the result.

Key
The key.
pOut
Receives the value. May be null.
pCtx
Context passed to the loader.
pLoader
The loader.
eOk, eLoadFailed without a loader, or the error of the loader.
function

Size

#
std::size_t Size() const noexcept

Number of entries.

function

Cost

#
std::size_t Cost() const noexcept

Total cost of the entries.

function

Capacity

#
std::size_t Capacity() const noexcept

Number of slots in the slab.

function

MemoryUsage

#
std::size_t MemoryUsage() const noexcept

Bytes this cache takes. Fixed after startup.

function

Stats

#
SCacheStats Stats() const

Snapshot of the counters.

cache_types.hpp

#include <ethereal/cpp/cache/cache_types.hpp>

Shared types of the Cache module: status, eviction policies, the clock seam, the hash and the parameters.

A cache exists to be faster than the thing it caches. If a lookup costs more than a few tens of nanoseconds it stops earning its place. That sentence of the spec drives everything here:

  • Open addressing table, with no chained buckets and no node per entry. A chained table makes a lookup chase pointers across different cache lines, and that is what costs in a cache, not the hash computation.
  • Preallocated slab. All the entries come from one block sized at startup. Evicting returns one to the slab and inserting takes it again. Memory reaches its final value at once and never grows.
  • Zero allocations on a lookup, hit or miss.
  • The clock is not read on every lookup. Expiry is compared against a coarse timestamp, refreshed now and then. The error this introduces is documented and configurable, see 'uCoarseClockMs'.

This module has its own clock for the same reason as the Resilience module, and it is the third time in the tree. Section 2 of the conventions forbids a module from including the header of another to get functionality, and the spec promises "Depends on: nothing at link time". Ten duplicated lines keep the Time module out of the way of whoever only wants a cache. If it happens a fourth time, the clock seam is worth promoting to a 'resource' header, which is no module.

enum

EStatus

Ethereal::Cache#
C++
enum class   EStatus : ETL_UINT8
{
    /// @brief  Success.
    eOk = 0,

    /// @brief  @ref CCache::Init was not called yet, or it failed.
    eNotInitialized,

    /// @brief  No memory for the slab.
    eOutOfMemory,

    /// @brief  A parameter makes no sense.
    eInvalidArgument,

    /// @brief  Not stored: the admission filter refused it. See @ref EEviction::eTinyLfu.
    eRejected,

    /// @brief  The loader failed.
    eLoadFailed,

    /// @brief  Refused: no license was accepted and the evaluation of this machine has
    ///          ended, or the license passed was refused (see Bundle::UnlockBundle).
    eNotLicensed,

    /// @brief  Old British spelling of eNotInitialized, same value. Will be removed.
    eNotInitialised [[deprecated( "use EStatus::eNotInitialized" )]] = eNotInitialized
};

How an operation ended.

enum

EEviction

Ethereal::Cache#
C++
enum class   EEviction : ETL_UINT8
{
    /// @brief  The least recently used leaves. Intrusive linked list.
    ///
    /// @details  Single thread variant only. A strict list is a contention magnet:
    ///            every read modifies it, and in a cache reads are almost everything.
    ///            In the concurrent variant use @ref eClock.
    eLru = 0,

    /// @brief  LRU approximation with one bit per entry and a sweeping hand.
    ///
    /// @details  The recommended one for many threads. A read costs one relaxed
    ///            write of the reference bit and nothing else: no list to reorder,
    ///            no lock to take.
    eClock,

    /// @brief  The least frequently used leaves, with aging.
    ///
    /// @details  Aging is not optional. Without it, an entry that was used a lot an
    ///            hour ago stays ahead forever of one that is being used now, and
    ///            the cache ends up keeping the past.
    eLfu,

    /// @brief  The oldest to enter leaves, regardless of accesses.
    eFifo,

    /// @brief  Admission filter by a count sketch in front of an LRU.
    ///
    /// @details  The best hit rate per byte spent. A new entry only enters when the
    ///            sketch says it was seen more often than the one that would leave.
    ///            That stops a scan from filling the cache with things nobody asks
    ///            for again.
    eTinyLfu
};

How the entry that leaves is chosen.

enum

EEvictReason

Ethereal::Cache#
C++
enum class   EEvictReason : ETL_UINT8
{
    /// @brief  There was no room for another one.
    eCapacity = 0,

    /// @brief  The total cost went over the limit.
    eCost,

    /// @brief  It expired.
    eExpired,

    /// @brief  Another one was put with the same key.
    eReplaced,

    /// @brief  It was removed by a call.
    eExplicit,

    /// @brief  Everything was cleared.
    eCleared,

    /// @brief  The generation changed, so it became logically invalid.
    eGeneration
};

Why an entry left.

function

EvictReasonName

Ethereal::Cache#
const ETL_CHAR * EvictReasonName( EEvictReason eReason ) noexcept;

Name of an eviction reason, for logs.

eReason
The reason.
A static string, "unknown" for a value out of range.
function

CheckLicense

Ethereal::Cache#
EStatus CheckLicense() noexcept;

Says whether a cache may start.

Called by CCache::Init and CShardedCache::Init, whose bodies live in the headers. Paid once per Init, never on a Get or a Put.

eOk, or eNotLicensed when the library is not licensed.
class

IClock

Ethereal::Cache#

Where time comes from.

class IClock
destructor

~IClock

#
virtual ~IClock() = default;

Destructor.

function

NowNs

#
virtual ETL_UINT64 NowNs() const noexcept = 0;

Current time in nanoseconds, from an arbitrary mark.

function

SystemClock

Ethereal::Cache#
IClock & SystemClock() noexcept;
class

CManualClock

Ethereal::Cache#

A clock that moves when told to. For tests.

class CManualClock final : public IClock

This is what makes expiry testable. An entry that expires in an hour is not checked by waiting an hour.

function

NowNs

#
ETL_UINT64 NowNs() const noexcept override

Current time of the manual clock.

function

AdvanceMs

#
void AdvanceMs( const ETL_UINT64 uMs ) noexcept

Moves the clock forward.

uMs
Milliseconds to advance.
function

MixBits

Ethereal::Cache#
ETL_UINT64 MixBits( ETL_UINT64 x ) noexcept

Bit mixer (the 64 bit finalizer of MurmurHash3).

function

HashBytes

Ethereal::Cache#
ETL_UINT64 HashBytes( const void * pData, std::size_t uSize, ETL_UINT64 uSeed ) noexcept;

Hashes a block of bytes.

pData
The bytes. May be null.
uSize
Number of bytes.
uSeed
Seed of the hash.
The 64 bit hash. The size goes into the mix.
struct

SDefaultHash

Ethereal::Cache#
C++
template< typename T >
struct   SDefaultHash
{
    /// @brief  Hash of the key.
    ///
    ETL_UINT64 operator()( const T & Key ) const ETL_NOEXCEPT
    {
        if constexpr ( std::is_trivially_copyable_v< T > && ( sizeof( T ) <= 8u ) )
        {
            ETL_UINT64 u = 0;

            std::memcpy( &u, &Key, sizeof( T ) );

            /// The xor with a constant stops the zero key from giving zero.
            return MixBits( u ^ 0x9E3779B97F4A7C15ull );
        }
        else
        {
            return HashBytes( &Key, sizeof( T ), 0u );
        }
    }
};

The default hash. Specialize it for your types.

struct

SDefaultHash

Ethereal::Cache#
C++
template<>
struct   SDefaultHash< std::string >
{
    /// @brief  Hash of the key.
    ///
    ETL_UINT64 operator()( const std::string & Key ) const ETL_NOEXCEPT
    {
        return HashBytes( Key.data(), Key.size(), 0u );
    }
};

Hash of a std::string, by its characters.

struct

SDefaultHash

Ethereal::Cache#
C++
template<>
struct   SDefaultHash< std::string_view >
{
    /// @brief  Hash of the key.
    ///
    ETL_UINT64 operator()( const std::string_view Key ) const ETL_NOEXCEPT
    {
        return HashBytes( Key.data(), Key.size(), 0u );
    }
};

Hash of a std::string_view, by its characters.

struct

SCacheParams

Ethereal::Cache#
C++
struct   SCacheParams   final
{
    /// @brief  How many entries fit. The slab is sized from this.
    std::size_t        uMaxEntries = 1024u;

    /// @brief  Limit of the total cost. Zero means no limit.
    std::size_t        uMaxCostBytes = 0u;

    /// @brief  Eviction policy.
    EEviction        ePolicy = EEviction::eLru;

    /// @brief  Default time to live. Zero means no expiry.
    ETL_UINT64        uDefaultTtlMs = 0u;

    /// @brief  Expires after this time without being touched. Zero means never.
    ETL_UINT64        uIdleTtlMs = 0u;

    /// @brief  How often the coarse timestamp is refreshed.
    ///
    /// @details  Reading the clock on every lookup costs more than the lookup
    ///            itself. So a timestamp is kept and the clock is read once every
    ///            sixteen operations.
    ///
    ///           What it costs: an entry can be served after it expired, and the
    ///            delay is the wall time of fifteen operations, not the value of
    ///            this field. In a busy cache that is nanoseconds. In a cache with
    ///            one lookup per minute it is fifteen minutes.
    ///
    ///           Zero turns the timestamp off and reads the clock every time. A
    ///            cache with little traffic should use it, and the tests use it
    ///            with a manual clock so expiry can be checked at once.
    ///
    ///           Any other value turns the timestamp on. The number itself stays
    ///            recorded as the tolerance the caller declared to accept.
    ETL_UINT64        uCoarseClockMs = 20u;

    /// @brief  How many shards, in the concurrent variant. Zero chooses on its own.
    ETL_UINT32        uShardCount = 0u;

    /// @brief  The clock. Null uses SystemClock.
    IClock *        pClock = nullptr;

    /// @brief  Every how many touches the LFU halves its counters.
    ETL_UINT64        uLfuAgingPeriod = 10000u;
};

How a cache is built.

struct

SCacheStats

Ethereal::Cache#
C++
struct   SCacheStats   final
{
    /// @brief  Lookups that found the key.
    ETL_UINT64    uHits = 0;

    /// @brief  Lookups that did not find the key.
    ETL_UINT64    uMisses = 0;

    /// @brief  Entries evicted to make room or to fit the cost.
    ETL_UINT64    uEvictions = 0;

    /// @brief  Entries found expired on a lookup.
    ETL_UINT64    uExpirations = 0;

    /// @brief  Loader calls.
    ETL_UINT64    uLoads = 0;

    /// @brief  Loader calls that failed.
    ETL_UINT64    uLoadFailures = 0;

    /// @brief  Total time spent in the loader, in nanoseconds.
    ETL_UINT64    uLoadNanos = 0;

    /// @brief  New entries refused by the admission filter.
    ETL_UINT64    uAdmissionRejects = 0;

    /// @brief  Entries in the cache.
    ETL_UINT64    uSize = 0;

    /// @brief  Total cost of the entries.
    ETL_UINT64    uCostBytes = 0;
};

Snapshot of the counters.

The hit rate is computed outside. Keeping a running floating point ratio would cost a division per operation and give a number nobody can reproduce from the others.

sharded.hpp

#include <ethereal/cpp/cache/sharded.hpp>

Concurrent cache of the Cache module, split into shards with their own locks.

Shards with their own locks, not one lock for everything. The spec: "A single mutex around the whole cache is a scalability disaster: every read serialises." In a cache, reads are almost everything that happens. A single lock turns eight threads reading into eight threads in a queue, and the cache becomes slower than the thing it caches, the one thing it cannot be. Each shard is a whole CCache, with its own lock, slab and table. Two keys in different shards never see each other.

Each shard sits on a cache line of its own. Two locks on the same cache line contend for the line even when nobody contends for the lock: every write of one invalidates the line for the other. That is false sharing, and it costs as much as real sharing, so the shard is aligned.

There is no 'GetRef' here, on purpose. Returning a pointer into a cache that another thread can evict the next instant is a use after free waiting to happen, and no comment makes it safe. Whoever needs the value copies it, or keeps a 'shared_ptr' as the value.

The EEviction::eLru policy still works, but it is not the recommended one: a strict list is modified by every read, and inside a shard that is a write where there should only be a read. For many threads, use EEviction::eClock.

class

CShardedCache

Ethereal::Cache#

The cache split into shards, each with its own lock.

template< typename TKey, typename TValue, typename THash = SDefaultHash< TKey > > class CShardedCache final
alias

Inner

#
using Inner = CCache< TKey, TValue, THash >;

The cache inside each shard.

alias

void

#
using EvictFn = void ( * )( void * pCtx, const TKey & Key, const TValue & Value, EEvictReason eReason );

Called when an entry leaves. Runs outside any lock.

alias

EStatus

#
using LoaderFn = EStatus ( * )( void * pCtx, const TKey & Key, TValue * pOut );

Produces the value of a key that missed.

const

kMinPerShard

#
static constexpr std::size_t kMinPerShard = 64u;

No shard gets fewer entries than this when the class chooses how many shards there are.

constructor

CShardedCache

#
CShardedCache() = default;

Default constructor. Call Init before use.

function

Init

#
EStatus Init( const SCacheParams & Params )

Chooses the number of shards and initializes each one.

Eight shards per hardware thread, rounded up to a power of two. The eight came from the bench, not from a guess: with four per thread the scaling from one to eight threads measured 1.76x, and with many more it measured 2.63x on the same machine in the same run.

The reason is that two threads in the same shard do not contend only for the lock. They contend for the cache line it lives on, and for the slab lines where CLOCK writes the reference bit.

The upper limit is the hit rate. Each shard evicts on its own, and a shard with four slots evicts a popular key only because it landed in that piece. So no shard gets fewer than 64 entries, even if that means fewer shards than threads.

Params
Cache parameters. uMaxEntries and uMaxCostBytes are for the whole cache.
eOk, eInvalidArgument, or the error of a shard. Also eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
function

SetEvictCallback

#
void SetEvictCallback( const EvictFn pFn, void * const pCtx ) noexcept

Sets the function called when an entry leaves.

It always runs outside the shard lock, and a test requires it: the callback calls the cache again and must not deadlock.

pFn
The callback. Null disables it.
pCtx
Context passed back to the callback.
function

Get

#
bool Get( const TKey & Key, TValue * const pOut )

Looks up a key and copies the value.

Key
The key.
pOut
Receives the value. May be null.
false when the key is missing, expired, or of another generation.
function

Contains

#
bool Contains( const TKey & Key )

The key is in the cache.

function

Put

#
EStatus Put( const TKey & Key, const TValue & Value, const ETL_UINT64 uTtlMs = 0u, const std::size_t uCost = 1u )

Stores a value, replacing the one with the same key.

Key
The key.
Value
The value.
uTtlMs
Time to live. Zero uses uDefaultTtlMs.
uCost
Cost of the entry.
eOk, eNotInitialized, eRejected or eOutOfMemory.
function

Remove

#
bool Remove( const TKey & Key )

Removes a key.

false when the key was not there.
function

Clear

#
void Clear()

Removes everything, one shard at a time.

function

InvalidateAll

#
void InvalidateAll()

Invalidates everything in O(number of shards). Touches no entry.

function

GetOrLoad

#
EStatus GetOrLoad( const TKey & Key, TValue * const pOut, void * const pCtx, const LoaderFn pLoader )

Looks up a key and, on a miss, loads it with exactly one loader call for all the threads that missed at the same time.

Key
The key.
pOut
Receives the value. May be null.
pCtx
Context passed to the loader.
pLoader
The loader.
eOk, eNotInitialized, eLoadFailed without a loader, or the error of the loader.
function

ShardCount

#
std::size_t ShardCount() const noexcept

Number of shards.

function

Size

#
std::size_t Size()

Number of entries, summed shard by shard.

function

MemoryUsage

#
std::size_t MemoryUsage()

Bytes of all the shards.

function

Stats

#
SCacheStats Stats()

Sum of the counters of all the shards.

Not a coherent snapshot, and it could not be: that would require holding all the locks at once, which is exactly the single lock this class exists to avoid.