Duo Li

Systems Engineering

B+Tree + mmap + bitmap + offset:内存映射索引架构

一种用 mmap 直接承载 B+Tree 索引文件的架构:父节点存的是文件偏移量而不是内存指针,虚拟地址 = mmap_base + file_offset,省去反序列化;配合一个 Byte Map(空闲页分配位图)可以 O(1) 找到一个空闲页分配出去——它标记的是页是否空闲,不是页里有没有某个 key。

1. 核心思想:父节点存的是文件偏移量,不是指针

普通的内存里的 B+Tree,父节点里存的是子节点的内存指针(Node* child);这种架构反过来:父节点里存的是子节点在文件里的偏移量(offset_t child_offset),而不是内存指针。整个索引文件通过 mmap 一次性映射进虚拟地址空间之后,任何一个文件偏移量都可以直接转换成虚拟地址,不需要读文件、不需要反序列化、不需要单独维护一份内存中的树结构:

virtual_address = mmap_base + file_offset
void* mmap_base = mmap(NULL, file_size,
    PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

// 用文件偏移量直接换算出虚拟地址,是整个架构最核心的一行代码
Node* get_node(offset_t file_offset) {
    return (Node*)(mmap_base + file_offset);
}

// 父节点存的 child_offset 本身就是一个文件偏移量,可以直接喂给 get_node
Node* get_child(Node* parent, int idx) {
    offset_t child_offset = parent->child_offsets[idx];
    return get_node(child_offset);
}

char* get_data(offset_t data_offset) {
    return (char*)(mmap_base + data_offset);
}

这样设计的好处是文件里的字节布局就是内存里的字节布局——磁盘上第 0x1000 字节处的节点,一旦被 mmap,在虚拟内存里就是 mmap_base + 0x1000 这个地址,两者说的是同一份数据,不需要"加载时转换成另一种内存表示"这一步。这也是为什么这类结构常被称为 zero-copy:文件内容本身就是可以直接使用的内存结构。

2. 可视化:B+Tree 逻辑结构 + Byte Map / 虚拟内存 / 文件布局四栏对照

早先发布的版本用的是一份措辞不准确的草稿(把 bitmap 描述成 key 存在性索引),下面换成了修正稿(Mmap with bytemap architecture.html)的忠实复刻:bitmap 被正确地设计成 Byte Map(空闲页分配位图),"key 是否存在"的概率型检查被拆成一个明确标注为 Optional、仅存在于内存的 Bloom Filter。上半部分是 B+Tree 逻辑结构,下半部分按四栏分别展示 Byte Map、虚拟内存、映射与操作流程、文件布局四个视角。

🌳 Complete B+ Tree Memory-Mapped Architecture with Byte Map Indexing

ARCHITECTURE OVERVIEW: Memory-mapped B+ Tree with byte map space management, direct file offset navigation, and separated data storage for optimal I/O performance. The byte map occupies the initial 16KB of the main index file.

🌳 B+ TREE LOGICAL STRUCTURE
ROOT
[10, 20]
@0x1000
⬇️ ⬇️ ⬇️
INTERNAL
[5]
@0x2000
INTERNAL
[15]
@0x3000
INTERNAL
[25]
@0x4000
⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️
LEAF
[1,3,4]
@0x5000
LEAF
[6,7,8]
@0x6000
LEAF
[12,13,14]
@0x7000
LEAF
[16,17,18]
@0x8000
LEAF
[22,23,24]
@0x9000
LEAF
[26,27,28]
@0xA000
⬇️ DATA RECORDS ⬇️
Key=1
@0x10000
"John Doe"
Key=3
@0x10100
"Jane Smith"
Key=4
@0x10200
"Bob Wilson"
Key=6
@0x10300
"Alice Brown"
Key=7
@0x10400
"Charlie Davis"
...
More Records
"..."
🎯 BYTE MAP INDEXING

Purpose: Free space management for 4KB pages. Occupies initial 16KB of the file.
It's a byte map with a header, followed by a byte array.

file_start = 0x0000

Free Space Byte Map (16KB)
Tracks allocated/free 4KB pages within the file.
array[0] refers to offset 16k (0x4000), array[1] to 16k + 4k (0x5000), etc.

0x00 0x00 0x01 0x01 ...
Each byte represents allocation status for a block of pages.
Conceptual Page Allocation (from Byte Map)

Page at 0x1000 (conceptual) is allocated (Root)
Page at 0x2000 (conceptual) is allocated (Internal)
Page at 0x3000 (conceptual) is allocated (Internal)
Page at 0x4000 (conceptual) is allocated (Internal)
Page at 0x5000 (conceptual) is allocated (Leaf)
Page at 0x6000 (conceptual) is allocated (Leaf)
Page at 0x7000 (conceptual) is free
Page at 0x8000 (conceptual) is free

// Byte map is part of the mmap'd file
// It occupies the first 16KB (0x0000-0x3FFF)
typedef struct {
  uint8_t* byte_map_array; // Starts after bitmap header
  uint32_t total_pages;
  uint32_t free_pages;
} ByteMapManager;


// Fast allocation based on 4KB pages
offset_t alloc_page(ByteMapManager* bm) {
  // Find first free byte/index in the byte_map_array
  int free_idx = find_first_free_byte(bm->byte_map_array);
  set_byte_allocated(bm->byte_map_array, free_idx);
  // Convert index to file offset: conceptual_btree_start_offset + free_idx * 4KB
  return 0x4000 + (offset_t)free_idx * 4096;
}

Bloom Filter (Optional)

Key Existence Check
Size: 1024 bits
Hash functions: 3

00100101 11000010 01010100
Quick "key might exist" check (in-memory)

BYTE MAP BENEFITS:
• O(1) free page lookup
• Reduced fragmentation
• Direct mapping within file
• OS page cache optimization for bitmap access

Persistence:
The byte map is part of the main btree.db file and is persisted with it through the OS's memory-mapping mechanisms.

🧠 VIRTUAL MEMORY (mmap)
mmap_base = 0x7f8000000000

void* mmap_base = mmap(NULL, file_size,
    PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);

0x7f8000001000 = base + 0x1000

ROOT NODE
Keys: [10, 20]
Child Offsets: 0x2000 0x3000 0x4000

0x7f8000002000 = base + 0x2000

INTERNAL NODE
Keys: [5]
Child Offsets: 0x5000 0x6000

0x7f8000003000 = base + 0x3000

INTERNAL NODE
Keys: [15]
Child Offsets: 0x7000 0x8000

0x7f8000004000 = base + 0x4000

INTERNAL NODE
Keys: [25]
Child Offsets: 0x9000 0xA000

0x7f8000005000 = base + 0x5000

LEAF NODE
Keys: [1, 3, 4]
Data Pointers: 0x10000 0x10100 0x10200
Next: 0x6000

0x7f8000006000 = base + 0x6000

LEAF NODE
Keys: [6, 7, 8]
Data Pointers: 0x10300 0x10400 0x10500
Next: 0x7000

LEAF DATA SECTION

0x7f8000010000: "John Doe, Age 25"
0x7f8000010100: "Jane Smith, Age 30"
0x7f8000010200: "Bob Wilson, Age 28"
0x7f8000010300: "Alice Brown, Age 32"
0x7f8000010400: "Charlie Davis, Age 29"

// Direct pointer arithmetic navigation using file offsets
Node* get_node(offset_t file_offset) {
  return (Node*)(mmap_base + file_offset);
}


Node* get_child(Node* parent, int idx) {
  offset_t child_offset = parent->child_offsets[idx];
  return get_node(child_offset);
}


char* get_data(offset_t data_offset) {
  return (char*)(mmap_base + data_offset);
}

🔄 MAPPING & OPERATIONS
⬅️ BYTE MAP MANAGEMENT ➡️

The byte map is memory-mapped as part of the main btree.db file (first 16KB), allowing direct access via mmap_base + offset.

⬅️ DIRECT MAPPING ➡️

Virtual Address = mmap_base + file_offset
No translation needed! All B+ tree nodes and data are accessed via this direct mapping.

Search Operation Flow
  1. Bloom Filter Check:
    hash(key) → bloom_filter

  2. Root Navigation:
    root = mmap_base + ROOT_OFFSET (e.g., 0x1000 as depicted)

  3. Tree Traversal:
    child_offset = node->child_offsets[idx]
    child = mmap_base + child_offset

  4. Data Access:
    data_offset = leaf->data_offsets[j]
    data = mmap_base + data_offset

// Complete search operation
SearchResult search(int key) {
  // 1. Quick bloom filter check
  if (!bloom_might_contain(&bloom, key)) {
    return NOT_FOUND;
  }


  // 2. Navigate from root (adjusting for conceptual start of nodes)
  // Assuming ROOT_OFFSET points to the depicted 0x1000
  Node* node = get_node(ROOT_OFFSET);


  // 3. Tree traversal
  while (node->type == INTERNAL) {
    int idx = binary_search(node->keys, key);
    offset_t child_offset = node->child_offsets[idx];
    node = get_node(child_offset);
  }


  // 4. Leaf search
  int idx = binary_search(node->keys, key);
  if (node->keys[idx] == key) {
    offset_t data_offset = node->data_offsets[idx];
    char* data = get_data(data_offset);
    return SUCCESS(data);
  }


  return NOT_FOUND;
}

Insert Operation Flow
  1. Find free page:
    Find free index in byte_map_array

  2. Allocate space:
    Set byte in map to allocated

  3. Calculate new offset:
    new_offset = conceptual_btree_start_offset + index * 4KB

  4. Update bloom filter:
    bloom_add(&bloom, key)

PERFORMANCE BENEFITS:
• Zero-copy file loading via mmap
• OS page cache optimization
• Direct pointer arithmetic for node/data access
• Efficient in-file byte map space management
• Fast existence checks with Bloom filter

Memory Layout Strategy

Separated Storage within btree.db:
• Byte Map: Initial 16KB of the file
• Tree nodes: Follow after the byte map
• Leaf data: Located at the end of the file
• Bloom filter: In-memory only

💾 FILE LAYOUT (Persistent)

btree.db: The main B+ tree index file, including the byte map.
Total index file size: 128KB.

File Offset: 0x0000 (0 bytes)

FILE HEADER
Magic: 0xB7EE, Version: 1
File Size: 128KB
Root Offset: 0x1000 (as depicted in tree)

File Offset: 0x0000 - 0x3FFF (First 16KB)

BYTE MAP ARRAY & HEADER
Used for tracking 4KB page allocation status. array[i] maps to a page at 16k + i*4k.

File Offset: 0x1000 (4096 bytes)

ROOT NODE (Conceptual B+ Tree Nodes Start)
The B+ tree nodes section effectively begins here for addressing as shown in the tree structure, following the initial 16KB byte map.

File Offset: 0x2000
INTERNAL NODE
...
File Offset: 0x3000
INTERNAL NODE
...
File Offset: 0x4000
INTERNAL NODE
...
File Offset: 0x5000
LEAF NODE
...
File Offset: 0x6000
LEAF NODE
...
File Offset: 0x10000 (65536 bytes)

LEAF DATA SECTION
Actual data records stored here.

// File structure on disk (conceptual overview given diagram offsets):
// 0x0000-0x3FFF: File header & 16KB Byte Map for page allocation
// 0x4000: Conceptual B-tree header / first B-tree data block
// (However, nodes in this diagram start addressing from 0x1000)
// 0x1000-0xFFFF: All B+ tree nodes (as depicted)
// 0x10000+: Leaf data records


struct FileLayout {
  FileHeader header; // @0x0000
  uint8_t byte_map[16*1024]; // @0x0000-0x3FFF, including its header
  BTreeNode nodes[]; // Conceptual start after byte map (e.g., 0x4000)
  DataRecord leaf_data[]; // @0x10000+
};

以上是修正稿(Mmap with bytemap architecture.html)的忠实复刻——配色、分栏结构、每个 offset 数值都与原稿一致,只是从独立 HTML 文件迁移成了页面内嵌的组件。下面几节是在这份素材基础上重新组织的文字讲解,两者互补:这一节负责"一眼看全貌",下面负责"讲清楚为什么"。

3. 逻辑结构:一棵具体的 B+Tree(补充范围扫描链表视角)

上面的图已经完整展示了 B+Tree 结构和 Byte Map/虚拟内存/文件布局的对照,这里再补一张更紧凑的版本,专门标出上面没画的两处细节:叶子节点之间从左到右的链表(图中的水平虚线箭头,范围扫描时不需要回到上层节点就能顺序读取下一个叶子)、以及每个叶子页和下方 Byte Map 里对应 bit 的逻辑关联(虚线)——位图里的一个 bit 对应文件里的一个页,标记的是这个页当前是不是空闲,不是这个页里有没有某个 key:

next-leaf 链表(范围扫描用)ROOT[10, 20] @0x1000INTERNAL[5] @0x2000INTERNAL[15] @0x3000INTERNAL[25] @0x4000LEAF[1,3,4]@0x5000LEAF[6,7,8]@0x6000LEAF[12,13,14]@0x7000LEAF[16,17,18]@0x8000LEAF[22,23,24]@0x9000LEAF[26,27,28]@0xA000BYTE MAP @0x200001 bit / 页,1 = 已分配(非空闲)

这棵树的路由关系是自洽的:root 的 key [10, 20] 把空间切成三段(<10、[10,20)、≥20),对应三个 internal 子节点;每个 internal 节点的单个 key 又把自己负责的区间再切成两半,对应两个叶子——例如最左边的 internal 节点 key 是 5,两个叶子分别是 [1,3,4](都 <5)和 [6,7,8](都在 [5,10)),完全对得上。

4. Byte Map:空闲页分配位图,不是"某页有没有 key"的存在性索引

这里的位图更准确的名字应该是 Byte Map——它对应的是常见存储引擎里"溢出块/空闲块分配器"的位图:核心操作是"O(1) 找一个空闲块分配出去、用完了再归还",从来不回答"这一页里有没有某个 key":

uint64_t* byte_map = (uint64_t*)(mmap_base + 0x20000);

// 分配:找到第一个空闲页(bit == 0),标记成已分配(bit = 1)
int alloc_page() {
    for (int page_id = 0; page_id < total_pages; page_id++) {
        if (!(byte_map[page_id / 64] & (1ULL << (page_id % 64)))) {
            byte_map[page_id / 64] |= (1ULL << (page_id % 64));
            return page_id;
        }
    }
    return -1; // 没有空闲页了
}

// 释放:把对应 bit 清零,归还给分配器
void free_page(int page_id) {
    byte_map[page_id / 64] &= ~(1ULL << (page_id % 64));
}
  • 每个 bit 对应文件里的一个页(block):bit == 1 表示这个页已经被分配出去在用,bit == 0 表示这个页是空闲的,可以被下一次 alloc_page() 拿走。
  • 用途是给"分配器"用的,不是给"查找"用的:正常按 key 查找 B+Tree,走的还是 root → internal → leaf 这条标准路径;Byte Map 只在"需要一块新页(比如叶子分裂、插入新叶子)"或者"一块页被删除、需要归还"的时候才会被访问,和查找路径完全无关。
  • 随主文件一起 mmap、一起持久化:Byte Map 本身就是索引文件的一段字节,进程重启后不需要重新扫描整棵树来重建分配状态。

可选:Bloom Filter(仅内存,这个架构目前没有这个结构)

如果确实需要"这个 key 一定不存在,可以跳过整页"这种能力,需要的是一个概率型的 Bloom Filter,这是和 Byte Map 完全独立的另一个结构:

  • Bloom Filter 允许假阳性(说"可能存在"其实不存在),换来极小的内存占用,适合放在内存里做快速预筛;
  • 它和 Byte Map 的关键区别:Byte Map 记录的是"页的分配状态"(精确、随文件持久化),Bloom Filter 记录的是"key 的存在性猜测"(概率型、通常只在内存里,不需要持久化);
  • 这个架构目前的设计里没有 Bloom Filter——上面这一段是作为"如果要做这类查找优化,应该长什么样"的补充说明,标注为 Optional,避免把它误当成已经存在的机制。

5. Byte Map 本身也活在同一个 mmap 区域里

这个架构的另一个关键点是:Byte Map 不是一个独立于文件之外的、只在内存里维护的结构,它就是同一个索引文件里的一段字节,同样通过 mmap_base + offset 访问:

virtual_addr = mmap_base + 0x20000 = Byte Map 在这次进程里的实际地址

这意味着 Byte Map 的更新(比如某个页被分配或者释放)会通过 mmap 的写回机制自动持久化到磁盘上,不需要额外写一份"位图快照"文件,也不需要在进程重启后重新扫描整棵树来重建分配状态——Byte Map 和树节点、叶子数据享有完全相同的持久化路径。

6. 文件布局:三段互不重叠的区域

整个索引文件在磁盘上按偏移量分成三段互不重叠的区域——这一点必须精确,如果某一段的边界估算错误,两段数据会在同一个偏移量上"打架":

文件偏移范围内容
0x0000 – 0x0FFF文件头(magic、version、root 偏移量、节点数、data 起始偏移量等元信息)
0x1000 – 0xFFFF所有 B+Tree 节点(root、internal、leaf,每个节点固定占用一个 4KB 页)
0x10000 起叶子数据记录(真正的 value,比如 "John Doe, Age 25" 这样的字符串)
0x20000 起Byte Map(空闲页分配位图)
struct FileLayout {
    FileHeader header;       // @0x0000
    BTreeNode  nodes[];      // @0x1000+
    DataRecord leaf_data[];  // @0x10000+
    ByteMap    byte_map;     // @0x20000+ 空闲页分配位图
};

这三段之间没有重叠,是这个设计能够正确工作的前提——任何一个偏移量在任意时刻只能属于其中一段。

7. 虚拟内存地址与文件偏移量的对应关系

下面是几个关键节点在"文件偏移量"和"这次进程里实际虚拟地址"两个维度下的对照,mmap_base 假设是 0x7f8000000000:

内容文件偏移量这次运行时的虚拟地址(mmap_base + offset)
Root 节点0x10000x7f8000001000
Internal 节点 [5]0x20000x7f8000002000
Leaf 节点 [1,3,4]0x50000x7f8000005000
Key=1 的数据记录0x100000x7f8000010000
Byte Map(空闲页位图)0x200000x7f8000020000

右边这一列每次进程重新 mmap 同一个文件时都可能不同(mmap_base 由操作系统决定,不保证固定),但左边的文件偏移量永远不变——这正是为什么父节点必须存偏移量而不是指针:指针只在当前进程、当前这次 mmap 有效,偏移量在文件的生命周期里永远有效。

8. 查找的过程:标准 B+Tree 下降,只是每一步都换算成 mmap 地址

查找某个 key 的过程和普通 B+Tree 完全一样——从 root 开始,在当前节点的 key 数组里做二分查找,找到 key 所在的区间,取出对应的 child_offset,用 get_node(child_offset) 换算成当前进程里的虚拟地址,重复这个过程直到走到叶子节点,再在叶子节点内部查找目标 key。这个架构相对于"内存指针版" B+Tree 唯一的区别是:每次"走到子节点"这一步,做的不是普通的指针解引用,而是"偏移量 + mmap_base 的加法"——两者在 CPU 层面几乎一样便宜,但换来的是整棵树可以直接以文件的形式持久化,进程重启后不需要重新构建,mmap 一下就能立刻在原来的偏移量上继续工作。

9. 架构收益小结

  • Zero-Copy Loading:mmap() 直接把文件映射进内存,没有"读取字节流 → 反序列化成对象"这一步,加载一个几十 MB 甚至几 GB 的索引文件的成本接近于零。
  • 偏移量可移植:文件偏移量在任何一次 mmap、任何一台机器上都表示同一份逻辑数据,不像内存指针那样只在当前进程这一次运行里有意义。
  • 导航效率:从父节点走到子节点,退化成一次加法 + 一次解引用,没有额外的查找表或者反序列化开销。
  • 数据与索引物理分离,但共享同一套持久化机制:树节点、叶子数据、Byte Map 在文件里各自占据独立区域,逻辑上分离、避免互相干扰;但因为都在同一个 mmap 区域里,天然共享同一套持久化(写回磁盘)和缓存(OS page cache)机制,不需要为 Byte Map 单独设计一套持久化逻辑。

Personal notes: to be added.