CONTRIBUTOR REFERENCE edgestore v2.2.x

Internals

A working guide to the edgestore crate for contributors. Covers key types, the 3-phase flush protocol, read/write paths, segment format, helper functions, macros, and the Tiger Style constraints applied across the codebase.

Architecture

The codebase has a strict layering rule: the async wrapper holds no storage logic. Every write goes through WAL → MemTable → flush → SegmentStore in that order.

Application
↓ put / get / range / prefix
Engine — edgestore/src/engine/mod.rs
All writes are &mut self. Reads are &self. LSN counter increments on every put/delete.
MemTable
In-memory write buffer — memtable.rs
WAL
Append-only durability log — wal.rs
↓ flush (3-phase protocol)
SegmentStore — segment.rs
Immutable on-disk sorted runs. Never modified after write.
startup
Recovery — recovery.rs
WAL replay at open(). Replays all wal-*.log files in ascending order.
edgestore-tokio is Arc<RwLock<Engine>> + spawn_blocking. Zero storage logic. docs.rs →

Key Types

Engine docs.rs →
engine/mod.rs:103
memtable in-memory write buffer, Box<dyn MemTable>
segment_store ordered set of immutable on-disk segments
wal append-only durability log, rotated at 64 MiB / 60s
lsn_counter monotone sequence number, increments on every write
MemEntry docs.rs →
types.rs — single record in memtable or segment
key
Vec<u8>
value
Option<Vec<u8>>
op
Put | Delete
lsn
u64
timestamp
i64
ttl
u32 secs
A Delete entry is a tombstone. value: None for tombstones.
FlushWork
segment.rs:389 — self-contained flush work package

Carries a snapshot of memtable entries and a reserved segment ID. Phase 2 (execute()) holds no engine lock — it writes to disk independently. Callers pass flushed_max_lsn to finalize_flush for correct memtable rebuild.

BudgetedScan
engine/mod.rs:60 — range/prefix scan result
itemsVec of decoded key/value pairs
truncatedtrue if budget was hit
statsQueryStats (segments, items, bytes scanned)

3-Phase Flush Protocol

Flush converts the current memtable into an immutable on-disk segment without blocking writes during I/O. The engine stays writable throughout Phases 1 and 2.

Engine::begin_flush() write lock

Snapshot memtable entries into a FlushWork. Reserve the next segment ID. The memtable is not cleared — writes continue while the snapshot is on disk.

// records max LSN across all snapshot entries let flushed_max_lsn = entries.iter().map(|(_, e)| e.lsn).max().unwrap_or(0);
FlushWork::execute() no lock held

Writes all four segment files to disk. No engine state required. In AsyncEngine, this phase runs in spawn_blocking.

// all disk I/O happens here — engine is unlocked segment-NNNNNNNN.dat // LZ4 compressed data blocks segment-NNNNNNNN.idx // sparse key index segment-NNNNNNNN.xf // Xor8 probabilistic filter segment-NNNNNNNN.meta // JSON metadata
Engine::finalize_flush(&meta, flushed_max_lsn) write lock

Register the segment in the manifest. Open a SegmentReader. Rebuild the memtable, keeping only entries whose lsn > flushed_max_lsn.

// entries written during Phase 2 survive the flush let rebuilt: Vec<_> = self.memtable.iter() .filter(|(_, e)| e.lsn > flushed_max_lsn) .collect();
Invariant: Entries at lsn ≤ flushed_max_lsn are durably in the segment after Phase 3. Entries at lsn > flushed_max_lsn arrived during Phase 2 and are retained.
Covered by test: test_finalize_flush_retains_writes_after_snapshot

Write Path

put(ns, key, value)
↓ readonly guard + ns length ≤ u16::MAX
write_entry(ns, key, val, ttl=0)
1. lsn_counter += 1
2. WAL record + BLAKE3 value hash
3. memtable.insert(encode_key(ns, key), entry)
↓ if memtable.len() × 256 ≥ memtable_max_bytes
flush_to_segments_inner() — error propagates
put_with_ttl is identical but skips auto-flush and passes ttl_secs to write_entry. Auto-flush failure is not silent: put returns the error.

Read Path

Point Lookup

get(ns, key)
encode_key(ns, key)
1. Check memtable
hit → return
miss → segments
2. SegmentStore (newest → oldest)
Xor8 filter → sparse index → block decode
not found → None

Range / Prefix Scan

range(ns, start, end)
1. seg_results from SegmentStore (sorted)
2. mem_results from MemTable (sorted)
3. merge_sorted_scans(seg, mem)
O(n), 2 allocations
4. dedup_filter_scan(merged, …)
highest LSN wins · filter tombstones · apply budget
HashMap approach: O(n log n), 4 allocations. The 2-pointer merge is preferred.

Segment File Format

Four files per segment. ID is zero-padded 8-digit decimal: segment-00000001.dat.

.dat

Data blocks

4096-byte aligned, LZ4-compressed. Magic: 0x45445347 (EDSG)

.idx

Sparse index

First key of every 64th entry + byte offset in .dat

.xf

Xor8 filter

Probabilistic filter — eliminates unnecessary .dat reads. No false negatives.

.meta

Metadata

JSON — segment_id, record_count, min/max_key, BLAKE3 hash, cohort

Constants segment.rs

