05 kvstore 与 dict:键空间的三层结构


 TL;DR
键空间在这棵树里是三层:redisDb 持有 kvstore,kvstore 持有一组按槽位切分的 dict,dict 底层是新的 bucket + child bucket 链。本文把三层逐个拆开,讲清槽位怎么定、键怎么落位、rehash 怎么走。
难度 中等

这一章回答四个问题:

  1. redisDb 里的 keys 字段为什么不是 dict * 而是 kvstore *?
  2. kvstore 底下挂了多少个 dict?非集群模式下是几个?
  3. 新的 dict.c 说的「bucket + child bucket 链」是什么形状?64 字节里装了什么?
  4. no_value 这个标志省掉了什么?为什么它要求指针 8 字节对齐?

本文不讨论:dict 的扩容与 rehash 细节(那是本文 5.8 节的简化版,完整机制见
src/dict.c)、紧凑编码 listpack/quicklist(见 06 章)、
命令怎么找到并执行(见 07、08 章)。

本文所有行号基于 /work/ai/cwork/redis,分支 unstable,
git describe --tags = 8.12-m02-int-184-gff28c55fc,HEAD = ff28c55f,
核对时间:2026-12-04。

版本号为什么是 255.255.255:src/version.h:1 是 unstable 分支的占位符,
真实发布号在切稳定分支时人工改写。认准 git describe --tags 的结果,
别拿 INFO 里的 redis_version 当版本。

5.1 先问对问题:一个 key 存在哪

在 7.x 里,这个问题有两层答案:key 存在 redisDb->dict 里,
过期时间存在 redisDb->expires 里。前者是一个 dict *,键是 sds,值是 robj *。

这棵树里答案变成了三层。 先看 redisDb 的定义:

// src/server.h:1269-1285
typedef struct redisDb {
    kvstore *keys;              /* The keyspace for this DB. As metadata, holds keysizes histogram */
    kvstore *expires;           /* Timeout of keys with a timeout set */
    kvstore *blessed_keys;      /* Blessed key name (sds) -> bless level (slot-partitioned, per-DB, like expires). */
    estore *subexpires;         /* Timeout of sub-keys with a timeout set. (Currently only used for hashes) */
    dict *blocking_keys;        /* Keys with clients waiting for data (BLPOP)*/
    dict *blocking_keys_unblock_on_nokey;   /* Keys with clients waiting for
                                             * data, and should be unblocked if key is deleted (XREADEDGROUP).
                                             * This is a subset of blocking_keys*/
    dict *stream_claim_pending_keys; /* Keys with clients waiting to claim pending entries */
    dict *stream_idmp_keys; /* Stream keys with IDMP tracking */
    dict *ready_keys;           /* Blocked keys that received a PUSH */
    dict *watched_keys;         /* WATCHED keys for MULTI/EXEC CAS */
    int id;                     /* Database ID */
    long long avg_ttl;          /* Average TTL, just for stats */
    unsigned long expires_cursor; /* Cursor of the active expire cycle. */
} redisDb;

先注意一件事:keys 和 expires 都是 kvstore *,但后面那五个还是 dict *。

这说明 kvstore 不是「所有 dict 的统一封装」,而是只用在需要按槽位切分的地方。
blocking_keys、watched_keys 这些是进程级的辅助索引,跟槽位无关,
用裸 dict 就够。

三个 kvstore 各管什么:

字段 装什么 槽位切分?
keys 主键空间:key → value 是
expires 设了 TTL 的 key 是
blessed_keys 被标记为「不可淘汰」的 key 名 是
subexpires hash / set 成员级的过期时间 是

blessed_keys 是这棵树的新东西:它记的是「哪些 key 被显式保护、淘汰时不能动它」。
src/bless.c:99-110 里的 blessIsNoEvict / blessSetNoEvict 就是在维护这个索引,
no_evict 这个标志本身存在 kvobj 的 kvBits 里(src/object.h:130),
blessed_keys 只是它的副索引 —— 目的是让淘汰算法能快速跳过这些 key。

5.2 kvstore:一堆 dict 的数组

kvstore 的文件头注释把它的定位说得很清楚:

// src/kvstore.h:12-23
 * KVSTORE
 * -------
 * Index-based KV store implementation. This file implements a KV store comprised
 * of an array of dicts (see dict.c) The purpose of this KV store is to have easy
 * access to all keys that belong in the same dict (i.e. are in the same dict-index)
 *
 * For example, when Redis is running in cluster mode, we use kvstore to save
 * all keys that map to the same hash-slot in a separate dict within the kvstore
 * struct.
 * This enables us to easily access all keys that map to a specific hash-slot.
 *
 * Portions of this file are available under BSD3 terms; see REDISCONTRIBUTIONS for more information.

一句话:kvstore 是一组 dict 的数组,按「dict 索引」把它们分开。

为什么要这么绕?因为集群模式下一个节点只负责一部分槽位。
把同槽位的 key 放进同一个 dict,那么:

  • 「这个节点有哪些槽」→ 只看哪些 dict 非空;
  • 「迁移一个槽」→ 整块搬一个 dict,不用一个 key 一个 key 地挑;
  • 「这个槽有多少 key」→ 一个 dict 的大小。

结构体本身:

// src/kvstore.c:28-44
struct _kvstore {
    int flags;
    kvstoreType *type;
    dictType dtype;
    dict **dicts;
    long long num_dicts;
    long long num_dicts_bits;
    list *rehashing;                       /* List of dictionaries in this kvstore that are currently rehashing. */
    int resize_cursor;                     /* Cron job uses this cursor to gradually resize dictionaries (only used if num_dicts > 1). */
    int allocated_dicts;                   /* The number of allocated dicts. */
    int non_empty_dicts;                   /* The number of non-empty dicts. */
    unsigned long long key_count;          /* Total number of keys in this kvstore. */
    unsigned long long bucket_count;       /* Total number of buckets (top-level and child) in this kvstore across dictionaries. */
    fenwickTree *dict_sizes;               /* Binary indexed tree (BIT) that describes cumulative key frequencies up until given dict-index. */
    size_t overhead_hashtable_rehashing;   /* The overhead of dictionaries rehashing. */
    void *metadata[];                      /* conditionally allocated based on "flags" */
};

几个关键字段:

  • dict **dicts —— 数组本体,第 i 个元素是第 i 个 dict;
  • num_dicts / num_dicts_bits —— dict 的个数是 2 的幂,幂指数单独存;
  • fenwickTree *dict_sizes —— 树状数组,记每个 dict 前面累计多少 key
    (本文 5.7 节讲它干嘛用的);
  • void *metadata[] —— 柔性数组,按需分配的额外元数据;
    keys 这个 kvstore 就借它挂了 keysize 直方图。

dict_sizes 那行注释里说的 BIT 就是 Binary Indexed Tree,
即树状数组 / Fenwick Tree。它实现在 src/fwtree.c ——
也就是第 01 章提过的那个「不是模糊树」的 fwtree.c。

5.3 dict 的个数:1 个还是 16384 个

kvstore 的 dict 个数由创建时传的 num_dicts_bits 决定
(2^num_dicts_bits 个)。这个值从哪来?看 initServer():

// src/server.c:3178-3199
    /* Create the Redis databases, and initialize other internal state. */
    int slot_count_bits = 0;
    int flags = KVSTORE_ALLOCATE_DICTS_ON_DEMAND;
    if (server.cluster_enabled) {
        slot_count_bits = CLUSTER_SLOT_MASK_BITS;
        flags |= KVSTORE_FREE_EMPTY_DICTS;
    }
    for (j = 0; j < server.dbnum; j++) {
        server.db[j].keys = kvstoreCreate(&kvstoreExType, &dbDictType, slot_count_bits, flags);
        server.db[j].expires = kvstoreCreate(&kvstoreBaseType, &dbExpiresDictType, slot_count_bits, flags);
        server.db[j].blessed_keys = blessedKvstoreCreate(slot_count_bits, flags);
        server.db[j].subexpires = estoreCreate(&subexpiresBucketsType, slot_count_bits);
        server.db[j].expires_cursor = 0;
        server.db[j].blocking_keys = dictCreate(&keylistDictType);
        server.db[j].blocking_keys_unblock_on_nokey = dictCreate(&objectKeyPointerValueDictType);
        server.db[j].stream_claim_pending_keys = dictCreate(&objectKeyPointerValueDictType);
        server.db[j].stream_idmp_keys = dictCreate(&objectKeyNoValueDictType);
        server.db[j].ready_keys = dictCreate(&objectKeyPointerValueDictType);
        server.db[j].watched_keys = dictCreate(&keylistDictType);
        server.db[j].id = j;
        server.db[j].avg_ttl = 0;
    }

