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.
Key Types
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
keyvalueoplsntimestampttlDelete entry is a tombstone. value: None for tombstones.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.
itemsVec of decoded key/value pairstruncatedtrue if budget was hitstatsQueryStats (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();
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.
test_finalize_flush_retains_writes_after_snapshot
Write Path
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
Range / Prefix Scan
Segment File Format
Four files per segment. ID is zero-padded 8-digit decimal: segment-00000001.dat.
Data blocks
4096-byte aligned, LZ4-compressed. Magic: 0x45445347 (EDSG)
Sparse index
First key of every 64th entry + byte offset in .dat
Xor8 filter
Probabilistic filter — eliminates unnecessary .dat reads. No false negatives.
Metadata
JSON — segment_id, record_count, min/max_key, BLAKE3 hash, cohort
Constants segment.rs
| Constant | Value | Meaning |
|---|---|---|
SEGMENT_BLOCK_SIZE | 4096 | Aligned block size in bytes |
BLOCK_TARGET_BYTES | 3900 | Target payload before a block boundary is forced |
SEGMENT_FILE_MAGIC | 0x45445347 | .dat header magic ("EDSG" in ASCII) |
SEGMENT_FORMAT_VERSION | 1 | .dat format version byte |
SEGMENT_HEADER_LEN | 8 | Bytes before first block (magic + version + padding) |
MAX_BLOCK_DECOMPRESSED | 2 MiB | Upper bound on decompressed block size |
AVG_ENTRY_SIZE_ESTIMATE | 256 | Heuristic for auto-flush threshold only (engine/mod.rs:28) |
MemTable Implementations
Three implementations in memtable.rs. Default is BBTreeConcurrentMemTable, set in EdgestoreConfig::default().
| Type | Backend | Concurrency | Notes |
|---|---|---|---|
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);
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
| Function | Signature sketch | Purpose |
|---|---|---|
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
| Function | Purpose |
|---|---|
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_entry | Entry wire format encode/decode |
recovery.rs
| Function | Purpose |
|---|---|
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.
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");
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()?;
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;
}
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)
| Invariant | Test |
|---|---|
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) |
# all crates, including edgestore-tokio
cargo test --workspace
# engine suite only (215 tests)
cargo test -p edgestore engine