ConstantValueMeaning
SEGMENT_BLOCK_SIZE4096Aligned block size in bytes
BLOCK_TARGET_BYTES3900Target payload before a block boundary is forced
SEGMENT_FILE_MAGIC0x45445347.dat header magic ("EDSG" in ASCII)
SEGMENT_FORMAT_VERSION1.dat format version byte
SEGMENT_HEADER_LEN8Bytes before first block (magic + version + padding)
MAX_BLOCK_DECOMPRESSED2 MiBUpper bound on decompressed block size
AVG_ENTRY_SIZE_ESTIMATE256Heuristic for auto-flush threshold only (engine/mod.rs:28)

MemTable Implementations

Three implementations in memtable.rs. Default is BBTreeConcurrentMemTable, set in EdgestoreConfig::default().

TypeBackendConcurrencyNotes
BTreeMemTable std::collections::BTreeMap &mut self writes Reference implementation
BBTreeMemTable bbtree::unsync::BBTreeMap &mut self writes ~5× faster point lookups via SIMD node search
BBTreeConcurrentMemTable bbtree::BBTreeMap concurrent reads Default. Readers never write cache lines during read. Uses scan() not range(). Manual count field (no .len()). OOM panics.

impl_simple_memtable! macro memtable.rs:58

BTreeMemTable and BBTreeMemTable share identical MemTable impl bodies — both backing types expose the same interface. The macro generates the impl from a single body to prevent silent divergence. BBTreeConcurrentMemTable is not covered: it uses scan() instead of range()/iter() and has different allocation semantics.

macro_rules! impl_simple_memtable { ($name:ident) => { impl MemTable for $name { fn insert(&mut self, key: Vec<u8>, entry: MemEntry) { self.inner.insert(key, entry); } fn get(&self, key: &[u8]) -> Option<MemEntry> { self.inner.get(key).cloned() } // range(), prefix(), iter(), len(), clear() follow the same pattern } }; } impl_simple_memtable!(BTreeMemTable); impl_simple_memtable!(BBTreeMemTable);
OOM behavior: BBTreeConcurrentMemTable::insert panics on allocator exhaustion. This is documented on the MemTable::insert trait and on the impl. The other two implementations do not panic.

Helper Functions

engine/mod.rs

FunctionSignature sketchPurpose
write_entry (ns, key, val, ttl) → Result<Lsn> Shared WAL write + memtable insert for all put operations. One WAL record per call.
merge_sorted_scans (seg, mem) → Vec<…> O(n) 2-pointer merge of two already-sorted entry slices. Ascending order, may contain duplicates per key.
dedup_filter_scan (merged, has_seg, budget, truncated) → Result<BudgetedKvScan> Dedup by key (highest LSN wins), filter tombstones, decode keys, apply byte/item budget.
range_core (ns, start, end, budget) → … Full range scan pipeline using the two helpers above. ~15 lines.
prefix_core (ns, prefix, budget) → … Prefix scan pipeline. Converts prefix to [prefix, upper_bound) range.
flush_to_segments_inner (&mut self) → Result<…> Synchronous orchestration of all three flush phases.

segment.rs

FunctionPurpose
find_block_offset(index, key)Binary search on sparse index → byte offset in .dat
build_xor_filter(keys)Build Xor8 filter from key slice
filter_contains(filter, key)Xor8 membership test (no false negatives)
read_block_at_offset(file, offset)Read and decompress one 4096-byte block
serialize_entry / deserialize_entryEntry wire format encode/decode

recovery.rs

FunctionPurpose
list_wal_files(db_path)Enumerate WAL files matching wal-[16 hex].log, sorted ascending
recover_from_wal(db_path, memtable)Replay WAL files into memtable; returns RecoveryResult

Tiger Style Rules in Force

This codebase applies Tiger Style constraints. The rules below are actively enforced — each one has at least one code site where it was applied or repaired.

Assertions

Minimum 2 debug_assert! per non-trivial function: entry condition + return-value invariant. Assert at every external call boundary.

debug_assert!(!ns.is_empty(), "ns must not be empty"); // ... body ... debug_assert!(lsn > 0, "lsn must be positive");
No Silent Error Discard

Every Result is handled explicitly. let _ = expr is banned on fallible paths that affect correctness.

// before (silent discard): let _ = self.flush_to_segments_inner(); // after (error propagates): self.flush_to_segments_inner()?;
Loop Bounds

Every non-trivial loop has an explicit upper bound with an assertion.

let blocks_max = (dat_len / SEGMENT_BLOCK_SIZE as u64) + 1; let mut blocks_visited = 0u64; loop { debug_assert!(blocks_visited <= blocks_max, "exceeded block bound"); blocks_visited += 1; }
Function Size & Purpose

Max 70 lines per function. One purpose per function — must be nameable as a verb-noun pair. merge_sorted_scans only merges. dedup_filter_scan only deduplicates. write_entry only writes one WAL record.

Key Invariants (tested)

InvariantTest
lsn > 0 for every write; LSN strictly monotone test_put_lsn_monotone_and_positive
Writes after begin_flush survive finalize_flush test_finalize_flush_retains_writes_after_snapshot
Tombstone in memtable shadows segment value test_delete_from_segment_via_memtable_tombstone
Range merge deduplicates same key across segments test_range_merge_dedups_same_key
put_with_ttl stores the TTL field in the memtable entry test_put_with_ttl_stores_ttl_field
Segment sparse index is cached at open() test_reader_caches_index_at_open
remove_segment updates manifest before deleting files test_remove_segment_manifest_updated_before_files_gone
flushed_max_lsn = max LSN across all snapshot entries enforced in prepare_flush (no dedicated test)
Run the full test suite
# all crates, including edgestore-tokio cargo test --workspace # engine suite only (215 tests) cargo test -p edgestore engine

References