答案很清楚:

模式 slot_count_bits dict 个数
非集群 0 1 个
集群 CLUSTER_SLOT_MASK_BITS = 14 16384 个

CLUSTER_SLOT_MASK_BITS 的定义在 src/cluster.h:22:
槽位总数是 1 << 14 = 16384,这是 Redis Cluster 从 3.0 沿用至今的定值。

所以在普通单机 Redis 上,db->keys 这个 kvstore 底下只有 1 个 dict。
这就是为什么非集群模式下 getKeySlot() 直接返回 0:

// src/db.c:501-517
int getKeySlot(sds key) {
    if (!server.cluster_enabled) return 0;
    /* This is performance optimization that uses pre-set slot id from the current command,
     * in order to avoid calculation of the key hash.
     *
     * This optimization is only used when current_client flag `CLIENT_EXECUTING_COMMAND` is set.
     * It only gets set during the execution of command under `call` method. Other flows requesting
     * the key slot would fallback to calculateKeySlot.
     */
    if (server.current_client && server.current_client->slot >= 0 && server.current_client->flags & CLIENT_EXECUTING_COMMAND) {
        debugServerAssertWithInfo(server.current_client, NULL,
                                  (int)keyHashSlot(key, (int)sdslen(key)) == server.current_client->slot);
        return server.current_client->slot;
    }
    int slot = keyHashSlot(key, (int)sdslen(key));
    return slot;
}

注意那个 debugServerAssertWithInfo:如果当前命令已经算过一次槽位了,
就直接复用,但会断言这个 key 算出来的槽位确实等于它
。
这是为了「省一次 CRC16 计算」做的优化,同时用断言兜底防止算错。

非集群模式下 kvstore 这一层几乎退化成透明:只有一个 dict,
getKeySlot() 永远返回 0,索引计算全部走 didx == 0 这条路。
但代码路径是统一的 —— 同一份代码同时服务集群和单机,
这是这棵树的一贯做法。

5.4 两个 flag:按需分配与空则释放

kvstoreCreate() 的 flags 只有两个:

// src/kvstore.h:87-88
#define KVSTORE_ALLOCATE_DICTS_ON_DEMAND (1<<0)
#define KVSTORE_FREE_EMPTY_DICTS (1<<1)
flag 含义
KVSTORE_ALLOCATE_DICTS_ON_DEMAND 按需分配:用到哪个 dict 才创建哪个
KVSTORE_FREE_EMPTY_DICTS 空了就释放:dict 变空就把它 free 掉

看 kvstoreCreate() 怎么用它们:

// src/kvstore.c:196-242
kvstore *kvstoreCreate(kvstoreType *type, dictType *dtype, int num_dicts_bits, int flags) {
    /* We can't support more than 2^16 dicts because we want to save 48 bits
     * for the dict cursor, see kvstoreScan */
    assert(num_dicts_bits <= 16);
    assert(!type->dictMetadataBytes || type->dictMetadataBytes(NULL) >= sizeof(kvstoreDictMetaBase));

    /* Calc kvstore size */
    size_t kvsize = sizeof(kvstore);
    /* Conditionally calc also histogram size */
    if (type->kvstoreMetadataBytes)
        kvsize += type->kvstoreMetadataBytes(NULL);
    
    kvstore *kvs = zcalloc(kvsize);
    memcpy(&kvs->dtype, dtype, sizeof(kvs->dtype));
    kvs->flags = flags;
    kvs->type = type;

    /* kvstore must be the one to set these callbacks, so we make sure the
     * caller didn't do it */
    assert(!dtype->userdata);
    assert(!dtype->dictMetadataBytes);
    assert(!dtype->rehashingStarted);
    assert(!dtype->rehashingCompleted);
    kvs->dtype.userdata = kvs;
    kvs->dtype.dictMetadataBytes = type->dictMetadataBytes ?
        type->dictMetadataBytes : kvstoreDictBaseMetaSize;
    kvs->dtype.rehashingStarted = kvstoreDictRehashingStarted;
    kvs->dtype.rehashingCompleted = kvstoreDictRehashingCompleted;
    kvs->dtype.bucketChanged = kvstoreDictBucketChanged;

    kvs->num_dicts_bits = num_dicts_bits;
    kvs->num_dicts = 1 << kvs->num_dicts_bits;
    kvs->dicts = zcalloc(sizeof(dict*) * kvs->num_dicts);
    if (!(kvs->flags & KVSTORE_ALLOCATE_DICTS_ON_DEMAND)) {
        for (int i = 0; i < kvs->num_dicts; i++)
            createDictIfNeeded(kvs, i);
    }

    kvs->rehashing = listCreate();
    kvs->key_count = 0;
    kvs->non_empty_dicts = 0;
    kvs->resize_cursor = 0;
    kvs->dict_sizes = kvs->num_dicts > 1 ? fwTreeCreate(kvs->num_dicts_bits) : NULL;
    kvs->bucket_count = 0;
    kvs->overhead_hashtable_rehashing = 0;
    return kvs;
}

几个细节:

  • num_dicts_bits <= 16 的断言,注释解释了原因:要给 dict 游标留 48 位
    (64 位游标 - 16 位 dict 索引 = 48 位给哈希表定位)。见 5.9 节。
  • kvstore 强行设置四个回调(userdata / dictMetadataBytes /
    rehashingStarted / rehashingCompleted),并且断言调用方没设。
    换句话说:这些钩子归 kvstore 所有,调用方不许插手。
    rehashingStarted 的作用是把正在 rehash 的 dict 挂到 kvs->rehashing 链表上,
    好让后台任务能找到它们。
  • dict_sizes 只在 num_dicts > 1 时才创建。单机模式下不需要树状数组,
    省掉这块内存。
  • dict **dicts 是一次性 zcalloc 的(16384 个指针 = 128KB),
    但每个 dict 是按需创建的 —— 这两件事不冲突:指针数组一直在,
    dict 本体用到才建。

5.5 主键空间的 dict 长什么样

keys 这个 kvstore 底下挂的 dict 类型是 dbDictType:

// src/server.c:634-647
/* Db->dict, keys are of type kvobj, unification of key and value */
dictType dbDictType = {
    dictSdsHash,            /* hash function */
    NULL,                   /* key dup */
    NULL,                   /* val dup */
    dictSdsCompareKV,       /* lookup key compare */
    dictDestructorKV,       /* key destructor */
    NULL,                   /* val destructor */
    dictResizeAllowed,      /* allow to resize */
    .no_value = 1,          /* keys and values are unified (kvobj) */
    .keys_are_odd = 0,      /* simple kvobj (robj) struct */
    .keyFromStoredKey = kvGetKey,    /* get key from stored-key */
    .prefetchEntryValue = dbDictPrefetchEntryValue,
};

.no_value = 1 是最值得注意的一行。

这棵树把键和值统一成了一个对象 kvobj —— 名字、值、TTL 元数据、
LRU 时间全在一个结构体里。所以主键空间的 dict 里,
桶槽位直接存 kvobj 指针,不需要再套一层 dictEntry。

kvobj 和 robj 是同一个结构体(两个 typedef 别名):

// src/object.h:104-122
struct redisObject {
    unsigned type:4;
    unsigned encoding:5;
    unsigned refcount : OBJ_REFCOUNT_BITS;
    unsigned iskvobj : 1;   /* 1 if this struct serves as a kvobj base */
    
    /* metabits and lru are Relevant only when iskvobj is set: */     
    unsigned metabits :8;  /* Bitmap of metadata (+expiry) attached to this kvobj */
    unsigned lru:LRU_BITS; /* LRU time (relative to global lru_clock) or
                            * LFU data (least significant 8 bits frequency
                            * and most significant 16 bits access time). */
    void *ptr;
};

/* robj - General purpose redis object */
typedef struct redisObject robj;

/* kvobj: see header comment above for definition and memory layout. */
typedef struct redisObject kvobj;

.keyFromStoredKey = kvGetKey 补上了另一半:
dict 存的是 kvobj,但查找时手里拿的是 sds 字符串。
这个回调负责「从存进去的东西里把 key 抽出来」,好让比较函数能工作:

// src/server.c:335-352
static const void *kvGetKey(const void *kv) {
    sds sdsKey = kvobjGetKey((kvobj *) kv);
    return sdsKey;
}

int dictSdsCompareKV(dictCmpCache *cache, const void *sdsKey1, const void *sdsKey2)
{
    /* is first cmp call of a new lookup */
    if (cache->useCache == 0) {
        cache->useCache = 1;
        cache->data[0].sz = sdslen((sds) sdsKey1);
    }

    size_t l1 = cache->data[0].sz;
    size_t l2 = sdslen((sds)sdsKey2);
    if (l1 != l2) return 0;
    return memcmp(sdsKey1, sdsKey2, l1) == 0;
}

dictCmpCache 是个一次查找内的缓存:第一次比较时把「查找 key 的长度」存下来,
后面的比较直接用。注释写得很清楚:
「如果提取被查找的 key 很贵(比如 sdslen()、kvobjGetKey()),缓存可以减少重复计算」。

这棵树还多了一个 7.x 没有的东西:prefetchEntryValue。
它是个可选钩子,在查找命中时把「值所在的那块内存」预取进 L1:

// src/server.c:585-595
/* dbDictType prefetch callback.
 * The main keyspace stores a kvobj as the entry's "stored key" (no_value=1),
 * so the bucket slots hold the kvobj pointers, and the entry prefetch of the
 * prefetch state machine (dictPrefetchNext() in dict.c) already brings the
 * kvobj head in. This hook brings kv->ptr into L1 when the value lives in its
 * own allocation (RAW strings, listpacks, ...), since the caller reads it next. */
static void *dbDictPrefetchEntryValue(const dictEntry *de) {
    kvobj *kv = dictGetKey(de);
    if (inlineEncodedObject(kv)) return NULL;
    return kv->ptr;
}

小对象(inline 编码)不需要预取 —— 它的数据就在 kvobj 后面,
预取 kvobj 头就等于预取了数据。大对象(RAW 字符串、listpack)
数据在别的分配里,得单独 kv->ptr 一下。

5.6 dict 内部:64 字节的 bucket 与 child bucket 链

这是这棵树相对 7.x 最大的单点改动。7.x 的 dict 是:

/* 7.x 的形状,不是这棵树的 */
dictEntry **table;      /* 指向桶数组的指针 */
dictEntry **buckets;    /* 每个桶一个指针,冲突时挂链表 */

这棵树换成了「桶里直接装若干个槽位,冲突就链子桶」。
文件头注释交代得很清楚:

// src/dict.h:216-228
/* A bucket is 64 bytes (one cache line) and holds DICT_BUCKET_SLOTS entries.
 * A bucket that overflows uses its last slot to point to a child bucket. */
#if SIZE_MAX == UINT64_MAX
#define DICT_BUCKET_SLOTS        7
#else
#define DICT_BUCKET_SLOTS        12
#endif
#define DICT_BUCKET_BYTES        64

/* This is the initial size of every hash table: a single bucket of
 * DICT_HT_INITIAL_SIZE slots */
#define DICT_HT_INITIAL_EXP      0
#define DICT_HT_INITIAL_SIZE     DICT_BUCKET_SLOTS

64 位机上每个桶 7 个槽位,32 位机上 12 个。
64 字节 = 一条 cache line,这是整个设计的锚点。

桶的内部布局:

// src/dict.c:217-242
/* Bucket layout (64 bytes):
 *
 *   chained(1 bit) presence(SLOTS bits) hashes[SLOTS] slots[SLOTS]
 *
 * presence tells which positions hold an entry. hashes[] holds the top byte of
 * the hash of each entry and is used to rule out most non-matching entries
 * without touching them. When chained is set, the last slot is not an entry
 * but a pointer to a child bucket and its presence bit is clear. */
#if DICT_BUCKET_SLOTS == 7
#define BUCKET_BITS_TYPE uint8_t
#define BUCKET_FACTOR 5
#else
#define BUCKET_BITS_TYPE uint16_t
#define BUCKET_FACTOR 3
#endif
#define BUCKET_DIVISOR 32
#define BUCKET_BITS_TYPE_EX __extension__ BUCKET_BITS_TYPE

struct dictBucket {
    BUCKET_BITS_TYPE_EX chained : 1;
    BUCKET_BITS_TYPE_EX presence : DICT_BUCKET_SLOTS;
    uint8_t hashes[DICT_BUCKET_SLOTS];
    dictEntry *slots[DICT_BUCKET_SLOTS];
};

static_assert(sizeof(dictBucket) == DICT_BUCKET_BYTES, "dictBucket must be one cache line");

64 字节怎么装下这些的(64 位机,7 槽位):

字段 字节 说明
chained 1 bit 本桶是否已溢出、末位是子桶指针
presence 7 bits 哪些槽位有东西
hashes[7] 7 字节 每个条目的哈希高 8 位
slots[7] 56 字节 7 个指针
合计 1 + 7 + 56 = 64 正好一条 cache line

hashes[] 存哈希的高 8 位,这是这个设计里最巧的一处。
桶下标用哈希的低位决定,槽位里存的 tag 用哈希的高位。
两者互不干扰(表大小最多 2^56 个桶),所以:

查找时先按高位 tag 过滤掉绝大多数不匹配的槽位,
连指针都不用解引用。
注释里说的是「rule out most non-matching entries
without touching them」。

对应的过滤函数:

// src/dict.c:409-415
/* Returns the mask of the positions whose hash tag is `tag`. */
static inline bucketBits findHashMatches(const uint8_t *hashes, uint8_t tag) {
    bucketBits m = 0;
    for (int i = 0; i < DICT_BUCKET_SLOTS; i++)
        m |= (bucketBits)((hashes[i] == tag) << i);
    return m;
}

桶满了怎么办?链一个子桶。
chained 位置 1 时,最后一个槽位不再存条目,而是存子桶指针,
它的 presence 位是清的。所以「7 个槽位」在链了子桶的桶里只有 6 个能用:

// src/dict.c:363-393
/* Returns the number of positions of a bucket that can hold an entry. */
static inline int numBucketPositions(const dictBucket *b) {
    return DICT_BUCKET_SLOTS - (b->chained ? 1 : 0);
}

static inline int bucketIsFull(const dictBucket *b) {
    return b->presence == (bucketBits)((1u << numBucketPositions(b)) - 1);
}

static inline int isPositionFilled(const dictBucket *b, int pos) {
    return b->presence & (1u << pos);
}

/* Returns 1 if the bucket's own positions hold at most one entry (child
 * buckets are not counted), 0 otherwise. */
static inline int bucketHasAtMostOneEntry(const dictBucket *b) {
    return (b->presence & (b->presence - 1)) == 0;
}

static inline dictBucket *getChildBucket(const dictBucket *b) {
    return b->chained ? (dictBucket *)(void *)b->slots[DICT_BUCKET_SLOTS - 1] : NULL;
}

static inline void setChildBucket(dictBucket *b, dictBucket *child) {
    b->slots[DICT_BUCKET_SLOTS - 1] = (dictEntry *)(void *)child;
}

/* A bucket with nothing in it and no child. */
static inline int bucketIsEmpty(const dictBucket *b) {
    return b->presence == 0 && !b->chained;
}

这个链是「桶链」而不是 7.x 的「entry 链表」。
7.x 是每个桶一个头指针,冲突的 entry 串成链表;
这棵树是每个桶本身能装 7 个 entry,装不下才挂一个子桶,
子桶再满就挂子桶的子桶。

查找路径

findBucketForKey() 沿着桶链往下走:

// src/dict.c:587-616
/* Find the bucket and position of a key. Does not rehash or write anything.
 * If `parent_out` is not NULL, it is set to the bucket whose child is the
 * returned bucket, or NULL for a top-level bucket. */
static dictBucket *findBucketForKey(dict *d, uint64_t hash, const void *key, int *pos_out,
                                    int *table_out, dictBucket **parent_out)
{
    dictCmpCache cache = {0};
    keyCmpFunc cmp = dictGetCmpFunc(d);
    uint8_t tag = hashTag(hash);
    for (int table = 0; table <= 1; table++) {
        if (d->ht_used[table] == 0) continue;
        size_t idx = hash & DICTHT_SIZE_MASK(d->ht_size_exp[table]);
        /* Buckets before rehashidx have already been moved to the new table. */
        if (table == 0 && (long)idx < d->rehashidx) continue;
        dictBucket *b = &d->ht_table[table][idx];
        dictBucket *parent = NULL;
        do {
            int pos = bucketFindKey(d, b, tag, key, cmp, &cache);
            if (pos >= 0) {
                *pos_out = pos;
                if (table_out) *table_out = table;
                if (parent_out) *parent_out = parent;
                return b;
            }
            parent = b;
            b = getChildBucket(b);
        } while (b);
    }
    return NULL;
}

for (table = 0; table <= 1; ...) 这层循环是增量 rehash 的痕迹:
rehash 期间两张表并存,key 可能还在老表里(idx < rehashidx 的跳过),
也可能在新表里。查找要同时看两张表。

单桶内的比较:

// src/dict.c:572-585
/* Search a single bucket (not its child buckets) for the key. Returns the
 * position of the key, or -1 if it is not in this bucket. */
static inline int bucketFindKey(dict *d, dictBucket *b, uint8_t tag, const void *key,
                                keyCmpFunc cmp, dictCmpCache *cache)
{
    bucketBits candidates = b->presence & findHashMatches(b->hashes, tag);
    while (candidates) {
        int pos = __builtin_ctz(candidates);
        const void *visitedKey = dictStoredKey2Key(d, dictGetKey(b->slots[pos]));
        if (key == visitedKey || cmp(cache, key, visitedKey)) return pos;
        candidates &= candidates - 1;
    }
    return -1;
}

__builtin_ctz 是「count trailing zeros」 ——
找出最低的一个置位位的位置。candidates &= candidates - 1 是标准的
「取最低置位然后清掉」惯用法。整个查找过程不碰任何不匹配的条目。

插入路径

// src/dict.c:1003-1031
/* Adds a key that is not in the dict yet, at a free position of the bucket
 * chain that its hash maps to, and returns the new entry. For no_value dicts
 * the entry is the encoded key. If `link` is not NULL, it is set to the link
 * of the new entry. This is a low level function which assumes that
 * dictExpandIfNeeded() was called before. */
static dictEntry *dictInsertKey(dict *d, uint64_t hash, void *key __stored_key, dictEntryLink *link) {
    dictEntry *entry;
    int pos, htidx;
    if (d->type->no_value) {
        /* We can store the key directly in the bucket slot without
         * allocating dictEntry. */
        entry = encodeEntryKey(d, key);
        assert(entryIsKey(entry));
    } else {
        /* Allocate the memory and store the new entry. */
        entry = zmalloc(sizeof(*entry));
        assert(entryIsNormal(entry)); /* Check alignment of allocation */
        entry->key = key;
    }
    /* If rehashing is ongoing, we insert in table 1, otherwise in table 0. */
    dictBucket *b = findBucketForInsert(d, hash, &pos, &htidx);
    b->slots[pos] = entry;
    b->hashes[pos] = hashTag(hash);
    b->presence |= (1u << pos);
    d->ht_used[htidx]++;
    if (link) *link = &b->slots[pos];

    return entry;
}

no_value 的省法就在这里:entry = encodeEntryKey(d, key),
连 dictEntry 都不分配,桶槽位直接放 key 指针。

5.7 指针标记:为什么要求 8 字节对齐

上面那句 encodeEntryKey(d, key) 看着简单,但它要往指针里塞标记位。
src/dict.h 有一段专门的注释解释这套机制:

// src/dict.h:16-39
 * Dict usage of pointer tagging
 * -----------------------------
 * In the "normal" case (no_value=0), every bucket slot holds a pointer to a
 * dictEntry, and dictEntry holds untagged pointers to key and value. When a
 * dict is used as a set (no_value=1), every slot holds the key pointer itself,
 * avoiding dictEntry allocation. Accessors such as dictGetKey() get only the
 * entry pointer, not the dict, so the entry pointer itself tells which of the
 * two it is: Redis dicts use pointer tagging, i.e. embedding metadata in the
 * lowest three bits of pointers. This requires 8-byte alignment, which
 * zmalloc() guarantees on both 32-bit and 64-bit systems (via jemalloc/tcmalloc,
 * or standard malloc with explicit PREFIX_SIZE=8).
 * 
 * Besides of distinguishing direct key pointers from dictEntry pointers, we also 
 * need to distinguish between even and odd key pointers that being stored in the 
 * dict. Therefore, we use the following tagging scheme:
 * - dictEntry pointer: Points to a dictEntry structure (8-byte aligned). Left intact: 
 *   ENTRY_PTR_NORMAL=000
 * - Odd-address key (keys_are_odd=1): Direct pointer to a 
 *   key with odd address (e.g., all SDS strings), Left intact: 
 *   ENTRY_PTR_IS_ODD_KEY=XX1
 * - Even-address key  (keys_are_odd=0): Direct pointer to a key with 
 *   even address. Since 8-byte alignment yields bits = 000, same as dictEntry, 
 *   we tag it by setting bit 1 which results with: 
 *   ENTRY_PTR_IS_EVEN_KEY=010.

低 3 位编码成三种:

编码 含义
000 指向 dictEntry 结构体
XX1 直接指向一个奇地址的 key(比如所有 SDS 字符串)
010 直接指向一个偶地址的 key

为什么要区分奇偶? 因为 SDS 字符串是 8 字节对齐的(偶地址),
而 dictEntry 也是 8 字节对齐的(偶地址)—— 两者低 3 位都是 000,会撞。
所以给偶地址的 key 打上 010,把 bit 1 置起来。

「为什么区分 dictEntry 指针和 key 指针」? 因为
dictGetKey() 只拿到 entry 指针、拿不到 dict 指针:

// src/dict.c:306-327
/* --------------------- dictEntry pointer bit tricks ----------------------  */

/* The 3 least significant bits in a pointer to a dictEntry determines what the
 * pointer actually points to. If the least bit is set, it's a key. Otherwise,
 * the bit pattern of the least 3 significant bits mark the kind of entry. */

#define ENTRY_PTR_MASK        7 /* 111 */
#define ENTRY_PTR_NORMAL      0 /* 000 : If a pointer to an entry with value. */
#define ENTRY_PTR_IS_ODD_KEY  1 /* XX1 : If a pointer to odd key address (must be 1). */
#define ENTRY_PTR_IS_EVEN_KEY 2 /* 010 : If a pointer to even key address. (must be 2 or 4). */

/* Returns 1 if the entry pointer is a pointer to a key, rather than to an
 * allocated entry. Returns 0 otherwise. */
static inline int entryIsKey(const dictEntry *de) {
    return ((uintptr_t)de & (ENTRY_PTR_IS_ODD_KEY | ENTRY_PTR_IS_EVEN_KEY));
}

/* Returns 1 if the pointer is actually a pointer to a dictEntry struct. Returns
 * 0 otherwise. */
static inline int entryIsNormal(const dictEntry *de) {
    return ((uintptr_t)(void *)de & ENTRY_PTR_MASK) == ENTRY_PTR_NORMAL;
}

「没有 dict 指针,就没法查 dictType」 ——
所以标记位必须自带在指针里,让 dictGetKey() 单看指针就知道该怎么办。

这就是为什么 zmalloc() 必须保证 8 字节对齐:
标记位要占低 3 位,指针得留出这 3 位。
第 03 章讲过 zmalloc 的 PREFIX_SIZE=8 就是为这事准备的。

5.8 键怎么落到 kvstore 里

从 db.c 看一次完整的写入。dbAddInternal() 是核心:

// src/db.c:440-470
kvobj *dbAddInternal(redisDb *db, robj *key, robj **valref, dictEntryLink *link, 
                     const kvSpec *spec)
{
    int slot = getKeySlot(key->ptr);
    dictEntryLink tmp = NULL;
    if (link == NULL) link = &tmp;
    robj *val = *valref;
    kvobj *kv = kvobjSet(key->ptr, val, spec->metabits);
    initObjectLRUOrLFU(kv);
    kvstoreDictSetAtLink(db->keys, slot, kv, link, 1);
    
    /* Handle metadata (expiration and modules metadata) */
    if (spec->metabits) {
        if (spec->metabits & KEY_META_MASK_EXPIRE) {
            /* Expiry is always the first meta (from last) */
            long long expire = spec->meta[KEY_META_ID_MAX - 1];
            kvobj *newkv = setExpireByLink(NULL, db, key->ptr, expire, *link);
            serverAssert(newkv == kv);
        }
        
        /* memcpy modules metadata to beginning of kvobj */
        if (spec->metabits & KEY_META_MASK_MODULES)
            /* Also trivial overwrite expire */
            memcpy(kvobjGetAllocPtr(kv), 
                   spec->meta + KEY_META_ID_MAX - spec->numMeta,
                   spec->numMeta * sizeof(uint64_t));
    }

    if (spec->no_evict) blessSetNoEvict(db, kv, 1);

    signalKeyAsReady(db, key, kv->type);

这条路径把「slot → dict → 桶槽位」串了起来:

  1. getKeySlot(key->ptr) —— 算出槽位(非集群是 0);
  2. kvobjSet(key->ptr, val, spec->metabits) —— 把 key 和 value 合成一个 kvobj;
  3. kvstoreDictSetAtLink(db->keys, slot, kv, link, 1) —— 塞进对应的 dict。

第三步的实现在 kvstore 这一层:

// src/kvstore.c:877-900
/* Set a key (or key-value) in the specified kvstore.
 *
 * This function inserts a new key or updates an existing one, depending on
 * the `newItem` flag.
 *
 * Parameters:
 * link:      - When `newItem` is set, `link` points to the bucket of the key.
 *            - When `newItem` is not set, `link` points to the link of the key.
 *            - If link is NULL, dictFindLink() will be called to locate the link.
 *
 * newItem: - If set, add a new key with a new dictEntry.
 *          - If not set, update the key of an existing dictEntry.
 */
void kvstoreDictSetAtLink(kvstore *kvs, int didx, void *kv, dictEntryLink *link, int newItem) {
    dict *d;
    if (newItem) {
        d = createDictIfNeeded(kvs, didx);
        dictSetKeyAtLink(d, kv, link, newItem);
        cumulativeKeyCountAdd(kvs, didx, 1); /* must be called only after updating dict */
    } else {
        d = kvstoreGetDict(kvs, didx);
        dictSetKeyAtLink(d, kv, link, newItem);
    }
}

createDictIfNeeded(kvs, didx) —— 这就是 KVSTORE_ALLOCATE_DICTS_ON_DEMAND
落地的地方:第一次往这个槽位放 key 时才创建 dict。

cumulativeKeyCountAdd(kvs, didx, 1) 更新两个计数:总 key 数和树状数组:

// src/kvstore.c:82-99
/* Updates binary index tree (Fenwick tree), updates key count for a given dict */
static void cumulativeKeyCountAdd(kvstore *kvs, int didx, long delta) {
    kvs->key_count += delta;

    dict *d = kvstoreGetDict(kvs, didx);
    size_t dsize = dictSize(d);
    /* Increment if dsize is 1 and delta is positive (first element inserted, dict becomes non-empty).
     * Decrement if dsize is 0 (dict becomes empty). */
    int non_empty_dicts_delta = (dsize == 1 && delta > 0) ? 1 : (dsize == 0) ? -1 : 0;
    kvs->non_empty_dicts += non_empty_dicts_delta;

    /* BIT does not need to be calculated when there's only one dict. */
    if (kvs->num_dicts == 1)
        return;

    /* Update the BIT */
    fwTreeUpdate(kvs->dict_sizes, didx, delta);
}

「只有一个 dict 时不更新树状数组」 —— 单机模式下这一段是空操作,
树状数组只服务集群模式。

树状数组的更新是 O(log n):

// src/fwtree.c:58-74
/* Update the tree by adding delta to the element at idx (0-based) */
void fwTreeUpdate(fenwickTree *ft, int idx, long long delta) {
    if (!ft || idx < 0 || idx >= ft->size) return;

    /* Convert to 1-based indexing */
    idx++;
    ft->total += delta;

    while (idx <= ft->size) {
        if (delta < 0) {
            assert(ft->tree[idx] >= (unsigned long long)(-delta));
        }
        ft->tree[idx] += delta;
        idx += (idx & -idx);
    }
    debugAssert(ft->total == fwTreePrefixSum(ft, ft->size - 1));
}

idx += (idx & -idx) 是树状数组的经典步进:
每次跳到「负责区间的下一个节点」。最后那行 debugAssert 是不变式检查 ——
total 必须等于「从头到尾的前缀和」。

树状数组用来干什么

kvstoreFindDictIndexByKeyIndex() 是它的主要消费者:

// src/kvstore.c:496-519
/* Finds a dict containing target element in a key space ordered by dict index.
 * Consider this example. Dictionaries are represented by brackets and keys by dots:
 *  #0   #1   #2     #3    #4
 * [..][....][...][.......][.]
 *                    ^
 *                 target
 *
 * In this case dict #3 contains key that we are trying to find.
 *
 * The return value is 0 based dict-index, and the range of the target is [1..kvstoreSize], kvstoreSize inclusive.
 *
 * To find the dict, we start with the root node of the binary index tree and search through its children
 * from the highest index (2^num_dicts_bits in our case) to the lowest index. At each node, we check if the target
 * value is greater than the node's value. If it is, we remove the node's value from the target and recursively
 * search for the new target using the current node as the parent.
 * Time complexity of this function is O(log(kvs->num_dicts))
 */
int kvstoreFindDictIndexByKeyIndex(kvstore *kvs, unsigned long target) {
    if (kvs->num_dicts == 1 || kvstoreSize(kvs) == 0)
        return 0;
    assert(target <= kvstoreSize(kvs));

    return fwTreeFindIndex(kvs->dict_sizes, target);
}

「按 key 的序号找到它落在哪个 dict」 —— O(log n)。

这个能力的直接用途是「公平随机取一个 key」。
7.x 的 RANDOMKEY / SCAN 在集群模式下有个经典问题:
如果按 slot 顺序取,热点 slot 里的 key 会被反复抽中。
这棵树的做法是先按 key 数量加权抽一个 dict,再在 dict 里抽:

// src/kvstore.c:395-445
/* Returns fair random dict index, probability of each dict being returned is
 * proportional to the number of elements that dictionary holds.
 * This function guarantees that it returns a dict-index of a non-empty dict,
 * unless the entire kvstore is empty or all dicts are skipped.
 *
 * Parameters:
 * - kvs: the kvstore instance
 * - skip_cb: callback to determine if a dict should be skipped (NULL means no skipping)
 * - fair_attempts: number of fair selection attempts before falling back
 * - slow_fallback: if 1, uses systematic search when fair attempts fail
 *
 * Returns:
 * - Valid dict index (>= 0) on success
 * - -1 if no valid dict found (either slow_fallback is 0 or all dicts are skipped)
 *
 * Time complexity: O(fair_attempts * log(kvs->num_dicts)) for fair attempts,
 * plus O(kvs->num_dicts) for systematic fallback if enabled.
 */
int kvstoreGetFairRandomDictIndex(kvstore *kvs, kvstoreRandomShouldSkipDictIndex *skip_cb,
                                  int fair_attempts, int slow_fallback)
{
    if (kvs->num_dicts == 1 || kvstoreSize(kvs) == 0)
        return 0;

    unsigned long long total_size = kvstoreSize(kvs);

    /* Try fair attempts first. If skip_cb is not applicable, execute only once. */
    for (int attempt = 0; attempt < fair_attempts; attempt++) {
        unsigned long target = (randomULong() % total_size) + 1;
        int didx = kvstoreFindDictIndexByKeyIndex(kvs, target);
        if (!skip_cb || !skip_cb(didx)) {
            return didx;
        }
    }

    /* If fair attempts failed and slow fallback is allowed */
    if (slow_fallback) {
        /* systematic check from random start */
        int start = randomULong() % kvs->num_dicts;
        for (int i = 0; i < kvs->num_dicts; i++) {
            int didx = (start + i) % kvs->num_dicts;
            dict *d = kvstoreGetDict(kvs, didx);
            if (d && (!skip_cb || !skip_cb(didx))) {
                return didx;
            }
        }
    }

    /* Failed to find valid dict that has elements */
    return -1;
}

「抽一个 1..total 的随机数 → 树状数组查它落在哪个 dict」 ——
因为树状数组记的是累计 key 数,所以「dict 3 有 100 个 key」意味着
序号 3 那一段的 100 个数都会落到 dict 3。按 key 数加权,天然公平。

5.9 SCAN 的游标:48 位 + 16 位

SCAN 的游标在这棵树里是 64 位,被拆成两段用:

// src/kvstore.c:327-369
unsigned long long kvstoreScan(kvstore *kvs, unsigned long long cursor,
                               int onlydidx, dictScanFunction *scan_cb,
                               kvstoreScanShouldSkipDict *skip_cb,
                               void *privdata)
{
    unsigned long long _cursor = 0;
    /* During dictionary traversal, 48 upper bits in the cursor are used for positioning in the HT.
     * Following lower bits are used for the dict index number, ranging from 0 to 2^num_dicts_bits-1.
     * Dict index is always 0 at the start of iteration and can be incremented only if there are
     * multiple dicts. */
    int didx = getAndClearDictIndexFromCursor(kvs, &cursor);
    if (onlydidx >= 0) {
        if (didx < onlydidx) {
            /* Fast-forward to onlydidx. */
            assert(onlydidx < kvs->num_dicts);
            didx = onlydidx;
            cursor = 0;
        } else if (didx > onlydidx) {
            /* The cursor is already past onlydidx. */
            return 0;
        }
    }

    dict *d = kvstoreGetDict(kvs, didx);

    int skip = !d || (skip_cb && skip_cb(d, didx));
    if (!skip) {
        _cursor = dictScan(d, cursor, scan_cb, privdata);
        /* In dictScan, scan_cb may delete entries (e.g., in active expire case). */
        freeDictIfNeeded(kvs, didx);
    }
    /* scanning done for the current dictionary or if the scanning wasn't possible, move to the next dict index. */
    if (_cursor == 0 || skip) {
        if (onlydidx >= 0)
            return 0;
        didx = kvstoreGetNextNonEmptyDictIndex(kvs, didx);
    }
    if (didx == -1) {
        return 0;
    }
    addDictIndexToCursor(kvs, didx, &_cursor);
    return _cursor;
}

「48 位高位给哈希表定位,低位给 dict 索引」 ——
这正好解释了 kvstoreCreate() 里那个 num_dicts_bits <= 16 的断言。

两个辅助函数:

// src/kvstore.c:65-80
static void addDictIndexToCursor(kvstore *kvs, int didx, unsigned long long *cursor) {
    if (kvs->num_dicts == 1)
        return;
    /* didx can be -1 when iteration is over and there are no more dicts to visit. */
    if (didx < 0)
        return;
    *cursor = (*cursor << kvs->num_dicts_bits) | didx;
}

static int getAndClearDictIndexFromCursor(kvstore *kvs, unsigned long long *cursor) {
    if (kvs->num_dicts == 1)
        return 0;
    int didx = (int) (*cursor & (kvs->num_dicts-1));
    *cursor = *cursor >> kvs->num_dicts_bits;
    return didx;
}

单机模式下这两个函数都是空操作(num_dicts == 1 直接返回),
游标就是纯哈希表游标 —— 和 7.x 完全一致。

5.10 查一个 key 的完整链路

把前面的碎片拼起来。lookupKey() 是读路径的总入口:

// src/db.c:302-361
kvobj *lookupKey(redisDb *db, robj *key, int flags, dictEntryLink *link) {

    kvobj *val = dbFindByLink(db, key->ptr, link);

    if (val) {
        /* Forcing deletion of expired keys on a replica makes the replica
         * inconsistent with the master. We forbid it on readonly replicas, but
         * we have to allow it on writable replicas to make write commands
         * behave consistently.
         *
         * It's possible that the WRITE flag is set even during a readonly
         * command, since the command may trigger events that cause modules to
         * perform additional writes. */
        int is_ro_replica = server.masterhost && server.repl_slave_ro;
        int expire_flags = 0;
        if (flags & LOOKUP_WRITE && !is_ro_replica)
            expire_flags |= EXPIRE_FORCE_DELETE_EXPIRED;
        if (flags & LOOKUP_NOEXPIRE)
            expire_flags |= EXPIRE_AVOID_DELETE_EXPIRED;
        if (flags & LOOKUP_ACCESS_EXPIRED)
            expire_flags |= EXPIRE_ALLOW_ACCESS_EXPIRED;
        if (flags & LOOKUP_ACCESS_TRIMMED)
            expire_flags |= EXPIRE_ALLOW_ACCESS_TRIMMED;
        if (expireIfNeeded(db, key, val, expire_flags) != KEY_VALID) {
            /* The key is no longer valid. */
            val = NULL;
            if (link) *link = NULL;
        }
    }

    if (val) {
        /* Update the access time for the ageing algorithm.
         * Don't do it if we have a saving child, as this will trigger
         * a copy on write madness. */
        if (((flags & LOOKUP_NOTOUCH) == 0) &&
            (server.current_client && server.current_client->flags & CLIENT_NO_TOUCH) &&
            (server.executing_client && server.executing_client->cmd->proc != touchCommand))
            flags |= LOOKUP_NOTOUCH;
        if (!hasActiveChildProcess() && !(flags & LOOKUP_NOTOUCH)){
            if (server.maxmemory_policy & MAXMEMORY_FLAG_LFU) {
                updateLFU(val);
            } else if (!(server.maxmemory_policy & MAXMEMORY_FLAG_LRM)) {
                /* LRM policy should NOT update timestamp on reads. */
                val->lru = LRU_CLOCK();
            }
        }

        if (!(flags & (LOOKUP_NOSTATS | LOOKUP_WRITE)))
            server.stat_keyspace_hits++;
        /* TODO: Use separate hits stats for WRITE */
    } else {
        if (!(flags & (LOOKUP_NONOTIFY | LOOKUP_WRITE)))
            notifyKeyspaceEvent(NOTIFY_KEY_MISS, "keymiss", key, db->id);
        if (!(flags & (LOOKUP_NOSTATS | LOOKUP_WRITE)))
            server.stat_keyspace_misses++;
        /* TODO: Use separate misses stats and notify event for WRITE */
    }

    return val;
}

「查一个 key」的完整调用栈:

lookupKey(db, key, flags, link)            src/db.c:302
  └─ dbFindByLink(db, key, link)           src/db.c:3261
       ├─ getKeySlot(key)                  src/db.c:501   ← 算槽位
       └─ kvstoreDictFindLink(db->keys, slot, key, &bucket)   src/kvstore.c:870
            └─ dictFindLink(d, key, bucket)                   src/dict.c:1312
                 └─ dictFindLinkInternal(...)                 src/dict.c:1214
                      ├─ _dictRehashStepIfNeeded(...)          ← 顺手走一步 rehash
                      └─ findBucketForKey(...)                 src/dict.c:590
                           └─ bucketFindKey(...)               src/dict.c:574

几个值得注意的点:

一、lookupKey 会顺手做过期检查。
expireIfNeeded() 在 src/db.c:3135(不在 src/expire.c)。
第 08 章会详细讲这个函数。

二、lookupKey 会顺手更新 LRU/LFU。
val->lru = LRU_CLOCK()。但有子进程时不做 ——
注释说「否则会引发 copy-on-write 疯狂」。这是 Redis 的老规矩。

三、dbFindByLink 返回的 link 有两种含义:

// src/db.c:3255-3273
/* Find a KV in the main db. Return also link to it.
 *
 * plink - If found, set to the link of the key in the dict.
 *         If not found, set to the bucket where the key should be added.
 *         If set to NULL, then HT of dict not allocated yet.
 */
kvobj *dbFindByLink(redisDb *db, sds key, dictEntryLink *plink) {
    int slot = getKeySlot(key);
    dictEntryLink link, bucket;

    link = kvstoreDictFindLink(db->keys, slot, key, &bucket);
    if (link == NULL) {
        if (plink) *plink = bucket;
        return NULL;
    } else {
        if (plink) *plink = link;
        return dictGetKV(*link);
    }
}

找到了 → 返回条目的位置;没找到 → 返回「应该插进去的那个桶」。
这样查找和插入可以共用一次哈希计算。这是这套新 API 的核心设计 ——
dictFindLink() 返回的是桶槽位的地址(dictEntryLink)而不是条目本身。

dictFindLink() 的文档把「link 什么时候会失效」讲得非常重要:

// src/dict.c:1275-1318
/* Find a key and return its dictEntryLink reference. Otherwise, return NULL
 * 
 * A dictEntryLink is the address of the bucket slot that holds the entry of the
 * searched item. It is Useful for deletion, addition, unlinking and updating,
 * especially for dict configured with 'no_value'. In such cases returning only
 * `dictEntry` from a lookup may be insufficient since it might be opt-out to be
 * the object itself. By locating the slot (dictEntryLink) these ops can be
 * properly handled.
 *
 * A link is valid only until the dict is modified: an insert into the same
 * bucket chain (a full bucket moves its last entry to a child bucket), a delete
 * that compacts the chain, a rehash step (that lookups do too) and a resize
 * can invalidate it. dictPauseRehashing() keeps it valid across lookups and
 * deletes of other keys in the same dict, but not across inserts.
 * 
 * After calling link = dictFindLink(...), any necessary updates based on returned 
 * link or bucket must be performed immediately after by calling dictSetKeyAtLink() 
 * without any intervening operations on given dict. Otherwise, `dictEntryLink` may 
 * become invalid. Plain lookups count too: they may run a rehash step that moves
 * entries (e.g. keyspace notifications running module callbacks).
 * Example with kvobj of replacing key with new key:
 * 
 *      link = dictFindLink(d, key, &bucket);
 *      ... Do something, but don't modify the dict ...
 *      // assert(link != NULL);
 *      dictSetKeyAtLink(d, kv, &link, 0);
 *      
 * To add new value (dictSetKeyAtLink() expands the dict if there is no space
 * for the new key, and looks up the insert position again):
 *   
 *      link = dictFindLink(d, key, &bucket);
 *      ... Do something, but don't modify the dict ...
 *      // assert(link == NULL);
 *      dictSetKeyAtLink(d, kv, &bucket, 1);
 *  
 *  bucket - return link to bucket that the key was mapped. unless dict is empty.
 */
dictEntryLink dictFindLink(dict *d, const void *key, dictEntryLink *bucket) {
    if (bucket) *bucket = NULL;
    if (unlikely(dictSize(d) == 0))
        return NULL;
    
    return dictFindLinkInternal(d, key, dictGetHash(d, key), bucket);
}

「连普通的查找都会让 link 失效」 ——
因为查找本身可能触发一步 rehash,把条目搬走了。
这是新 dict 设计里最容易踩的坑,注释里明确要求:
拿到 link 之后必须立刻用,中间不能插任何操作。

dbRefreshLink() 就是为这个坑准备的补丁:

// src/db.c:585-602
/* Keep `*plink` if it still points at `kv`, otherwise look the key up again and
 * update `*plink`. The key must exist. Use before reusing a link after code that
 * may look up keys (KSN, module hooks): a lookup may run a rehash step that
 * moves entries (see dictFindLink()).
 *
 * `kv` is compared by address only and may already be freed (e.g. a module
 * hook replaced the value), so the key is passed separately.
 *
 * The check reads through the old link, so it assumes that code didn't free
 * what the link points into: it must not add or delete keys, and no rehash
 * may complete in between (completing a rehash frees the old table). */
void dbRefreshLink(redisDb *db, sds key, dictEntryLink *plink, kvobj *kv) {
    dictEntryLink link = *plink;
    if (link && *link && dictGetKV(*link) == kv) return;
    link = kvstoreDictFindLink(db->keys, getKeySlot(key), key, NULL);
    serverAssert(link != NULL);
    *plink = link;
}

5.11 过期:TTL 搬进了对象里

值得单独提一句,因为这棵树把过期时间从独立的 expires 表搬进了 kvobj 的元数据位。

7.x 的做法:db->expires 是一个 dict *,键是 key 的 sds,值是过期时间戳。
同一个 key 存了两遍(一遍在 db->dict 存值,一遍在 db->expires 存时间)。

这棵树的做法:

  • db->expires 仍然存在(是个 kvstore *),但它存的是 kvobj 指针,不是时间戳;
  • 真正的过期时间存在 kvobj 的元数据槽 0 里。

getExpire() 一眼就能看出:

// src/db.c:2960-2969
/* Retrieve the expiration time for the specified key.
 * Returns -1 if the key has no expiration set or doesn't exists
 *
 * To avoid lookup, pass key-value object (`kv`) instead of `key`.
 */
long long getExpire(redisDb *db, sds key, kvobj *kv) {
    if (kv == NULL) kv = dbFindExpires(db, key);
    if (kv == NULL) return -1;
    return kvobjGetExpire(kv);
}

从 expires 表里取出来的就是 kvobj 本身,
时间戳从 kvobjGetExpire(kv) 里读 —— 也就是从对象的元数据位读的。

元数据框架在 src/keymeta.h:

// src/keymeta.h:49-60
/* kvmeta - Metadata to be attached to kvobj */
#define KEY_META_ID_EXPIRE        0 /* Must be first */
/* IDs 1..7 are available for modules */
#define KEY_META_ID_MODULE_FIRST  1
#define KEY_META_ID_MODULE_LAST   7
#define KEY_META_ID_MAX           8

#define KEY_META_MAX_NUM_MODULES  (KEY_META_ID_MODULE_LAST - KEY_META_ID_MODULE_FIRST + 1)

#define KEY_META_MASK_NONE        0
#define KEY_META_MASK_MODULES     (((1U << KEY_META_MAX_NUM_MODULES) - 1) << KEY_META_ID_MODULE_FIRST)
#define KEY_META_MASK_EXPIRE      (1U << KEY_META_ID_EXPIRE)

8 个元数据类,类 0 固定给过期时间,类 1..7 留给模块。
每个 key 最多带 8 个 8 字节的元数据值。

这个设计的意义:模块可以在自己的 key 上挂自定义元数据,
而内核不需要知道那些元数据是什么。
这是这棵树扩展机制的一部分
(第 15 章会讲模块系统)。

内存布局在 src/object.h 的头注释里画得很清楚:

// src/object.h:45-57
 * kvobj with metadata (+expiration)
 * ---------------------------------
 * Up to 8 metadata classes are supported, each storing one 8-byte field.
 * Class 0 is reserved for expiration time. Metadata blocks are placed before
 * the kvobj itself, in reverse class order.
 * 
 * Example of a key with expiration time (metabits=0b00000001):
 *     +--------------+--------------+----------+--------------------+
 *     | Expiry Time  | serverObject | kvbits   | sdshdr5 "mykey" \0 |
 *     | 8 byte       | 16 bytes     | 1 byte   | 1      +   5   + 1 |
 *     +--------------+--------------+----------+--------------------+
 *                    ^
 *                    +---- kvobjCreate() returns pointer here

元数据块放在 kvobj 之前,所以 kvobjCreate() 返回的指针指向中间的
serverObject —— 往回走就能找到元数据。metabits 这个 8 位掩码
(在 struct redisObject 里)记录「哪些元数据类有值」。

5.12 与网文 / 7.x 的差异

位置 教科书(7.x) 这棵树(unstable) 出处
键空间容器 redisDb->dict 是 dict * kvstore *,底下是 dict 数组 src/server.h:1270
过期表 redisDb->expires 是 dict *,键 sds → 时间戳 kvstore *,存 kvobj 指针,时间戳在 kvobj 元数据里 src/server.h:1271、src/db.c:2965
非集群的 dict 数 1 1(slot_count_bits = 0) src/server.c:3180
集群的 dict 数 1 个大 dict + 槽位标记 16384 个 dict,按槽位切 src/server.c:3182
哈希桶 dictEntry **buckets,冲突挂 entry 链表 64 字节 bucket,7 个槽位,冲突挂子桶 src/dict.c:235-240
桶的元数据 无 presence 位图 + hashes[] 高 8 位 tag src/dict.c:217-240
条目分配 每个 entry 都 zmalloc 一个 dictEntry no_value=1 时直接存 key 指针,省掉 dictEntry src/dict.c:1011-1015
键值关系 key 是 sds,value 是 robj * 统一成 kvobj,键值合一 src/server.c:643
查找返回值 dictEntry * dictEntryLink(桶槽位地址) src/dict.c:1312
随机取 key 按桶随机 先按 key 数加权抽 dict,再在 dict 里抽 src/kvstore.c:413
SCAN 游标 16 位反转游标 64 位:48 位表内定位 + 16 位 dict 索引 src/kvstore.c:333-336
key 元数据 只有 expires 表 8 个元数据类,类 0 给 TTL,1..7 给模块 src/keymeta.h:49-54
不可淘汰标记 无 blessed_keys 索引 + kvobj 的 no_evict 位 src/bless.c:99-110
预取 无 prefetchEntryValue 钩子 + memory_prefetch.c src/server.c:591

5.13 本章要点回顾

关键要点

  1. redisDb->keys 是 kvstore * 不是 dict *(src/server.h:1270)。kvstore 是一组按「dict 索引」切分的 dict 数组(src/kvstore.h:12-23)。
  2. dict 的个数由 num_dicts_bits 决定:非集群 1 个,集群 16384 个(src/server.c:3179-3184)。非集群下 getKeySlot() 恒返回 0(src/db.c:502)。
  3. kvstore 的两个 flag:KVSTORE_ALLOCATE_DICTS_ON_DEMAND(用到才建 dict)、KVSTORE_FREE_EMPTY_DICTS(空了释放)(src/kvstore.h:87-88)。
  4. kvstoreCreate 断言 num_dicts_bits <= 16 —— 因为要给 SCAN 游标留 48 位(src/kvstore.c:197-199)。
  5. kvstore 强制接管四个 dictType 回调(userdata/dictMetadataBytes/rehashingStarted/rehashingCompleted),并断言调用方没设(src/kvstore.c:213-224)。
  6. 新的 dict 是 64 字节 bucket 链:64 位机每桶 7 槽位、32 位机 12 槽位(src/dict.h:216-228)。桶满了把最后一个槽位改成子桶指针。
  7. 桶内存了哈希的高 8 位(hashes[]),查找时先用它过滤掉绝大多数不匹配项,连指针都不解引用(src/dict.c:217-224、src/dict.c:409-415)。
  8. no_value=1 时桶槽位直接存 key 指针,省掉 dictEntry 分配;主键空间就是这么干的(src/dict.c:1011-1015、src/server.c:643)。
  9. 指针标记用低 3 位区分三种东西:000 是 dictEntry 指针、XX1 是奇地址 key、010 是偶地址 key(src/dict.h:29-40)。所以 zmalloc 必须 8 字节对齐。
  10. kvobj 和 robj 是同一个结构体的两个 typedef(src/object.h:104-122);键和值、TTL 元数据、LRU 全部合一。
  11. keyFromStoredKey = kvGetKey 补上「存的是 kvobj、查的是 sds」的落差(src/server.c:645、src/server.c:335-338)。
  12. 树状数组(src/fwtree.c)记的是各 dict 的累计 key 数,用来做「按 key 数加权抽 dict」的公平随机(src/kvstore.c:413-445);单机模式下树状数组不创建(src/kvstore.c:238)。
  13. SCAN 游标是 64 位:48 位高位给哈希表定位,低位给 dict 索引(src/kvstore.c:333-336)。
  14. 新的 dict API 返回 dictEntryLink(桶槽位地址)而不是 dictEntry,因为 no_value 时槽位里存的就是对象本身(src/dict.c:1275-1294)。
  15. 拿到 link 后必须立刻用 —— 连普通查找都可能触发一步 rehash 让 link 失效(src/dict.c:1284-1288)。dbRefreshLink() 是补救(src/db.c:596-602)。
  16. 过期时间搬进了 kvobj 的元数据:类 0 固定给 TTL,类 1..7 留给模块(src/keymeta.h:49-54)。db->expires 现在存的是 kvobj 指针而不是时间戳(src/db.c:2965-2969)。
  17. expireIfNeeded 在 src/db.c:3135,不在 src/expire.c(那里是主动过期周期)。
  18. blessed_keys 是新加的 kvstore,索引被标记为不可淘汰的 key(src/server.h:1272、src/bless.c:99-110)。

5.14 接下来

下一篇 06 紧凑编码与编码转换 往下一层走。

本文讲的是键空间怎么组织:一个 key 落在哪个桶、桶里装什么。
下一篇讲值本身怎么装:同一个 hash 在小的时候是 listpack,
长大了会换成哈希表;zset 从 listpack 升到 skiplist 再升到 B+ tree;
这些「形态」叫 encoding,转换的阈值写在配置项里、由某个函数检查。

对完这两章,一个 key 从「在哪」到「长什么样」就都清楚了。
再往后是命令怎么找到它(07、08 章)。

引用

本文涉及的结构体、宏与函数,均取自 Redis 源码
(/work/ai/cwork/redis,分支 unstable,
git describe --tags = 8.12-m02-int-184-gff28c55fc,HEAD = ff28c55f,
核对时间:2026-12-04):

事实 出处
redisDb 的字段布局(三个 kvstore + 五个 dict) src/server.h:1269-1285
kvstore 的定位:dict 数组,按 dict 索引切分 src/kvstore.h:12-23
struct _kvstore 的全部字段 src/kvstore.c:28-44
kvstore 的两个 flag src/kvstore.h:87-88
kvstoreCreate() 全文 src/kvstore.c:196-242
kvstore 强制接管四个 dictType 回调 src/kvstore.c:213-224
dict_sizes 只在多 dict 时创建 src/kvstore.c:238
cumulativeKeyCountAdd() 与树状数组更新 src/kvstore.c:82-99
fwTreeUpdate() 的树状数组步进与不变式断言 src/fwtree.c:58-74
kvstoreFindDictIndexByKeyIndex() 与其示例图 src/kvstore.c:496-519
kvstoreGetFairRandomDictIndex() 的公平随机算法 src/kvstore.c:395-445
kvstoreScan() 的游标拆分 src/kvstore.c:327-369
游标的两个辅助函数 src/kvstore.c:65-80
kvstoreDictSetAtLink() 与按需建 dict src/kvstore.c:877-900
kvstoreDictFindLink() src/kvstore.c:870-875
各 db 的 kvstore/dict 创建(槽位数与 flags) src/server.c:3179-3199
dbDictType(no_value + keyFromStoredKey + 预取钩子) src/server.c:634-647
dbDictPrefetchEntryValue() src/server.c:585-595
kvGetKey() 与 dictSdsCompareKV() src/server.c:335-352
getKeySlot() 的槽位复用优化 src/db.c:501-517
dbAddInternal() 的写入路径 src/db.c:440-470
dbFindByLink() 的 link 两种语义 src/db.c:3255-3273
lookupKey() 的过期检查、LRU 更新与命中统计 src/db.c:302-361
dbRefreshLink() src/db.c:585-602
getExpire() 从 kvobj 元数据读时间戳 src/db.c:2960-2969
expireIfNeeded() 的位置与四种返回值 src/db.c:3135
struct dict 的字段 src/dict.h:160-180
指针标记的三种编码与 8 字节对齐要求 src/dict.h:16-40
bucket 尺寸常量(64 字节 / 7 或 12 槽位) src/dict.h:216-228
dictSize / dictBuckets 等宏 src/dict.h:244-253
struct dictBucket 的字段与 static_assert src/dict.c:217-242
hashTag() 取哈希高 8 位 src/dict.c:357-361
桶链相关的内联函数 src/dict.c:363-393
findHashMatches() 的高位过滤 src/dict.c:409-415
bucketFindKey() 的候选位筛选 src/dict.c:572-585
findBucketForKey() 的双表查找 src/dict.c:587-616
dictInsertKey() 的 no_value 快路径 src/dict.c:1003-1031
dictFindLink() 文档:link 的失效条件 src/dict.c:1275-1318
ENTRY_PTR_* 标记常量与判定函数 src/dict.c:306-327
dictExpandIfNeeded() 的扩容阈值 src/dict.c:2279-2306
dictShrinkIfNeeded() 的缩容阈值 src/dict.c:2319-2342
struct redisObject 与 robj/kvobj 别名 src/object.h:104-122
kvobj 的内存布局与元数据位置 src/object.h:45-57
kvBits 的字段(no_evict 等) src/object.h:126-132
kvobjGetExpire() src/object.c:263-269
kvobjSetExpire() src/object.c:271-287
keymeta 的 8 个元数据类与掩码 src/keymeta.h:49-60
keymeta 的整体设计说明 src/keymeta.h:1-29
blessIsNoEvict() / blessSetNoEvict() src/bless.c:99-110
blessedKvstoreCreate() src/bless.c:71-75
槽位总数 16384 的定义 src/cluster.h:22-24

文章作者: growdu
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 growdu !
  目录