<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Stan Hsu on Medium]]></title>
        <description><![CDATA[Stories by Stan Hsu on Medium]]></description>
        <link>https://medium.com/@wudiheroback?source=rss-83005aa59123------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wxeu1Hb7drylJcuFCdUGrw.jpeg</url>
            <title>Stories by Stan Hsu on Medium</title>
            <link>https://medium.com/@wudiheroback?source=rss-83005aa59123------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 22:12:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wudiheroback/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[toyDB MVCC Source Code Analysis (Part 1)]]></title>
            <link>https://medium.com/@wudiheroback/toydb-mvcc-source-code-analysis-part-1-79a9440200b9?source=rss-83005aa59123------2</link>
            <guid isPermaLink="false">https://medium.com/p/79a9440200b9</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Stan Hsu]]></dc:creator>
            <pubDate>Fri, 14 Nov 2025 16:33:12 GMT</pubDate>
            <atom:updated>2025-11-14T16:33:12.584Z</atom:updated>
            <content:encoded><![CDATA[<p>The article is divided into two parts:</p><ul><li>Part 1: MVCC structure, begin(), begin_read_only()</li><li>Part 2: resume(), read/write operations, commit/rollback, scan iterator</li></ul><h3>MVCC Structure</h3><p>MVCC is a transactional key-value engine based on multi-version concurrency control, wrapping an underlying storage engine for raw key-value storage.</p><pre>pub struct MVCC&lt;E: Engine&gt; {<br>    pub engine: Arc&lt;Mutex&lt;E&gt;&gt;,<br>}</pre><p>Field Description</p><ul><li>engine: Arc&lt;Mutex&lt;E&gt;&gt;: Contains three layers of concepts. Arc is atomic reference counting, allowing multiple transactions to share the same storage engine. Mutex is a mutual exclusion lock, ensuring serialized access to the storage engine. E: Engine is a generic parameter, can be any storage engine implementing the Engine trait (such as BitCask, Memory)</li></ul><h4>Why Mutex is Needed</h4><p>Although MVCC supports any number of concurrent transactions, individual read/write operations must be serialized through a mutex. There are two reasons:</p><ol><li>Storage engine is not thread-safe: The underlying Engine (like BitCask) requires serialized access</li><li>Raft state machine limitation: The Raft state machine managing the MVCC engine applies commands one at a time from the Raft log, serializing them anyway</li></ol><h4>MVCC Public Methods</h4><pre>impl&lt;E: Engine&gt; MVCC&lt;E&gt; {<br>    pub fn new(engine: E) -&gt; Self<br>    pub fn begin(&amp;self) -&gt; Result&lt;Transaction&lt;E&gt;&gt;<br>    pub fn begin_read_only(&amp;self) -&gt; Result&lt;Transaction&lt;E&gt;&gt;<br>    pub fn begin_as_of(&amp;self, version: Version) -&gt; Result&lt;Transaction&lt;E&gt;&gt;<br>    pub fn resume(&amp;self, state: TransactionState) -&gt; Result&lt;Transaction&lt;E&gt;&gt;<br>    pub fn get_unversioned(&amp;self, key: &amp;[u8]) -&gt; Result&lt;Option&lt;Vec&lt;u8&gt;&gt;&gt;<br>    pub fn set_unversioned(&amp;self, key: &amp;[u8], value: Vec&lt;u8&gt;) -&gt; Result&lt;()&gt;<br>    pub fn status(&amp;self) -&gt; Result&lt;Status&gt;<br>}</pre><p>Next, we’ll start with the begin() method and go through each one in detail.</p><h3>begin() Method: Starting a Read-Write Transaction</h3><p>begin() is one of the core methods of MVCC, used to start a new read-write transaction.</p><pre>pub fn begin(&amp;self) -&gt; Result&lt;Transaction&lt;E&gt;&gt; {<br>    Transaction::begin(self.engine.clone())<br>}</pre><p>This method is simple, delegating directly to Transaction::begin(), passing in the shared engine reference (Arc clone only increments the reference count, doesn&#39;t copy the engine itself).</p><h4>Transaction::begin() Implementation</h4><pre>fn begin(engine: Arc&lt;Mutex&lt;E&gt;&gt;) -&gt; Result&lt;Self&gt; {<br>    let mut session = engine.lock()?;<br><br>    // Allocate a new version for writes<br>    let version = match session.get(&amp;Key::NextVersion.encode())? {<br>        Some(ref v) =&gt; Version::decode(v)?,<br>        None =&gt; 1,<br>    };<br>    session.set(&amp;Key::NextVersion.encode(), (version + 1).encode())?;<br><br>    // Get current active transaction set, persist if non-empty for time-travel queries<br>    let active = Self::scan_active(&amp;mut session)?;<br>    if !active.is_empty() {<br>        session.set(&amp;Key::TxnActiveSnapshot(version).encode(), active.encode())?<br>    }<br>    session.set(&amp;Key::TxnActive(version).encode(), vec![])?;<br>    drop(session);<br><br>    Ok(Self { engine, state: TransactionState { version, read_only: false, active } })<br>}</pre><h4>Related Data Structures</h4><p>Before diving into begin(), we need to understand the related data structures.</p><p><strong>Version Type</strong></p><pre>pub type Version = u64;</pre><p>Version is a type alias for u64, representing a logical timestamp. Each read-write transaction has a unique version number.</p><p><strong>Key enum</strong></p><p>MVCC uses special key encoding to organize data:</p><pre>pub enum Key&lt;&#39;a&gt; {<br>    NextVersion,<br>    TxnActive(Version),<br>    TxnActiveSnapshot(Version),<br>    TxnWrite(Version, Cow&lt;&#39;a, [u8]&gt;),<br>    Version(Cow&lt;&#39;a, [u8]&gt;, Version),<br>    Unversioned(Cow&lt;&#39;a, [u8]&gt;),<br>}</pre><p>Key Variant Descriptions</p><ul><li>NextVersion: Stores the next available version number, acts as a global counter. Format is NextVersion =&gt; u64, read and incremented when a new read-write transaction starts</li><li>TxnActive(Version): Records active (uncommitted) transactions. Format is TxnActive(version) =&gt; [], written when transaction begins, deleted when committed or rolled back</li><li>TxnActiveSnapshot(Version): Stores snapshot of active set when transaction begins. Format is TxnActiveSnapshot(version) =&gt; BTreeSet&lt;Version&gt;, only written when active set is non-empty, used for time-travel queries</li><li>TxnWrite(Version, key): Tracks keys written by a transaction. Format is TxnWrite(version, key) =&gt; [], used during rollback to find and delete all writes</li><li>Version(key, Version): Actual versioned data. Format is Version(key, version) =&gt; Option&lt;Vec&lt;u8&gt;&gt;, None represents a tombstone (deletion marker)</li><li>Unversioned(key): Unversioned key-value pairs. Format is Unversioned(key) =&gt; Vec&lt;u8&gt;, used for metadata, independent of versioned keys</li></ul><p>Key Encoding</p><p>The Key enum implements the encoding::Key trait, using Keycode encoding to ensure:</p><ul><li>Preserves lexicographical order: Range scans work correctly</li><li>Variant clustering: Keys of the same type are stored consecutively</li></ul><p><strong>Transaction Structure</strong></p><pre>pub struct Transaction&lt;E: Engine&gt; {<br>    engine: Arc&lt;Mutex&lt;E&gt;&gt;,<br>    state: TransactionState,<br>}</pre><ul><li>engine: Shared storage engine reference</li><li>state: Transaction state, containing version number, read-only flag, and active set</li></ul><p><strong>TransactionState Structure</strong></p><pre>pub struct TransactionState {<br>    pub version: Version,<br>    pub read_only: bool,<br>    pub active: BTreeSet&lt;Version&gt;,<br>}</pre><p>Field Descriptions</p><ul><li><strong>version</strong>: Transaction’s version number. For read-write transactions, uniquely identifies its writes. For read-only transactions, represents the database snapshot version it sees</li><li><strong>read_only</strong>: Whether this is a read-only transaction. When true, cannot write and uses strict less-than visibility rule. When false, can write and uses less-than-or-equal visibility rule</li><li><strong>active</strong>: Set of concurrent active transactions (snapshot)</li></ul><pre>Definition     → When a transaction starts, records all transaction IDs<br>                 that are &quot;in progress but not yet committed&quot;<br>Immutability   → Does not change throughout the transaction&#39;s lifetime<br>                → Even if these transactions later commit or new transactions<br>                  start, the active set remains unchanged<br>Visibility     → Writes from transactions in the active set are invisible<br>                 to the current transaction<br><br>Example:<br>T1 -------- [start] ----------- [commit] --------&gt;<br>T2 -------- [start] ---------------------- [commit] --&gt;<br>T3 -------- [start] ---------------------------------&gt;<br>               ↑<br>            T4 starts here<br><br>T4&#39;s active = {1, 2, 3}  // T1, T2, T3 are all still running<br><br>After T4 starts:<br>- T1 commits → T4&#39;s active is still {1, 2, 3}<br>- T5 starts → T4&#39;s active is still {1, 2, 3}<br><br>Why are T1&#39;s writes invisible to T4:<br>Suppose T1 writes key = &quot;x&quot;, value = &quot;a&quot;, then commits<br>→ When T4 reads key = &quot;x&quot;, it sees the version was written by T1<br>→ T1 is in T4&#39;s active set<br>→ This means T1 was a transaction &quot;still running when T4 started&quot;<br>→ T4 cannot see this write (even though T1 later committed)<br><br>Significance: This is the core mechanism of Snapshot Isolation<br>             Guarantees the transaction sees a consistent snapshot<br>             from its start time</pre><h3>begin() Execution Flow Breakdown</h3><p>Now let’s break down the six core steps of Transaction::begin().</p><h4>Step 1: Acquire Mutex Lock</h4><pre>let mut session = engine.lock()?;</pre><p>Purpose</p><ul><li>Acquire exclusive access to the underlying storage engine</li><li>? handles lock poisoning (another thread panicked while holding the lock)</li></ul><p>Why Lock is Needed</p><p>Although MVCC supports concurrent transactions, operations on metadata (like version number allocation, active set scanning) must be atomic to avoid race conditions.</p><h4>Step 2: Allocate Version Number</h4><pre>let version = match session.get(&amp;Key::NextVersion.encode())? {<br>    Some(ref v) =&gt; Version::decode(v)?,<br>    None =&gt; 1,<br>};<br>session.set(&amp;Key::NextVersion.encode(), (version + 1).encode())?;</pre><p>Execution Details</p><ul><li>Read NextVersion: Use Key::NextVersion.encode() to encode enum variant to binary key. If exists, decode to u64 version number. If doesn&#39;t exist (brand new database), default to 1</li><li>Increment and write back: Current version is allocated to this transaction, then version + 1 is written back to NextVersion for the next transaction</li><li>Encoding format: Uses Keycode encoding to ensure key lexicographical order, value uses Bincode encoding (u64&#39;s compact binary representation)</li></ul><p>Examples</p><pre>// First transaction<br>NextVersion: None -&gt; version = 1, write NextVersion = 2<br><br>// Second transaction<br>NextVersion: 2 -&gt; version = 2, write NextVersion = 3<br><br>// Third transaction<br>NextVersion: 3 -&gt; version = 3, write NextVersion = 4</pre><h4>Step 3: Scan Active Transactions</h4><pre>let active = Self::scan_active(&amp;mut session)?;</pre><p>scan_active() Source Code</p><pre>fn scan_active(session: &amp;mut MutexGuard&lt;E&gt;) -&gt; Result&lt;BTreeSet&lt;Version&gt;&gt; {<br>    let mut active = BTreeSet::new();<br>    let mut scan = session.scan_prefix(&amp;KeyPrefix::TxnActive.encode());<br>    while let Some((key, _)) = scan.next().transpose()? {<br>        match Key::decode(&amp;key)? {<br>            Key::TxnActive(version) =&gt; active.insert(version),<br>            key =&gt; return errdata!(&quot;expected TxnActive key, got {key:?}&quot;),<br>        };<br>    }<br>    Ok(active)<br>}</pre><p>How It Works</p><ul><li>Prefix scan: Use KeyPrefix::TxnActive.encode() to generate prefix key matching all TxnActive(version) keys. scan_prefix() returns an iterator of all key-value pairs with this prefix</li><li>Decode version numbers: Iterate through each TxnActive(version) key, extract version number and insert into BTreeSet</li><li>Why use BTreeSet: Automatic sorting is convenient for testing and debugging, and provides O(log n) query efficiency</li></ul><p><strong>Prefix Scan Encoding Mechanism</strong></p><p>Keycode encoding ensures keys of the same variant are stored consecutively:</p><pre>TxnActive(1)  -&gt; [0x01, 0x00, 0x00, 0x00, 0x01]<br>TxnActive(2)  -&gt; [0x01, 0x00, 0x00, 0x00, 0x02]<br>TxnActive(5)  -&gt; [0x01, 0x00, 0x00, 0x00, 0x05]</pre><p>The prefix [0x01] matches all TxnActive keys; scanning only needs to compare the prefix.</p><h4>Step 4: Persist Active Set Snapshot</h4><p><strong>Why Persistence is Needed</strong></p><p>Supports time-travel queries:</p><ul><li>Future begin_as_of(version) needs to restore the active set from when that version started</li><li>Ensures time-travel queries see the same data as the transaction at that time</li></ul><p><strong>Why Only Write When Non-Empty</strong></p><ul><li>If active is empty, means no concurrent transactions</li><li>Time-travel queries can safely use an empty set</li><li>Reduces storage overhead</li></ul><p>Encoding Format</p><pre>Key::TxnActiveSnapshot(3) =&gt; BTreeSet([1, 2])<br>// After encoding:<br>// Key: [0x02, version=3&#39;s Keycode]<br>// Value: BTreeSet&#39;s Bincode serialization</pre><h4>Step 5: Mark as Active Transaction</h4><pre>session.set(&amp;Key::TxnActive(version).encode(), vec![])?;</pre><p>Purpose</p><ul><li>Add self to active set</li><li>Value is empty vec![], only need key existence</li></ul><p>Why Empty Value</p><ul><li>TxnActive only needs to know &quot;which versions are active&quot;</li><li>Key itself already carries version number information</li><li>Empty value saves storage space</li></ul><p>Subsequent Operations</p><ul><li>On commit: Delete this key (delete(Key::TxnActive(version)))</li><li>On rollback: First delete all writes, then delete this key</li></ul><h4>Step 6: Release Lock and Return</h4><pre>drop(session);<br><br>Ok(Self { engine, state: TransactionState { version, read_only: false, active } })</pre><p>Release Lock</p><ul><li>Explicitly drop(session) releases Mutex</li><li>Allows other transactions to acquire lock</li><li>Remaining time of begin() doesn&#39;t need to hold lock</li></ul><p>Construct Transaction</p><ul><li>engine: Shared engine reference (Arc clone)</li><li>state: Contains version number, read-only flag (false), active set snapshot</li></ul><p>Transaction State Immutability</p><ul><li>active doesn&#39;t change throughout transaction lifetime</li><li>Even if other transactions commit or start, current transaction’s visibility rules are unaffected</li><li>This is the core of Snapshot Isolation</li></ul><h4>begin() Timeline Diagram</h4><p>Here’s the complete flow of three transactions starting sequentially:</p><pre>Initial state: NextVersion = 1, active = {}<br><br>=== Transaction 1 Starts ===<br>T1 -----&gt; [lock Engine]<br>          |<br>          get(NextVersion) -&gt; None (first transaction)<br>          set(NextVersion, 2)      (reserve next version)<br>          |<br>          scan_active() -&gt; {}      (no other active transactions)<br>          (active is empty, don&#39;t write TxnActiveSnapshot)<br>          |<br>          set(TxnActive(1), [])    (mark self as active)<br>          |<br>          [unlock Engine]<br>Result: T1 version = 1, active = {}<br><br>=== Transaction 2 Starts (T1 still running) ===<br>T2 -----&gt; [lock Engine]<br>          |<br>          get(NextVersion) -&gt; 2    (read next available version)<br>          set(NextVersion, 3)      (reserve next version)<br>          |<br>          scan_active() -&gt; {1}     (found T1 still running)<br>          set(TxnActiveSnapshot(2), [1])  (persist snapshot)<br>          set(TxnActive(2), [])    (mark self as active)<br>          |<br>          [unlock Engine]<br>Result: T2 version = 2, active = {1}<br><br>=== Transaction 3 Starts (T1, T2 both still running) ===<br>T3 -----&gt; [lock Engine]<br>          |<br>          get(NextVersion) -&gt; 3    (read next available version)<br>          set(NextVersion, 4)      (reserve next version)<br>          |<br>          scan_active() -&gt; {1, 2}  (found T1, T2 both running)<br>          set(TxnActiveSnapshot(3), [1, 2])  (persist snapshot)<br>          set(TxnActive(3), [])    (mark self as active)<br>          |<br>          [unlock Engine]<br>Result: T3 version = 3, active = {1, 2}<br><br>Final state:<br>  NextVersion = 4<br>  TxnActive = {1, 2, 3}<br>  T1 cannot see writes from T2, T3<br>  T2 cannot see writes from T1, T3<br>  T3 cannot see writes from T1, T2</pre><p>Key Observations</p><ol><li>Serialized execution: Each transaction’s begin() runs entirely within the lock, avoiding race conditions</li><li>Monotonic version increase: Version numbers monotonically increase (1, 2, 3…)</li><li>Active set snapshot: Each transaction sees transactions that were active before it started, remains unchanged thereafter</li><li>Snapshot persistence: T2 and T3 store snapshots because their active sets are non-empty</li></ol><p>Visibility Impact</p><ul><li>Transaction 1 can see data with version ≤ 1</li><li>Transaction 2 can see data with version ≤ 2, but version 1’s writes are invisible (because 1 ∈ active)</li><li>Even if Transaction 1 commits later, Transaction 2 still can’t see its writes (snapshot isolation)</li></ul><h3>begin_read_only() Read-Only Transaction</h3><h4>Function Signature and Entry Points</h4><p>begin_read_only() has two public entry points:</p><pre>// MVCC public methods<br>impl&lt;E: Engine&gt; MVCC&lt;E&gt; {<br>    /// Begins a new read-only transaction at the latest version.<br>    pub fn begin_read_only(&amp;self) -&gt; Result&lt;Transaction&lt;E&gt;&gt; {<br>        Transaction::begin_read_only(self.engine.clone(), None)<br>    }<br><br>    /// Begins a new read-only transaction as of the given version.<br>    pub fn begin_as_of(&amp;self, version: Version) -&gt; Result&lt;Transaction&lt;E&gt;&gt; {<br>        Transaction::begin_read_only(self.engine.clone(), Some(version))<br>    }<br>}</pre><p>The difference:</p><pre>begin_read_only()     → as_of = None      → Read latest version<br>begin_as_of(v)        → as_of = Some(v)   → Time-travel query, read historical version v</pre><h3>Core Implementation</h3><pre>/// Begins a new read-only transaction. If version is given it will see the<br>/// state as of the beginning of that version (ignoring writes at that<br>/// version). In other words, it sees the same state as the read-write<br>/// transaction at that version saw when it began.<br>fn begin_read_only(engine: Arc&lt;Mutex&lt;E&gt;&gt;, as_of: Option&lt;Version&gt;) -&gt; Result&lt;Self&gt; {<br>    let mut session = engine.lock()?;<br><br>    // Fetch the latest version.<br>    let mut version = match session.get(&amp;Key::NextVersion.encode())? {<br>        Some(ref v) =&gt; Version::decode(v)?,<br>        None =&gt; 1,<br>    };<br><br>    // If requested, create the transaction as of a past version, restoring<br>    // the active snapshot as of the beginning of that version. Otherwise,<br>    // use the latest version and get the current, real-time snapshot.<br>    let mut active = BTreeSet::new();<br>    if let Some(as_of) = as_of {<br>        if as_of &gt;= version {<br>            return errinput!(&quot;version {as_of} does not exist&quot;);<br>        }<br>        version = as_of;<br>        if let Some(value) = session.get(&amp;Key::TxnActiveSnapshot(version).encode())? {<br>            active = BTreeSet::&lt;Version&gt;::decode(&amp;value)?;<br>        }<br>    } else {<br>        active = Self::scan_active(&amp;mut session)?;<br>    }<br><br>    drop(session);<br><br>    Ok(Self { engine, state: TransactionState { version, read_only: true, active } })<br>}</pre><h4>Execution Flow Breakdown</h4><p>Step 1: Get Latest Version Number</p><pre>let mut version = match session.get(&amp;Key::NextVersion.encode())? {<br>    Some(ref v) =&gt; Version::decode(v)?,<br>    None =&gt; 1,<br>};</pre><pre>Meaning of NextVersion:<br>- Points to &quot;the version number the next read-write transaction will use&quot;<br>- For example, NextVersion = 5 means the latest committed version is 4<br><br>Why read-only transactions read NextVersion:<br>- Determine current database&#39;s latest state<br>- Acts as upper bound for time-travel queries (can&#39;t query future versions)</pre><p>Step 2: Handle Time-Travel Queries</p><p>This is the most special part of begin_read_only(), supporting two modes:</p><p>Mode A: Read Latest Version (as_of = None)</p><pre>if let Some(as_of) = as_of {<br>    // ...<br>} else {<br>    active = Self::scan_active(&amp;mut session)?;  // Scan current active transactions<br>}</pre><pre>Process:<br>1. Use NextVersion - 1 as version number<br>2. Scan all current active transactions (TxnActive)<br>3. Create real-time snapshot<br><br>Example:<br>NextVersion = 5<br>TxnActive = {3, 4}<br><br>→ Read-only transaction version = 5<br>→ active = {3, 4}<br>→ Can see writes from versions 1, 2<br>→ Cannot see writes from versions 3, 4 (still running)</pre><p>Mode B: Time-Travel Query (as_of = Some(version))</p><pre>if let Some(as_of) = as_of {<br>    if as_of &gt;= version {<br>        return errinput!(&quot;version {as_of} does not exist&quot;);<br>    }<br>    version = as_of;<br>    if let Some(value) = session.get(&amp;Key::TxnActiveSnapshot(version).encode())? {<br>        active = BTreeSet::&lt;Version&gt;::decode(&amp;value)?;<br>    }<br>}</pre><pre>Process:<br>1. Check version validity (can&#39;t query future)<br>2. Set version to as_of<br>3. Restore active snapshot from TxnActiveSnapshot(as_of)<br>4. If snapshot doesn&#39;t exist, active is empty (means no concurrent transactions at that time)<br><br>Example:<br>NextVersion = 10<br>as_of = 5<br><br>→ Check: 5 &lt; 10 ✓ Valid<br>→ version = 5<br>→ Read TxnActiveSnapshot(5) = {2, 3}<br>→ active = {2, 3}<br><br>Result: Sees database state exactly as &quot;version 5 read-write transaction saw when it started&quot;</pre><p>Step 3: Create Read-Only Transaction</p><pre>Ok(Self {<br>    engine,<br>    state: TransactionState {<br>        version,<br>        read_only: true,  // Mark as read-only<br>        active<br>    }<br>})</pre><pre>Impact of read_only: true:<br>1. Cannot perform write operations (set/delete will error)<br>2. Uses strict less-than visibility rule (version &lt; self.version)<br>3. Not recorded in TxnActive (doesn&#39;t occupy version number)<br>4. No need for commit/rollback (just drop it)</pre><h4>Comparison: Read-Write vs Read-Only Transactions</h4><pre>                Read-Write (begin)            Read-Only (begin_read_only)<br>================================================================================<br>Version         Increments, occupies          Doesn&#39;t allocate, uses existing<br>allocation      version = NextVersion         version = NextVersion (latest)<br>                NextVersion += 1              or version = as_of (historical)<br><br>Active          Write TxnActive(version)      Don&#39;t write TxnActive<br>marking         Hold version until commit     Don&#39;t occupy resources<br><br>Snapshot        Write TxnActiveSnapshot       Read TxnActiveSnapshot (time-travel)<br>recording       Record current active         or scan current active (latest)<br><br>Visibility      version &lt;= self.version       version &lt; self.version<br>rule            Can see own writes            Cannot have writes<br><br>Write           Can write                     Read-only<br>permission<br><br>Lifecycle       Need commit/rollback          No need, just drop<br><br>Concurrency     Blocks other read-write       Doesn&#39;t block any transaction<br>impact          transactions</pre><h4>Time-Travel Query Examples</h4><p>Assume current state:</p><pre>Version history:<br>Version 1: INSERT INTO users VALUES (1, &#39;Alice&#39;)    [committed]<br>Version 2: INSERT INTO users VALUES (2, &#39;Bob&#39;)      [committed]<br>Version 3: UPDATE users SET name = &#39;Carol&#39; WHERE id = 1  [active]<br>Version 4: INSERT INTO users VALUES (3, &#39;David&#39;)    [active]<br><br>NextVersion = 5<br>TxnActive = {3, 4}<br>TxnActiveSnapshot(3) = {1, 2}  (assume)<br>TxnActiveSnapshot(4) = {1, 2, 3}</pre><p>Query 1: Read Latest Version</p><pre>let txn = mvcc.begin_read_only()?;  // as_of = None</pre><pre>Result:<br>version = 5<br>active = {3, 4}<br><br>SELECT * FROM users:<br>→ See writes from Version 1, 2<br>→ Don&#39;t see Version 3, 4 (in active)<br>Result:<br>| id | name  |<br>|----|-------|<br>| 1  | Alice |<br>| 2  | Bob   |</pre><p>Query 2: Time-Travel to Version 3</p><pre>let txn = mvcc.begin_as_of(3)?;  // as_of = Some(3)</pre><pre>Result:<br>version = 3<br>active = {1, 2}  (restored from TxnActiveSnapshot(3))<br><br>SELECT * FROM users:<br>→ Don&#39;t see Version 1, 2 (in active)<br>→ Don&#39;t see Version 3 (own version, read-only excludes)<br><br>Result: Empty (no committed data when Version 3 started)</pre><p>Query 3: Time-Travel to Version 2</p><pre>let txn = mvcc.begin_as_of(2)?;</pre><pre>Result:<br>version = 2<br>active = {}  (assume no concurrent transactions when Version 2 started)<br><br>SELECT * FROM users:<br>→ See Version 1 (version 1 &lt; 2, and 1 ∉ active)<br>→ Don&#39;t see Version 2 (own version)<br><br>Result:<br>| id | name  |<br>|----|-------|<br>| 1  | Alice |</pre><h3>Advantages of Read-Only Transactions</h3><pre>Performance advantages:<br>- Don&#39;t occupy version number      → Won&#39;t block read-write transactions<br>- Don&#39;t write TxnActive            → Reduce disk I/O<br>- No need for commit/rollback      → Zero cleanup cost<br>- Multiple read-only transactions  → No lock contention<br>  can run fully concurrently<br><br>Consistency guarantees:<br>- Snapshot isolation               → Repeatable reads<br>- Time-travel queries              → Auditing and debugging<br>Use cases:<br>- Analytical queries (long-running)<br>- Report generation<br>- Data backup<br>- Point-in-Time Recovery<br>- Audit log queries</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79a9440200b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【知其然，更知其所以然】toyDB：MVCC 源碼解析 (上)]]></title>
            <link>https://medium.com/@wudiheroback/%E7%9F%A5%E5%85%B6%E7%84%B6-%E6%9B%B4%E7%9F%A5%E5%85%B6%E6%89%80%E4%BB%A5%E7%84%B6-toydb-mvcc-%E6%BA%90%E7%A2%BC%E8%A7%A3%E6%9E%90-%E4%B8%8A-801fdab644e6?source=rss-83005aa59123------2</link>
            <guid isPermaLink="false">https://medium.com/p/801fdab644e6</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Stan Hsu]]></dc:creator>
            <pubDate>Fri, 14 Nov 2025 16:20:42 GMT</pubDate>
            <atom:updated>2025-11-14T16:20:42.148Z</atom:updated>
            <content:encoded><![CDATA[<p>文章分為上下兩篇：</p><ul><li>上篇：MVCC 結構體、begin()、begin_read_only()</li><li>下篇：resume()、讀寫操作、commit/rollback、scan 迭代器</li></ul><h3>MVCC 結構體</h3><p>MVCC 是基於多版本並發控制的事務性鍵值引擎，包裝底層存儲引擎用於原始鍵值儲存。</p><pre>pub struct MVCC&lt;E: Engine&gt; {<br>    pub engine: Arc&lt;Mutex&lt;E&gt;&gt;,<br>}</pre><p>欄位說明</p><p>engine: Arc&lt;Mutex&lt;E&gt;&gt;</p><ul><li>Arc：原子引用計數，允許多個事務共享同一個存儲引擎</li><li>Mutex：互斥鎖，確保對存儲引擎的存取是序列化的</li><li>E: Engine：泛型參數，可以是任何實現了 Engine trait 的存儲引擎（如 BitCask、Memory）</li></ul><h4>為什麼需要 Mutex</h4><p>雖然 MVCC 支援任意數量的並發事務，但個別讀寫操作必須透過互斥鎖序列化執行。原因有二：</p><p>存儲引擎不是執行緒安全的：底層的 Engine（如 BitCask）需要序列化存取</p><p>Raft 狀態機的限制：管理 MVCC 引擎的 Raft 狀態機從 Raft 日誌一次應用一個命令，無論如何都會序列化它們</p><h4><strong>MVCC 的公開方法</strong></h4><pre>impl&lt;E: Engine&gt; MVCC&lt;E&gt; {<br>    pub fn new(engine: E) -&gt; Self<br>    pub fn begin(&amp;self) -&gt; Result&lt;Transaction&lt;E&gt;&gt;<br>    pub fn begin_read_only(&amp;self) -&gt; Result&lt;Transaction&lt;E&gt;&gt;<br>    pub fn begin_as_of(&amp;self, version: Version) -&gt; Result&lt;Transaction&lt;E&gt;&gt;<br>    pub fn resume(&amp;self, state: TransactionState) -&gt; Result&lt;Transaction&lt;E&gt;&gt;<br>    pub fn get_unversioned(&amp;self, key: &amp;[u8]) -&gt; Result&lt;Option&lt;Vec&lt;u8&gt;&gt;&gt;<br>    pub fn set_unversioned(&amp;self, key: &amp;[u8], value: Vec&lt;u8&gt;) -&gt; Result&lt;()&gt;<br>    pub fn status(&amp;self) -&gt; Result&lt;Status&gt;<br>}</pre><p>下來我們將從 begin() 方法開始，逐一深入講解。</p><h3>begin() 方法：開始讀寫事務</h3><p>begin() 是 MVCC 最核心的方法之一，用於開始一個新的讀寫事務。</p><pre>pub fn begin(&amp;self) -&gt; Result&lt;Transaction&lt;E&gt;&gt; {<br>    Transaction::begin(self.engine.clone())<br>}</pre><p>這個方法很簡單，直接委託給 Transaction::begin()，傳入共享的引擎引用（Arc 的 clone 只是增加引用計數，不會複製引擎本身）。</p><h4>Transaction::begin() 實現</h4><pre>fn begin(engine: Arc&lt;Mutex&lt;E&gt;&gt;) -&gt; Result&lt;Self&gt; {<br>    let mut session = engine.lock()?;<br><br>    // 分配新版本供寫入<br>    let version = match session.get(&amp;Key::NextVersion.encode())? {<br>        Some(ref v) =&gt; Version::decode(v)?,<br>        None =&gt; 1,<br>    };<br>    session.set(&amp;Key::NextVersion.encode(), (version + 1).encode())?;<br><br>    // 取得當前活躍事務集合，如果非空則持久化供時間旅行查詢使用<br>    let active = Self::scan_active(&amp;mut session)?;<br>    if !active.is_empty() {<br>        session.set(&amp;Key::TxnActiveSnapshot(version).encode(), active.encode())?<br>    }<br>    session.set(&amp;Key::TxnActive(version).encode(), vec![])?;<br>    drop(session);<br><br>    Ok(Self { engine, state: TransactionState { version, read_only: false, active } })<br>}</pre><h4><strong>相關資料結構</strong></h4><p>在深入講解 begin() 之前，我們需要先了解相關的資料結構。</p><h4><strong>Version 型別</strong></h4><pre>pub type Version = u64;</pre><p>Version 是 u64 的型別別名，代表邏輯時間戳。每個讀寫事務都有一個唯一的版本號。</p><h4><strong>Key enum</strong></h4><p>MVCC 使用特殊的鍵編碼來組織資料：</p><pre>pub enum Key&lt;&#39;a&gt; {<br>    NextVersion,<br>    TxnActive(Version),<br>    TxnActiveSnapshot(Version),<br>    TxnWrite(Version, Cow&lt;&#39;a, [u8]&gt;),<br>    Version(Cow&lt;&#39;a, [u8]&gt;, Version),<br>    Unversioned(Cow&lt;&#39;a, [u8]&gt;),<br>}</pre><h4><strong>Key 變體說明</strong></h4><ul><li>NextVersion：儲存下一個可用的版本號，是全局計數器。格式為 NextVersion =&gt; u64，每次新讀寫事務開始時讀取並遞增</li><li>TxnActive(Version)：記錄活躍（未提交）的事務。格式為 TxnActive(版本號) =&gt; []，事務開始時寫入，提交或回滾時刪除</li><li>TxnActiveSnapshot(Version)：儲存事務開始時的活躍集合快照。格式為 TxnActiveSnapshot(版本號) =&gt; BTreeSet&lt;Version&gt;，僅在 active set 非空時寫入，用於時間旅行查詢</li><li>TxnWrite(Version, key)：追蹤事務寫入的鍵。格式為 TxnWrite(版本號, 鍵) =&gt; []，用於回滾時找到並刪除所有寫入</li><li>Version(key, Version)：實際的版本化資料。格式為 Version(鍵, 版本號) =&gt; Option&lt;Vec&lt;u8&gt;&gt;，None 表示墓碑（刪除標記）</li><li>Unversioned(key)：未版本化的鍵值對。格式為 Unversioned(鍵) =&gt; Vec&lt;u8&gt;，用於元資料，與版本化鍵獨立</li></ul><h4>Key 的編碼</h4><p>Key enum 實現了 encoding::Key trait，使用 Keycode 編碼，確保：</p><ul><li>保持字典序：範圍掃描能正確工作</li><li>變體聚集：相同類型的鍵連續排列</li></ul><h4>Transaction 結構體</h4><pre>pub struct Transaction&lt;E: Engine&gt; {<br>    engine: Arc&lt;Mutex&lt;E&gt;&gt;,<br>    state: TransactionState,<br>}</pre><ul><li>engine：共享的存儲引擎引用</li><li>state：事務狀態，包含版本號、唯讀標記和活躍集合</li></ul><h4>TransactionState 結構體</h4><pre>pub struct TransactionState {<br>    pub version: Version,<br>    pub read_only: bool,<br>    pub active: BTreeSet&lt;Version&gt;,<br>}</pre><p>欄位說明</p><ul><li>version：事務的版本號。對於讀寫事務，唯一識別其寫入的版本。對於唯讀事務，代表看到的資料庫快照版本</li><li>read_only：是否為唯讀事務。為 true 時不能寫入，使用嚴格小於的可見性規則。為 false 時可以寫入，使用小於等於的可見性規則</li><li>active：並發活躍事務的集合（快照）</li></ul><pre>定義        → 事務開始時，記錄所有「正在執行中但還沒 commit」的事務 ID<br>不變性      → 整個事務生命週期中不會改變<br>            → 即使這些事務後來 commit 或新事務開始，active 集合仍保持不變<br>可見性規則  → active 中的事務寫入對當前事務不可見<br><br>例子：<br>T1 -------- [開始] ----------- [commit] --------&gt;<br>T2 -------- [開始] ---------------------- [commit] --&gt;<br>T3 -------- [開始] ---------------------------------&gt;<br>               ↑<br>            這時 T4 開始<br><br>T4 的 active = {1, 2, 3}  // T1, T2, T3 都還在執行中<br><br>T4 開始後：<br>- T1 commit 了 → T4 的 active 仍然是 {1, 2, 3}<br>- T5 新開始了 → T4 的 active 仍然是 {1, 2, 3}<br><br>為什麼 T1 的寫入對 T4 不可見：<br>假設 T1 寫入 key = &quot;x&quot;, value = &quot;a&quot;，然後 commit<br>→ T4 讀取 key = &quot;x&quot; 時，看到 version 是 T1 寫的<br>→ T1 在 T4 的 active 集合中<br>→ 代表 T1 是「T4 開始時還在執行中」的事務<br>→ T4 看不到這個寫入（即使 T1 後來 commit 了）<br><br>意義：這是快照隔離 (Snapshot Isolation) 的核心機制<br>     保證事務看到的是開始時刻的一致性快照</pre><h3>begin() 執行流程詳解</h3><p>現在我們逐步拆解 Transaction::begin() 的六個核心步驟。</p><h4>步驟 1：獲取互斥鎖</h4><pre>let mut session = engine.lock()?;</pre><p>作用</p><ul><li>獲取底層存儲引擎的獨佔訪問權</li><li>? 處理鎖中毒（另一個執行緒在持有鎖時發生 panic）</li></ul><p>為什麼需要鎖</p><p>雖然 MVCC 支援並發事務，但對元資料的操作（如版本號分配、活躍集合掃描）必須是原子的，避免競態條件。</p><h4>步驟 2：分配版本號</h4><pre>let version = match session.get(&amp;Key::NextVersion.encode())? {<br>    Some(ref v) =&gt; Version::decode(v)?,<br>    None =&gt; 1,<br>};<br>session.set(&amp;Key::NextVersion.encode(), (version + 1).encode())?;</pre><p>執行細節</p><ul><li>讀取 NextVersion：使用 Key::NextVersion.encode() 將 enum 變體編碼為二進制鍵。如果存在則解碼為 u64 版本號，如果不存在（全新資料庫）則預設為 1</li><li>遞增並寫回：當前版本分配給此事務，然後將 version + 1 存回 NextVersion，供下一個事務使用</li><li>編碼格式：使用 Keycode 編碼確保鍵的字典序，值使用 Bincode 編碼（u64 的緊湊二進制表示）</li></ul><p>範例</p><pre>// 第一個事務<br>NextVersion: None -&gt; version = 1, 寫入 NextVersion = 2<br><br>// 第二個事務<br>NextVersion: 2 -&gt; version = 2, 寫入 NextVersion = 3<br><br>// 第三個事務<br>NextVersion: 3 -&gt; version = 3, 寫入 NextVersion = 4</pre><h4>步驟 3：掃描活躍事務</h4><pre>let active = Self::scan_active(&amp;mut session)?;</pre><p>scan_active() 源碼</p><pre>fn scan_active(session: &amp;mut MutexGuard&lt;E&gt;) -&gt; Result&lt;BTreeSet&lt;Version&gt;&gt; {<br>    let mut active = BTreeSet::new();<br>    let mut scan = session.scan_prefix(&amp;KeyPrefix::TxnActive.encode());<br>    while let Some((key, _)) = scan.next().transpose()? {<br>        match Key::decode(&amp;key)? {<br>            Key::TxnActive(version) =&gt; active.insert(version),<br>            key =&gt; return errdata!(&quot;expected TxnActive key, got {key:?}&quot;),<br>        };<br>    }<br>    Ok(active)<br>}</pre><p>運作原理</p><ul><li>前綴掃描：使用 KeyPrefix::TxnActive.encode() 生成前綴鍵，匹配所有 TxnActive(version) 鍵。scan_prefix() 返回所有以此前綴開頭的鍵值對迭代器</li><li>解碼版本號：遍歷每個 TxnActive(version) 鍵，提取版本號並插入 BTreeSet</li><li>為何使用 BTreeSet：自動排序方便測試和除錯，並提供 O(log n) 的查詢效率</li></ul><p>前綴掃描的編碼機制</p><p>Keycode 編碼確保相同變體的鍵連續排列：</p><pre>TxnActive(1)  -&gt; [0x01, 0x00, 0x00, 0x00, 0x01]<br>TxnActive(2)  -&gt; [0x01, 0x00, 0x00, 0x00, 0x02]<br>TxnActive(5)  -&gt; [0x01, 0x00, 0x00, 0x00, 0x05]</pre><p>前綴 [0x01] 匹配所有 TxnActive 鍵，掃描時只需比較前綴即可。</p><h4>步驟 4：持久化活躍集合快照</h4><pre>if !active.is_empty() {<br>    session.set(&amp;Key::TxnActiveSnapshot(version).encode(), active.encode())?<br>}</pre><p>為什麼需要持久化</p><p>支援時間旅行查詢（time-travel queries）：</p><ul><li>未來的 begin_as_of(version) 需要還原此版本開始時的活躍集合</li><li>確保時間旅行查詢看到的資料與當時事務看到的一致</li></ul><p>為何只在非空時寫入</p><ul><li>如果 active 為空，代表沒有並發事務</li><li>時間旅行查詢可以安全地使用空集合</li><li>減少存儲開銷</li></ul><p>編碼格式</p><pre>Key::TxnActiveSnapshot(3) =&gt; BTreeSet([1, 2])<br>// 編碼後：<br>// 鍵：[0x02, version=3 的 Keycode]<br>// 值：BTreeSet 的 Bincode 序列化</pre><h4>步驟 5：標記為活躍事務</h4><pre>session.set(&amp;Key::TxnActive(version).encode(), vec![])?;</pre><p>作用</p><ul><li>將自己加入活躍集合</li><li>值為空 vec![]，只需要鍵的存在</li></ul><p>為何值為空</p><ul><li>TxnActive 只需要知道「哪些版本活躍」</li><li>鍵本身已攜帶版本號資訊</li><li>空值節省存儲空間</li></ul><p>後續操作</p><ul><li>提交時：刪除此鍵（delete(Key::TxnActive(version))）</li><li>回滾時：先刪除所有寫入，再刪除此鍵</li></ul><h4>步驟 6：釋放鎖並返回</h4><pre>drop(session);<br><br>Ok(Self { engine, state: TransactionState { version, read_only: false, active } })</pre><p>釋放鎖</p><ul><li>顯式 drop(session) 釋放 Mutex</li><li>允許其他事務獲取鎖</li><li>begin() 的剩餘時間不需要持鎖</li></ul><p>構造 Transaction</p><ul><li>engine：共享的引擎引用（Arc clone）</li><li>state：包含版本號、唯讀標記（false）、活躍集合快照</li></ul><p>事務狀態不可變性</p><ul><li>active 在整個事務生命週期中不變</li><li>即使其他事務提交或開始，當前事務的可見性規則不受影響</li><li>這是快照隔離（Snapshot Isolation）的核心</li></ul><h3>begin() 時間序列圖</h3><p>以下是三個事務依序開始的完整流程：</p><pre>初始狀態: NextVersion = 1, active = {}</pre><pre>=== Transaction 1 開始 ===</pre><pre>T1 -----&gt; [lock Engine]<br>          |<br>          get(NextVersion) -&gt; None (第一個事務)<br>          set(NextVersion, 2)      (預留下一個版本號)<br>          |<br>          scan_active() -&gt; {}      (沒有其他活躍事務)<br>          (active 為空，不寫入 TxnActiveSnapshot)<br>          |<br>          set(TxnActive(1), [])    (標記自己為活躍)<br>          |<br>          [unlock Engine]</pre><pre>結果: T1 版本 = 1, active = {}<br></pre><pre>=== Transaction 2 開始 (T1 還在執行中) ===</pre><pre>T2 -----&gt; [lock Engine]<br>          |<br>          get(NextVersion) -&gt; 2    (讀取下一個可用版本)<br>          set(NextVersion, 3)      (預留下一個版本號)<br>          |<br>          scan_active() -&gt; {1}     (發現 T1 還在執行)<br>          set(TxnActiveSnapshot(2), [1])  (持久化快照)<br>          set(TxnActive(2), [])    (標記自己為活躍)<br>          |<br>          [unlock Engine]</pre><pre>結果: T2 版本 = 2, active = {1}<br></pre><pre>=== Transaction 3 開始 (T1, T2 都還在執行中) ===</pre><pre>T3 -----&gt; [lock Engine]<br>          |<br>          get(NextVersion) -&gt; 3    (讀取下一個可用版本)<br>          set(NextVersion, 4)      (預留下一個版本號)<br>          |<br>          scan_active() -&gt; {1, 2}  (發現 T1, T2 都在執行)<br>          set(TxnActiveSnapshot(3), [1, 2])  (持久化快照)<br>          set(TxnActive(3), [])    (標記自己為活躍)<br>          |<br>          [unlock Engine]</pre><pre>結果: T3 版本 = 3, active = {1, 2}<br></pre><pre>最終狀態:<br>  NextVersion = 4<br>  TxnActive = {1, 2, 3}</pre><pre>  T1 看不到 T2, T3 的寫入<br>  T2 看不到 T1, T3 的寫入<br>  T3 看不到 T1, T2 的寫入</pre><p>關鍵觀察</p><ol><li>互斥執行：每個事務的 begin() 完全在鎖內執行，避免競態條件</li><li>版本遞增：版本號單調遞增（1, 2, 3…）</li><li>活躍集合快照：每個事務看到開始前已活躍的事務，後續不變</li><li>快照持久化：T2 和 T3 儲存快照，因為 active 非空</li></ol><p>可見性影響</p><ul><li>事務 1 可以看到版本 ≤ 1 的資料</li><li>事務 2 可以看到版本 ≤ 2 的資料，但版本 1 的寫入不可見（因為 1 ∈ active）</li><li>即使事務 1 稍後提交，事務 2 仍看不到其寫入（快照隔離）</li></ul><h3>begin_read_only() 唯讀事務</h3><h4>函數簽名與入口</h4><p>begin_read_only() 有兩個公開入口：</p><pre>// MVCC 的公開方法<br>impl&lt;E: Engine&gt; MVCC&lt;E&gt; {<br>    /// Begins a new read-only transaction at the latest version.<br>    pub fn begin_read_only(&amp;self) -&gt; Result&lt;Transaction&lt;E&gt;&gt; {<br>        Transaction::begin_read_only(self.engine.clone(), None)<br>    }<br><br>    /// Begins a new read-only transaction as of the given version.<br>    pub fn begin_as_of(&amp;self, version: Version) -&gt; Result&lt;Transaction&lt;E&gt;&gt; {<br>        Transaction::begin_read_only(self.engine.clone(), Some(version))<br>    }<br>}</pre><p>兩者差異：</p><pre>begin_read_only()     → as_of = None      → 讀取最新版本<br>begin_as_of(v)        → as_of = Some(v)   → 時光旅行查詢，讀取歷史版本 v</pre><h4>核心實現</h4><pre>/// Begins a new read-only transaction. If version is given it will see the<br>/// state as of the beginning of that version (ignoring writes at that<br>/// version). In other words, it sees the same state as the read-write<br>/// transaction at that version saw when it began.<br>fn begin_read_only(engine: Arc&lt;Mutex&lt;E&gt;&gt;, as_of: Option&lt;Version&gt;) -&gt; Result&lt;Self&gt; {<br>    let mut session = engine.lock()?;<br><br>    // Fetch the latest version.<br>    let mut version = match session.get(&amp;Key::NextVersion.encode())? {<br>        Some(ref v) =&gt; Version::decode(v)?,<br>        None =&gt; 1,<br>    };<br><br>    // If requested, create the transaction as of a past version, restoring<br>    // the active snapshot as of the beginning of that version. Otherwise,<br>    // use the latest version and get the current, real-time snapshot.<br>    let mut active = BTreeSet::new();<br>    if let Some(as_of) = as_of {<br>        if as_of &gt;= version {<br>            return errinput!(&quot;version {as_of} does not exist&quot;);<br>        }<br>        version = as_of;<br>        if let Some(value) = session.get(&amp;Key::TxnActiveSnapshot(version).encode())? {<br>            active = BTreeSet::&lt;Version&gt;::decode(&amp;value)?;<br>        }<br>    } else {<br>        active = Self::scan_active(&amp;mut session)?;<br>    }<br><br>    drop(session);<br><br>    Ok(Self { engine, state: TransactionState { version, read_only: true, active } })<br>}</pre><h4>執行流程拆解</h4><p>步驟 1：取得最新版本號</p><pre>let mut version = match session.get(&amp;Key::NextVersion.encode())? {<br>    Some(ref v) =&gt; Version::decode(v)?,<br>    None =&gt; 1,<br>};</pre><pre>NextVersion 的意義：<br>- 指向「下一個讀寫事務會使用的版本號」<br>- 例如 NextVersion = 5，代表目前最新的已提交版本是 4<br><br>為什麼讀唯讀事務要讀 NextVersion：<br>- 確定當前資料庫的最新狀態<br>- 作為時光旅行查詢的上界（不能查詢未來版本）</pre><p>步驟 2：處理時光旅行查詢</p><p>這是 begin_read_only() 最特別的地方，支援兩種模式：</p><p>模式 A：讀取最新版本 (as_of = None)</p><pre>if let Some(as_of) = as_of {<br>    // ...<br>} else {<br>    active = Self::scan_active(&amp;mut session)?;  // 掃描當前活躍事務<br>}</pre><pre>流程：<br>1. 使用 NextVersion - 1 作為版本號<br>2. 掃描當前所有活躍事務 (TxnActive)<br>3. 建立即時快照<br><br>例子：<br>NextVersion = 5<br>TxnActive = {3, 4}<br><br>→ 唯讀事務版本 = 5<br>→ active = {3, 4}<br>→ 可以看到版本 1, 2 的寫入<br>→ 看不到版本 3, 4 的寫入（還在執行中）</pre><p>模式 B：時光旅行查詢 (as_of = Some(version))</p><pre>if let Some(as_of) = as_of {<br>    if as_of &gt;= version {<br>        return errinput!(&quot;version {as_of} does not exist&quot;);<br>    }<br>    version = as_of;<br>    if let Some(value) = session.get(&amp;Key::TxnActiveSnapshot(version).encode())? {<br>        active = BTreeSet::&lt;Version&gt;::decode(&amp;value)?;<br>    }<br>}</pre><pre>流程：<br>1. 檢查版本合法性（不能查詢未來）<br>2. 設定版本為 as_of<br>3. 從 TxnActiveSnapshot(as_of) 恢復當時的 active 快照<br>4. 如果快照不存在，active 為空（代表當時沒有並發事務）<br><br>例子：<br>NextVersion = 10<br>as_of = 5<br><br>→ 檢查：5 &lt; 10 ✓ 合法<br>→ version = 5<br>→ 讀取 TxnActiveSnapshot(5) = {2, 3}<br>→ active = {2, 3}<br><br>結果：看到的資料狀態與「版本 5 的讀寫事務開始時」完全一致</pre><p>步驟 3：建立唯讀事務</p><pre>Ok(Self {<br>    engine,<br>    state: TransactionState {<br>        version,<br>        read_only: true,  // 標記為唯讀<br>        active<br>    }<br>})</pre><pre>read_only: true 的影響：<br>1. 不能執行寫入操作（set/delete 會報錯）<br>2. 使用嚴格小於的可見性規則（version &lt; self.version）<br>3. 不會被記錄到 TxnActive（不佔用版本號）<br>4. 不需要 commit/rollback（直接 drop 即可）</pre><h4>與讀寫事務的差異對比</h4><pre>                讀寫事務 (begin)              唯讀事務 (begin_read_only)<br>================================================================================<br>版本分配        遞增，佔用版本號               不分配，使用現有版本號<br>                version = NextVersion          version = NextVersion (最新)<br>                NextVersion += 1               或 version = as_of (歷史)<br><br>活躍標記        寫入 TxnActive(version)        不寫入 TxnActive<br>                持有版本號直到 commit           不佔用資源<br><br>快照記錄        寫入 TxnActiveSnapshot         讀取 TxnActiveSnapshot（時光旅行）<br>                記錄當時的 active               或掃描當前 active（最新）<br><br>可見性規則      version &lt;= self.version        version &lt; self.version<br>                可以看到自己的寫入             不能有寫入<br><br>寫入權限        可寫                           唯讀<br><br>生命週期        需要 commit/rollback           不需要，直接 drop<br><br>並發影響        阻塞其他讀寫事務               不阻塞任何事務</pre><h4>時光旅行查詢實例</h4><p>假設當前狀態：</p><pre>版本歷史：<br>Version 1: INSERT INTO users VALUES (1, &#39;Alice&#39;)    [committed]<br>Version 2: INSERT INTO users VALUES (2, &#39;Bob&#39;)      [committed]<br>Version 3: UPDATE users SET name = &#39;Carol&#39; WHERE id = 1  [active]<br>Version 4: INSERT INTO users VALUES (3, &#39;David&#39;)    [active]<br><br>NextVersion = 5<br>TxnActive = {3, 4}<br>TxnActiveSnapshot(3) = {1, 2}  (假設)<br>TxnActiveSnapshot(4) = {1, 2, 3}</pre><p>查詢 1：讀取最新版本</p><pre>let txn = mvcc.begin_read_only()?;  // as_of = None</pre><pre>結果：<br>version = 5<br>active = {3, 4}<br><br>SELECT * FROM users:<br>→ 看到 Version 1, 2 的寫入<br>→ 看不到 Version 3, 4（在 active 中）<br><br>結果：<br>| id | name  |<br>|----|-------|<br>| 1  | Alice |<br>| 2  | Bob   |</pre><p>查詢 2：時光旅行到 Version 3</p><pre>let txn = mvcc.begin_as_of(3)?;  // as_of = Some(3)</pre><pre>結果：<br>version = 3<br>active = {1, 2}  (從 TxnActiveSnapshot(3) 恢復)<br><br>SELECT * FROM users:<br>→ 看不到 Version 1, 2（在 active 中）<br>→ 看不到 Version 3（自己的版本，唯讀不包含）<br>結果：空（Version 3 開始時還沒有任何已提交資料）</pre><p>查詢 3：時光旅行到 Version 2</p><pre>let txn = mvcc.begin_as_of(2)?;</pre><pre>結果：<br>version = 2<br>active = {}  (假設 Version 2 開始時沒有並發事務)<br><br>SELECT * FROM users:<br>→ 看到 Version 1（version 1 &lt; 2, 且 1 ∉ active）<br>→ 看不到 Version 2（自己的版本）<br><br>結果：<br>| id | name  |<br>|----|-------|<br>| 1  | Alice |</pre><h4>唯讀事務的優勢</h4><pre>性能優勢：<br>- 不佔用版本號               → 不會阻塞讀寫事務<br>- 不寫入 TxnActive            → 減少磁碟 I/O<br>- 不需要 commit/rollback      → 零清理成本<br>- 多個唯讀事務可完全並發      → 無鎖競爭<br><br>一致性保證：<br>- 快照隔離                   → 可重複讀<br>- 時光旅行查詢               → 審計與調試<br><br>使用場景：<br>- 分析查詢（長時間執行）<br>- 報表生成<br>- 資料備份<br>- 時間點恢復（Point-in-Time Recovery）<br>- 審計日誌查詢</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=801fdab644e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[toyDB: encoding]]></title>
            <link>https://medium.com/@wudiheroback/toydb-encoding-239e5f28a3cd?source=rss-83005aa59123------2</link>
            <guid isPermaLink="false">https://medium.com/p/239e5f28a3cd</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Stan Hsu]]></dc:creator>
            <pubDate>Wed, 22 Oct 2025 14:11:35 GMT</pubDate>
            <atom:updated>2025-10-22T14:11:35.013Z</atom:updated>
            <content:encoded><![CDATA[<h3>Module Structure Overview</h3><p>src/encoding/mod.rs defines the structure of the entire encoding module:</p><pre>//! Binary data encodings.<br>//!<br>//! * keycode: used for keys in the key/value store.<br>//! * bincode: used for values in the key/value store and network protocols.<br><br>pub mod bincode;<br>pub mod keycode;</pre><p>The two submodules serve distinct purposes:</p><ul><li>keycode: Order-preserving key encoding</li><li>bincode: Efficient value encoding</li></ul><h3>Value trait: Unified Interface for Values</h3><pre>/// Adds automatic Bincode encode/decode methods to value types. These are used<br>/// for values in key/value storage engines, and also for e.g. network protocol<br>/// messages and other values.<br>pub trait Value: Serialize + DeserializeOwned {<br>    /// Decodes a value from a byte slice using Bincode.<br>    fn decode(bytes: &amp;[u8]) -&gt; Result&lt;Self&gt; {<br>        bincode::deserialize(bytes)<br>    }<br><br>    /// Decodes a value from a reader using Bincode.<br>    fn decode_from&lt;R: Read&gt;(reader: R) -&gt; Result&lt;Self&gt; {<br>        bincode::deserialize_from(reader)<br>    }<br><br>    /// Decodes a value from a reader using Bincode, or returns None if the<br>    /// reader is closed.<br>    fn maybe_decode_from&lt;R: Read&gt;(reader: R) -&gt; Result&lt;Option&lt;Self&gt;&gt; {<br>        bincode::maybe_deserialize_from(reader)<br>    }<br><br>    /// Encodes a value to a byte vector using Bincode.<br>    fn encode(&amp;self) -&gt; Vec&lt;u8&gt; {<br>        bincode::serialize(self)<br>    }<br><br>    /// Encodes a value into a writer using Bincode.<br>    fn encode_into&lt;W: Write&gt;(&amp;self, writer: W) -&gt; Result&lt;()&gt; {<br>        bincode::serialize_into(writer, self)<br>    }<br>}</pre><p>Design Highlights:</p><ul><li>Unified Interface: All value types only need to implement Serialize + DeserializeOwned to automatically gain encode/decode methods</li><li>Internal bincode calls: Ensures all values use efficient encoding</li><li>DeserializeOwned instead of Deserialize&lt;’de&gt;: Value is used for network protocols and streaming reads</li></ul><pre>Reason              → Data comes from temporary buffers<br>decode_from(R)      → Owns the reader, destroyed after reading<br>                    → Cannot return results borrowing its internal data<br>Conclusion          → Decoded results must own all data</pre><ul><li>Streaming Operations: Provides decode_from and encode_into to support streaming from Read/Write</li></ul><pre>Definition      → Progressively read/write without loading all data at once<br>Use cases       → Network communication (read directly from TCP sockets)<br>                → Large file processing<br>Example         → Value::decode_from(tcp_stream) reads from network directly</pre><ul><li>Fault-tolerant Decoding: maybe_decode_from handles connection closure cases, returning Option&lt;T&gt;</li></ul><h3>Generic Implementations: Automatic Extension Support</h3><pre>/// Blanket implementations for various types wrapping a value type.<br>impl&lt;V: Value&gt; Value for Option&lt;V&gt; {}<br>impl&lt;V: Value&gt; Value for Result&lt;V&gt; {}<br>impl&lt;V: Value&gt; Value for Vec&lt;V&gt; {}<br>impl&lt;V1: Value, V2: Value&gt; Value for (V1, V2) {}<br>impl&lt;V: Value + Eq + Hash&gt; Value for HashSet&lt;V&gt; {}<br>impl&lt;V: Value + Eq + Ord + Hash&gt; Value for BTreeSet&lt;V&gt; {}</pre><p>Generic Magic:</p><p>As long as T implements Value, these wrapper types automatically implement Value.</p><p>Concrete Example:</p><p>Suppose you have a struct:</p><pre>#[derive(Serialize, Deserialize)]<br>struct User {<br>    id: u64,<br>    name: String,<br>}<br><br>impl Value for User {}</pre><p>Now, because of the generic implementations above, the following types automatically implement Value without additional code:</p><pre>// Option&lt;User&gt; automatically implements Value<br>let user: Option&lt;User&gt; = Some(User { id: 1, name: &quot;Alice&quot;.into() });<br>let bytes = user.encode();  // ✓ can call directly<br>let decoded: Option&lt;User&gt; = Value::decode(&amp;bytes)?;  // ✓ can decode directly<br><br>// Vec&lt;User&gt; automatically implements Value<br>let users: Vec&lt;User&gt; = vec![<br>    User { id: 1, name: &quot;Alice&quot;.into() },<br>    User { id: 2, name: &quot;Bob&quot;.into() },<br>];<br>let bytes = users.encode();  // ✓ can call directly<br>let decoded: Vec&lt;User&gt; = Value::decode(&amp;bytes)?;  // ✓ can decode directly<br>// (User, String) automatically implements Value<br>let pair: (User, String) = (User { id: 1, name: &quot;Alice&quot;.into() }, &quot;metadata&quot;.into());<br>let bytes = pair.encode();  // ✓ can call directly<br>let decoded: (User, String) = Value::decode(&amp;bytes)?;  // ✓ can decode directly<br>// Even nested types work<br>let complex: Option&lt;Vec&lt;User&gt;&gt; = Some(vec![User { id: 1, name: &quot;Alice&quot;.into() }]);<br>let bytes = complex.encode();  // ✓ can call directly<br>let decoded: Option&lt;Vec&lt;User&gt;&gt; = Value::decode(&amp;bytes)?;  // ✓ can decode directly</pre><p>Without these generic implementations, you’d need to manually write code for each combination:</p><pre>// Without generic implementations, you&#39;d need to manually write these (very tedious):<br>impl Value for Option&lt;User&gt; {}<br>impl Value for Vec&lt;User&gt; {}<br>impl Value for (User, String) {}<br>impl Value for Option&lt;Vec&lt;User&gt;&gt; {}<br>// ... endless combinations</pre><p>This is the power of blanket implementations: Implementing a trait for all types meeting certain conditions at once, greatly reducing boilerplate code.</p><h3>Bincode: Efficient Value Encoding</h3><p>src/encoding/bincode.rs is a thin wrapper around the bincode crate.</p><h3>Configuration and Design Philosophy</h3><pre>/// Use the standard Bincode configuration.<br>const CONFIG: bincode::config::Configuration = bincode::config::standard();</pre><p>standard() configuration:</p><ul><li>Little-endian: Matches most modern CPU architectures</li><li>Fixed-size integers: Does not use varint compression</li></ul><pre>varint          → Variable-length encoding (small → few bytes, large → many bytes)<br>Bincode choice  → Fixed size (u64 always 8 bytes)<br>Advantage       → Faster encoding/decoding<br>Disadvantage    → Small numbers waste space</pre><h3>Core Function Implementations</h3><p>serialize function: Serialize to vector</p><pre>/// Serializes a value using Bincode.<br>pub fn serialize&lt;T: Serialize&gt;(value: &amp;T) -&gt; Vec&lt;u8&gt; {<br>    // Panic on failure, as this is a problem with the data structure.<br>    bincode::serde::encode_to_vec(value, CONFIG).expect(&quot;value must be serializable&quot;)<br>}</pre><p>Design decisions:</p><ul><li>Panic instead of Result: Serialization failure is considered a program error (data structure definition issue)</li><li>expect message: Clearly indicates the reason for failure</li></ul><p>deserialize function: Deserialize from byte slice</p><pre>/// Deserializes a value using Bincode.<br>pub fn deserialize&lt;&#39;de, T: Deserialize&lt;&#39;de&gt;&gt;(bytes: &amp;&#39;de [u8]) -&gt; Result&lt;T&gt; {<br>    Ok(bincode::serde::borrow_decode_from_slice(bytes, CONFIG)?.0)<br>}</pre><p>Implementation details:</p><ul><li>borrow_decode_from_slice: Zero-copy deserialization, returns (T, usize)</li><li>.0: Only takes the value, ignoring the bytes read count</li><li>Returns Result: Deserialization may fail due to corrupted data</li></ul><p>serialize_into / deserialize_from functions: Streaming operations</p><pre>/// Serializes a value to a writer using Bincode.<br>pub fn serialize_into&lt;W: Write, T: Serialize&gt;(mut writer: W, value: &amp;T) -&gt; Result&lt;()&gt; {<br>    bincode::serde::encode_into_std_write(value, &amp;mut writer, CONFIG)?;<br>    Ok(())<br>}<br><br>/// Deserializes a value from a reader using Bincode.<br>pub fn deserialize_from&lt;R: Read, T: DeserializeOwned&gt;(mut reader: R) -&gt; Result&lt;T&gt; {<br>    Ok(bincode::serde::decode_from_std_read(&amp;mut reader, CONFIG)?)<br>}</pre><p>Advantages of streaming operations:</p><ul><li>No need to load all data into memory at once</li><li>Suitable for network protocols (reading directly from TCP sockets)</li><li>Suitable for large file processing</li></ul><p>maybe_deserialize_from function: Fault-tolerant deserialization</p><pre>/// Deserializes a value from a reader using Bincode, or returns None if the<br>/// reader is closed.<br>pub fn maybe_deserialize_from&lt;R: Read, T: DeserializeOwned&gt;(mut reader: R) -&gt; Result&lt;Option&lt;T&gt;&gt; {<br>    match bincode::serde::decode_from_std_read(&amp;mut reader, CONFIG) {<br>        Ok(t) =&gt; Ok(Some(t)),<br>        Err(bincode::error::DecodeError::Io { inner, .. })<br>            if inner.kind() == std::io::ErrorKind::UnexpectedEof<br>                || inner.kind() == std::io::ErrorKind::ConnectionReset =&gt;<br>        {<br>            Ok(None)<br>        }<br>        Err(err) =&gt; Err(Error::from(err)),<br>    }<br>}</pre><p>Error handling logic:</p><ul><li>Success: Returns Ok(Some(value))</li><li>Connection closed: UnexpectedEof or ConnectionReset → Returns Ok(None)</li><li>Other errors: Returns Err</li></ul><p>This function is specifically designed for network communication: when a client disconnects, it’s not treated as an error but returns None normally.</p><h3>Why Bincode is Unsuitable for Key Encoding</h3><p>Let’s understand through experiments why Bincode cannot be used for key encoding. These issues are precisely why we need to introduce Keycode.</p><p>Experiment 1: Little-endian breaks order</p><pre>use toydb::encoding::bincode;<br><br>let val1: u64 = 1;<br>let val2: u64 = 256;<br>let bytes1 = bincode::serialize(&amp;val1);<br>let bytes2 = bincode::serialize(&amp;val2);<br>println!(&quot;{:?}&quot;, bytes1); // [01, 00, 00, 00, 00, 00, 00, 00]<br>println!(&quot;{:?}&quot;, bytes2); // [00, 01, 00, 00, 00, 00, 00, 00]<br>// Byte comparison: bytes1 &gt; bytes2<br>// But actually: 1 &lt; 256  X Order is wrong!</pre><p>Reason: Little-endian places the low-order byte first, bytes1[0] = 0x01 &gt; bytes2[0] = 0x00.</p><p>Experiment 2: Variable-length encoding breaks order</p><pre>let s1 = &quot;a&quot;;<br>let s2 = &quot;aa&quot;;<br>let s3 = &quot;b&quot;;<br><br>let b1 = bincode::serialize(&amp;s1); // [1, 0, 0, 0, 0, 0, 0, 0, &#39;a&#39;]      length + content<br>let b2 = bincode::serialize(&amp;s2); // [2, 0, 0, 0, 0, 0, 0, 0, &#39;a&#39;, &#39;a&#39;]<br>let b3 = bincode::serialize(&amp;s3); // [1, 0, 0, 0, 0, 0, 0, 0, &#39;b&#39;]<br>// Lexicographic order: &#39;a&#39; &lt; &#39;aa&#39; &lt; &#39;b&#39;<br>// Byte comparison: b1 &lt; b2 ✓, but b2 &gt; b3 X (should be &#39;aa&#39; &lt; &#39;b&#39;)<br>// Problem: length prefix [2...] &gt; [1...]</pre><p>Experiment 3: Sign bit breaks negative number order</p><pre>let n1: i64 = -1;<br>let n2: i64 = 0;<br>let n3: i64 = 1;<br><br>let b1 = bincode::serialize(&amp;n1); // [ff, ff, ff, ff, ff, ff, ff, ff]<br>let b2 = bincode::serialize(&amp;n2); // [00, 00, 00, 00, 00, 00, 00, 00]<br>let b3 = bincode::serialize(&amp;n3); // [01, 00, 00, 00, 00, 00, 00, 00]<br>// Byte comparison: b1 &gt; b3 &gt; b2<br>// Result: -1 &gt; 1 &gt; 0  X Completely wrong!</pre><p>Conclusion: Bincode’s design goal is efficient serialization, completely disregarding lexicographic order. For key/value storage engines, we need to perform range queries and prefix scans based on key order, which requires an encoding method that preserves lexicographic order. This is precisely why Keycode exists.</p><h3>Key trait: Unified Interface for Keys</h3><pre>/// Adds automatic Keycode encode/decode methods to key enums. These are used<br>/// as keys in the key/value store.<br>pub trait Key&lt;&#39;de&gt;: Serialize + Deserialize&lt;&#39;de&gt; {<br>    /// Decodes a key from a byte slice using Keycode.<br>    fn decode(bytes: &amp;&#39;de [u8]) -&gt; Result&lt;Self&gt; {<br>        keycode::deserialize(bytes)<br>    }<br><br>    /// Encodes a key to a byte vector using Keycode.<br>    ///<br>    /// In the common case, the encoded key is borrowed for a storage engine<br>    /// call and then thrown away. We could avoid a bunch of allocations by<br>    /// taking a reusable byte vector to encode into and return a reference to<br>    /// it, but we keep it simple.<br>    fn encode(&amp;self) -&gt; Vec&lt;u8&gt; {<br>        keycode::serialize(self)<br>    }<br>}</pre><p>Design Highlights:</p><ul><li>Unified Interface: All key types only need to implement Serialize + Deserialize to automatically gain encode/decode methods</li><li>Internal keycode calls: Ensures all keys use order-preserving encoding</li><li>Differences from Value trait: Key trait design differences</li></ul><pre>Lifetime        → Has &#39;de parameter (allows zero-copy deserialization)<br>Trait bound     → Uses Deserialize&lt;&#39;de&gt; instead of DeserializeOwned<br>Reason          → Keys read from memory-mapped files or persistent buffers<br>                → Data has sufficiently long lifetimes</pre><p>Comment interpretation:</p><pre>/// In the common case, the encoded key is borrowed for a storage engine<br>/// call and then thrown away. We could avoid a bunch of allocations by<br>/// taking a reusable byte vector to encode into and return a reference to<br>/// it, but we keep it simple.</pre><p>This comment explains a potential performance optimization: you could pass in a reusable Vec&lt;u8&gt; to avoid allocations, but for simplicity it chooses to allocate a new vector each time. This is toyDB&#39;s design philosophy: simplicity over performance.</p><h3>Keycode: Order-preserving Key Encoding</h3><p>src/encoding/keycode.rs is toyDB&#39;s own implementation of an order-preserving encoding system.</p><h3>Design Goals and Implementation Strategy</h3><pre>//! Keycode is a lexicographical order-preserving binary encoding for use with<br>//! keys in key/value stores. It is designed for simplicity, not efficiency<br>//! (i.e. it does not use varints or other compression methods).</pre><p>Core Design Principles:</p><ul><li>Lexicographic order preservation: a &lt; b ⇔ encode(a) &lt; encode(b) (byte-wise comparison)</li><li>Simplicity first: Does not use varint compression, fixed-length encoding</li><li>Supports range scanning: Foundation for prefix scanning and range queries</li></ul><h3>Core Function Implementations</h3><p>serialize function: Serialize keys</p><pre>/// Serializes a key to a binary Keycode representation.<br>pub fn serialize&lt;T: Serialize&gt;(key: &amp;T) -&gt; Vec&lt;u8&gt; {<br>    let mut serializer = Serializer { output: Vec::new() };<br>    // Panic on failure, as this is a problem with the data structure.<br>    key.serialize(&amp;mut serializer).expect(&quot;key must be serializable&quot;);<br>    serializer.output<br>}</pre><p>Implementation pattern:</p><ul><li>Create Serializer structure (contains output buffer)</li><li>Call key.serialize(&amp;mut serializer) (Serde mechanism)</li><li>Return serialization result</li></ul><p>deserialize function: Deserialize keys</p><pre>/// Deserializes a key from a binary Keycode representation.<br>pub fn deserialize&lt;&#39;a, T: Deserialize&lt;&#39;a&gt;&gt;(input: &amp;&#39;a [u8]) -&gt; Result&lt;T&gt; {<br>    let mut deserializer = Deserializer::from_bytes(input);<br>    let t = T::deserialize(&amp;mut deserializer)?;<br>    if !deserializer.input.is_empty() {<br>        return errdata!(<br>            &quot;unexpected trailing bytes {:x?} at end of key {input:x?}&quot;,<br>            deserializer.input,<br>        );<br>    }<br>    Ok(t)<br>}</pre><p>Code Explanation</p><p>Function Signature</p><pre>pub fn deserialize&lt;&#39;a, T: Deserialize&lt;&#39;a&gt;&gt;(input: &amp;&#39;a [u8]) -&gt; Result&lt;T&gt;</pre><ul><li>&#39;a: Lifetime parameter, allows returned T to borrow data from input (zero-copy)</li><li>T: Deserialize&lt;&#39;a&gt;: Target type must implement Deserialize trait</li><li>input: &amp;&#39;a [u8]: Byte slice to decode</li><li>Result&lt;T&gt;: Returns decoded value on success, error on failure</li></ul><p>Step 1: Create Deserializer</p><pre>let mut deserializer = Deserializer::from_bytes(input);</pre><p>Creates a Deserializer object to wrap the input:</p><pre>// Deserializer structure (simplified)<br>struct Deserializer&lt;&#39;de&gt; {<br>    input: &amp;&#39;de [u8],  // Points to remaining unparsed bytes<br>}<br><br>impl&lt;&#39;de&gt; Deserializer&lt;&#39;de&gt; {<br>    fn from_bytes(input: &amp;&#39;de [u8]) -&gt; Self {<br>        Self { input }<br>    }<br>}</pre><ul><li>input initially points to the entire byte slice</li><li>As parsing proceeds, input progressively moves forward (consuming bytes)</li></ul><p>Step 2: Call type’s deserialize method</p><pre>let t = T::deserialize(&amp;mut deserializer)?;</pre><p>This is the key step!</p><p>Syntax parsing:</p><ul><li>T::deserialize: Associated function call (not an instance method)</li><li>Equivalent to: &lt;T as Deserialize&gt;::deserialize(&amp;mut deserializer)</li><li>Automatically generated by Serde via #[derive(Deserialize)]</li></ul><p>What actually happens:</p><p>Assuming T = Key enum, the code generated by Serde looks like:</p><pre>impl&lt;&#39;de&gt; Deserialize&lt;&#39;de&gt; for Key&lt;&#39;de&gt; {<br>    fn deserialize&lt;D&gt;(deserializer: D) -&gt; Result&lt;Self, D::Error&gt;<br>    where<br>        D: serde::Deserializer&lt;&#39;de&gt;,<br>    {<br>        // Serde calls the corresponding deserialize_* method based on type<br>        deserializer.deserialize_enum(<br>            &quot;Key&quot;,<br>            &amp;[&quot;NextVersion&quot;, &quot;TxnActive&quot;, ...],<br>            KeyVisitor,<br>        )<br>    }<br>}</pre><p>Serde’s call chain:</p><pre>T::deserialize(&amp;mut deserializer)<br>  ↓<br>deserializer.deserialize_enum(...)  // Choose method based on T&#39;s type<br>  ↓<br>KeyVisitor::visit_enum(...)         // Visitor pattern constructs final value<br>  ↓<br>Returns Key::TxnActive(5)</pre><p>Step 3: Check remaining bytes</p><pre>if !deserializer.input.is_empty() {<br>    return errdata!(<br>        &quot;unexpected trailing bytes {:x?} at end of key {input:x?}&quot;,<br>        deserializer.input,<br>    );<br>}</pre><p>Why is this check needed:</p><ul><li>Ensures all bytes have been consumed</li><li>If there are remaining bytes, it indicates input data format error or type mismatch</li></ul><p>Error example:</p><pre>// Key::NextVersion encoding only needs [0x00, 0x00]<br>// But input contains extra garbage bytes<br>let bad_input = [0x00, 0x00, 0xFF, 0xFF];<br>                              ^^^^^^^^ Extra bytes<br><br>let result: Result&lt;Key&gt; = deserialize(&amp;bad_input);<br>// Error: unexpected trailing bytes [ff, ff] at end of key [00, 00, ff, ff]</pre><p>Step 4: Return result</p><pre>Ok(t)</pre><p>After all checks pass, return the decoded value.</p><h3>Serializer/Deserializer Implementation</h3><p>Keycode fully implements the serde::Serializer and serde::Deserializer traits according to Serde framework specifications. Serde defines a unified serialization interface, allowing different formats (JSON, Bincode, Keycode) to handle arbitrary Rust types the same way.</p><p>How it works:</p><pre>// Serialization flow<br>keycode::serialize(value)<br>  → Serde calls corresponding serialize_* method based on type<br>  → Keycode encodes output according to order-preserving rules<br><br>// Deserialization flow<br>keycode::deserialize(bytes)<br>  → Serde calls corresponding deserialize_* method based on target type<br>  → Keycode parses bytes according to rules to restore original value</pre><p>Complete Serializer/Deserializer implementation details in source code: <a href="https://github.com/erikgrinaker/toydb/blob/master/src/encoding/keycode.rs">keycode.rs</a></p><h3>Byte Slice Encoding/Decoding: Most Complex Case</h3><p>Byte slices (&amp;[u8], String) are the most complex type in Keycode, reasons:</p><ul><li>Variable length: Cannot predict how many bytes will be occupied</li><li>Need terminator: Marks the end position of the string</li><li>Terminator collision: Data itself may contain terminator bytes, needs escaping</li><li>Preserve lexicographic order: Encoded byte order must match original lexicographic order</li></ul><p>Encoding Implementation</p><pre>// Strings are encoded like bytes.<br>fn serialize_str(self, v: &amp;str) -&gt; Result&lt;()&gt; {<br>    self.serialize_bytes(v.as_bytes())<br>}<br><br>// Byte slices are terminated by 0x0000, escaping 0x00 as 0x00ff. This<br>// ensures that we can detect the end, and that for two overlapping slices,<br>// the shorter one orders before the longer one.<br>//<br>// We can&#39;t use e.g. length prefix encoding, since it doesn&#39;t sort correctly.<br>fn serialize_bytes(self, v: &amp;[u8]) -&gt; Result&lt;()&gt; {<br>    let bytes = v<br>        .iter()<br>        .flat_map(|&amp;byte| match byte {<br>            0x00 =&gt; Either::Left([0x00, 0xff].into_iter()),<br>            byte =&gt; Either::Right([byte].into_iter()),<br>        })<br>        .chain([0x00, 0x00]);<br>    self.output.extend(bytes);<br>    Ok(())<br>}</pre><p>Code explanation:</p><ul><li>v.iter(): Iterate over each byte of the input byte slice</li><li>flat_map(|&amp;byte| ...): Map each byte to an iterator of one or more bytes</li></ul><pre>&amp;byte          → Dereference &amp;u8 → u8<br>flat_map       → Flattens all iterators into a single sequence</pre><ul><li>match byte: Decide output based on byte value</li></ul><pre>0x00 → Either::Left([0x00, 0xff].into_iter())    // Escape to two bytes<br>byte → Either::Right([byte].into_iter())         // Keep unchanged</pre><ul><li>Either&lt;L, R&gt;: Unifies different length iterator types so flat_map can handle them</li><li>.chain([0x00, 0x00]): Append terminator</li><li>self.output.extend(bytes): Write all bytes to output</li></ul><p>Complete execution example:</p><pre>// Input: &quot;a\x00b&quot; = [0x61, 0x00, 0x62]<br><br>v.iter()             // 0x61, 0x00, 0x62<br>  .flat_map(...)     // 0x61, 0x00, 0xff, 0x62<br>                     //      ^^^^^ 0x00 escaped to 0x00 0xff<br>  .chain([0x00, 0x00]) // 0x61, 0x00, 0xff, 0x62, 0x00, 0x00<br>                     //                            ^^^^^ terminator<br>// Final output: [0x61, 0x00, 0xff, 0x62, 0x00, 0x00]</pre><p>Encoding rules:</p><ul><li>0x00 in data → Encoded as 0x00 0xff</li><li>Other bytes → Output directly</li><li>End of string → Append terminator 0x00 0x00</li></ul><p>Why can’t length prefix be used?</p><p>Length prefix breaks lexicographic order:</p><pre>// Length prefix encoding (wrong)<br>&quot;a&quot;  → [01 00 00 00 00 00 00 00 61]<br>&quot;aa&quot; → [02 00 00 00 00 00 00 00 61 61]<br>&quot;b&quot;  → [01 00 00 00 00 00 00 00 62]<br><br>// Byte comparison: &quot;aa&quot; vs &quot;b&quot; → 02 &gt; 01  ❌ Wrong!<br>// Correct order should be: &quot;aa&quot; &lt; &quot;b&quot;</pre><p>Null-terminated encoding preserves lexicographic order:</p><pre>&quot;a&quot;  → [61 00 00]        // &#39;a&#39; + terminator<br>&quot;aa&quot; → [61 61 00 00]     // &#39;aa&#39; + terminator<br>&quot;b&quot;  → [62 00 00]        // &#39;b&#39; + terminator<br><br>// Byte comparison:<br>// &quot;a&quot; vs &quot;aa&quot;: [61 00] &lt; [61 61]  ✓ Correct<br>// &quot;aa&quot; vs &quot;b&quot;: [61 61] &lt; [62 00]  ✓ Correct</pre><p>Why escape 0x00?</p><p>Problem: Data itself may contain 0x00, which would be confused with terminator 0x00 0x00</p><pre>// If not escaped (wrong)<br>&quot;a\x00b&quot; → [61 00 62 00 00]<br>           //    ^^ Decoder mistakes this for terminator!<br>           // Only decodes &quot;a&quot;, loses &quot;b&quot;</pre><p>Solution: Escape 0x00 in data</p><pre>// Correct escaping<br>&quot;a\x00b&quot; → [61 00 ff 62 00 00]<br>          //    ^^^^^ Escape sequence (0x00 in data)<br>          //             ^^^^^ Terminator (end of string)</pre><p>Encoding examples:</p><pre>&quot;&quot;           → [00 00]<br>&quot;a&quot;          → [61 00 00]<br>&quot;ab&quot;         → [61 62 00 00]<br>&quot;a\x00b&quot;     → [61 00 ff 62 00 00]<br>&quot;\x00&quot;       → [00 ff 00 00]<br>&quot;\x00\x00&quot;   → [00 ff 00 ff 00 00]</pre><p>Decoding Implementation</p><p>In the source code, decoding is split into two parts: public methods calling internal helper functions</p><p>Public methods (required by Serde trait):</p><pre>fn deserialize_bytes&lt;V: Visitor&lt;&#39;de&gt;&gt;(self, visitor: V) -&gt; Result&lt;V::Value&gt; {<br>    let bytes = self.decode_next_bytes()?;  // Call helper function<br>    visitor.visit_bytes(&amp;bytes)             // Pass result to visitor for processing<br>}<br><br>fn deserialize_byte_buf&lt;V: Visitor&lt;&#39;de&gt;&gt;(self, visitor: V) -&gt; Result&lt;V::Value&gt; {<br>    let bytes = self.decode_next_bytes()?;<br>    visitor.visit_byte_buf(bytes)<br>}<br>fn deserialize_string&lt;V: Visitor&lt;&#39;de&gt;&gt;(self, visitor: V) -&gt; Result&lt;V::Value&gt; {<br>    let bytes = self.decode_next_bytes()?;<br>    visitor.visit_str(&amp;String::from_utf8(bytes)?)<br>}</pre><p>Visitor Pattern Explanation:</p><p>visitor is Serde&#39;s Visitor pattern implementation, used to convert decoded data to the target type:</p><pre>// Serde&#39;s Visitor trait (simplified)<br>pub trait Visitor&lt;&#39;de&gt; {<br>    type Value;  // Final return type<br><br>    // Borrow byte slice<br>    fn visit_bytes&lt;E&gt;(self, v: &amp;[u8]) -&gt; Result&lt;Self::Value, E&gt;;<br>    // Own byte vector<br>    fn visit_byte_buf&lt;E&gt;(self, v: Vec&lt;u8&gt;) -&gt; Result&lt;Self::Value, E&gt;;<br>    // Borrow string slice<br>    fn visit_str&lt;E&gt;(self, v: &amp;str) -&gt; Result&lt;Self::Value, E&gt;;<br>    // ... other visit_* methods<br>}</pre><p>Workflow:</p><ul><li>Deserializer decodes bytes:</li></ul><pre>let bytes = self.decode_next_bytes()?;  // [0x61, 0x00, 0x62] → &quot;a\x00b&quot;</pre><ul><li>Visitor constructs target type:</li></ul><pre>visitor.visit_bytes(&amp;bytes)  // Convert &amp;[u8] to target type</pre><ul><li>Call different visit methods based on target type:</li></ul><pre>// If target is Vec&lt;u8&gt;<br>visitor.visit_byte_buf(bytes) → Vec&lt;u8&gt;<br><br>// If target is String<br>visitor.visit_str(&amp;String::from_utf8(bytes)?) → String<br><br>// If target is &amp;[u8] (borrowed)<br>visitor.visit_bytes(&amp;bytes) → &amp;[u8]</pre><p>Why is Visitor needed?</p><p>This is Serde’s two-phase decoding design:</p><pre>Phase 1: Deserializer parses byte format<br>   ↓<br>Phase 2: Visitor constructs target type</pre><p>Core decoding logic (helper function):</p><pre>/// Decodes and chops off the next encoded byte slice.<br>fn decode_next_bytes(&amp;mut self) -&gt; Result&lt;Vec&lt;u8&gt;&gt; {<br>    let mut decoded = Vec::new();<br>    let mut iter = self.input.iter().enumerate();<br>    let taken = loop {<br>        match iter.next() {<br>            Some((_, 0x00)) =&gt; match iter.next() {<br>                Some((i, 0x00)) =&gt; break i + 1,        // Terminator, return read position<br>                Some((_, 0xff)) =&gt; decoded.push(0x00), // Escape, restore to 0x00<br>                _ =&gt; return errdata!(&quot;invalid escape sequence&quot;),<br>            },<br>            Some((_, b)) =&gt; decoded.push(*b),          // Regular byte<br>            None =&gt; return errdata!(&quot;unexpected end of input&quot;),<br>        }<br>    };<br>    self.input = &amp;self.input[taken..];  // Update input, skip decoded part<br>    Ok(decoded)<br>}</pre><p>Code explanation:</p><ul><li>iter().enumerate(): Iterate over bytes while recording position. The position is needed to know how many bytes were consumed after decoding.</li><li>Loop processing bytes:</li></ul><pre>match iter.next() {<br>    Some((_, 0x00)) =&gt; { /* Encountered possible terminator or escape */ }<br>    Some((_, b))    =&gt; { /* Regular byte */ }<br>    None            =&gt; { /* Unexpected end */ }<br>}</pre><ul><li>Check next byte when encountering 0x00:</li></ul><pre>Some((_, 0x00)) =&gt; match iter.next() {<br>    Some((i, 0x00)) =&gt; break i + 1,        // [00 00] → terminator<br>    Some((_, 0xff)) =&gt; decoded.push(0x00), // [00 ff] → escaped 0x00<br>    _               =&gt; return errdata!(&quot;invalid escape sequence&quot;),<br>}</pre><ul><li>break i + 1: Returns number of bytes consumed</li></ul><pre>i          → Index of the second 0x00<br>i + 1      → Total bytes to skip (including both terminator bytes)</pre><ul><li>self.input = &amp;self.input[taken..]: Update input slice</li></ul><pre>Action      → Skip decoded bytes<br>Purpose     → Prepare for next decode</pre><p>Decoding example:</p><pre>// Input: [61 00 ff 62 00 00]<br>// Decode &quot;a\x00b&quot;<br><br>iter.next() → (0, 0x61)  → decoded.push(0x61)  // &#39;a&#39;<br>iter.next() → (1, 0x00)  → Encountered 0x00, check next<br>iter.next() → (2, 0xff)  → decoded.push(0x00)  // Escape, restore to \x00<br>iter.next() → (3, 0x62)  → decoded.push(0x62)  // &#39;b&#39;<br>iter.next() → (4, 0x00)  → Encountered 0x00, check next<br>iter.next() → (5, 0x00)  → break 6             // Terminator, return position 6<br><br>// decoded = [0x61, 0x00, 0x62] = &quot;a\x00b&quot;<br>// self.input updated: skip first 6 bytes</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=239e5f28a3cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【知其然，更知其所以然】toyDB：Encoding 源碼解析]]></title>
            <link>https://medium.com/@wudiheroback/toydb-encoding-cf850fd58df0?source=rss-83005aa59123------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf850fd58df0</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Stan Hsu]]></dc:creator>
            <pubDate>Wed, 22 Oct 2025 13:41:49 GMT</pubDate>
            <atom:updated>2025-10-22T13:41:49.254Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>模塊結構概覽</strong></h3><p>src/encoding/mod.rs 定義了整個編碼模塊的結構，兩個子模塊各司其職:</p><p>- <strong>keycode</strong>:保序的鍵編碼</p><p>- <strong>bincode</strong>:高效的值編碼</p><h3>Value trait:值的統一接口</h3><pre>/// Adds automatic Bincode encode/decode methods to value types. These are used<br>/// for values in key/value storage engines, and also for e.g. network protocol<br>/// messages and other values.<br>pub trait Value: Serialize + DeserializeOwned {<br>    /// Decodes a value from a byte slice using Bincode.<br>    fn decode(bytes: &amp;[u8]) -&gt; Result&lt;Self&gt; {<br>        bincode::deserialize(bytes)<br>    }<br><br>    /// Decodes a value from a reader using Bincode.<br>    fn decode_from&lt;R: Read&gt;(reader: R) -&gt; Result&lt;Self&gt; {<br>        bincode::deserialize_from(reader)<br>    }<br><br>    /// Decodes a value from a reader using Bincode, or returns None if the<br>    /// reader is closed.<br>    fn maybe_decode_from&lt;R: Read&gt;(reader: R) -&gt; Result&lt;Option&lt;Self&gt;&gt; {<br>        bincode::maybe_deserialize_from(reader)<br>    }<br><br>    /// Encodes a value to a byte vector using Bincode.<br>    fn encode(&amp;self) -&gt; Vec&lt;u8&gt; {<br>        bincode::serialize(self)<br>    }<br><br>    /// Encodes a value into a writer using Bincode.<br>    fn encode_into&lt;W: Write&gt;(&amp;self, writer: W) -&gt; Result&lt;()&gt; {<br>        bincode::serialize_into(writer, self)<br>    }<br>}</pre><p>設計要點:</p><p>1.統一接口:所有值類型只需實現 Serialize + DeserializeOwned,自動獲得編解碼方法</p><p>2.內部調用 bincode:保證所有值使用高效編碼</p><p>3.DeserializeOwned 而非 Deserialize&lt;&#39;de&gt;:</p><ul><li>原因:Value 用於網絡協議和流式讀取,數據來自臨時緩衝區</li><li>decode_from(reader: R) 擁有 reader,讀取後 reader 被銷毀,無法返回借用其內部數據的結果</li><li>所以解碼結果必須擁有所有數據,不能依賴任何借用</li></ul><p>4.流式操作:提供 decode_from 和 encode_into,支持從 Read/Write 流式處理</p><ul><li>流式處理:逐步讀取/寫入數據,不需要一次性加載整個數據到內存</li><li>適合網絡通信(從 TCP socket 直接讀取)和大文件處理</li><li>例如:Value::decode_from(tcp_stream) 直接從網絡讀取,而非先緩衝再解碼</li></ul><p>5.容錯解碼:maybe_decode_from 處理連接關閉的情況,返回 Option&lt;T&gt;</p><h3>泛型實現:自動擴展支持</h3><pre>/// Blanket implementations for various types wrapping a value type.<br>impl&lt;V: Value&gt; Value for Option&lt;V&gt; {}<br>impl&lt;V: Value&gt; Value for Result&lt;V&gt; {}<br>impl&lt;V: Value&gt; Value for Vec&lt;V&gt; {}<br>impl&lt;V1: Value, V2: Value&gt; Value for (V1, V2) {}<br>impl&lt;V: Value + Eq + Hash&gt; Value for HashSet&lt;V&gt; {}<br>impl&lt;V: Value + Eq + Ord + Hash&gt; Value for BTreeSet&lt;V&gt; {}</pre><p>泛型魔法:</p><p>只要 T 實現了 Value,這些包裝類型自動實現 Value。</p><p>具體例子:</p><p>假設你有一個結構體:</p><pre>#[derive(Serialize, Deserialize)]<br>struct User {<br>    id: u64,<br>    name: String,<br>}<br><br>impl Value for User {}</pre><p>現在,因為有了上面的泛型實現,下面這些類型自動實現了 Value,不需要再寫代碼:</p><pre>// 1. Option&lt;User&gt; 自動實現 Value<br>let user: Option&lt;User&gt; = Some(User { id: 1, name: &quot;Alice&quot;.into() });<br>let bytes = user.encode();  // ✓ 可以直接調用<br>let decoded: Option&lt;User&gt; = Value::decode(&amp;bytes)?;  // ✓ 可以直接解碼<br><br>// 2. Vec&lt;User&gt; 自動實現 Value<br>let users: Vec&lt;User&gt; = vec![<br>    User { id: 1, name: &quot;Alice&quot;.into() },<br>    User { id: 2, name: &quot;Bob&quot;.into() },<br>];<br>let bytes = users.encode();  // ✓ 可以直接調用<br>let decoded: Vec&lt;User&gt; = Value::decode(&amp;bytes)?;  // ✓ 可以直接解碼<br><br>// 3. (User, String) 自動實現 Value<br>let pair: (User, String) = (User { id: 1, name: &quot;Alice&quot;.into() }, &quot;metadata&quot;.into());<br>let bytes = pair.encode();  // ✓ 可以直接調用<br>let decoded: (User, String) = Value::decode(&amp;bytes)?;  // ✓ 可以直接解碼<br><br>// 4. 甚至嵌套也可以<br>let complex: Option&lt;Vec&lt;User&gt;&gt; = Some(vec![User { id: 1, name: &quot;Alice&quot;.into() }]);<br>let bytes = complex.encode();  // ✓ 可以直接調用<br>let decoded: Option&lt;Vec&lt;User&gt;&gt; = Value::decode(&amp;bytes)?;  // ✓ 可以直接解碼</pre><p>如果沒有這些泛型實現,你需要手動為每個組合寫代碼:</p><pre>// 如果沒有泛型實現,需要手動寫這些(非常繁瑣):<br>impl Value for Option&lt;User&gt; {}<br>impl Value for Vec&lt;User&gt; {}<br>impl Value for (User, String) {}<br>impl Value for Option&lt;Vec&lt;User&gt;&gt; {}<br>// ... 無窮無盡的組合</pre><p>這就是 blanket implementation 的威力:一次性為所有符合條件的類型實現 trait,極大減少樣板代碼。</p><h3>Bincode:高效值編碼</h3><p>src/encoding/bincode.rs 是對 bincode crate 的薄封裝。</p><h4>配置與設計理念</h4><pre>/// Use the standard Bincode configuration.<br>const CONFIG: bincode::config::Configuration = bincode::config::standard();</pre><p>standard() 配置:</p><ul><li>小端序(little-endian):符合大多數現代 CPU 架構</li><li>固定大小整數:不使用 varint 壓縮</li><li>varint (variable-length integer):變長整數編碼,小數字用少字節,大數字用多字節</li><li>Bincode 選擇固定大小:u64 永遠 8 字節,無論值大小</li><li>優點:編碼/解碼更快;缺點:小數字佔用較多空間</li></ul><h3>核心函數實現</h3><p><strong>serialize 函數:序列化到向量</strong></p><pre>/// Serializes a value using Bincode.<br>pub fn serialize&lt;T: Serialize&gt;(value: &amp;T) -&gt; Vec&lt;u8&gt; {<br>    // Panic on failure, as this is a problem with the data structure.<br>    bincode::serde::encode_to_vec(value, CONFIG).expect(&quot;value must be serializable&quot;)<br>}</pre><p>設計決策:</p><ul><li>Panic 而非 Result:序列化失敗被視為程序錯誤(數據結構定義問題)</li><li>expect 訊息:明確說明失敗原因</li></ul><p><strong>deserialize 函數:從字節切片反序列化</strong></p><pre>/// Deserializes a value using Bincode.<br>pub fn deserialize&lt;&#39;de, T: Deserialize&lt;&#39;de&gt;&gt;(bytes: &amp;&#39;de [u8]) -&gt; Result&lt;T&gt; {<br>    Ok(bincode::serde::borrow_decode_from_slice(bytes, CONFIG)?.0)<br>}</pre><p>實現細節:</p><ul><li>borrow_decode_from_slice:零拷貝反序列化,返回 (T, usize)</li><li>.0:只取值,忽略已讀字節數</li><li>返回 Result:反序列化可能因數據損壞而失敗</li></ul><p><strong>serialize_into / deserialize_from 函數:流式操作</strong></p><pre>/// Serializes a value to a writer using Bincode.<br>pub fn serialize_into&lt;W: Write, T: Serialize&gt;(mut writer: W, value: &amp;T) -&gt; Result&lt;()&gt; {<br>    bincode::serde::encode_into_std_write(value, &amp;mut writer, CONFIG)?;<br>    Ok(())<br>}</pre><pre>/// Deserializes a value from a reader using Bincode.<br>pub fn deserialize_from&lt;R: Read, T: DeserializeOwned&gt;(mut reader: R) -&gt; Result&lt;T&gt; {<br>    Ok(bincode::serde::decode_from_std_read(&amp;mut reader, CONFIG)?)<br>}</pre><p>流式操作的優勢:</p><ul><li>不需要一次性加載整個數據到內存</li><li>適合網絡協議(從 TCP socket 直接讀取)</li><li>適合大文件處理</li></ul><p><strong>maybe_deserialize_from 函數:容錯反序列化</strong></p><pre>/// Deserializes a value from a reader using Bincode, or returns None if the<br>/// reader is closed.<br>pub fn maybe_deserialize_from&lt;R: Read, T: DeserializeOwned&gt;(mut reader: R) -&gt; Result&lt;Option&lt;T&gt;&gt; {<br>    match bincode::serde::decode_from_std_read(&amp;mut reader, CONFIG) {<br>        Ok(t) =&gt; Ok(Some(t)),<br>        Err(bincode::error::DecodeError::Io { inner, .. })<br>            if inner.kind() == std::io::ErrorKind::UnexpectedEof<br>                || inner.kind() == std::io::ErrorKind::ConnectionReset =&gt;<br>        {<br>            Ok(None)<br>        }<br>        Err(err) =&gt; Err(Error::from(err)),<br>    }<br>}</pre><p>錯誤處理邏輯:</p><ol><li>成功:返回 Ok(Some(value))</li><li>連接關閉:UnexpectedEof 或 ConnectionReset → 返回 Ok(None)</li><li>其他錯誤:返回 Err</li></ol><p>這個函數專門用於網絡通信:當客戶端斷開連接時,不視為錯誤,而是正常返回 None。</p><h4>Bincode 為何不適合鍵編碼</h4><p>讓我們通過實驗理解為什麼不能用 Bincode 編碼鍵。這些問題正是我們需要引入 Keycode 的原因。</p><p><strong>實驗 1:小端序破壞順序</strong></p><pre>use toydb::encoding::bincode;<br><br>let val1: u64 = 1;<br>let val2: u64 = 256;<br>let bytes1 = bincode::serialize(&amp;val1);<br>let bytes2 = bincode::serialize(&amp;val2);<br>println!(&quot;{:?}&quot;, bytes1); // [01, 00, 00, 00, 00, 00, 00, 00]<br>println!(&quot;{:?}&quot;, bytes2); // [00, 01, 00, 00, 00, 00, 00, 00]<br>// 字節序比較:bytes1 &gt; bytes2<br>// 但實際:1 &lt; 256  X 順序錯誤!</pre><p>原因:小端序將低位字節放在前面,bytes1[0] = 0x01 &gt; bytes2[0] = 0x00。</p><p>實驗 2:變長編碼破壞順序</p><pre>let s1 = &quot;a&quot;;<br>let s2 = &quot;aa&quot;;<br>let s3 = &quot;b&quot;;<br><br>let b1 = bincode::serialize(&amp;s1); // [1, 0, 0, 0, 0, 0, 0, 0, &#39;a&#39;]      長度 + 內容<br>let b2 = bincode::serialize(&amp;s2); // [2, 0, 0, 0, 0, 0, 0, 0, &#39;a&#39;, &#39;a&#39;]<br>let b3 = bincode::serialize(&amp;s3); // [1, 0, 0, 0, 0, 0, 0, 0, &#39;b&#39;]<br>// 字典序:&#39;a&#39; &lt; &#39;aa&#39; &lt; &#39;b&#39;<br>// 字節比較:b1 &lt; b2 ✓,但 b2 &gt; b3 X (應該 &#39;aa&#39; &lt; &#39;b&#39;)<br>// 問題:長度前綴 [2...] &gt; [1...]</pre><p>實驗 3:符號位破壞負數順序</p><pre>let n1: i64 = -1;<br>let n2: i64 = 0;<br>let n3: i64 = 1;<br><br>let b1 = bincode::serialize(&amp;n1); // [ff, ff, ff, ff, ff, ff, ff, ff]<br>let b2 = bincode::serialize(&amp;n2); // [00, 00, 00, 00, 00, 00, 00, 00]<br>let b3 = bincode::serialize(&amp;n3); // [01, 00, 00, 00, 00, 00, 00, 00]<br>// 字節比較:b1 &gt; b3 &gt; b2<br>// 結果:-1 &gt; 1 &gt; 0  X 完全錯誤!</pre><p>結論:Bincode 的設計目標是高效序列化,完全不考慮字典序。對於 key/value 存儲引擎來說,我們需要能夠根據鍵的順序進行範圍查詢和前綴掃描,這就需要一種能夠保持字典序的編碼方式。這正是 Keycode 存在的理由。</p><h4>Key trait:鍵的統一接口</h4><pre>/// Adds automatic Keycode encode/decode methods to key enums. These are used<br>/// as keys in the key/value store.<br>pub trait Key&lt;&#39;de&gt;: Serialize + Deserialize&lt;&#39;de&gt; {<br>    /// Decodes a key from a byte slice using Keycode.<br>    fn decode(bytes: &amp;&#39;de [u8]) -&gt; Result&lt;Self&gt; {<br>        keycode::deserialize(bytes)<br>    }<br><br>    /// Encodes a key to a byte vector using Keycode.<br>    ///<br>    /// In the common case, the encoded key is borrowed for a storage engine<br>    /// call and then thrown away. We could avoid a bunch of allocations by<br>    /// taking a reusable byte vector to encode into and return a reference to<br>    /// it, but we keep it simple.<br>    fn encode(&amp;self) -&gt; Vec&lt;u8&gt; {<br>        keycode::serialize(self)<br>    }<br>}</pre><p>設計要點:</p><ol><li>統一接口:所有鍵類型只需實現 Serialize + Deserialize,自動獲得 encode/decode 方法</li><li>內部調用 keycode:保證所有鍵都使用保序編碼</li><li>與 Value trait 的差異:</li></ol><ul><li>Key trait 有生命週期參數 &#39;de,允許零拷貝反序列化</li><li>使用 Deserialize&lt;&#39;de&gt; 而非 DeserializeOwned</li><li>原因:鍵通常從存儲引擎的內存映射文件或持久化緩衝區讀取,這些數據生命週期足夠長</li></ul><p>註釋解讀:</p><pre>/// In the common case, the encoded key is borrowed for a storage engine<br>/// call and then thrown away. We could avoid a bunch of allocations by<br>/// taking a reusable byte vector to encode into and return a reference to<br>/// it, but we keep it simple.</pre><p>這段註釋說明了性能優化的可能性:可以傳入可重用的 Vec&lt;u8&gt; 來避免分配,但為了簡潔性選擇每次分配新的向量。這是 toyDB 的設計哲學:簡潔性優先於性能。</p><h3>Keycode:保序鍵編碼</h3><p>src/encoding/keycode.rs 是 toyDB 自己實現的保序編碼系統。</p><h4>設計目標與實現策略</h4><pre>//! Keycode is a lexicographical order-preserving binary encoding for use with<br>//! keys in key/value stores. It is designed for simplicity, not efficiency<br>//! (i.e. it does not use varints or other compression methods).</pre><p>核心設計原則:</p><ol><li>字典序保持:a &lt; b ⇔ encode(a) &lt; encode(b)(字節序比較)</li><li>簡潔性優先:不使用 varint 壓縮,固定長度編碼</li><li>支持範圍掃描:前綴掃描、範圍查詢的基礎</li></ol><h4>核心函數實現</h4><p><strong>serialize 函數:序列化鍵</strong></p><pre>/// Serializes a key to a binary Keycode representation.<br>pub fn serialize&lt;T: Serialize&gt;(key: &amp;T) -&gt; Vec&lt;u8&gt; {<br>    let mut serializer = Serializer { output: Vec::new() };<br>    // Panic on failure, as this is a problem with the data structure.<br>    key.serialize(&amp;mut serializer).expect(&quot;key must be serializable&quot;);<br>    serializer.output<br>}</pre><p>實現模式:</p><ol><li>創建 Serializer 結構(包含輸出緩衝區)</li><li>調用 key.serialize(&amp;mut serializer)(Serde 機制)</li><li>返回序列化結果</li></ol><p><strong>deserialize 函數：反序列化鍵</strong></p><pre>/// Deserializes a key from a binary Keycode representation.<br>pub fn deserialize&lt;&#39;a, T: Deserialize&lt;&#39;a&gt;&gt;(input: &amp;&#39;a [u8]) -&gt; Result&lt;T&gt; {<br>    let mut deserializer = Deserializer::from_bytes(input);<br>    let t = T::deserialize(&amp;mut deserializer)?;<br>    if !deserializer.input.is_empty() {<br>        return errdata!(<br>            &quot;unexpected trailing bytes {:x?} at end of key {input:x?}&quot;,<br>            deserializer.input,<br>        );<br>    }<br>    Ok(t)<br>}</pre><p>代碼詳解</p><p>函數簽名</p><pre>pub fn deserialize&lt;&#39;a, T: Deserialize&lt;&#39;a&gt;&gt;(input: &amp;&#39;a [u8]) -&gt; Result&lt;T&gt;</pre><ul><li>&#39;a：生命週期參數，允許返回的 T 借用 input 中的數據（零拷貝）</li><li>T: Deserialize&lt;&#39;a&gt;：目標類型必須實現 Deserialize trait</li><li>input: &amp;&#39;a [u8]：待解碼的字節切片</li><li>Result&lt;T&gt;：成功返回解碼的值，失敗返回錯誤</li></ul><p>步驟 1：創建 Deserializer</p><pre>let mut deserializer = Deserializer::from_bytes(input);</pre><p>創建一個 Deserializer 對象來包裝輸入：</p><pre>// Deserializer 結構體（簡化）<br>struct Deserializer&lt;&#39;de&gt; {<br>    input: &amp;&#39;de [u8],  // 指向剩餘未解析的字節<br>}<br><br>impl&lt;&#39;de&gt; Deserializer&lt;&#39;de&gt; {<br>    fn from_bytes(input: &amp;&#39;de [u8]) -&gt; Self {<br>        Self { input }<br>    }<br>}</pre><ul><li>input 初始指向整個字節切片</li><li>隨著解析進行，input 會逐步向後移動（消耗字節）</li></ul><p>步驟 2：調用類型的 deserialize 方法</p><pre>let t = T::deserialize(&amp;mut deserializer)?;</pre><p>這是關鍵的一步！</p><p>語法解析：</p><ul><li>T::deserialize：關聯函數調用（不是實例方法）</li><li>等價於：&lt;T as Deserialize&gt;::deserialize(&amp;mut deserializer)</li><li>由 Serde 透過 #[derive(Deserialize)] 自動生成</li></ul><p>實際發生什麼：</p><p>假設 T = Key enum，Serde 生成的代碼類似：</p><pre>impl&lt;&#39;de&gt; Deserialize&lt;&#39;de&gt; for Key&lt;&#39;de&gt; {<br>    fn deserialize&lt;D&gt;(deserializer: D) -&gt; Result&lt;Self, D::Error&gt;<br>    where<br>        D: serde::Deserializer&lt;&#39;de&gt;,<br>    {<br>        // Serde 根據類型調用對應的 deserialize_* 方法<br>        deserializer.deserialize_enum(<br>            &quot;Key&quot;,<br>            &amp;[&quot;NextVersion&quot;, &quot;TxnActive&quot;, ...],<br>            KeyVisitor,<br>        )<br>    }<br>}</pre><p>Serde 的調用鏈：</p><pre>T::deserialize(&amp;mut deserializer)<br>  ↓<br>deserializer.deserialize_enum(...)  // 根據 T 的類型選擇方法<br>  ↓<br>KeyVisitor::visit_enum(...)         // Visitor 模式構造最終值<br>  ↓<br>返回 Key::TxnActive(5)</pre><p>步驟 3：檢查剩餘字節</p><pre>if !deserializer.input.is_empty() {<br>    return errdata!(<br>        &quot;unexpected trailing bytes {:x?} at end of key {input:x?}&quot;,<br>        deserializer.input,<br>    );<br>}</pre><p>為什麼需要這個檢查：</p><ul><li>確保所有字節都被消耗完畢</li><li>如果還有剩餘，說明輸入數據格式錯誤或類型不匹配</li></ul><p>錯誤範例：</p><pre>// Key::NextVersion 的編碼只需要 [0x00, 0x00]<br>// 但輸入包含額外的垃圾字節<br>let bad_input = [0x00, 0x00, 0xFF, 0xFF];<br>                              ^^^^^^^^ 多餘的字節<br><br>let result: Result&lt;Key&gt; = deserialize(&amp;bad_input);<br>// 錯誤：unexpected trailing bytes [ff, ff] at end of key [00, 00, ff, ff]</pre><p>步驟 4：返回結果</p><pre>Ok(t)</pre><p>所有檢查通過後，返回解碼的值。</p><h4>Serializer/Deserializer 實現</h4><p>Keycode 完全按照 Serde 框架規範實現 serde::Serializer 和 serde::Deserializer trait。 Serde 定義了統一的序列化介面,讓不同格式(JSON、Bincode、Keycode)能用相同方式處理任意 Rust 類型。</p><p>工作原理:</p><pre>// 序列化流程<br>keycode::serialize(value)<br>  → Serde 根據類型調用對應的 serialize_* 方法<br>  → Keycode 按保序規則編碼輸出<br><br>// 反序列化流程<br>keycode::deserialize(bytes)<br>  → Serde 根據目標類型調用對應的 deserialize_* 方法<br>  → Keycode 按規則解析字節恢復原值</pre><h4>字節切片編碼/解碼:最複雜案例</h4><p>字節切片(&amp;[u8]、String)是 Keycode 中最複雜的類型,原因:</p><ol><li>長度可變:無法預先知道佔用多少字節</li><li>需要終止符:標記字符串結束位置</li><li>終止符衝突:數據本身可能包含終止符字節,需要轉義</li><li>保持字典序:編碼後字節序必須與原始字典序一致</li></ol><p>編碼實現</p><pre>// Strings are encoded like bytes.<br>fn serialize_str(self, v: &amp;str) -&gt; Result&lt;()&gt; {<br>    self.serialize_bytes(v.as_bytes())<br>}<br><br>// Byte slices are terminated by 0x0000, escaping 0x00 as 0x00ff. This<br>// ensures that we can detect the end, and that for two overlapping slices,<br>// the shorter one orders before the longer one.<br>//<br>// We can&#39;t use e.g. length prefix encoding, since it doesn&#39;t sort correctly.<br>fn serialize_bytes(self, v: &amp;[u8]) -&gt; Result&lt;()&gt; {<br>    let bytes = v<br>        .iter()<br>        .flat_map(|&amp;byte| match byte {<br>            0x00 =&gt; Either::Left([0x00, 0xff].into_iter()),<br>            byte =&gt; Either::Right([byte].into_iter()),<br>        })<br>        .chain([0x00, 0x00]);<br>    self.output.extend(bytes);<br>    Ok(())<br>}</pre><p>代碼詳解:</p><ol><li>v.iter(): 遍歷輸入字節切片的每個字節</li><li>flat_map(|&amp;byte| ...): 將每個字節映射為一個或多個字節的迭代器</li></ol><ul><li>&amp;byte: 解引用 &amp;u8 → u8</li><li>flat_map 將所有迭代器拉平成單一序列</li></ul><ol><li>match byte: 根據字節值決定輸出</li></ol><ul><li>0x00 → Either::Left([0x00, 0xff].into_iter()):轉義為兩字節</li><li>其他 → Either::Right([byte].into_iter()):保持不變</li></ul><ol><li>Either&lt;L, R&gt;: 統一不同長度迭代器的類型,讓 flat_map 可處理</li><li>.chain([0x00, 0x00]): 追加終止符</li><li>self.output.extend(bytes): 將所有字節寫入輸出</li></ol><p>完整執行示例:</p><pre>// 輸入: &quot;a\x00b&quot; = [0x61, 0x00, 0x62]<br><br>v.iter()             // 0x61, 0x00, 0x62<br>  .flat_map(...)     // 0x61, 0x00, 0xff, 0x62<br>                     //      ^^^^^ 0x00 轉義為 0x00 0xff<br>  .chain([0x00, 0x00]) // 0x61, 0x00, 0xff, 0x62, 0x00, 0x00<br>                     //                            ^^^^^ 終止符<br><br>// 最終輸出: [0x61, 0x00, 0xff, 0x62, 0x00, 0x00]</pre><p>編碼規則:</p><ul><li>數據中的 0x00 → 編碼為 0x00 0xff</li><li>其他字節 → 直接輸出</li><li>字符串末尾 → 追加終止符 0x00 0x00</li></ul><p>為什麼不能用長度前綴?</p><p>長度前綴會破壞字典序:</p><pre>// 長度前綴編碼(錯誤)<br>&quot;a&quot;  → [01 00 00 00 00 00 00 00 61]<br>&quot;aa&quot; → [02 00 00 00 00 00 00 00 61 61]<br>&quot;b&quot;  → [01 00 00 00 00 00 00 00 62]<br><br>// 字節比較: &quot;aa&quot; vs &quot;b&quot; → 02 &gt; 01  ❌ 錯誤!<br>// 正確順序應該: &quot;aa&quot; &lt; &quot;b&quot;</pre><p>null 終止編碼保持字典序:</p><pre>&quot;a&quot;  → [61 00 00]        // &#39;a&#39; + 終止符<br>&quot;aa&quot; → [61 61 00 00]     // &#39;aa&#39; + 終止符<br>&quot;b&quot;  → [62 00 00]        // &#39;b&#39; + 終止符<br><br>// 字節比較:<br>// &quot;a&quot; vs &quot;aa&quot;: [61 00] &lt; [61 61]  ✓ 正確<br>// &quot;aa&quot; vs &quot;b&quot;: [61 61] &lt; [62 00]  ✓ 正確</pre><p>為什麼要轉義 0x00?</p><p>問題:數據本身可能包含 0x00,會與終止符 0x00 0x00 混淆</p><pre>// 如果不轉義(錯誤)<br>&quot;a\x00b&quot; → [61 00 62 00 00]<br>           //    ^^ 解碼器誤認為終止符!<br>           // 只解碼出 &quot;a&quot;,丟失 &quot;b&quot;</pre><p>解決方案:轉義數據中的 0x00</p><pre>// 正確轉義<br>&quot;a\x00b&quot; → [61 00 ff 62 00 00]<br>          //    ^^^^^ 轉義序列(數據中的 0x00)<br>          //             ^^^^^ 終止符(字符串結束)</pre><p>編碼示例:</p><pre>&quot;&quot;           → [00 00]<br>&quot;a&quot;          → [61 00 00]<br>&quot;ab&quot;         → [61 62 00 00]<br>&quot;a\x00b&quot;     → [61 00 ff 62 00 00]<br>&quot;\x00&quot;       → [00 ff 00 00]<br>&quot;\x00\x00&quot;   → [00 ff 00 ff 00 00]</pre><p>解碼實現</p><p>源碼中解碼分為兩部分：公開方法調用內部輔助函數</p><p>公開方法(Serde trait 要求):</p><pre>fn deserialize_bytes&lt;V: Visitor&lt;&#39;de&gt;&gt;(self, visitor: V) -&gt; Result&lt;V::Value&gt; {<br>    let bytes = self.decode_next_bytes()?;  // 調用輔助函數<br>    visitor.visit_bytes(&amp;bytes)             // 將結果交給 visitor 處理<br>}<br><br>fn deserialize_byte_buf&lt;V: Visitor&lt;&#39;de&gt;&gt;(self, visitor: V) -&gt; Result&lt;V::Value&gt; {<br>    let bytes = self.decode_next_bytes()?;<br>    visitor.visit_byte_buf(bytes)<br>}<br>fn deserialize_string&lt;V: Visitor&lt;&#39;de&gt;&gt;(self, visitor: V) -&gt; Result&lt;V::Value&gt; {<br>    let bytes = self.decode_next_bytes()?;<br>    visitor.visit_str(&amp;String::from_utf8(bytes)?)<br>}</pre><p>Visitor 模式說明:</p><p>visitor 是 Serde 的 Visitor 模式實現,用於將解碼後的數據轉換為目標類型:</p><pre>// Serde 定義的 Visitor trait（簡化版）<br>pub trait Visitor&lt;&#39;de&gt; {<br>    type Value;  // 最終返回的類型<br><br>    // 借用字節切片<br>    fn visit_bytes&lt;E&gt;(self, v: &amp;[u8]) -&gt; Result&lt;Self::Value, E&gt;;<br><br>    // 擁有字節向量<br>    fn visit_byte_buf&lt;E&gt;(self, v: Vec&lt;u8&gt;) -&gt; Result&lt;Self::Value, E&gt;;<br><br>    // 借用字符串切片<br>    fn visit_str&lt;E&gt;(self, v: &amp;str) -&gt; Result&lt;Self::Value, E&gt;;<br><br>    // ... 其他 visit_* 方法<br>}</pre><p>工作流程:</p><p>1.Deserializer 負責解碼字節:</p><pre>let bytes = self.decode_next_bytes()?;  // [0x61, 0x00, 0x62] → &quot;a\x00b&quot;</pre><p>2.Visitor 負責構造目標類型:</p><pre>visitor.visit_bytes(&amp;bytes)  // 將 &amp;[u8] 轉換為目標類型</pre><p>3.根據目標類型調用不同的 visit 方法:</p><pre>// 如果目標是 Vec&lt;u8&gt;<br>visitor.visit_byte_buf(bytes) → Vec&lt;u8&gt;<br><br>// 如果目標是 String<br>visitor.visit_str(&amp;String::from_utf8(bytes)?) → String<br><br>// 如果目標是 &amp;[u8]（借用）<br>visitor.visit_bytes(&amp;bytes) → &amp;[u8]</pre><p>為什麼需要 Visitor?</p><p>這是 Serde 的兩階段解碼設計:</p><pre>階段1: Deserializer 解析字節格式<br>   ↓<br>階段2: Visitor 構造目標類型</pre><p>核心解碼邏輯(輔助函數):</p><pre>/// Decodes and chops off the next encoded byte slice.<br>fn decode_next_bytes(&amp;mut self) -&gt; Result&lt;Vec&lt;u8&gt;&gt; {<br>    let mut decoded = Vec::new();<br>    let mut iter = self.input.iter().enumerate();<br>    let taken = loop {<br>        match iter.next() {<br>            Some((_, 0x00)) =&gt; match iter.next() {<br>                Some((i, 0x00)) =&gt; break i + 1,        // 終止符,返回已讀位置<br>                Some((_, 0xff)) =&gt; decoded.push(0x00), // 轉義,還原為 0x00<br>                _ =&gt; return errdata!(&quot;invalid escape sequence&quot;),<br>            },<br>            Some((_, b)) =&gt; decoded.push(*b),          // 普通字節<br>            None =&gt; return errdata!(&quot;unexpected end of input&quot;),<br>        }<br>    };<br>    self.input = &amp;self.input[taken..];  // 更新輸入,跳過已解碼部分<br>    Ok(decoded)<br>}</pre><p>代碼詳解:</p><p>1.iter().enumerate(): 遍歷字節同時記錄位置</p><ul><li>為什麼需要位置？解碼完成後需要知道消費了多少字節</li></ul><p>2.循環處理字節:</p><pre>match iter.next() {<br>    Some((_, 0x00)) =&gt; { /* 遇到可能的終止符或轉義 */ }<br>    Some((_, b))    =&gt; { /* 普通字節 */ }<br>    None            =&gt; { /* 意外結束 */ }<br>}</pre><p>3.遇到 0x00 時檢查下一字節:</p><pre>Some((_, 0x00)) =&gt; match iter.next() {<br>    Some((i, 0x00)) =&gt; break i + 1,        // [00 00] → 終止符<br>    Some((_, 0xff)) =&gt; decoded.push(0x00), // [00 ff] → 轉義的 0x00<br>    _               =&gt; return errdata!(&quot;invalid escape sequence&quot;),<br>}</pre><p>4.break i + 1: 返回已消費的字節數</p><ul><li>i 是第二個 0x00 的索引</li><li>i + 1 是需要跳過的總字節數(包括兩個終止符)</li></ul><p>5.self.input = &amp;self.input[taken..]: 更新輸入切片</p><ul><li>跳過已解碼的字節</li><li>為下一次解碼準備</li></ul><p>解碼示例:</p><pre>// 輸入: [61 00 ff 62 00 00]<br>// 解碼 &quot;a\x00b&quot;<br><br>iter.next() → (0, 0x61)  → decoded.push(0x61)  // &#39;a&#39;<br>iter.next() → (1, 0x00)  → 遇到 0x00,檢查下一個<br>iter.next() → (2, 0xff)  → decoded.push(0x00)  // 轉義,還原為 \x00<br>iter.next() → (3, 0x62)  → decoded.push(0x62)  // &#39;b&#39;<br>iter.next() → (4, 0x00)  → 遇到 0x00,檢查下一個<br>iter.next() → (5, 0x00)  → break 6             // 終止符,返回位置 6<br>// decoded = [0x61, 0x00, 0x62] = &quot;a\x00b&quot;<br>// self.input 更新:跳過前 6 個字節</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf850fd58df0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[toyDB: BitCask Storage Engine Analysis]]></title>
            <link>https://medium.com/@wudiheroback/toydb-bitcask-storage-engine-analysis-548c882a57cb?source=rss-83005aa59123------2</link>
            <guid isPermaLink="false">https://medium.com/p/548c882a57cb</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Stan Hsu]]></dc:creator>
            <pubDate>Sun, 12 Oct 2025 04:32:06 GMT</pubDate>
            <atom:updated>2025-10-12T04:50:43.408Z</atom:updated>
            <content:encoded><![CDATA[<p>This article provides an in-depth analysis of toyDB’s BitCask storage engine, demonstrating how to implement a simple yet efficient persistent key-value storage system.</p><p>BitCask is toyDB’s primary storage engine, using an append-only log structure with an in-memory index to provide extremely fast read/write performance while ensuring durability. This implementation is based on the BitCask paper from Riak database but significantly simplified for educational purposes.</p><p><a href="https://github.com/erikgrinaker/toydb/blob/main/src/storage/bitcask.rs">Full source code</a></p><h3>Core Design Philosophy</h3><p>BitCask’s core idea is: append all writes to a log file and maintain an in-memory mapping from keys to file offsets.</p><h4>Design Advantages</h4><ol><li>Excellent write performance: All writes are sequential appends, fully leveraging disk sequential write advantages</li><li>Good read performance: One in-memory lookup + one random disk read</li><li>Simple crash recovery: Rebuild in-memory index by scanning the log file</li></ol><h4>Design Limitations</h4><ol><li>All active keys must fit in memory: KeyDir stores all keys, limiting the number of keys that can be stored</li><li>Periodic compaction required: Deletes and updates generate garbage data requiring compaction to reclaim space</li><li>Potentially large files: Uses a single log file which may exceed filesystem limits</li></ol><p>toyDB’s implementation further simplifies standard BitCask for educational scenarios:</p><ul><li>Uses a single log file instead of multiple fixed-size files</li><li>Database is locked during compaction</li><li>No hint files, scans log directly</li><li>No timestamps or checksums</li></ul><h3>Data Structure Design</h3><h4>BitCask Structure</h4><pre>pub struct BitCask {<br>    /// The current append-only log file<br>    log: Log,<br>    /// Maps keys to value locations and lengths in the log<br>    keydir: KeyDir,<br>}</pre><p>Core components:</p><ul><li>log: Encapsulates log file read/write operations</li><li>keydir: In-memory index recording each key’s value location in the file</li></ul><h4>KeyDir Index</h4><pre>type KeyDir = BTreeMap&lt;Vec&lt;u8&gt;, ValueLocation&gt;;</pre><p>KeyDir is a mapping from keys to value locations:</p><p>- Uses `BTreeMap` to maintain key ordering, supporting range scans</p><p>- Keys are `Vec&lt;u8&gt;`: raw bytes, supporting arbitrary data</p><p>- Values are `ValueLocation`: record value location in file</p><h4>ValueLocation Structure</h4><pre>struct ValueLocation {<br>    offset: u64,    // Value&#39;s starting position in file<br>    length: usize,  // Value length<br>}<br><br>impl ValueLocation {<br>    fn end(&amp;self) -&gt; u64 {<br>        self.offset + self.length as u64<br>    }<br>}</pre><p>ValueLocation records value position information:</p><ul><li>offset: Byte offset from file beginning</li><li>length: Value byte length</li><li>end(): Calculate value end position</li></ul><h4>Log Structure</h4><pre>struct Log {<br>    file: File,      // Open log file<br>    path: PathBuf,   // Log file path<br>}</pre><p>Log encapsulates log file operations:</p><ul><li>file: Actual file handle, supporting read/write</li><li>path: File path, used for reopening and renaming</li></ul><h3>Log File Format</h3><p>BitCask’s log file consists of a series of entries, each with the format:</p><pre>+------------------+------------------+------------------+------------------+<br>| Key Length (4B)  | Value Length (4B)|      Key         |      Value       |<br>| Big-Endian u32   | Big-Endian i32   |   Raw Bytes      |   Raw Bytes      |<br>+------------------+------------------+------------------+------------------+</pre><h4>Format Details</h4><p>1.Key Length: 4 bytes, big-endian u32</p><p>2.Value Length: 4 bytes, big-endian i32</p><ul><li>Positive number: indicates value length</li><li>-1: indicates tombstone (deletion marker)</li></ul><p>3.Key: Raw bytes, length specified by Key Length</p><p>4.Value: Raw bytes, length specified by Value Length (tombstones don’t have this part)</p><h3>Creating and Opening</h3><h4>Opening Database</h4><pre>impl BitCask {<br>    pub fn new(path: PathBuf) -&gt; Result&lt;Self&gt; {<br>        let mut log = Log::new(path.clone())?;<br>        let keydir = log.build_keydir()?;<br>        info!(&quot;Opened {} with {} live keys&quot;, path.display(), keydir.len());<br>        Ok(Self { log, keydir })<br>    }<br>}</pre><p>Opening process:</p><ol><li>Create or open log file (Log::new)</li><li>Scan log to build KeyDir (log.build_keydir)</li><li>Log message showing number of live keys</li><li>Return BitCask instance</li></ol><h4>Opening with Auto-Compaction</h4><pre>impl BitCask {<br>    pub fn new_maybe_compact(<br>        path: PathBuf,<br>        garbage_min_fraction: f64,<br>        garbage_min_bytes: u64,<br>    ) -&gt; Result&lt;Self&gt; {<br>        let mut engine = Self::new(path)?;<br><br>    let status = engine.status()?;<br>    let total_size = status.disk_size;<br>    let garbage_size = status.garbage_disk_size();<br>    let garbage_fraction = garbage_size as f64 / total_size as f64;<br><br>    if garbage_size &gt; 0<br>        &amp;&amp; garbage_size &gt;= garbage_min_bytes<br>        &amp;&amp; garbage_fraction &gt;= garbage_min_fraction<br>    {<br>        info!(<br>            &quot;Compacting {} to remove {:.0}% garbage ({:.1} MB out of {:.1} MB)&quot;,<br>            engine.log.path.display(),<br>            garbage_fraction * 100.0,<br>            garbage_size as f64 / 1024.0 / 1024.0,<br>            total_size as f64 / 1024.0 / 1024.0<br>        );<br>        engine.compact()?;<br>        info!(<br>            &quot;Compacted {} to size {:.1} MB&quot;,<br>            engine.log.path.display(),<br>            (total_size - garbage_size) as f64 / 1024.0 / 1024.0<br>        );<br>    }<br><br>    Ok(engine)<br>    }<br>}</pre><p>Auto-compaction logic:</p><ol><li>Open database normally</li><li>Query status, calculate garbage ratio</li><li>If both garbage size and ratio exceed thresholds, perform compaction</li><li>Log pre/post compaction sizes</li></ol><p>This method is suitable for use during node startup, automatically cleaning accumulated garbage data.</p><h4>Opening Log File</h4><pre>impl Log {<br>    fn new(path: PathBuf) -&gt; Result&lt;Self&gt; {<br>        if let Some(dir) = path.parent() {<br>            std::fs::create_dir_all(dir)?<br>        }<br>        let file = std::fs::OpenOptions::new()<br>            .read(true)<br>            .write(true)<br>            .create(true)<br>            .truncate(false)<br>            .open(&amp;path)?;<br>        if !file.try_lock_exclusive()? {<br>            return Err(Error::IO(format!(&quot;file {path:?} is already is use&quot;)));<br>        }<br>        Ok(Self { file, path })<br>    }<br>}</pre><p>Key steps:</p><ol><li>Create directory: Ensure parent directory exists</li><li>Open file: Read-write mode, create if doesn’t exist, don’t truncate</li><li>Exclusive lock: Use fs4 crate to acquire exclusive lock, preventing multi-process concurrent access</li><li>Return Log: Contains file handle and path</li></ol><p>Exclusive lock is critical: ensures only one process can access database file at a time, avoiding data corruption.</p><h3>Building KeyDir</h3><p>KeyDir is the in-memory index recording all active key locations. When opening the database, the log file must be scanned to build it.</p><h4>build_keydir Implementation</h4><p>Scanning Detail Diagram</p><pre>Scanning a single entry:<br><br>File position: offset = 0<br>┌───────────────────────────────────────────────────┐<br>│  [00 00 00 03]  [00 00 00 05]  [6B 65 79]  [...]  │<br>│   Key Length     Value Length      Key      Value │<br>│    (u32=3)        (i32=5)        &quot;key&quot;    &quot;alice&quot; │<br>└───────────────────────────────────────────────────┘<br>     ↓                ↓                ↓         ↓<br>   Read &amp; parse    Read &amp; parse     Read key   Skip value<br>                                               (only need location)<br><br>Calculate ValueLocation:<br>  offset = current_pos + 8 (two length fields) + key_len<br>        = 0 + 8 + 3 = 11<br>  length = value_len = 5<br><br>Update KeyDir:<br>  KeyDir.insert(&quot;key&quot;, ValueLocation { offset: 11, length: 5 })<br><br>Move to next entry:<br>  next_offset = current_pos + 8 + key_len + value_len<br>              = 0 + 8 + 3 + 5 = 16</pre><pre>impl Log {<br>    fn build_keydir(&amp;mut self) -&gt; Result&lt;KeyDir&gt; {<br>    let mut len_buf = [0u8; 4];<br>    let mut keydir = KeyDir::new();<br>    let file_len = self.file.metadata()?.len();<br>    let mut r = BufReader::new(&amp;mut self.file);<br>    let mut offset = r.seek(SeekFrom::Start(0))?;<br><br>    while offset &lt; file_len {<br>        // Read next entry, return key and value location (None for tombstone)<br>        let result = || -&gt; StdResult&lt;(Vec&lt;u8&gt;, Option&lt;ValueLocation&gt;), std::io::Error&gt; {<br>            // Read key length: 4-byte u32<br>            r.read_exact(&amp;mut len_buf)?;<br>            let key_len = u32::from_be_bytes(len_buf);<br><br>            // Read value length: 4-byte i32, -1 for tombstone<br>            r.read_exact(&amp;mut len_buf)?;<br>            let value_loc = match i32::from_be_bytes(len_buf) {<br>                ..0 =&gt; None, // tombstone<br>                len =&gt; Some(ValueLocation {<br>                    offset: offset + 8 + key_len as u64,<br>                    length: len as usize,<br>                }),<br>            };<br><br>            // Read key<br>            let mut key = vec![0; key_len as usize];<br>            r.read_exact(&amp;mut key)?;<br><br>            // Skip value (only need location, not content)<br>            if let Some(value_loc) = value_loc {<br>                if value_loc.end() &gt; file_len {<br>                    return Err(std::io::Error::new(<br>                        std::io::ErrorKind::UnexpectedEof,<br>                        &quot;value extends beyond end of file&quot;,<br>                    ));<br>                }<br>                r.seek_relative(value_loc.length as i64)?;<br>            }<br><br>            // Update file offset<br>            offset += 8 + key_len as u64 + value_loc.map_or(0, |v| v.length) as u64;<br><br>            Ok((key, value_loc))<br>        }();<br><br>        // Update KeyDir<br>        match result {<br>            Ok((key, Some(value_loc))) =&gt; keydir.insert(key, value_loc),<br>            Ok((key, None)) =&gt; keydir.remove(&amp;key),<br>            // If incomplete entry found at end of file, assume incomplete write and truncate<br>            Err(err) if err.kind() == std::io::ErrorKind::UnexpectedEof =&gt; {<br>                error!(&quot;Found incomplete entry at offset {offset}, truncating file&quot;);<br>                self.file.set_len(offset)?;<br>                break;<br>            }<br>            Err(err) =&gt; return Err(err.into()),<br>        };<br>    }<br><br>    Ok(keydir)<br>    }<br>}</pre><h4>Scanning Process</h4><p>1.Initialize: Create empty KeyDir, get file length</p><p>2.Scan entry by entry:</p><ul><li>Read key length and value length</li><li>Read key content</li><li>Skip value content (only need location)</li><li>Calculate value location: offset + 8 + key_len</li></ul><p>3.Update KeyDir:</p><ul><li>Normal value: insert or update key</li><li>Tombstone: delete key</li><li>Incomplete entry: truncate file, stop scanning</li></ul><p>4.Return KeyDir</p><h4>Crash Recovery</h4><p>If the program crashes during write, there may be an incomplete entry at the end of the file. build_keydir will:</p><ol><li>Detect UnexpectedEof error</li><li>Truncate file to last complete entry</li><li>Continue normal startup</li></ol><p>This design ensures crash recovery simplicity: just rescan the file.</p><h3>Basic Operations</h3><h4>Writing Data — set</h4><pre>impl Engine for BitCask {<br>    fn set(&amp;mut self, key: &amp;[u8], value: Vec&lt;u8&gt;) -&gt; Result&lt;()&gt; {<br>        let value_location = self.log.write_entry(key, Some(&amp;*value))?;<br>        self.keydir.insert(key.to_vec(), value_location);<br>        Ok(())<br>    }<br>}</pre><p>Write process:</p><ol><li>Call log.write_entry to append entry to log</li><li>Get value location information</li><li>Update mapping in KeyDir</li></ol><p>Note: Some(&amp;*value) converts Vec&lt;u8&gt; to Option&lt;&amp;[u8]&gt;.</p><h4>Reading Data — get</h4><pre>impl Engine for BitCask {<br>    fn get(&amp;mut self, key: &amp;[u8]) -&gt; Result&lt;Option&lt;Vec&lt;u8&gt;&gt;&gt; {<br>        let Some(location) = self.keydir.get(key) else {<br>            return Ok(None);<br>        };<br>        self.log.read_value(*location).map(Some)<br>    }<br>}</pre><p>Read process:</p><ol><li>Look up key in KeyDir</li><li>If doesn’t exist, return None</li><li>If exists, read value from log based on location</li></ol><p>Performance characteristics:</p><ul><li>One in-memory lookup (KeyDir): O(log n)</li><li>One random disk read (log file): O(1)</li></ul><h4>Deleting Data — delete</h4><pre>impl Engine for BitCask {<br>    fn delete(&amp;mut self, key: &amp;[u8]) -&gt; Result&lt;()&gt; {<br>        self.log.write_entry(key, None)?;<br>        self.keydir.remove(key);<br>        Ok(())<br>    }<br>}</pre><p>Delete process:</p><ol><li>Write tombstone to log (value = None)</li><li>Remove key from KeyDir</li></ol><p>Key points:</p><ul><li>Delete doesn’t immediately reclaim space</li><li>Tombstone remains permanently in log until compaction</li><li>KeyDir updates immediately, deleted keys invisible during reads</li></ul><h3>Log Read/Write</h3><h4>Writing Entry — write_entry</h4><p><strong>Write Process Diagram</strong></p><pre>Write operation: log.write_entry(b&quot;user&quot;, Some(b&quot;alice&quot;))<br><br>Step 1: Seek to end of file<br>┌─────────────────────────────────────┐<br>│  Existing data...                   │<br>│                                     │  ← File end: offset = 100<br>└─────────────────────────────────────┘<br><br>Step 2: Prepare data to write<br>key = &quot;user&quot; (4 bytes)<br>value = &quot;alice&quot; (5 bytes)<br><br>Encode as:<br>┌──────────────┬──────────────┬──────────────┬───────────────┐<br>│ [00 00 00 04]│ [00 00 00 05]│ [75 73 65 72]│ [61 6C 69...] │<br>│  Key Length  │ Value Length │     Key      │     Value     │<br>│   (u32=4)    │   (i32=5)    │    &quot;user&quot;    │    &quot;alice&quot;    │<br>└──────────────┴──────────────┴──────────────┴───────────────┘<br>   4 bytes        4 bytes         4 bytes        5 bytes<br><br>   Total: 8 + 4 + 5 = 17 bytes<br><br>Step 3: Write to file<br>┌─────────────────────────────────────┬──────────────────────┐<br>│  Existing data...                   │ [New entry 17 bytes] │<br>│                                     │                      │<br>└─────────────────────────────────────┴──────────────────────┘<br> ↑                                     ↑<br> offset = 0                            offset = 100 (write position)<br><br>Step 4: Return ValueLocation<br>ValueLocation {<br>    offset: 100 + 8 + 4 = 112,  // skip two length fields and key<br>    length: 5                    // value length<br>}</pre><p><strong>Tombstone Write Diagram</strong></p><pre>Delete operation: log.write_entry(b&quot;user&quot;, None)<br><br>Encode as:<br>┌──────────────┬──────────────┬──────────────┐<br>│ [00 00 00 04]│ [FF FF FF FF]│ [75 73 65 72]│  (no Value part)<br>│  Key Length  │ Value Length │     Key      │<br>│   (u32=4)    │   (i32=-1)   │    &quot;user&quot;    │<br>└──────────────┴──────────────┴──────────────┘<br>   4 bytes        4 bytes         4 bytes<br><br>   Total: 8 + 4 = 12 bytes (tombstone has no value)<br><br>Return ValueLocation {<br>    offset: 112,  // value position (though no value exists)<br>    length: 0     // length is 0<br>}</pre><p><strong>Sequential Write Diagram</strong></p><pre>Three consecutive writes:<br>1. write_entry(b&quot;a&quot;, Some(b&quot;x&quot;))<br>2. write_entry(b&quot;bb&quot;, Some(b&quot;yy&quot;))<br>3. write_entry(b&quot;a&quot;, None)  // delete &quot;a&quot;<br><br>File content:<br>┌─────────────────────────────────────────────────────────────────────┐<br>│ Entry 0: offset=0                                                   │<br>│ ┌─────────┬─────────┬─────┬─────┐                                   │<br>│ │ KL: 1   │ VL: 1   │ a   │ x   │  ValueLocation{offset:9, len:1}   │<br>│ │ (4 B)   │ (4 B)   │(1 B)│(1 B)│                                   │<br>│ └─────────┴─────────┴─────┴─────┘                                   │<br>│ Total: 4 + 4 + 1 + 1 = 10 bytes                                     │<br>├─────────────────────────────────────────────────────────────────────┤<br>│ Entry 1: offset=10                                                  │<br>│ ┌─────────┬─────────┬──────┬──────┐                                 │<br>│ │ KL: 2   │ VL: 2   │ bb   │ yy   │  ValueLocation{offset:20, len:2}│<br>│ │ (4 B)   │ (4 B)   │(2 B) │(2 B) │                                 │<br>│ └─────────┴─────────┴──────┴──────┘                                 │<br>│ Total: 4 + 4 + 2 + 2 = 12 bytes                                     │<br>├─────────────────────────────────────────────────────────────────────┤<br>│ Entry 2: offset=22                                                  │<br>│ ┌─────────┬─────────┬─────┐                                         │<br>│ │ KL: 1   │ VL: -1  │ a   │  (tombstone)                            │<br>│ │ (4 B)   │ (4 B)   │(1 B)│  ValueLocation{offset:31, len:0}        │<br>│ └─────────┴─────────┴─────┘                                         │<br>│ Total: 4 + 4 + 1 = 9 bytes (no value for tombstone)                 │<br>└─────────────────────────────────────────────────────────────────────┘<br><br>KeyDir state changes:<br>After Entry 0: KeyDir[&quot;a&quot;] = {offset:9, len:1}<br>                (offset = 0 + 4(KL) + 4(VL) + 1(key) = 9)<br>After Entry 1: KeyDir[&quot;bb&quot;] = {offset:20, len:2}<br>                (offset = 10 + 4(KL) + 4(VL) + 2(key) = 20)<br>After Entry 2: KeyDir.remove(&quot;a&quot;)<br><br>Final KeyDir:<br>  Only &quot;bb&quot; → {offset:20, len:2}<br><br>Garbage data:<br>  Entry 0 (a=x) and Entry 2 (tombstone) are both garbage, need compaction</pre><pre>impl Log {<br>    fn write_entry(&amp;mut self, key: &amp;[u8], value: Option&lt;&amp;[u8]&gt;) -&gt; Result&lt;ValueLocation&gt; {<br>    let length = 8 + key.len() + value.map_or(0, |v| v.len());<br>    let offset = self.file.seek(SeekFrom::End(0))?;<br>    let mut w = BufWriter::with_capacity(length, &amp;mut self.file);<br><br>    // Key length: 4-byte u32<br>    w.write_all(&amp;(key.len() as u32).to_be_bytes())?;<br><br>    // Value length: 4-byte i32, -1 for tombstone<br>    w.write_all(&amp;value.map_or(-1, |v| v.len() as i32).to_be_bytes())?;<br><br>    // Actual key and value<br>    w.write_all(key)?;<br>    w.write_all(value.unwrap_or_default())?;<br>    w.flush()?;<br><br>    // Convert entry location to value location<br>    Ok(ValueLocation {<br>        offset: offset + 8 + key.len() as u64,<br>        length: value.map_or(0, |v| v.len()),<br>    })<br>    }<br>}</pre><p>Write steps:</p><p>1.Calculate length: 8 + key_len + value_len (8 is two length fields)</p><p>2.Seek to file end: seek(SeekFrom::End(0))</p><p>3.Create buffered writer: Use calculated length as buffer size</p><p>4.Write four parts:</p><ul><li>Key length (4 bytes)</li><li>Value length (4 bytes, -1 for tombstone)</li><li>Key content</li><li>Value content (empty for tombstone)</li></ul><p>5.Flush buffer: Ensure data written to file</p><p>6.Return location: Value starting offset and length</p><h4>Reading Value — read_value</h4><p><strong>Read Value Diagram</strong></p><pre>Given: ValueLocation{offset:20, len:5}<br>Task: Read the value &quot;alice&quot; from the log file<br><br>Log file content:<br>┌────────────────────────────────────────────────────────────────────────────┐<br>│                                                                            │<br>│  offset:                                                                   │<br>│     0        10       20       25                                          │<br>│     │         │        │        │                                          │<br>│     v         v        v        v                                          │<br>│  [Entry 0] [Entry 1] [alice] [Entry 2]...                                  │<br>│                        ┌─────────────────────┐                             │<br>│                        │    4B   │   4B  │2B │ 5B                          │<br>│                        │   KL    │  VL   │key│value                        │<br>│                        │    2    │   5   │bb │alice                        │<br>│                        └─────────────────────┘                             │<br>│                                              ↑                             │<br>│                                              └─ ValueLocation points here  │<br>└────────────────────────────────────────────────────────────────────────────┘<br><br>Step 1: Allocate buffer<br>  let mut value = vec![0; 5];  // Create 5-byte buffer<br>  value = [0x00, 0x00, 0x00, 0x00, 0x00]<br><br>Step 2: Seek to offset<br>  file.seek(SeekFrom::Start(20))<br>  ┌─────────────────────────────────────┐<br>  │  [Entry 0] [Entry 1] [alice] ...    │<br>  │                       ↑             │<br>  │                    offset=20        │<br>  │                   (seek here)       │<br>  └─────────────────────────────────────┘<br><br>Step 3: Read exact bytes<br>  file.read_exact(&amp;mut value)<br>  Read 5 bytes from current position<br>  ┌─────────────────────────────────────┐<br>  │  [Entry 0] [Entry 1] [alice] ...    │<br>  │                       ├─────┤       │<br>  │                       read 5B       │<br>  └─────────────────────────────────────┘<br><br>  value = [0x61, 0x6C, 0x69, 0x63, 0x65]<br>        = [&#39;a&#39;,  &#39;l&#39;,  &#39;i&#39;,  &#39;c&#39;,  &#39;e&#39;]<br><br>Step 4: Return value<br>  Ok(vec![0x61, 0x6C, 0x69, 0x63, 0x65])</pre><p><strong>Complete Example with KeyDir Lookup</strong></p><pre>User request: engine.get(b&quot;bb&quot;)<br><br>Step 1: Lookup in KeyDir<br>  KeyDir:<br>  ┌────────────────────────────┐<br>  │ Key  │  ValueLocation      │<br>  ├──────┼─────────────────────┤<br>  │ &quot;bb&quot; │ {offset:20, len:5}  │ ← Found!<br>  └────────────────────────────┘<br><br>Step 2: Read value from log<br>  log.read_value(ValueLocation{offset:20, len:5})<br><br>  Log file structure:<br>  ┌──────────────────────────────────────────────────────────────┐<br>  │ Offset: 0                  10                    22          │<br>  │         │                   │                     │          │<br>  │         v                   v                     v          │<br>  │  ┌──────────────┐  ┌────────────────────────┐  ┌───────┐     │<br>  │  │   Entry 0    │  │      Entry 1           │  │Entry 2│     │<br>  │  │ (10 bytes)   │  │     (12 bytes)         │  │(9 B)  │     │<br>  │  ├──┬──┬──┬──┬──┤  ├──┬──┬────┬─────────────┤  └───────┘     │<br>  │  │KL│VL│a │x │  │  │KL│VL│ bb │   alice     │                │<br>  │  │4B│4B│1B│1B│  │  │4B│4B│ 2B │    5B       │                │<br>  │  └──┴──┴──┴──┴──┘  └──┴──┴────┴─────────────┘                │<br>  │                               ↑             ↑                │<br>  │                           offset:20     offset:25            │<br>  │                           (value start) (value end)          │<br>  │                               └─────────────┘                │<br>  │                                Read 5 bytes                  │<br>  └──────────────────────────────────────────────────────────────┘<br><br>Step 3: Return result<br>  Some(b&quot;alice&quot;.to_vec())<br><br>Performance:<br>  - KeyDir lookup: O(log n) in-memory BTreeMap search<br>  - Disk seek: O(1) single random seek to offset 20<br>  - Disk read: O(1) single sequential read of 5 bytes<br>  - Total: O(log n) + 2 * O(1) disk I/O</pre><pre>impl Log {<br>    fn read_value(&amp;mut self, location: ValueLocation) -&gt; Result&lt;Vec&lt;u8&gt;&gt; {<br>        let mut value = vec![0; location.length];<br>        self.file.seek(SeekFrom::Start(location.offset))?;<br>        self.file.read_exact(&amp;mut value)?;<br>        Ok(value)<br>    }<br>}</pre><p>Read steps:</p><ol><li>Allocate buffer of value size</li><li>Seek to value starting position</li><li>Read exact length of data</li><li>Return value</li></ol><p>Simple and straightforward: one seek + one read.</p><h3>Range Scanning</h3><p>Range scanning leverages KeyDir’s (BTreeMap) ordering to implement efficient range queries.</p><h3>scan Implementation</h3><pre>impl Engine for BitCask {<br>    fn scan(&amp;mut self, range: impl RangeBounds&lt;Vec&lt;u8&gt;&gt;) -&gt; Self::ScanIterator&lt;&#39;_&gt; {<br>        ScanIterator { inner: self.keydir.range(range), log: &amp;mut self.log }<br>    }<br>}</pre><p>Directly wraps BTreeMap’s range iterator:</p><ul><li>keydir.range(range) returns key-value pairs within range</li><li>Creates ScanIterator wrapping it</li></ul><h4>ScanIterator Structure</h4><pre>pub struct ScanIterator&lt;&#39;a&gt; {<br>    inner: Range&lt;&#39;a, Vec&lt;u8&gt;, ValueLocation&gt;,<br>    log: &amp;&#39;a mut Log,<br>}</pre><p>Contains:</p><ul><li>inner: BTreeMap’s range iterator</li><li>log: Mutable reference to log file for reading values</li></ul><h4>Iterator Implementation</h4><p>Scan Iterator Diagram</p><pre>User request: engine.scan(b&quot;b&quot;.to_vec()..b&quot;d&quot;.to_vec())<br>Task: Scan all keys in range [b, d)<br><br>Initial state:<br>  KeyDir (BTreeMap):<br>  ┌─────────────────────────────────────┐<br>  │ Key     │  ValueLocation            │<br>  ├─────────┼───────────────────────────┤<br>  │ &quot;apple&quot; │  {offset:10, len:5}       │  (before range)<br>  │ &quot;banana&quot;│  {offset:30, len:6}       │  ← Range starts here<br>  │ &quot;cherry&quot;│  {offset:50, len:6}       │  ← In range<br>  │ &quot;date&quot;  │  {offset:70, len:4}       │  (after range, excluded)<br>  └─────────────────────────────────────┘<br><br>Create ScanIterator:<br>  ScanIterator {<br>    inner: keydir.range(b&quot;b&quot;..b&quot;d&quot;),  // BTreeMap range iterator<br>    log: &amp;mut self.log                 // Reference to log file<br>  }<br><br>Iteration process:<br><br>┌─────────────────────────────────────────────────────────────────┐<br>│ Call #1: iter.next()                                            │<br>├─────────────────────────────────────────────────────────────────┤<br>│ Step 1: inner.next() returns Some((&quot;banana&quot;, ValueLocation))    │<br>│         ┌────────────────────────────┐                          │<br>│         │ Key: &quot;banana&quot;              │                          │<br>│         │ ValueLocation{offset:30,   │                          │<br>│         │               len:6}       │                          │<br>│         └────────────────────────────┘                          │<br>│                                                                 │<br>│ Step 2: Clone key: &quot;banana&quot;.to_vec()                            │<br>│                                                                 │<br>│ Step 3: Read value from log:                                    │<br>│         log.read_value(ValueLocation{offset:30, len:6})         │<br>│                                                                 │<br>│         Log file:                                               │<br>│         ┌─────────────────────────┐                             │<br>│         │  offset:30              │                             │<br>│         │    ↓                    │                             │<br>│         │  [yellow]  (6 bytes)    │                             │<br>│         └─────────────────────────┘                             │<br>│                                                                 │<br>│ Step 4: Return Some(Ok((&quot;banana&quot;, &quot;yellow&quot;)))                   │<br>└─────────────────────────────────────────────────────────────────┘<br><br>┌─────────────────────────────────────────────────────────────────┐<br>│ Call #2: iter.next()                                            │<br>├─────────────────────────────────────────────────────────────────┤<br>│ Step 1: inner.next() returns Some((&quot;cherry&quot;, ValueLocation))    │<br>│         ┌────────────────────────────┐                          │<br>│         │ Key: &quot;cherry&quot;              │                          │<br>│         │ ValueLocation{offset:50,   │                          │<br>│         │               len:6}       │                          │<br>│         └────────────────────────────┘                          │<br>│                                                                 │<br>│ Step 2: Clone key: &quot;cherry&quot;.to_vec()                            │<br>│                                                                 │<br>│ Step 3: Read value from log:                                    │<br>│         log.read_value(ValueLocation{offset:50, len:6})         │<br>│                                                                 │<br>│         Log file:                                               │<br>│         ┌─────────────────────────┐                             │<br>│         │  offset:50              │                             │<br>│         │    ↓                    │                             │<br>│         │  [red]  (6 bytes)       │                             │<br>│         └─────────────────────────┘                             │<br>│                                                                 │<br>│ Step 4: Return Some(Ok((&quot;cherry&quot;, &quot;red&quot;)))                      │<br>└─────────────────────────────────────────────────────────────────┘<br><br>┌─────────────────────────────────────────────────────────────────┐<br>│ Call #3: iter.next()                                            │<br>├─────────────────────────────────────────────────────────────────┤<br>│ Step 1: inner.next() returns None (end of range)                │<br>│                                                                 │<br>│ Step 2: Return None                                             │<br>└─────────────────────────────────────────────────────────────────┘<br><br>Final result:<br>  vec![<br>    (&quot;banana&quot;, &quot;yellow&quot;),<br>    (&quot;cherry&quot;, &quot;red&quot;),<br>  ]<br><br>Key insight:<br>  - BTreeMap&#39;s range iterator handles ordered traversal (in memory)<br>  - Each iteration requires one disk read to fetch the value<br>  - Keys are sorted, so scan is efficient<br>  - Performance: O(log n) to find start + O(k) iterations where k = result count</pre><pre>impl Iterator for ScanIterator&lt;&#39;_&gt; {<br>    type Item = Result&lt;(Vec&lt;u8&gt;, Vec&lt;u8&gt;)&gt;;<br><br>    fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {<br>        self.inner.next().map(|item| self.map(item))<br>    }<br>}<br><br>impl ScanIterator&lt;&#39;_&gt; {<br>    fn map(&amp;mut self, item: (&amp;Vec&lt;u8&gt;, &amp;ValueLocation)) -&gt; &lt;Self as Iterator&gt;::Item {<br>        let (key, value_loc) = item;<br>        Ok((key.clone(), self.log.read_value(*value_loc)?))<br>    }<br>}</pre><p>Iteration process:</p><ol><li>Get next key and location from inner</li><li>Clone key</li><li>Read value from log</li><li>Return key-value pair</li></ol><h4>Bidirectional Iteration</h4><pre>impl DoubleEndedIterator for ScanIterator&lt;&#39;_&gt; {<br>    fn next_back(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {<br>        self.inner.next_back().map(|item| self.map(item))<br>    }<br>}</pre><p>Supports reverse iteration:</p><ul><li>next(): Small to large</li><li>next_back(): Large to small</li></ul><p>This benefits from BTreeMap’s bidirectional iterator feature.</p><h3>Status Query</h3><h4>status Implementation</h4><pre>impl Engine for BitCask {<br>    fn status(&amp;mut self) -&gt; Result&lt;Status&gt; {<br>        // 1. Count active keys<br>        // KeyDir only contains live keys (deleted keys are removed)<br>        let keys = self.keydir.len() as u64;<br><br>        // 2. Calculate logical size of active data (keys + values only)<br>        // Iterate through all entries in KeyDir and sum up:<br>        //   - key.len(): size of each key in bytes<br>        //   - value_loc.length: size of each value in bytes<br>        // This does NOT include metadata (key length, value length fields)<br>        let size = self.keydir<br>            .iter()<br>            .map(|(key, value_loc)| {<br>                (key.len() + value_loc.length) as u64<br>            })<br>            .sum();<br><br>        // 3. Get total disk file size<br>        // This includes:<br>        //   - All active entries (keys + values + metadata)<br>        //   - All garbage (overwritten values, tombstones, deleted entries)<br>        let disk_size = self.log.file.metadata()?.len();<br><br>        // 4. Calculate disk size of active data<br>        // Active data on disk includes:<br>        //   - Keys and values (already counted in `size`)<br>        //   - Metadata: 8 bytes per entry (4B key_len + 4B value_len)<br>        // Formula: size + 8 * keys<br>        // Example: If we have 2 keys:<br>        //   - &quot;a&quot; = &quot;x&quot; (1B key + 1B value)<br>        //   - &quot;bb&quot; = &quot;yy&quot; (2B key + 2B value)<br>        //   size = 1 + 1 + 2 + 2 = 6 bytes<br>        //   live_disk_size = 6 + 8 * 2 = 22 bytes<br>        //     (includes 4+4+1+1=10B for entry 0, 4+4+2+2=12B for entry 1)<br>        let live_disk_size = size + 8 * keys;<br><br>        Ok(Status {<br>            name: &quot;bitcask&quot;.to_string(),<br>            keys,           // Number of active keys<br>            size,           // Logical size (keys + values only)<br>            disk_size,      // Total file size (including garbage)<br>            live_disk_size, // Active data on disk (keys + values + metadata)<br>        })<br>    }<br>}</pre><p><strong>Calculation Example</strong></p><pre>Assume we have this log file:<br><br>Entry 0: &quot;a&quot; = &quot;x&quot;     (written, then overwritten)<br>Entry 1: &quot;b&quot; = &quot;yy&quot;    (written, then deleted)<br>Entry 2: &quot;a&quot; = &quot;zzz&quot;   (current value)<br>Entry 3: &quot;b&quot; (tombstone for deletion)<br><br>Log file structure:<br>┌────────────────────────────────────────────────────────┐<br>│ Entry 0: KL=1, VL=1, key=&quot;a&quot;, value=&quot;x&quot;   (10 bytes)   │ ← Garbage<br>│ Entry 1: KL=1, VL=2, key=&quot;b&quot;, value=&quot;yy&quot;  (11 bytes)   │ ← Garbage<br>│ Entry 2: KL=1, VL=3, key=&quot;a&quot;, value=&quot;zzz&quot; (12 bytes)   │ ← Live<br>│ Entry 3: KL=1, VL=-1, key=&quot;b&quot; (tombstone) (9 bytes)    │ ← Garbage<br>└────────────────────────────────────────────────────────┘<br><br>KeyDir (only contains live keys):<br>  &quot;a&quot; → ValueLocation{offset:..., len:3}<br><br>Status calculation:<br>  keys = 1 (only &quot;a&quot; is live)<br><br>  size = 1 (key &quot;a&quot;) + 3 (value &quot;zzz&quot;) = 4 bytes<br>       = logical size of data (no metadata)<br><br>  disk_size = 10 + 11 + 12 + 9 = 42 bytes<br>            = total file size (all entries including garbage)<br><br>  live_disk_size = 4 + 8 * 1 = 12 bytes<br>                 = size of Entry 2 only (4B+4B+1B+3B)<br>                 = active data on disk<br><br>Garbage calculation:<br>  garbage_disk_size = disk_size - live_disk_size<br>                    = 42 - 12 = 30 bytes<br>                    = Entries 0, 1, 3 (overwritten + deleted + tombstone)</pre><p>Field calculations:</p><ul><li>name: Engine name “bitcask”</li><li>keys: Number of active keys, directly from KeyDir length</li><li>size: Logical size of active data, iterate KeyDir and sum key and value lengths (excluding metadata)</li><li>disk_size: Actual file size (including all garbage)</li><li>live_disk_size: Disk size of active data, including 8-byte length prefixes</li></ul><h4>Garbage Calculation</h4><pre>impl Status {<br>    pub fn garbage_disk_size(&amp;self) -&gt; u64 {<br>        self.disk_size.saturating_sub(self.live_disk_size)<br>    }<br>}</pre><p>Garbage size = Total disk size — Live disk size</p><p>Garbage includes:</p><ul><li>Overwritten old values</li><li>Tombstones of deleted keys</li><li>Old values of deleted keys</li></ul><h3>Compaction Mechanism</h3><p>Compaction is the only way to reclaim garbage space. It creates a new log file containing only active data.</p><p><strong>Compaction Overview Diagram</strong></p><pre>Before compaction:<br><br>Old log file (42 bytes total, 30 bytes garbage):<br>┌──────────────────────────────────────────────────────────────┐<br>│ Entry 0: &quot;a&quot;=&quot;x&quot;      (10B) │ ← Garbage (overwritten)        │<br>│ Entry 1: &quot;b&quot;=&quot;yy&quot;     (11B) │ ← Garbage (deleted)            │<br>│ Entry 2: &quot;a&quot;=&quot;zzz&quot;    (12B) │ ← Live                         │<br>│ Entry 3: &quot;b&quot; tombstone (9B) │ ← Garbage (tombstone)          │<br>└──────────────────────────────────────────────────────────────┘<br><br>KeyDir (only live keys):<br>  &quot;a&quot; → ValueLocation{offset:X, len:3}<br><br>After compaction:<br><br>New log file (12 bytes total, 0 bytes garbage):<br>┌──────────────────────────────┐<br>│ Entry 0: &quot;a&quot;=&quot;zzz&quot;    (12B)  │ ← Only live data<br>└──────────────────────────────┘<br><br>New KeyDir:<br>  &quot;a&quot; → ValueLocation{offset:9, len:3}  (updated offset!)<br><br>Space saved: 42 - 12 = 30 bytes (71% reduction)</pre><h3>compact Implementation</h3><pre>impl BitCask {<br>    pub fn compact(&amp;mut self) -&gt; Result&lt;()&gt; {<br>    // Create new temporary log file, truncate if exists<br>    let new_path = self.log.path.with_extension(&quot;new&quot;);<br>    let mut new_log = Log::new(new_path)?;<br>    new_log.file.set_len(0)?;<br><br>    // Write all live entries to new log, generate new KeyDir<br>    let mut new_keydir = KeyDir::new();<br>    for (key, value_loc) in &amp;self.keydir {<br>        let value = self.log.read_value(*value_loc)?;<br>        let value_loc = new_log.write_entry(key, Some(&amp;value))?;<br>        new_keydir.insert(key.clone(), value_loc);<br>    }<br><br>    // Replace current log with new log<br>    std::fs::rename(&amp;new_log.path, &amp;self.log.path)?;<br>    new_log.path = self.log.path.clone();<br><br>    self.log = new_log;<br>    self.keydir = new_keydir;<br>    Ok(())<br>    }<br>}</pre><h3>Compaction Process</h3><p><strong>Detailed Compaction Process</strong></p><pre>Using the same example from overview:<br>  Old log: 42 bytes with 4 entries (3 garbage, 1 live)<br>  KeyDir: only &quot;a&quot; → {offset:18, len:3}<br><br>Step 1: Create new temporary log file<br>  Old file: /data/bitcask.log (42 bytes)<br>  New file: /data/bitcask.log.new (0 bytes, empty)<br><br>  File system state:<br>  ┌─────────────────────────────────────────────────┐<br>  │ bitcask.log     │ 42 bytes (with garbage)       │<br>  │ bitcask.log.new │  0 bytes (empty, truncated)   │<br>  └─────────────────────────────────────────────────┘<br><br>Step 2: Iterate through KeyDir and copy live entries<br><br>  Old log file structure:<br>  ┌──────────────────────────────────────────────────────────┐<br>  │ Entry 0: &quot;a&quot;=&quot;x&quot;     (10B)  offset: 0-9    │ ← Garbage   │<br>  │ Entry 1: &quot;b&quot;=&quot;yy&quot;    (11B)  offset: 10-20  │ ← Garbage   │<br>  │ Entry 2: &quot;a&quot;=&quot;zzz&quot;   (12B)  offset: 21-32  │ ← Live      │<br>  │ Entry 3: &quot;b&quot; tomb    (9B)   offset: 33-41  │ ← Garbage   │<br>  └──────────────────────────────────────────────────────────┘<br><br>  Old KeyDir (only live keys):<br>  ┌──────────────────────────────────┐<br>  │ Key  │ Old ValueLocation         │<br>  ├──────┼───────────────────────────┤<br>  │ &quot;a&quot;  │ {offset:29, len:3}        │ ← Points to Entry 2&#39;s value<br>  └──────────────────────────────────┘<br>         (offset = 21 + 4(KL) + 4(VL) + 1(key) = 30)<br><br>  Iteration 1: key=&quot;a&quot; (the only live key)<br>    Step 2a: Read value from old log<br>      log.read_value(ValueLocation{offset:30, len:3})<br>      → reads &quot;zzz&quot; from old log<br><br>    Step 2b: Write entry to new log<br>      new_log.write_entry(&quot;a&quot;, Some(&quot;zzz&quot;))<br>      → writes: [KL:1][VL:3][a][zzz] to offset 0<br><br>    Step 2c: Get new ValueLocation<br>      → ValueLocation{offset:9, len:3}<br>         (offset = 0 + 4(KL) + 4(VL) + 1(key) = 9)<br><br>    Step 2d: Insert into new KeyDir<br>      new_keydir.insert(&quot;a&quot;, ValueLocation{offset:9, len:3})<br><br>  New log file after copying:<br>  ┌──────────────────────────────────────────────┐<br>  │ Entry 0: &quot;a&quot;=&quot;zzz&quot;   (12B)  offset: 0-11     │ ← Only entry<br>  └──────────────────────────────────────────────┘<br>  Total: 12 bytes (100% live data, 0% garbage)<br><br>  New KeyDir:<br>  ┌──────────────────────────────────┐<br>  │ Key  │ New ValueLocation         │<br>  ├──────┼───────────────────────────┤<br>  │ &quot;a&quot;  │ {offset:9, len:3}         │ ← Updated offset!<br>  └──────────────────────────────────┘<br><br>Step 3: Atomic replacement<br>  1. Rename: bitcask.log.new → bitcask.log<br>     (This is an atomic filesystem operation)<br><br>  2. Update BitCask struct:<br>     self.log = new_log           (points to new file)<br>     self.keydir = new_keydir     (uses new offsets)<br><br>  File system state after rename:<br>  ┌─────────────────────────────────────────────────┐<br>  │ bitcask.log     │ 12 bytes (new, no garbage)    │<br>  └─────────────────────────────────────────────────┘<br>  (Old file is gone, OS reclaimed the 42 bytes)<br><br>Final result:<br>  - Old log: deleted by OS (42 bytes freed)<br>  - New log: 12 bytes (all live data)<br>  - KeyDir: 1 entry with updated offset<br>  - Garbage: 0 bytes (30 bytes reclaimed)<br>  - Space saved: 30 bytes (71% reduction)</pre><p>Compaction process summary:</p><p>1.Create new log:</p><ul><li>Path is original file with .new extension</li><li>If exists, truncate to empty file</li></ul><p>2.Write live data:</p><ul><li>Iterate current KeyDir (only contains live keys)</li><li>Read each value from old log</li><li>Write to new log (compactly arranged, no garbage)</li><li>Build new KeyDir (all offsets are new)</li></ul><p>3.Atomic replacement:</p><ul><li>Atomically overwrite old log with rename() system call</li><li>Update self.log and self.keydir</li></ul><h4>Compaction Effect</h4><p>After compaction:</p><ul><li>All garbage data removed</li><li>File size equals live data size</li><li>All offsets in KeyDir updated</li></ul><h4>Compaction Timing</h4><p>toyDB’s compaction strategy:</p><ul><li>Auto-compact at node startup (if garbage exceeds threshold)</li><li>Manual trigger (via compact() method)</li><li>No online compaction support (locks database)</li></ul><p>This simplified strategy suits small databases, avoiding complex background compaction logic.</p><h3>Persistence and Flushing</h3><h4>flush Implementation</h4><pre>impl Engine for BitCask {<br>    fn flush(&amp;mut self) -&gt; Result&lt;()&gt; {<br>        #[cfg(not(test))]<br>        self.log.file.sync_all()?;<br>        Ok(())<br>    }<br>}</pre><p>Flush operation:</p><ul><li>Calls sync_all() to flush file buffer to disk</li><li>Skipped in test environment (speeds up tests)</li></ul><h4>Auto-Flush on Drop</h4><pre>impl Drop for BitCask {<br>    fn drop(&amp;mut self) {<br>        if let Err(error) = self.flush() {<br>            error!(&quot;failed to flush file: {}&quot;, error)<br>        }<br>    }<br>}</pre><p>When BitCask is released:</p><ul><li>Automatically attempts flush</li><li>Logs error on failure (doesn’t panic)</li></ul><p>This ensures data is persisted during normal shutdown.</p><h4>Durability Guarantees</h4><p>BitCask’s durability relies on:</p><ol><li>append-only writes: Data appended to file end</li><li>Periodic flush: Flush buffer to disk</li><li>Crash recovery: Scan log to rebuild index, truncate incomplete entries</li></ol><p>Tradeoffs:</p><ul><li>Flush every write: Maximum durability, poor performance</li><li>Batch flush: Good performance, may lose recent writes</li></ul><p>toyDB uses batch flush, with upper layer (Raft) controlling flush timing.</p><h3>Exclusive Lock Mechanism</h3><p>BitCask uses file locks to prevent multi-process concurrent access to the same database.</p><h4>Lock Logic</h4><pre>impl Log {<br>    fn new(path: PathBuf) -&gt; Result&lt;Self&gt; {<br>        // ... open file ...<br>        if !file.try_lock_exclusive()? {<br>            return Err(Error::IO(format!(&quot;file {path:?} is already is use&quot;)));<br>        }<br>        Ok(Self { file, path })<br>    }<br>}</pre><p>Uses fs4 crate&#39;s try_lock_exclusive():</p><ul><li>Attempts to acquire exclusive lock</li><li>If already held by another process, immediately returns error</li><li>Non-blocking</li></ul><h4>Unlock Timing</h4><p>Lock automatically released at:</p><ol><li>File handle closed (BitCask Drop)</li><li>Process exits</li><li>Process crashes (OS automatically releases)</li></ol><h4>Why Need Lock?</h4><p>If multiple processes write simultaneously:</p><ul><li>Log file corrupted (interleaved writes)</li><li>KeyDir inconsistent</li><li>Data may be permanently lost</li></ul><p>File lock ensures only one process can access database at a time.</p><h3>Summary</h3><p>BitCask is an elegant storage engine design that uses simple append-only logs and in-memory indexing to implement high-performance persistent key-value storage.</p><p>toyDB’s implementation further simplifies standard BitCask, removing complex multi-file management and online compaction, making it more suitable for learning. Although there are sacrifices (single file can be large, database locked during compaction), the core ideas and implementation details are fully preserved.</p><h3>Notes</h3><h4>Why Does Compaction Lock the Database?</h4><p><strong>Analysis</strong></p><pre>pub fn compact(&amp;mut self) -&gt; Result&lt;()&gt; {<br>    // 1. Create new log file<br>    let mut new_log = Log::new(new_path)?;<br><br>    // 2. Copy all live entries (takes time!)<br>    for (key, value_loc) in &amp;self.keydir {<br>        let value = self.log.read_value(*value_loc)?;  // Read from old<br>        new_log.write_entry(key, Some(&amp;value))?;       // Write to new<br>    }<br><br>    // 3. Atomic swap<br>    std::fs::rename(&amp;new_log.path, &amp;self.log.path)?;<br>    self.log = new_log;        // Update log reference<br>    self.keydir = new_keydir;  // Update KeyDir with new offsets<br>}</pre><p>Reasons for Locking:</p><p>1.&amp;mut self Exclusive Borrow</p><ul><li>compact(&amp;mut self) requires mutable borrow of entire BitCask</li><li>During compaction, cannot perform simultaneous read/write operations</li><li>Rust’s borrow checker enforces this restriction</li></ul><p>2.KeyDir Rebuild Process</p><ul><li>Compaction requires building new KeyDir</li><li>All ValueLocation offsets must be updated</li><li>If concurrent reads allowed, would read incorrect offsets</li></ul><p>3.Log File Switching</p><ul><li>Switching from old to new log requires atomic operation</li><li>Replacing self.log is not thread-safe</li><li>Concurrent access leads to data inconsistency</li></ul><p><strong>Concurrency Problem Example</strong></p><pre>Without locking, this race condition could occur:<br><br>Thread 1 (Compaction):              Thread 2 (Read):<br>1. Create new log<br>2. Copy entries to new log<br>3. Build new KeyDir<br>                                    4. Get key from old KeyDir<br>                                       offset=30 (points to old log)<br>5. Rename: new → old log<br>6. Update self.log (now new log)<br>7. Update self.keydir (new offsets)<br>                                    8. Read from self.log<br>                                       (now points to NEW log!)<br>                                    9. Seek to offset=30<br>                                       (but new log is smaller!)<br>                                    10. ERROR: Read past end of file!<br><br>The problem: Thread 2 got an offset from the old KeyDir,<br>but by the time it reads, the log file has been replaced!</pre><p><strong>Standard BitCask Solutions</strong></p><p>Standard BitCask implementations support online compaction using the following techniques:</p><p>1.Multiple Log Files</p><ul><li>Use multiple fixed-size log files</li><li>When compacting old files, new writes go to new file</li><li>Reads can concurrently access different files</li></ul><p><strong>Multi-File Strategy Diagram</strong></p><pre>Normal operation with multiple log files:<br><br>File structure:<br>┌─────────────────────────────────────────────────────────────┐<br>│ bitcask.0.log  │ 10 MB (full, immutable, old)               │<br>│ bitcask.1.log  │ 10 MB (full, immutable, old)               │<br>│ bitcask.2.log  │ 10 MB (full, immutable, old)               │<br>│ bitcask.3.log  │  7 MB (active, currently writing)          │<br>└─────────────────────────────────────────────────────────────┘<br><br>KeyDir (maps keys to file + offset):<br>┌─────────────────────────────────────────────────┐<br>│ Key     │ File ID │ Offset │ Length             │<br>├─────────┼─────────┼────────┼────────────────────┤<br>│ &quot;apple&quot; │    0    │  1000  │   5                │<br>│ &quot;banana&quot;│    1    │  2000  │   6                │<br>│ &quot;cherry&quot;│    2    │  3000  │   6                │<br>│ &quot;date&quot;  │    3    │  4000  │   4    ← active    │<br>└─────────────────────────────────────────────────┘<br><br>Compacting file 0 while serving reads/writes:<br><br>Timeline:<br>┌────────────────────────────────────────────────────────────────┐<br>│ Thread 1: Compaction of file 0                                 │<br>├────────────────────────────────────────────────────────────────┤<br>│ t0: Start compacting bitcask.0.log                             │<br>│     (reads old entries, writes to new file)                    │<br>│                                                                │<br>│     ┌──────────────────┐                                       │<br>│     │ bitcask.0.log    │ ──┐                                   │<br>│     │ (being compacted)│   │ Read                              │<br>│     └──────────────────┘   │                                   │<br>│                            ↓                                   │<br>│     ┌──────────────────┐                                       │<br>│     │ bitcask.0.log.new│ ← Write compacted data                │<br>│     └──────────────────┘                                       │<br>│                                                                │<br>│ Meanwhile...                                                   │<br>├────────────────────────────────────────────────────────────────┤<br>│ Thread 2: Read &quot;banana&quot; from file 1                            │<br>│     ✓ Not blocked! File 1 is independent                       │<br>│                                                                │<br>│ Thread 3: Write new key &quot;elderberry&quot; to file 3                 │<br>│     ✓ Not blocked! Writing to active file                      │<br>│                                                                │<br>│ Thread 4: Read &quot;apple&quot; from file 0                             │<br>│     ✓ Not blocked! Compaction doesn&#39;t lock reads               │<br>├────────────────────────────────────────────────────────────────┤<br>│ t1: Compaction complete, atomic swap                           │<br>│     Rename: bitcask.0.log.new → bitcask.0.log                  │<br>│     Update KeyDir entries for file 0 (brief exclusive lock)    │<br>│                                                                │<br>│ t2: Old file 0 marked for deletion                             │<br>│     Wait for active readers to finish                          │<br>│                                                                │<br>│ t3: Delete old file 0                                          │<br>└────────────────────────────────────────────────────────────────┘<br><br>Key benefits:<br>- Compaction of file N doesn&#39;t block access to files M (N ≠ M)<br>- New writes always go to active file (never blocked)<br>- Reads can proceed concurrently across all files<br>- Only brief lock during KeyDir update<br><br>File lifecycle:<br>┌───────────┐      ┌──────────┐      ┌───────────┐<br>│  Active   │─10MB→│Immutable │─comp→│ Deleted   │<br>│  (write)  │      │ (read)   │      │           │<br>└───────────┘      └──────────┘      └───────────┘<br>     ↑                                      ↓<br>     └──────────── New active file ─────────┘<br><br>Implementation structure:<br>```rust<br>pub struct BitCask {<br>    files: Vec&lt;LogFile&gt;,           // Multiple log files<br>    active_file_id: usize,         // Currently writing file<br>    keydir: Arc&lt;RwLock&lt;KeyDir&gt;&gt;,   // Maps key → (file_id, offset)<br>}<br><br>pub struct KeyDir {<br>    map: BTreeMap&lt;Vec&lt;u8&gt;, ValueLocation&gt;,<br>}<br><br>pub struct ValueLocation {<br>    file_id: usize,   // Which file contains the value<br>    offset: u64,      // Offset within that file<br>    length: usize,    // Value length<br>}<br><br>// Read from specific file<br>fn get(&amp;self, key: &amp;[u8]) -&gt; Result&lt;Option&lt;Vec&lt;u8&gt;&gt;&gt; {<br>    let keydir = self.keydir.read().unwrap();<br>    let Some(loc) = keydir.get(key) else {<br>        return Ok(None);<br>    };<br><br>    // Access specific file (no global lock needed)<br>    let file = &amp;self.files[loc.file_id];<br>    file.read_value(loc.offset, loc.length)<br>}<br><br>// Compact specific file<br>fn compact_file(&amp;mut self, file_id: usize) -&gt; Result&lt;()&gt; {<br>    // Only locks KeyDir briefly during swap<br>    // Doesn&#39;t block access to other files<br>}</pre><p>2.Read-Write Lock (RwLock)</p><ul><li>Read operations acquire shared lock</li><li>Write operations and compaction acquire exclusive lock</li><li>Allows multiple concurrent reads</li></ul><p>Actual implementation:</p><pre>pub struct BitCask {<br>    log: Arc&lt;RwLock&lt;Log&gt;&gt;,          // Wrap log in RwLock<br>    keydir: Arc&lt;RwLock&lt;KeyDir&gt;&gt;,    // Wrap KeyDir in RwLock<br>}<br><br>// Read operation (shared lock)<br>fn get(&amp;self, key: &amp;[u8]) -&gt; Result&lt;Option&lt;Vec&lt;u8&gt;&gt;&gt; {<br>    let keydir = self.keydir.read().unwrap();  // Shared lock<br>    let Some(location) = keydir.get(key) else {<br>        return Ok(None);<br>    };<br><br>    let log = self.log.read().unwrap();        // Shared lock<br>    log.read_value(*location).map(Some)<br>    // Locks released when keydir and log go out of scope<br>}<br><br>// Write operation (exclusive lock)<br>fn set(&amp;self, key: &amp;[u8], value: Vec&lt;u8&gt;) -&gt; Result&lt;()&gt; {<br>    let mut log = self.log.write().unwrap();     // Exclusive lock<br>    let value_loc = log.write_entry(key, Some(&amp;value))?;<br><br>    let mut keydir = self.keydir.write().unwrap(); // Exclusive lock<br>    keydir.insert(key.to_vec(), value_loc);<br>    Ok(())<br>}<br><br>// Compaction (exclusive lock during swap only)<br>fn compact(&amp;self) -&gt; Result&lt;()&gt; {<br>    // 1. Create new log (no lock needed)<br>    let mut new_log = Log::new(new_path)?;<br>    let mut new_keydir = KeyDir::new();<br><br>    // 2. Copy data (using read lock for old data)<br>    {<br>        let old_keydir = self.keydir.read().unwrap();  // Shared lock<br>        let old_log = self.log.read().unwrap();        // Shared lock<br><br>        for (key, value_loc) in old_keydir.iter() {<br>            let value = old_log.read_value(*value_loc)?;<br>            let new_loc = new_log.write_entry(key, Some(&amp;value))?;<br>            new_keydir.insert(key.clone(), new_loc);<br>        }<br>        // Shared locks released here<br>    }<br><br>    // 3. Atomic swap (exclusive lock for minimal time)<br>    {<br>        let mut log = self.log.write().unwrap();      // Exclusive lock<br>        let mut keydir = self.keydir.write().unwrap(); // Exclusive lock<br><br>        std::fs::rename(&amp;new_log.path, &amp;log.path)?;<br>        *log = new_log;          // Swap log<br>        *keydir = new_keydir;    // Swap KeyDir<br>        // Exclusive locks released here<br>    }<br><br>    Ok(())<br>}</pre><p>Key optimizations:</p><ul><li>Use shared locks when copying data (doesn’t block reads)</li><li>Use exclusive lock only during swap (minimal blocking time)</li><li>Read operations unaffected throughout</li><li>Write operations only briefly blocked during final swap</li></ul><p>3.Deferred Deletion</p><ul><li>Don’t immediately delete old files after compaction</li><li>Wait for all reads to complete before deletion</li><li>Use reference counting to track active reads</li></ul><p><strong>Deferred Deletion Implementation</strong></p><pre>use std::sync::Arc;<br><br>pub struct LogFile {<br>    file: File,<br>    path: PathBuf,<br>    file_id: usize,<br>    // Reference counter tracks active readers<br>    // When Arc count drops to 1, file can be deleted<br>}<br><br>pub struct BitCask {<br>    // Use Arc to share ownership with active readers<br>    files: Vec&lt;Arc&lt;LogFile&gt;&gt;,<br>    active_file_id: usize,<br>    keydir: Arc&lt;RwLock&lt;KeyDir&gt;&gt;,<br>}<br><br>// Read operation clones Arc (increments ref count)<br>fn get(&amp;self, key: &amp;[u8]) -&gt; Result&lt;Option&lt;Vec&lt;u8&gt;&gt;&gt; {<br>    let keydir = self.keydir.read().unwrap();<br>    let Some(loc) = keydir.get(key) else {<br>        return Ok(None);<br>    };<br><br>    // Clone Arc to get shared ownership<br>    let file = Arc::clone(&amp;self.files[loc.file_id]);<br>    drop(keydir);  // Release KeyDir lock<br><br>    // Read from file (file kept alive by Arc)<br>    file.read_value(loc.offset, loc.length)<br>    // Arc dropped here, ref count decremented<br>}<br><br>// Compaction marks file for deletion<br>fn compact_file(&amp;mut self, file_id: usize) -&gt; Result&lt;()&gt; {<br>    // ... compaction logic ...<br><br>    // After swap, old file is marked for deletion<br>    let old_file = std::mem::replace(<br>        &amp;mut self.files[file_id],<br>        Arc::new(new_file)<br>    );<br><br>    // Spawn background thread to wait and delete<br>    std::thread::spawn(move || {<br>        // Wait for all readers to finish<br>        // This blocks until Arc::strong_count == 1<br>        // (only this thread holds reference)<br>        while Arc::strong_count(&amp;old_file) &gt; 1 {<br>            std::thread::sleep(Duration::from_millis(100));<br>        }<br><br>        // Now safe to delete<br>        let path = old_file.path.clone();<br>        drop(old_file);  // Close file<br>        std::fs::remove_file(path).ok();<br>    });<br><br>    Ok(())<br>}</pre><p><strong>Timeline Example</strong></p><pre>Compaction with deferred deletion:<br><br>t0: Start compaction of file 0<br>    ┌──────────────────────────────────────────────┐<br>    │ File 0: Arc strong_count = 1                 │<br>    │ (only BitCask.files[0] holds reference)      │<br>    └──────────────────────────────────────────────┘<br><br>t1: Thread A starts reading from file 0<br>    ┌──────────────────────────────────────────────┐<br>    │ File 0: Arc strong_count = 2                 │<br>    │ - BitCask.files[0]: 1                        │<br>    │ - Thread A&#39;s clone: 1                        │<br>    └──────────────────────────────────────────────┘<br><br>t2: Compaction completes, swap occurs<br>    ┌──────────────────────────────────────────────┐<br>    │ Old file 0: Arc strong_count = 2             │<br>    │ - Deletion thread: 1                         │<br>    │ - Thread A (still reading): 1                │<br>    │                                              │<br>    │ New file 0: Arc strong_count = 1             │<br>    │ - BitCask.files[0]: 1                        │<br>    └──────────────────────────────────────────────┘<br><br>    Deletion thread: Waiting... (count &gt; 1)<br><br>t3: Thread A finishes reading<br>    ┌──────────────────────────────────────────────┐<br>    │ Old file 0: Arc strong_count = 1             │<br>    │ - Deletion thread: 1                         │<br>    │ - Thread A: dropped                          │<br>    └──────────────────────────────────────────────┘<br><br>    Deletion thread: Count == 1, safe to delete!<br><br>t4: File deleted<br>    ┌──────────────────────────────────────────────┐<br>    │ Old file 0: Deleted from filesystem          │<br>    │ - Arc dropped, file closed                   │<br>    │ - Disk space reclaimed                       │<br>    └──────────────────────────────────────────────┘</pre><p>Key Points</p><p>1.Arc (Atomic Reference Counting)</p><ul><li>Tracks how many references to file exist</li><li>Thread-safe, allows concurrent access</li><li>File kept alive while any reader holds Arc</li></ul><p>2.Safe Deletion</p><ul><li>Can’t delete while readers are active</li><li>Deletion thread polls reference count</li><li>Only deletes when count drops to 1</li></ul><p>3.No Race Conditions</p><pre>Scenario: Reader tries to access deleted file<br><br>x Without Arc:<br>Thread A: Get key from KeyDir (file_id=0)<br>Thread B: Compact file 0, swap, DELETE immediately<br>Thread A: Try to read file 0<br>Thread A: ERROR! File doesn&#39;t exist!<br><br>✓ With Arc:<br>Thread A: Get key from KeyDir, clone Arc (count=2)<br>Thread B: Compact file 0, swap, mark for deletion<br>Thread B: Wait... count=2 (Thread A still reading)<br>Thread A: Read from file 0 (Arc keeps file alive)<br>Thread A: Done, drop Arc (count=1)<br>Thread B: Count=1, safe to delete!<br>Thread B: Delete file 0</pre><p>4.Memory Overhead</p><ul><li>Each Arc is 16 bytes (pointer + counters)</li><li>Small cost for safe concurrent access</li><li>Alternative: use explicit reader tracking with mutexes</li></ul><p>5.Alternative: Epoch-Based Reclamation</p><pre>struct FileRegistry {<br>    current_epoch: AtomicU64,<br>    readers: Vec&lt;(FileId, Epoch)&gt;,<br>    pending_deletes: Vec&lt;(FileId, Epoch)&gt;,<br>}<br><br>// Reader marks epoch when starting<br>fn start_read() -&gt; Epoch {<br>    registry.current_epoch.load(Ordering::Acquire)<br>}<br><br>// Compaction marks file for deletion with current epoch<br>fn mark_for_delete(file_id: FileId) {<br>    let epoch = registry.current_epoch.fetch_add(1);<br>    registry.pending_deletes.push((file_id, epoch));<br>}<br><br>// Background thread deletes files older than all active readers<br>fn cleanup() {<br>    let min_active_epoch = registry.readers.iter()<br>        .map(|(_, epoch)| epoch)<br>        .min();<br><br>    registry.pending_deletes.retain(|(file_id, epoch)| {<br>        if epoch &lt; min_active_epoch {<br>            delete_file(file_id);<br>            false  // Remove from pending<br>        } else {<br>            true   // Keep waiting<br>        }<br>    });<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=548c882a57cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【知其然，更知其所以然】toyDB：BitCask 存儲引擎解析]]></title>
            <link>https://medium.com/@wudiheroback/%E7%9F%A5%E5%85%B6%E7%84%B6-%E6%9B%B4%E7%9F%A5%E5%85%B6%E6%89%80%E4%BB%A5%E7%84%B6-toydb-memory-%E5%AD%98%E5%84%B2%E5%BC%95%E6%93%8E%E8%A7%A3%E6%9E%90-241d06263998?source=rss-83005aa59123------2</link>
            <guid isPermaLink="false">https://medium.com/p/241d06263998</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Stan Hsu]]></dc:creator>
            <pubDate>Sat, 11 Oct 2025 13:19:51 GMT</pubDate>
            <atom:updated>2025-10-12T04:58:28.969Z</atom:updated>
            <content:encoded><![CDATA[<p>本文深入解析 toyDB 的 BitCask 存儲引擎，展示如何實現一個簡單高效的持久化 key-value 存儲系統。</p><p>BitCask 是 toyDB 的主要存儲引擎，使用 append-only 日誌結構和內存索引，在保證持久性的同時提供極快的讀寫性能。這個實現源自 Riak 數據庫的 BitCask 論文，但做了大幅簡化，更適合學習理解。</p><p><a href="https://github.com/erikgrinaker/toydb/blob/main/src/storage/bitcask.rs">完整源碼請查看</a></p><h3>核心設計理念</h3><p>BitCask 的核心思想是：將所有寫入追加到日誌文件，在內存中維護 key 到文件偏移的映射。</p><h4>設計優勢</h4><ol><li>寫入性能極佳：所有寫入都是順序追加，充分利用磁盤的順序寫入優勢</li><li>讀取性能優秀：一次內存查找 + 一次磁盤隨機讀取</li><li>崩潰恢復簡單：掃描日誌文件重建內存索引即可</li></ol><h4>設計限制</h4><ol><li>所有活躍 key 必須放入內存：KeyDir 存儲所有鍵，限制了可存儲的鍵數量</li><li>需要定期壓縮：刪除和更新會產生垃圾數據，需要壓縮回收空間</li><li>檔案可能很大：使用單一日誌文件，可能超過文件系統限制</li></ol><p>toyDB 的實現針對教學場景，進一步簡化了標準 BitCask：</p><ul><li>使用單一日誌文件而非多個固定大小的文件</li><li>壓縮時會鎖定整個數據庫</li><li>不使用 hint 文件，直接掃描日誌</li><li>不記錄時間戳和校驗和</li></ul><h3>數據結構設計</h3><h4>BitCask 結構</h4><pre>pub struct BitCask {<br>    /// 當前的 append-only 日誌文件<br>    log: Log,<br>    /// 從鍵映射到值在日誌中的位置和長度<br>    keydir: KeyDir,<br>}</pre><p>核心組件：</p><ul><li>log：封裝了日誌文件的讀寫操作</li><li>keydir：內存中的索引，記錄每個鍵的值在文件中的位置</li></ul><h4>KeyDir 索引</h4><pre>type KeyDir = BTreeMap&lt;Vec&lt;u8&gt;, ValueLocation&gt;;</pre><p>KeyDir 是從鍵到值位置的映射：</p><ul><li>使用 BTreeMap 保持鍵的有序性，支持範圍掃描</li><li>鍵是 Vec&lt;u8&gt;：原始字節，支持任意數據</li><li>值是 ValueLocation：記錄值在文件中的位置</li></ul><h4>ValueLocation 結構</h4><pre>struct ValueLocation {<br>    offset: u64,    // 值在文件中的起始位置<br>    length: usize,  // 值的長度<br>}<br><br>impl ValueLocation {<br>    fn end(&amp;self) -&gt; u64 {<br>        self.offset + self.length as u64<br>    }<br>}</pre><p>ValueLocation 記錄值的位置信息：</p><ul><li>offset：從文件開頭算起的字節偏移</li><li>length：值的字節長度</li><li>end()：計算值的結束位置</li></ul><h4>Log 結構</h4><pre>struct Log {<br>    file: File,      // 打開的日誌文件<br>    path: PathBuf,   // 日誌文件路徑<br>}</pre><p>Log 封裝了日誌文件的操作：</p><ul><li>file：實際的文件句柄，支持讀寫</li><li>path：文件路徑，用於重新打開和重命名</li></ul><h3>日誌文件格式</h3><p>BitCask 的日誌文件由一系列條目組成，每個條目的格式：</p><pre>|------------------+------------------+------------------+------------------|<br>| Key Length (4B)  | Value Length (4B)|      Key         |      Value       |<br>| Big-Endian u32   | Big-Endian i32   |   Raw Bytes      |   Raw Bytes      |<br>|------------------+------------------+------------------+------------------|</pre><h4>格式細節</h4><p>1.Key Length：4 字節，大端序 u32</p><p>2.Value Length：4 字節，大端序 i32</p><ul><li>正數：表示值的長度</li><li>-1：表示墓碑（tombstone），即刪除標記</li></ul><p>3.Key：原始字節，長度由 Key Length 指定</p><p>4.Value：原始字節，長度由 Value Length 指定（墓碑沒有這部分）</p><h3>創建和打開</h3><h4>打開數據庫</h4><pre>impl BitCask {<br>    pub fn new(path: PathBuf) -&gt; Result&lt;Self&gt; {<br>        let mut log = Log::new(path.clone())?;<br>        let keydir = log.build_keydir()?;<br>        info!(&quot;Opened {} with {} live keys&quot;, path.display(), keydir.len());<br>        Ok(Self { log, keydir })<br>    }<br>}</pre><p>打開流程：</p><ol><li>創建或打開日誌文件（Log::new）</li><li>掃描日誌構建 KeyDir（log.build_keydir）</li><li>記錄日誌，顯示活躍鍵數量</li><li>返回 BitCask 實例</li></ol><h4>帶自動壓縮的打開</h4><pre>impl BitCask {<br>    pub fn new_maybe_compact(<br>        path: PathBuf,<br>        garbage_min_fraction: f64,<br>        garbage_min_bytes: u64,<br>    ) -&gt; Result&lt;Self&gt; {<br>        let mut engine = Self::new(path)?;<br><br>    let status = engine.status()?;<br>    let total_size = status.disk_size;<br>    let garbage_size = status.garbage_disk_size();<br>    let garbage_fraction = garbage_size as f64 / total_size as f64;<br><br>    if garbage_size &gt; 0<br>        &amp;&amp; garbage_size &gt;= garbage_min_bytes<br>        &amp;&amp; garbage_fraction &gt;= garbage_min_fraction<br>    {<br>        info!(<br>            &quot;Compacting {} to remove {:.0}% garbage ({:.1} MB out of {:.1} MB)&quot;,<br>            engine.log.path.display(),<br>            garbage_fraction * 100.0,<br>            garbage_size as f64 / 1024.0 / 1024.0,<br>            total_size as f64 / 1024.0 / 1024.0<br>        );<br>        engine.compact()?;<br>        info!(<br>            &quot;Compacted {} to size {:.1} MB&quot;,<br>            engine.log.path.display(),<br>            (total_size - garbage_size) as f64 / 1024.0 / 1024.0<br>        );<br>    }<br><br>    Ok(engine)<br>    }<br>}</pre><p>自動壓縮邏輯：</p><ol><li>先正常打開數據庫</li><li>查詢狀態，計算垃圾比例</li><li>如果垃圾大小和比例都超過閾值，執行壓縮</li><li>記錄壓縮前後的大小</li></ol><p>這個方法適合在節點啟動時使用，自動清理累積的垃圾數據。</p><h4>打開日誌文件</h4><pre>impl Log {<br>    fn new(path: PathBuf) -&gt; Result&lt;Self&gt; {<br>        if let Some(dir) = path.parent() {<br>            std::fs::create_dir_all(dir)?<br>        }<br>        let file = std::fs::OpenOptions::new()<br>            .read(true)<br>            .write(true)<br>            .create(true)<br>            .truncate(false)<br>            .open(&amp;path)?;<br>        if !file.try_lock_exclusive()? {<br>            return Err(Error::IO(format!(&quot;file {path:?} is already is use&quot;)));<br>        }<br>        Ok(Self { file, path })<br>    }<br>}</pre><p>關鍵步驟：</p><ol><li>創建目錄：確保父目錄存在</li><li>打開文件：讀寫模式，不存在則創建，不截斷</li><li>獨占鎖：使用 fs4 crate 獲取排他鎖，防止多進程同時訪問</li><li>返回 Log：包含文件句柄和路徑</li></ol><p>獨占鎖是關鍵：確保同一時間只有一個進程能訪問數據庫文件，避免數據損壞。</p><h3>構建 KeyDir</h3><p>KeyDir 是內存索引，記錄所有活躍鍵的位置。打開數據庫時需要掃描日誌文件來構建它。</p><h4>build_keydir 實現</h4><p>Scanning Detail Diagram</p><pre>Scanning a single entry:<br><br>File position: offset = 0<br>┌───────────────────────────────────────────────────┐<br>│  [00 00 00 03]  [00 00 00 05]  [6B 65 79]  [...]  │<br>│   Key Length     Value Length      Key      Value │<br>│    (u32=3)        (i32=5)        &quot;key&quot;    &quot;alice&quot; │<br>└───────────────────────────────────────────────────┘<br>     ↓                ↓                ↓         ↓<br>   Read &amp; parse    Read &amp; parse     Read key   Skip value<br>                                               (only need location)<br><br>Calculate ValueLocation:<br>  offset = current_pos + 8 (two length fields) + key_len<br>        = 0 + 8 + 3 = 11<br>  length = value_len = 5<br><br>Update KeyDir:<br>  KeyDir.insert(&quot;key&quot;, ValueLocation { offset: 11, length: 5 })<br><br>Move to next entry:<br>  next_offset = current_pos + 8 + key_len + value_len<br>              = 0 + 8 + 3 + 5 = 16</pre><pre>impl Log {<br>    fn build_keydir(&amp;mut self) -&gt; Result&lt;KeyDir&gt; {<br>    let mut len_buf = [0u8; 4];<br>    let mut keydir = KeyDir::new();<br>    let file_len = self.file.metadata()?.len();<br>    let mut r = BufReader::new(&amp;mut self.file);<br>    let mut offset = r.seek(SeekFrom::Start(0))?;<br><br>    while offset &lt; file_len {<br>        // 讀取下一個條目，返回鍵和值位置（None 表示墓碑）<br>        let result = || -&gt; StdResult&lt;(Vec&lt;u8&gt;, Option&lt;ValueLocation&gt;), std::io::Error&gt; {<br>            // 讀取鍵長度：4 字節 u32<br>            r.read_exact(&amp;mut len_buf)?;<br>            let key_len = u32::from_be_bytes(len_buf);<br><br>            // 讀取值長度：4 字節 i32，-1 表示墓碑<br>            r.read_exact(&amp;mut len_buf)?;<br>            let value_loc = match i32::from_be_bytes(len_buf) {<br>                ..0 =&gt; None, // 墓碑<br>                len =&gt; Some(ValueLocation {<br>                    offset: offset + 8 + key_len as u64,<br>                    length: len as usize,<br>                }),<br>            };<br><br>            // 讀取鍵<br>            let mut key = vec![0; key_len as usize];<br>            r.read_exact(&amp;mut key)?;<br><br>            // 跳過值（只需要位置，不需要內容）<br>            if let Some(value_loc) = value_loc {<br>                if value_loc.end() &gt; file_len {<br>                    return Err(std::io::Error::new(<br>                        std::io::ErrorKind::UnexpectedEof,<br>                        &quot;value extends beyond end of file&quot;,<br>                    ));<br>                }<br>                r.seek_relative(value_loc.length as i64)?;<br>            }<br><br>            // 更新文件偏移<br>            offset += 8 + key_len as u64 + value_loc.map_or(0, |v| v.length) as u64;<br><br>            Ok((key, value_loc))<br>        }();<br><br>        // 更新 KeyDir<br>        match result {<br>            Ok((key, Some(value_loc))) =&gt; keydir.insert(key, value_loc),<br>            Ok((key, None)) =&gt; keydir.remove(&amp;key),<br>            // 如果在文件末尾發現不完整的條目，假設是不完整的寫入，截斷文件<br>            Err(err) if err.kind() == std::io::ErrorKind::UnexpectedEof =&gt; {<br>                error!(&quot;Found incomplete entry at offset {offset}, truncating file&quot;);<br>                self.file.set_len(offset)?;<br>                break;<br>            }<br>            Err(err) =&gt; return Err(err.into()),<br>        };<br>    }<br><br>    Ok(keydir)<br>    }<br>}</pre><h4>掃描過程</h4><p>1.初始化：創建空 KeyDir，獲取文件長度</p><p>2.逐條目掃描：</p><ul><li>讀取鍵長度和值長度</li><li>讀取鍵內容</li><li>跳過值內容（只需要位置）</li><li>計算值位置：offset + 8 + key_len</li></ul><p>3.更新 KeyDir：</p><ul><li>正常值：插入或更新鍵</li><li>墓碑：刪除鍵</li><li>不完整條目：截斷文件，停止掃描</li></ul><p>4.返回 KeyDir</p><h4>崩潰恢復</h4><p>如果寫入過程中程序崩潰，文件末尾可能有不完整的條目。build_keydir 會：</p><ol><li>檢測到 UnexpectedEof 錯誤</li><li>將文件截斷到最後一個完整條目</li><li>繼續正常啟動</li></ol><p>這個設計保證了崩潰恢復的簡單性：只需重新掃描文件即可。</p><h3>基本操作</h3><h4>寫入數據 — set</h4><pre>impl Engine for BitCask {<br>    fn set(&amp;mut self, key: &amp;[u8], value: Vec&lt;u8&gt;) -&gt; Result&lt;()&gt; {<br>        let value_location = self.log.write_entry(key, Some(&amp;*value))?;<br>        self.keydir.insert(key.to_vec(), value_location);<br>        Ok(())<br>    }<br>}</pre><p>寫入流程：</p><ol><li>調用 log.write_entry 將條目追加到日誌</li><li>獲取值的位置信息</li><li>更新 KeyDir 中的映射</li></ol><p>注意：Some(&amp;*value) 將 Vec&lt;u8&gt; 轉換為 Option&lt;&amp;[u8]&gt;。</p><h4>讀取數據 — get</h4><pre>impl Engine for BitCask {<br>    fn get(&amp;mut self, key: &amp;[u8]) -&gt; Result&lt;Option&lt;Vec&lt;u8&gt;&gt;&gt; {<br>        let Some(location) = self.keydir.get(key) else {<br>            return Ok(None);<br>        };<br>        self.log.read_value(*location).map(Some)<br>    }<br>}</pre><p>讀取流程：</p><ol><li>在 KeyDir 中查找鍵</li><li>如果不存在，返回 None</li><li>如果存在，根據位置從日誌讀取值</li></ol><p>性能特點：</p><ul><li>一次內存查找（KeyDir）：O(log n)</li><li>一次磁盤隨機讀（日誌文件）：O(1)</li></ul><h4>刪除數據 — delete</h4><pre>impl Engine for BitCask {<br>    fn delete(&amp;mut self, key: &amp;[u8]) -&gt; Result&lt;()&gt; {<br>        self.log.write_entry(key, None)?;<br>        self.keydir.remove(key);<br>        Ok(())<br>    }<br>}</pre><p>刪除流程：</p><ol><li>寫入墓碑到日誌（value = None）</li><li>從 KeyDir 中移除鍵</li></ol><p>關鍵點：</p><ul><li>刪除不會立即回收空間</li><li>墓碑會永久留在日誌中，直到壓縮</li><li>KeyDir 立即更新，讀取時看不到已刪除的鍵</li></ul><h3>日誌讀寫</h3><h4>寫入條目 — write_entry</h4><p>Write Process Diagram</p><pre>Write operation: log.write_entry(b&quot;user&quot;, Some(b&quot;alice&quot;))<br><br>Step 1: Seek to end of file<br>┌─────────────────────────────────────┐<br>│  Existing data...                   │<br>│                                     │  ← File end: offset = 100<br>└─────────────────────────────────────┘<br><br>Step 2: Prepare data to write<br>key = &quot;user&quot; (4 bytes)<br>value = &quot;alice&quot; (5 bytes)<br><br>Encode as:<br>┌──────────────┬──────────────┬──────────────┬───────────────┐<br>│ [00 00 00 04]│ [00 00 00 05]│ [75 73 65 72]│ [61 6C 69...] │<br>│  Key Length  │ Value Length │     Key      │     Value     │<br>│   (u32=4)    │   (i32=5)    │    &quot;user&quot;    │    &quot;alice&quot;    │<br>└──────────────┴──────────────┴──────────────┴───────────────┘<br>   4 bytes        4 bytes         4 bytes        5 bytes<br><br>   Total: 8 + 4 + 5 = 17 bytes<br><br>Step 3: Write to file<br>┌─────────────────────────────────────┬──────────────────────┐<br>│  Existing data...                   │ [New entry 17 bytes] │<br>│                                     │                      │<br>└─────────────────────────────────────┴──────────────────────┘<br> ↑                                     ↑<br> offset = 0                            offset = 100 (write position)<br><br>Step 4: Return ValueLocation<br>ValueLocation {<br>    offset: 100 + 8 + 4 = 112,  // skip two length fields and key<br>    length: 5                    // value length<br>}</pre><p><strong>Tombstone Write Diagram</strong></p><pre>Delete operation: log.write_entry(b&quot;user&quot;, None)<br><br>Encode as:<br>┌──────────────┬──────────────┬──────────────┐<br>│ [00 00 00 04]│ [FF FF FF FF]│ [75 73 65 72]│  (no Value part)<br>│  Key Length  │ Value Length │     Key      │<br>│   (u32=4)    │   (i32=-1)   │    &quot;user&quot;    │<br>└──────────────┴──────────────┴──────────────┘<br>   4 bytes        4 bytes         4 bytes<br><br>   Total: 8 + 4 = 12 bytes (tombstone has no value)<br><br>Return ValueLocation {<br>    offset: 112,  // value position (though no value exists)<br>    length: 0     // length is 0<br>}</pre><p><strong>Sequential Write Diagram</strong></p><pre>Three consecutive writes:<br>1. write_entry(b&quot;a&quot;, Some(b&quot;x&quot;))<br>2. write_entry(b&quot;bb&quot;, Some(b&quot;yy&quot;))<br>3. write_entry(b&quot;a&quot;, None)  // delete &quot;a&quot;<br><br>File content:<br>┌─────────────────────────────────────────────────────────────────────┐<br>│ Entry 0: offset=0                                                   │<br>│ ┌─────────┬─────────┬─────┬─────┐                                   │<br>│ │ KL: 1   │ VL: 1   │ a   │ x   │  ValueLocation{offset:9, len:1}   │<br>│ │ (4 B)   │ (4 B)   │(1 B)│(1 B)│                                   │<br>│ └─────────┴─────────┴─────┴─────┘                                   │<br>│ Total: 4 + 4 + 1 + 1 = 10 bytes                                     │<br>├─────────────────────────────────────────────────────────────────────┤<br>│ Entry 1: offset=10                                                  │<br>│ ┌─────────┬─────────┬──────┬──────┐                                 │<br>│ │ KL: 2   │ VL: 2   │ bb   │ yy   │  ValueLocation{offset:20, len:2}│<br>│ │ (4 B)   │ (4 B)   │(2 B) │(2 B) │                                 │<br>│ └─────────┴─────────┴──────┴──────┘                                 │<br>│ Total: 4 + 4 + 2 + 2 = 12 bytes                                     │<br>├─────────────────────────────────────────────────────────────────────┤<br>│ Entry 2: offset=22                                                  │<br>│ ┌─────────┬─────────┬─────┐                                         │<br>│ │ KL: 1   │ VL: -1  │ a   │  (tombstone)                            │<br>│ │ (4 B)   │ (4 B)   │(1 B)│  ValueLocation{offset:31, len:0}        │<br>│ └─────────┴─────────┴─────┘                                         │<br>│ Total: 4 + 4 + 1 = 9 bytes (no value for tombstone)                 │<br>└─────────────────────────────────────────────────────────────────────┘<br><br>KeyDir state changes:<br>After Entry 0: KeyDir[&quot;a&quot;] = {offset:9, len:1}<br>                (offset = 0 + 4(KL) + 4(VL) + 1(key) = 9)<br>After Entry 1: KeyDir[&quot;bb&quot;] = {offset:20, len:2}<br>                (offset = 10 + 4(KL) + 4(VL) + 2(key) = 20)<br>After Entry 2: KeyDir.remove(&quot;a&quot;)<br><br>Final KeyDir:<br>  Only &quot;bb&quot; → {offset:20, len:2}<br><br>Garbage data:<br>  Entry 0 (a=x) and Entry 2 (tombstone) are both garbage, need compaction</pre><pre>impl Log {<br>    fn write_entry(&amp;mut self, key: &amp;[u8], value: Option&lt;&amp;[u8]&gt;) -&gt; Result&lt;ValueLocation&gt; {<br>    let length = 8 + key.len() + value.map_or(0, |v| v.len());<br>    let offset = self.file.seek(SeekFrom::End(0))?;<br>    let mut w = BufWriter::with_capacity(length, &amp;mut self.file);<br><br>    // 鍵長度：4 字節 u32<br>    w.write_all(&amp;(key.len() as u32).to_be_bytes())?;<br><br>    // 值長度：4 字節 i32，墓碑為 -1<br>    w.write_all(&amp;value.map_or(-1, |v| v.len() as i32).to_be_bytes())?;<br><br>    // 實際的鍵和值<br>    w.write_all(key)?;<br>    w.write_all(value.unwrap_or_default())?;<br>    w.flush()?;<br><br>    // 將條目位置轉換為值位置<br>    Ok(ValueLocation {<br>        offset: offset + 8 + key.len() as u64,<br>        length: value.map_or(0, |v| v.len()),<br>    })<br>    }<br>}</pre><p>寫入步驟：</p><p>1.計算長度：8 + key_len + value_len（8 是兩個長度欄位）</p><p>2.定位到文件末尾：seek(SeekFrom::End(0))</p><p>3.創建緩衝寫入器：使用計算出的長度作為緩衝區大小</p><p>4.寫入四部分：</p><ul><li>鍵長度（4 字節）</li><li>值長度（4 字節，墓碑為 -1）</li><li>鍵內容</li><li>值內容（墓碑為空）</li></ul><p>5.刷新緩衝：確保數據寫入文件</p><p>6.返回位置：值的起始偏移和長度</p><h4>讀取值 — read_value</h4><p><strong>Read Value Diagram</strong></p><pre>Given: ValueLocation{offset:20, len:5}<br>Task: Read the value &quot;alice&quot; from the log file<br><br>Log file content:<br>┌────────────────────────────────────────────────────────────────────────────┐<br>│                                                                            │<br>│  offset:                                                                   │<br>│     0        10       20       25                                          │<br>│     │         │        │        │                                          │<br>│     v         v        v        v                                          │<br>│  [Entry 0] [Entry 1] [alice] [Entry 2]...                                  │<br>│                        ┌─────────────────────┐                             │<br>│                        │    4B   │   4B  │2B │ 5B                          │<br>│                        │   KL    │  VL   │key│value                        │<br>│                        │    2    │   5   │bb │alice                        │<br>│                        └─────────────────────┘                             │<br>│                                              ↑                             │<br>│                                              └─ ValueLocation points here  │<br>└────────────────────────────────────────────────────────────────────────────┘<br><br>Step 1: Allocate buffer<br>  let mut value = vec![0; 5];  // Create 5-byte buffer<br>  value = [0x00, 0x00, 0x00, 0x00, 0x00]<br><br>Step 2: Seek to offset<br>  file.seek(SeekFrom::Start(20))<br>  ┌─────────────────────────────────────┐<br>  │  [Entry 0] [Entry 1] [alice] ...    │<br>  │                       ↑             │<br>  │                    offset=20        │<br>  │                   (seek here)       │<br>  └─────────────────────────────────────┘<br><br>Step 3: Read exact bytes<br>  file.read_exact(&amp;mut value)<br>  Read 5 bytes from current position<br>  ┌─────────────────────────────────────┐<br>  │  [Entry 0] [Entry 1] [alice] ...    │<br>  │                       ├─────┤       │<br>  │                       read 5B       │<br>  └─────────────────────────────────────┘<br><br>  value = [0x61, 0x6C, 0x69, 0x63, 0x65]<br>        = [&#39;a&#39;,  &#39;l&#39;,  &#39;i&#39;,  &#39;c&#39;,  &#39;e&#39;]<br><br>Step 4: Return value<br>  Ok(vec![0x61, 0x6C, 0x69, 0x63, 0x65])</pre><p><strong>Complete Example with KeyDir Lookup</strong></p><pre>User request: engine.get(b&quot;bb&quot;)<br><br>Step 1: Lookup in KeyDir<br>  KeyDir:<br>  ┌────────────────────────────┐<br>  │ Key  │  ValueLocation      │<br>  ├──────┼─────────────────────┤<br>  │ &quot;bb&quot; │ {offset:20, len:5}  │ ← Found!<br>  └────────────────────────────┘<br><br>Step 2: Read value from log<br>  log.read_value(ValueLocation{offset:20, len:5})<br><br>  Log file structure:<br>  ┌──────────────────────────────────────────────────────────────┐<br>  │ Offset: 0                  10                    22          │<br>  │         │                   │                     │          │<br>  │         v                   v                     v          │<br>  │  ┌──────────────┐  ┌────────────────────────┐  ┌───────┐     │<br>  │  │   Entry 0    │  │      Entry 1           │  │Entry 2│     │<br>  │  │ (10 bytes)   │  │     (12 bytes)         │  │(9 B)  │     │<br>  │  ├──┬──┬──┬──┬──┤  ├──┬──┬────┬─────────────┤  └───────┘     │<br>  │  │KL│VL│a │x │  │  │KL│VL│ bb │   alice     │                │<br>  │  │4B│4B│1B│1B│  │  │4B│4B│ 2B │    5B       │                │<br>  │  └──┴──┴──┴──┴──┘  └──┴──┴────┴─────────────┘                │<br>  │                               ↑             ↑                │<br>  │                           offset:20     offset:25            │<br>  │                           (value start) (value end)          │<br>  │                               └─────────────┘                │<br>  │                                Read 5 bytes                  │<br>  └──────────────────────────────────────────────────────────────┘<br><br>Step 3: Return result<br>  Some(b&quot;alice&quot;.to_vec())<br><br>Performance:<br>  - KeyDir lookup: O(log n) in-memory BTreeMap search<br>  - Disk seek: O(1) single random seek to offset 20<br>  - Disk read: O(1) single sequential read of 5 bytes<br>  - Total: O(log n) + 2 * O(1) disk I/O</pre><pre>impl Log {<br>    fn read_value(&amp;mut self, location: ValueLocation) -&gt; Result&lt;Vec&lt;u8&gt;&gt; {<br>        let mut value = vec![0; location.length];<br>        self.file.seek(SeekFrom::Start(location.offset))?;<br>        self.file.read_exact(&amp;mut value)?;<br>        Ok(value)<br>    }<br>}</pre><p>讀取步驟：</p><ol><li>分配值大小的緩衝區</li><li>定位到值的起始位置</li><li>讀取精確長度的數據</li><li>返回值</li></ol><p>簡單直接：一次 seek + 一次 read。</p><h3>範圍掃描</h3><p>範圍掃描利用 KeyDir（BTreeMap）的有序性，實現高效的範圍查詢。</p><h4>scan 實現</h4><pre>impl Engine for BitCask {<br>    fn scan(&amp;mut self, range: impl RangeBounds&lt;Vec&lt;u8&gt;&gt;) -&gt; Self::ScanIterator&lt;&#39;_&gt; {<br>        ScanIterator { inner: self.keydir.range(range), log: &amp;mut self.log }<br>    }<br>}</pre><p>直接包裝 BTreeMap 的範圍迭代器：</p><ul><li>keydir.range(range) 返回範圍內的鍵值對</li><li>創建 ScanIterator 包裝它</li></ul><h4>ScanIterator 結構</h4><pre>pub struct ScanIterator&lt;&#39;a&gt; {<br>    inner: Range&lt;&#39;a, Vec&lt;u8&gt;, ValueLocation&gt;,<br>    log: &amp;&#39;a mut Log,<br>}</pre><p>包含：</p><ul><li>inner：BTreeMap 的範圍迭代器</li><li>log：日誌文件的可變引用，用於讀取值</li></ul><h4>Iterator 實現</h4><p>Scan Iterator Diagram</p><pre>User request: engine.scan(b&quot;b&quot;.to_vec()..b&quot;d&quot;.to_vec())<br>Task: Scan all keys in range [b, d)<br><br>Initial state:<br>  KeyDir (BTreeMap):<br>  ┌─────────────────────────────────────┐<br>  │ Key     │  ValueLocation            │<br>  ├─────────┼───────────────────────────┤<br>  │ &quot;apple&quot; │  {offset:10, len:5}       │  (before range)<br>  │ &quot;banana&quot;│  {offset:30, len:6}       │  ← Range starts here<br>  │ &quot;cherry&quot;│  {offset:50, len:6}       │  ← In range<br>  │ &quot;date&quot;  │  {offset:70, len:4}       │  (after range, excluded)<br>  └─────────────────────────────────────┘<br><br>Create ScanIterator:<br>  ScanIterator {<br>    inner: keydir.range(b&quot;b&quot;..b&quot;d&quot;),  // BTreeMap range iterator<br>    log: &amp;mut self.log                 // Reference to log file<br>  }<br><br>Iteration process:<br><br>┌─────────────────────────────────────────────────────────────────┐<br>│ Call #1: iter.next()                                            │<br>├─────────────────────────────────────────────────────────────────┤<br>│ Step 1: inner.next() returns Some((&quot;banana&quot;, ValueLocation))    │<br>│         ┌────────────────────────────┐                          │<br>│         │ Key: &quot;banana&quot;              │                          │<br>│         │ ValueLocation{offset:30,   │                          │<br>│         │               len:6}       │                          │<br>│         └────────────────────────────┘                          │<br>│                                                                 │<br>│ Step 2: Clone key: &quot;banana&quot;.to_vec()                            │<br>│                                                                 │<br>│ Step 3: Read value from log:                                    │<br>│         log.read_value(ValueLocation{offset:30, len:6})         │<br>│                                                                 │<br>│         Log file:                                               │<br>│         ┌─────────────────────────┐                             │<br>│         │  offset:30              │                             │<br>│         │    ↓                    │                             │<br>│         │  [yellow]  (6 bytes)    │                             │<br>│         └─────────────────────────┘                             │<br>│                                                                 │<br>│ Step 4: Return Some(Ok((&quot;banana&quot;, &quot;yellow&quot;)))                   │<br>└─────────────────────────────────────────────────────────────────┘<br><br>┌─────────────────────────────────────────────────────────────────┐<br>│ Call #2: iter.next()                                            │<br>├─────────────────────────────────────────────────────────────────┤<br>│ Step 1: inner.next() returns Some((&quot;cherry&quot;, ValueLocation))    │<br>│         ┌────────────────────────────┐                          │<br>│         │ Key: &quot;cherry&quot;              │                          │<br>│         │ ValueLocation{offset:50,   │                          │<br>│         │               len:6}       │                          │<br>│         └────────────────────────────┘                          │<br>│                                                                 │<br>│ Step 2: Clone key: &quot;cherry&quot;.to_vec()                            │<br>│                                                                 │<br>│ Step 3: Read value from log:                                    │<br>│         log.read_value(ValueLocation{offset:50, len:6})         │<br>│                                                                 │<br>│         Log file:                                               │<br>│         ┌─────────────────────────┐                             │<br>│         │  offset:50              │                             │<br>│         │    ↓                    │                             │<br>│         │  [red]  (6 bytes)       │                             │<br>│         └─────────────────────────┘                             │<br>│                                                                 │<br>│ Step 4: Return Some(Ok((&quot;cherry&quot;, &quot;red&quot;)))                      │<br>└─────────────────────────────────────────────────────────────────┘<br><br>┌─────────────────────────────────────────────────────────────────┐<br>│ Call #3: iter.next()                                            │<br>├─────────────────────────────────────────────────────────────────┤<br>│ Step 1: inner.next() returns None (end of range)                │<br>│                                                                 │<br>│ Step 2: Return None                                             │<br>└─────────────────────────────────────────────────────────────────┘<br><br>Final result:<br>  vec![<br>    (&quot;banana&quot;, &quot;yellow&quot;),<br>    (&quot;cherry&quot;, &quot;red&quot;),<br>  ]<br><br>Key insight:<br>  - BTreeMap&#39;s range iterator handles ordered traversal (in memory)<br>  - Each iteration requires one disk read to fetch the value<br>  - Keys are sorted, so scan is efficient<br>  - Performance: O(log n) to find start + O(k) iterations where k = result count</pre><pre>impl Iterator for ScanIterator&lt;&#39;_&gt; {<br>    type Item = Result&lt;(Vec&lt;u8&gt;, Vec&lt;u8&gt;)&gt;;<br><br>    fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {<br>        self.inner.next().map(|item| self.map(item))<br>    }<br>}<br><br>impl ScanIterator&lt;&#39;_&gt; {<br>    fn map(&amp;mut self, item: (&amp;Vec&lt;u8&gt;, &amp;ValueLocation)) -&gt; &lt;Self as Iterator&gt;::Item {<br>        let (key, value_loc) = item;<br>        Ok((key.clone(), self.log.read_value(*value_loc)?))<br>    }<br>}</pre><p>迭代過程：</p><ol><li>從 inner 獲取下一個鍵和位置</li><li>複製鍵</li><li>從日誌讀取值</li><li>返回鍵值對</li></ol><h4>雙向迭代</h4><pre>impl DoubleEndedIterator for ScanIterator&lt;&#39;_&gt; {<br>    fn next_back(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {<br>        self.inner.next_back().map(|item| self.map(item))<br>    }<br>}</pre><p>支持反向迭代：</p><ul><li>next()：從小到大</li><li>next_back()：從大到小</li></ul><p>這得益於 BTreeMap 的雙向迭代器特性。</p><h3>狀態查詢</h3><h4>status 實現</h4><pre>impl Engine for BitCask {<br>    fn status(&amp;mut self) -&gt; Result&lt;Status&gt; {<br>        // 1. Count active keys<br>        // KeyDir only contains live keys (deleted keys are removed)<br>        let keys = self.keydir.len() as u64;<br><br>        // 2. Calculate logical size of active data (keys + values only)<br>        // Iterate through all entries in KeyDir and sum up:<br>        //   - key.len(): size of each key in bytes<br>        //   - value_loc.length: size of each value in bytes<br>        // This does NOT include metadata (key length, value length fields)<br>        let size = self.keydir<br>            .iter()<br>            .map(|(key, value_loc)| {<br>                (key.len() + value_loc.length) as u64<br>            })<br>            .sum();<br><br>        // 3. Get total disk file size<br>        // This includes:<br>        //   - All active entries (keys + values + metadata)<br>        //   - All garbage (overwritten values, tombstones, deleted entries)<br>        let disk_size = self.log.file.metadata()?.len();<br><br>        // 4. Calculate disk size of active data<br>        // Active data on disk includes:<br>        //   - Keys and values (already counted in `size`)<br>        //   - Metadata: 8 bytes per entry (4B key_len + 4B value_len)<br>        // Formula: size + 8 * keys<br>        // Example: If we have 2 keys:<br>        //   - &quot;a&quot; = &quot;x&quot; (1B key + 1B value)<br>        //   - &quot;bb&quot; = &quot;yy&quot; (2B key + 2B value)<br>        //   size = 1 + 1 + 2 + 2 = 6 bytes<br>        //   live_disk_size = 6 + 8 * 2 = 22 bytes<br>        //     (includes 4+4+1+1=10B for entry 0, 4+4+2+2=12B for entry 1)<br>        let live_disk_size = size + 8 * keys;<br><br>        Ok(Status {<br>            name: &quot;bitcask&quot;.to_string(),<br>            keys,           // Number of active keys<br>            size,           // Logical size (keys + values only)<br>            disk_size,      // Total file size (including garbage)<br>            live_disk_size, // Active data on disk (keys + values + metadata)<br>        })<br>    }<br>}</pre><p><strong>計算示例</strong></p><pre>Assume we have this log file:<br><br>Entry 0: &quot;a&quot; = &quot;x&quot;     (written, then overwritten)<br>Entry 1: &quot;b&quot; = &quot;yy&quot;    (written, then deleted)<br>Entry 2: &quot;a&quot; = &quot;zzz&quot;   (current value)<br>Entry 3: &quot;b&quot; (tombstone for deletion)<br><br>Log file structure:<br>┌────────────────────────────────────────────────────────┐<br>│ Entry 0: KL=1, VL=1, key=&quot;a&quot;, value=&quot;x&quot;   (10 bytes)   │ ← Garbage<br>│ Entry 1: KL=1, VL=2, key=&quot;b&quot;, value=&quot;yy&quot;  (11 bytes)   │ ← Garbage<br>│ Entry 2: KL=1, VL=3, key=&quot;a&quot;, value=&quot;zzz&quot; (12 bytes)   │ ← Live<br>│ Entry 3: KL=1, VL=-1, key=&quot;b&quot; (tombstone) (9 bytes)    │ ← Garbage<br>└────────────────────────────────────────────────────────┘<br><br>KeyDir (only contains live keys):<br>  &quot;a&quot; → ValueLocation{offset:..., len:3}<br><br>Status calculation:<br>  keys = 1 (only &quot;a&quot; is live)<br><br>  size = 1 (key &quot;a&quot;) + 3 (value &quot;zzz&quot;) = 4 bytes<br>       = logical size of data (no metadata)<br><br>  disk_size = 10 + 11 + 12 + 9 = 42 bytes<br>            = total file size (all entries including garbage)<br><br>  live_disk_size = 4 + 8 * 1 = 12 bytes<br>                 = size of Entry 2 only (4B+4B+1B+3B)<br>                 = active data on disk<br><br>Garbage calculation:<br>  garbage_disk_size = disk_size - live_disk_size<br>                    = 42 - 12 = 30 bytes<br>                    = Entries 0, 1, 3 (overwritten + deleted + tombstone)</pre><p>各欄位計算：</p><ul><li>name：引擎名稱 “bitcask”</li><li>keys：活躍鍵數量，直接用 KeyDir 的長度</li><li>size：活躍數據的邏輯大小，遍歷 KeyDir 累加鍵和值的長度（不含元數據）</li><li>disk_size：實際文件大小（包含所有垃圾）</li><li>live_disk_size：活躍數據的磁盤大小，包括 8 字節的長度前綴</li></ul><h4>垃圾計算</h4><pre>impl Status {<br>    pub fn garbage_disk_size(&amp;self) -&gt; u64 {<br>        self.disk_size.saturating_sub(self.live_disk_size)<br>    }<br>}</pre><p>垃圾大小 = 總磁盤大小 — 活躍磁盤大小</p><p>垃圾包括：</p><ul><li>被覆蓋的舊值</li><li>已刪除鍵的墓碑</li><li>已刪除鍵的舊值</li></ul><h3>壓縮機制</h3><p>壓縮（compaction）是回收垃圾空間的唯一方法。它創建一個只包含活躍數據的新日誌文件。</p><p><strong>Compaction Overview Diagram</strong></p><pre>Before compaction:<br><br>Old log file (42 bytes total, 30 bytes garbage):<br>┌──────────────────────────────────────────────────────────────┐<br>│ Entry 0: &quot;a&quot;=&quot;x&quot;      (10B) │ ← Garbage (overwritten)        │<br>│ Entry 1: &quot;b&quot;=&quot;yy&quot;     (11B) │ ← Garbage (deleted)            │<br>│ Entry 2: &quot;a&quot;=&quot;zzz&quot;    (12B) │ ← Live                         │<br>│ Entry 3: &quot;b&quot; tombstone (9B) │ ← Garbage (tombstone)          │<br>└──────────────────────────────────────────────────────────────┘<br><br>KeyDir (only live keys):<br>  &quot;a&quot; → ValueLocation{offset:X, len:3}<br><br>After compaction:<br><br>New log file (12 bytes total, 0 bytes garbage):<br>┌──────────────────────────────┐<br>│ Entry 0: &quot;a&quot;=&quot;zzz&quot;    (12B)  │ ← Only live data<br>└──────────────────────────────┘<br><br>New KeyDir:<br>  &quot;a&quot; → ValueLocation{offset:9, len:3}  (updated offset!)<br><br>Space saved: 42 - 12 = 30 bytes (71% reduction)</pre><h4>compact 實現</h4><pre>impl BitCask {<br>    pub fn compact(&amp;mut self) -&gt; Result&lt;()&gt; {<br>    // 創建新的臨時日誌文件，如果已存在則截斷<br>    let new_path = self.log.path.with_extension(&quot;new&quot;);<br>    let mut new_log = Log::new(new_path)?;<br>    new_log.file.set_len(0)?;<br><br>    // 將所有活躍條目寫入新日誌，生成新的 KeyDir<br>    let mut new_keydir = KeyDir::new();<br>    for (key, value_loc) in &amp;self.keydir {<br>        let value = self.log.read_value(*value_loc)?;<br>        let value_loc = new_log.write_entry(key, Some(&amp;value))?;<br>        new_keydir.insert(key.clone(), value_loc);<br>    }<br><br>    // 用新日誌替換當前日誌<br>    std::fs::rename(&amp;new_log.path, &amp;self.log.path)?;<br>    new_log.path = self.log.path.clone();<br><br>    self.log = new_log;<br>    self.keydir = new_keydir;<br>    Ok(())<br>    }<br>}</pre><h4>壓縮流程</h4><p><strong>Detailed Compaction Process</strong></p><pre>Using the same example from overview:<br>  Old log: 42 bytes with 4 entries (3 garbage, 1 live)<br>  KeyDir: only &quot;a&quot; → {offset:18, len:3}<br><br>Step 1: Create new temporary log file<br>  Old file: /data/bitcask.log (42 bytes)<br>  New file: /data/bitcask.log.new (0 bytes, empty)<br><br>  File system state:<br>  ┌─────────────────────────────────────────────────┐<br>  │ bitcask.log     │ 42 bytes (with garbage)       │<br>  │ bitcask.log.new │  0 bytes (empty, truncated)   │<br>  └─────────────────────────────────────────────────┘<br><br>Step 2: Iterate through KeyDir and copy live entries<br><br>  Old log file structure:<br>  ┌──────────────────────────────────────────────────────────┐<br>  │ Entry 0: &quot;a&quot;=&quot;x&quot;     (10B)  offset: 0-9    │ ← Garbage   │<br>  │ Entry 1: &quot;b&quot;=&quot;yy&quot;    (11B)  offset: 10-20  │ ← Garbage   │<br>  │ Entry 2: &quot;a&quot;=&quot;zzz&quot;   (12B)  offset: 21-32  │ ← Live      │<br>  │ Entry 3: &quot;b&quot; tomb    (9B)   offset: 33-41  │ ← Garbage   │<br>  └──────────────────────────────────────────────────────────┘<br><br>  Old KeyDir (only live keys):<br>  ┌──────────────────────────────────┐<br>  │ Key  │ Old ValueLocation         │<br>  ├──────┼───────────────────────────┤<br>  │ &quot;a&quot;  │ {offset:29, len:3}        │ ← Points to Entry 2&#39;s value<br>  └──────────────────────────────────┘<br>         (offset = 21 + 4(KL) + 4(VL) + 1(key) = 30)<br><br>  Iteration 1: key=&quot;a&quot; (the only live key)<br>    Step 2a: Read value from old log<br>      log.read_value(ValueLocation{offset:30, len:3})<br>      → reads &quot;zzz&quot; from old log<br><br>    Step 2b: Write entry to new log<br>      new_log.write_entry(&quot;a&quot;, Some(&quot;zzz&quot;))<br>      → writes: [KL:1][VL:3][a][zzz] to offset 0<br><br>    Step 2c: Get new ValueLocation<br>      → ValueLocation{offset:9, len:3}<br>         (offset = 0 + 4(KL) + 4(VL) + 1(key) = 9)<br><br>    Step 2d: Insert into new KeyDir<br>      new_keydir.insert(&quot;a&quot;, ValueLocation{offset:9, len:3})<br><br>  New log file after copying:<br>  ┌──────────────────────────────────────────────┐<br>  │ Entry 0: &quot;a&quot;=&quot;zzz&quot;   (12B)  offset: 0-11     │ ← Only entry<br>  └──────────────────────────────────────────────┘<br>  Total: 12 bytes (100% live data, 0% garbage)<br><br>  New KeyDir:<br>  ┌──────────────────────────────────┐<br>  │ Key  │ New ValueLocation         │<br>  ├──────┼───────────────────────────┤<br>  │ &quot;a&quot;  │ {offset:9, len:3}         │ ← Updated offset!<br>  └──────────────────────────────────┘<br><br>Step 3: Atomic replacement<br>  1. Rename: bitcask.log.new → bitcask.log<br>     (This is an atomic filesystem operation)<br><br>  2. Update BitCask struct:<br>     self.log = new_log           (points to new file)<br>     self.keydir = new_keydir     (uses new offsets)<br><br>  File system state after rename:<br>  ┌─────────────────────────────────────────────────┐<br>  │ bitcask.log     │ 12 bytes (new, no garbage)    │<br>  └─────────────────────────────────────────────────┘<br>  (Old file is gone, OS reclaimed the 42 bytes)<br><br>Final result:<br>  - Old log: deleted by OS (42 bytes freed)<br>  - New log: 12 bytes (all live data)<br>  - KeyDir: 1 entry with updated offset<br>  - Garbage: 0 bytes (30 bytes reclaimed)<br>  - Space saved: 30 bytes (71% reduction)</pre><p>壓縮流程總結：</p><p>1.創建新日誌：</p><ul><li>路徑是原文件加 .new 擴展名</li><li>如果已存在，截斷為空文件</li></ul><p>2.寫入活躍數據：</p><ul><li>遍歷當前 KeyDir（只包含活躍鍵）</li><li>從舊日誌讀取每個值</li><li>寫入新日誌（緊密排列，無垃圾）</li><li>構建新 KeyDir（所有 offset 都是新的）</li></ul><p>3.原子替換：</p><ul><li>用 rename() 系統調用原子地覆蓋舊日誌</li><li>更新 self.log 和 self.keydir</li></ul><h4>壓縮效果</h4><p>壓縮後：</p><ul><li>所有垃圾數據被移除</li><li>文件大小等於活躍數據大小</li><li>KeyDir 中的偏移量全部更新</li></ul><h4>壓縮時機</h4><p>toyDB 的壓縮策略：</p><ul><li>節點啟動時自動壓縮（如果垃圾超過閾值）</li><li>手動觸發（通過 compact() 方法）</li><li>不支持在線壓縮（會鎖定數據庫）</li></ul><p>這個簡化策略適合小型數據庫，避免了複雜的後台壓縮邏輯。</p><h3>持久化和刷新</h3><h4>flush 實現</h4><pre>impl Engine for BitCask {<br>    fn flush(&amp;mut self) -&gt; Result&lt;()&gt; {<br>        #[cfg(not(test))]<br>        self.log.file.sync_all()?;<br>        Ok(())<br>    }<br>}</pre><p>刷新操作：</p><ul><li>調用 sync_all() 將文件緩衝刷新到磁盤</li><li>測試環境下跳過（加速測試）</li></ul><h4>Drop 時自動刷新</h4><pre>impl Drop for BitCask {<br>    fn drop(&amp;mut self) {<br>        if let Err(error) = self.flush() {<br>            error!(&quot;failed to flush file: {}&quot;, error)<br>        }<br>    }<br>}</pre><p>當 BitCask 被釋放時：</p><ul><li>自動嘗試刷新</li><li>失敗時記錄錯誤（不 panic）</li></ul><p>這確保了正常關閉時數據被持久化。</p><h4>持久性保證</h4><p>BitCask 的持久性依賴：</p><ol><li>append-only 寫入：數據追加到文件末尾</li><li>定期 flush：將緩衝刷新到磁盤</li><li>崩潰恢復：掃描日誌重建索引，截斷不完整條目</li></ol><p>權衡：</p><ul><li>每次寫入都 flush：最大持久性，性能差</li><li>批量 flush：性能好，可能丟失最近的寫入</li></ul><p>toyDB 採用批量 flush，由上層（Raft）控制刷新時機。</p><h3>獨占鎖機制</h3><p>BitCask 使用文件鎖防止多進程同時訪問同一數據庫。</p><h4>加鎖邏輯</h4><pre>impl Log {<br>    fn new(path: PathBuf) -&gt; Result&lt;Self&gt; {<br>        // ... 打開文件 ...<br>        if !file.try_lock_exclusive()? {<br>            return Err(Error::IO(format!(&quot;file {path:?} is already is use&quot;)));<br>        }<br>        Ok(Self { file, path })<br>    }<br>}</pre><p>使用 fs4 crate 的 try_lock_exclusive()：</p><ul><li>嘗試獲取排他鎖</li><li>如果已被其他進程持有，立即返回錯誤</li><li>非阻塞式</li></ul><h4>解鎖時機</h4><p>鎖會在以下時機自動釋放：</p><ol><li>文件句柄被關閉（BitCask Drop）</li><li>進程退出</li><li>進程崩潰（操作系統自動釋放）</li></ol><h4>為什麼需要鎖？</h4><p>如果多個進程同時寫入：</p><ul><li>日誌文件會損壞（交錯寫入）</li><li>KeyDir 會不一致</li><li>數據可能永久丟失</li></ul><p>文件鎖確保同一時間只有一個進程能訪問數據庫。</p><h3>總結</h3><p>BitCask 是一個優雅的存儲引擎設計，它用簡單的 append-only 日誌和內存索引，實現了高性能的持久化 key-value 存儲。</p><p>toyDB 的實現進一步簡化了標準 BitCask，去除了複雜的多文件管理和在線壓縮，更適合學習理解。雖然有所犧牲（單文件可能過大、壓縮時鎖定數據庫），但核心思想和實現細節都得到了完整保留。</p><h3>備注</h3><h4>為什麼壓縮會鎖定數據庫？</h4><p>原因分析</p><pre>pub fn compact(&amp;mut self) -&gt; Result&lt;()&gt; {<br>    // 1. Create new log file<br>    let mut new_log = Log::new(new_path)?;<br><br>    // 2. Copy all live entries (takes time!)<br>    for (key, value_loc) in &amp;self.keydir {<br>        let value = self.log.read_value(*value_loc)?;  // Read from old<br>        new_log.write_entry(key, Some(&amp;value))?;       // Write to new<br>    }<br><br>    // 3. Atomic swap<br>    std::fs::rename(&amp;new_log.path, &amp;self.log.path)?;<br>    self.log = new_log;        // Update log reference<br>    self.keydir = new_keydir;  // Update KeyDir with new offsets<br>}</pre><p>鎖定的原因：</p><p>1.&amp;mut self 獨占借用</p><ul><li>compact(&amp;mut self) 需要可變借用整個 BitCask</li><li>在壓縮期間，無法同時進行讀寫操作</li><li>Rust 的借用檢查器強制執行這個限制</li></ul><p>2.KeyDir 重建過程</p><ul><li>壓縮過程中需要構建新的 KeyDir</li><li>所有 ValueLocation 的 offset 都要更新</li><li>如果允許並發讀取，會讀到錯誤的 offset</li></ul><p>3.日誌文件切換</p><ul><li>從舊日誌切換到新日誌需要原子操作</li><li>self.log 的替換不是線程安全的</li><li>並發訪問會導致數據不一致</li></ul><p>並發問題示例</p><pre>Without locking, this race condition could occur:<br><br>Thread 1 (Compaction):              Thread 2 (Read):<br>1. Create new log<br>2. Copy entries to new log<br>3. Build new KeyDir<br>                                    4. Get key from old KeyDir<br>                                       offset=30 (points to old log)<br>5. Rename: new → old log<br>6. Update self.log (now new log)<br>7. Update self.keydir (new offsets)<br>                                    8. Read from self.log<br>                                       (now points to NEW log!)<br>                                    9. Seek to offset=30<br>                                       (but new log is smaller!)<br>                                    10. ERROR: Read past end of file!<br><br>The problem: Thread 2 got an offset from the old KeyDir,<br>but by the time it reads, the log file has been replaced!</pre><p><strong>標準 BitCask 的解決方案</strong></p><p>標準 BitCask 實現支持在線壓縮，使用以下技術：</p><ol><li>多個日誌文件</li></ol><ul><li>使用固定大小的多個日誌文件</li><li>壓縮舊文件時，新寫入去新文件</li><li>讀取時可以並發訪問不同文件</li></ul><p><strong>Multi-File Strategy Diagram</strong></p><pre>Normal operation with multiple log files:<br><br>File structure:<br>┌─────────────────────────────────────────────────────────────┐<br>│ bitcask.0.log  │ 10 MB (full, immutable, old)               │<br>│ bitcask.1.log  │ 10 MB (full, immutable, old)               │<br>│ bitcask.2.log  │ 10 MB (full, immutable, old)               │<br>│ bitcask.3.log  │  7 MB (active, currently writing)          │<br>└─────────────────────────────────────────────────────────────┘<br><br>KeyDir (maps keys to file + offset):<br>┌─────────────────────────────────────────────────┐<br>│ Key     │ File ID │ Offset │ Length             │<br>├─────────┼─────────┼────────┼────────────────────┤<br>│ &quot;apple&quot; │    0    │  1000  │   5                │<br>│ &quot;banana&quot;│    1    │  2000  │   6                │<br>│ &quot;cherry&quot;│    2    │  3000  │   6                │<br>│ &quot;date&quot;  │    3    │  4000  │   4    ← active    │<br>└─────────────────────────────────────────────────┘<br><br>Compacting file 0 while serving reads/writes:<br><br>Timeline:<br>┌────────────────────────────────────────────────────────────────┐<br>│ Thread 1: Compaction of file 0                                 │<br>├────────────────────────────────────────────────────────────────┤<br>│ t0: Start compacting bitcask.0.log                             │<br>│     (reads old entries, writes to new file)                    │<br>│                                                                │<br>│     ┌──────────────────┐                                       │<br>│     │ bitcask.0.log    │ ──┐                                   │<br>│     │ (being compacted)│   │ Read                              │<br>│     └──────────────────┘   │                                   │<br>│                            ↓                                   │<br>│     ┌──────────────────┐                                       │<br>│     │ bitcask.0.log.new│ ← Write compacted data                │<br>│     └──────────────────┘                                       │<br>│                                                                │<br>│ Meanwhile...                                                   │<br>├────────────────────────────────────────────────────────────────┤<br>│ Thread 2: Read &quot;banana&quot; from file 1                            │<br>│     ✓ Not blocked! File 1 is independent                       │<br>│                                                                │<br>│ Thread 3: Write new key &quot;elderberry&quot; to file 3                 │<br>│     ✓ Not blocked! Writing to active file                      │<br>│                                                                │<br>│ Thread 4: Read &quot;apple&quot; from file 0                             │<br>│     ✓ Not blocked! Compaction doesn&#39;t lock reads               │<br>├────────────────────────────────────────────────────────────────┤<br>│ t1: Compaction complete, atomic swap                           │<br>│     Rename: bitcask.0.log.new → bitcask.0.log                  │<br>│     Update KeyDir entries for file 0 (brief exclusive lock)    │<br>│                                                                │<br>│ t2: Old file 0 marked for deletion                             │<br>│     Wait for active readers to finish                          │<br>│                                                                │<br>│ t3: Delete old file 0                                          │<br>└────────────────────────────────────────────────────────────────┘<br><br>Key benefits:<br>- Compaction of file N doesn&#39;t block access to files M (N ≠ M)<br>- New writes always go to active file (never blocked)<br>- Reads can proceed concurrently across all files<br>- Only brief lock during KeyDir update<br><br>File lifecycle:<br>┌───────────┐      ┌──────────┐      ┌───────────┐<br>│  Active   │─10MB→│Immutable │─comp→│ Deleted   │<br>│  (write)  │      │ (read)   │      │           │<br>└───────────┘      └──────────┘      └───────────┘<br>     ↑                                      ↓<br>     └──────────── New active file ─────────┘<br><br>Implementation structure:<br>```rust<br>pub struct BitCask {<br>    files: Vec&lt;LogFile&gt;,           // Multiple log files<br>    active_file_id: usize,         // Currently writing file<br>    keydir: Arc&lt;RwLock&lt;KeyDir&gt;&gt;,   // Maps key → (file_id, offset)<br>}<br><br>pub struct KeyDir {<br>    map: BTreeMap&lt;Vec&lt;u8&gt;, ValueLocation&gt;,<br>}<br><br>pub struct ValueLocation {<br>    file_id: usize,   // Which file contains the value<br>    offset: u64,      // Offset within that file<br>    length: usize,    // Value length<br>}<br><br>// Read from specific file<br>fn get(&amp;self, key: &amp;[u8]) -&gt; Result&lt;Option&lt;Vec&lt;u8&gt;&gt;&gt; {<br>    let keydir = self.keydir.read().unwrap();<br>    let Some(loc) = keydir.get(key) else {<br>        return Ok(None);<br>    };<br><br>    // Access specific file (no global lock needed)<br>    let file = &amp;self.files[loc.file_id];<br>    file.read_value(loc.offset, loc.length)<br>}<br><br>// Compact specific file<br>fn compact_file(&amp;mut self, file_id: usize) -&gt; Result&lt;()&gt; {<br>    // Only locks KeyDir briefly during swap<br>    // Doesn&#39;t block access to other files<br>}</pre><p>2.讀寫鎖（RwLock）</p><ul><li>讀操作獲取共享鎖</li><li>寫操作和壓縮獲取獨占鎖</li><li>允許多個並發讀取</li></ul><p>實際實現方式：</p><pre>pub struct BitCask {<br>    log: Arc&lt;RwLock&lt;Log&gt;&gt;,          // Wrap log in RwLock<br>    keydir: Arc&lt;RwLock&lt;KeyDir&gt;&gt;,    // Wrap KeyDir in RwLock<br>}<br><br>// Read operation (shared lock)<br>fn get(&amp;self, key: &amp;[u8]) -&gt; Result&lt;Option&lt;Vec&lt;u8&gt;&gt;&gt; {<br>    let keydir = self.keydir.read().unwrap();  // Shared lock<br>    let Some(location) = keydir.get(key) else {<br>        return Ok(None);<br>    };<br><br>    let log = self.log.read().unwrap();        // Shared lock<br>    log.read_value(*location).map(Some)<br>    // Locks released when keydir and log go out of scope<br>}<br><br>// Write operation (exclusive lock)<br>fn set(&amp;self, key: &amp;[u8], value: Vec&lt;u8&gt;) -&gt; Result&lt;()&gt; {<br>    let mut log = self.log.write().unwrap();     // Exclusive lock<br>    let value_loc = log.write_entry(key, Some(&amp;value))?;<br><br>    let mut keydir = self.keydir.write().unwrap(); // Exclusive lock<br>    keydir.insert(key.to_vec(), value_loc);<br>    Ok(())<br>}<br><br>// Compaction (exclusive lock during swap only)<br>fn compact(&amp;self) -&gt; Result&lt;()&gt; {<br>    // 1. Create new log (no lock needed)<br>    let mut new_log = Log::new(new_path)?;<br>    let mut new_keydir = KeyDir::new();<br><br>    // 2. Copy data (using read lock for old data)<br>    {<br>        let old_keydir = self.keydir.read().unwrap();  // Shared lock<br>        let old_log = self.log.read().unwrap();        // Shared lock<br><br>        for (key, value_loc) in old_keydir.iter() {<br>            let value = old_log.read_value(*value_loc)?;<br>            let new_loc = new_log.write_entry(key, Some(&amp;value))?;<br>            new_keydir.insert(key.clone(), new_loc);<br>        }<br>        // Shared locks released here<br>    }<br><br>    // 3. Atomic swap (exclusive lock for minimal time)<br>    {<br>        let mut log = self.log.write().unwrap();      // Exclusive lock<br>        let mut keydir = self.keydir.write().unwrap(); // Exclusive lock<br><br>        std::fs::rename(&amp;new_log.path, &amp;log.path)?;<br>        *log = new_log;          // Swap log<br>        *keydir = new_keydir;    // Swap KeyDir<br>        // Exclusive locks released here<br>    }<br><br>    Ok(())<br>}</pre><p>關鍵優化：</p><ul><li>複製數據時使用共享鎖（不阻塞讀取）</li><li>只在切換時使用獨占鎖（阻塞時間最短）</li><li>讀操作全程不受影響</li><li>寫操作只在最後切換時短暫阻塞</li></ul><p>3.延遲刪除</p><ul><li>壓縮後不立即刪除舊文件</li><li>等待所有讀取完成後再刪除</li><li>使用引用計數追蹤活躍讀取</li></ul><p><strong>Deferred Deletion Implementation</strong></p><pre>use std::sync::Arc;<br><br>pub struct LogFile {<br>    file: File,<br>    path: PathBuf,<br>    file_id: usize,<br>    // Reference counter tracks active readers<br>    // When Arc count drops to 1, file can be deleted<br>}<br><br>pub struct BitCask {<br>    // Use Arc to share ownership with active readers<br>    files: Vec&lt;Arc&lt;LogFile&gt;&gt;,<br>    active_file_id: usize,<br>    keydir: Arc&lt;RwLock&lt;KeyDir&gt;&gt;,<br>}<br><br>// Read operation clones Arc (increments ref count)<br>fn get(&amp;self, key: &amp;[u8]) -&gt; Result&lt;Option&lt;Vec&lt;u8&gt;&gt;&gt; {<br>    let keydir = self.keydir.read().unwrap();<br>    let Some(loc) = keydir.get(key) else {<br>        return Ok(None);<br>    };<br><br>    // Clone Arc to get shared ownership<br>    let file = Arc::clone(&amp;self.files[loc.file_id]);<br>    drop(keydir);  // Release KeyDir lock<br><br>    // Read from file (file kept alive by Arc)<br>    file.read_value(loc.offset, loc.length)<br>    // Arc dropped here, ref count decremented<br>}<br><br>// Compaction marks file for deletion<br>fn compact_file(&amp;mut self, file_id: usize) -&gt; Result&lt;()&gt; {<br>    // ... compaction logic ...<br><br>    // After swap, old file is marked for deletion<br>    let old_file = std::mem::replace(<br>        &amp;mut self.files[file_id],<br>        Arc::new(new_file)<br>    );<br><br>    // Spawn background thread to wait and delete<br>    std::thread::spawn(move || {<br>        // Wait for all readers to finish<br>        // This blocks until Arc::strong_count == 1<br>        // (only this thread holds reference)<br>        while Arc::strong_count(&amp;old_file) &gt; 1 {<br>            std::thread::sleep(Duration::from_millis(100));<br>        }<br><br>        // Now safe to delete<br>        let path = old_file.path.clone();<br>        drop(old_file);  // Close file<br>        std::fs::remove_file(path).ok();<br>    });<br><br>    Ok(())<br>}</pre><p><strong>Timeline Example</strong></p><pre>Compaction with deferred deletion:<br><br>t0: Start compaction of file 0<br>    ┌──────────────────────────────────────────────┐<br>    │ File 0: Arc strong_count = 1                 │<br>    │ (only BitCask.files[0] holds reference)      │<br>    └──────────────────────────────────────────────┘<br><br>t1: Thread A starts reading from file 0<br>    ┌──────────────────────────────────────────────┐<br>    │ File 0: Arc strong_count = 2                 │<br>    │ - BitCask.files[0]: 1                        │<br>    │ - Thread A&#39;s clone: 1                        │<br>    └──────────────────────────────────────────────┘<br><br>t2: Compaction completes, swap occurs<br>    ┌──────────────────────────────────────────────┐<br>    │ Old file 0: Arc strong_count = 2             │<br>    │ - Deletion thread: 1                         │<br>    │ - Thread A (still reading): 1                │<br>    │                                              │<br>    │ New file 0: Arc strong_count = 1             │<br>    │ - BitCask.files[0]: 1                        │<br>    └──────────────────────────────────────────────┘<br><br>    Deletion thread: Waiting... (count &gt; 1)<br><br>t3: Thread A finishes reading<br>    ┌──────────────────────────────────────────────┐<br>    │ Old file 0: Arc strong_count = 1             │<br>    │ - Deletion thread: 1                         │<br>    │ - Thread A: dropped                          │<br>    └──────────────────────────────────────────────┘<br><br>    Deletion thread: Count == 1, safe to delete!<br><br>t4: File deleted<br>    ┌──────────────────────────────────────────────┐<br>    │ Old file 0: Deleted from filesystem          │<br>    │ - Arc dropped, file closed                   │<br>    │ - Disk space reclaimed                       │<br>    └──────────────────────────────────────────────┘</pre><p><strong>Key Points</strong></p><p>1.Arc (Atomic Reference Counting)</p><ul><li>Tracks how many references to file exist</li><li>Thread-safe, allows concurrent access</li><li>File kept alive while any reader holds Arc</li></ul><p>2.Safe Deletion</p><ul><li>Can’t delete while readers are active</li><li>Deletion thread polls reference count</li><li>Only deletes when count drops to 1</li></ul><p>3.No Race Conditions</p><pre>Scenario: Reader tries to access deleted file<br><br>x Without Arc:<br>Thread A: Get key from KeyDir (file_id=0)<br>Thread B: Compact file 0, swap, DELETE immediately<br>Thread A: Try to read file 0<br>Thread A: ERROR! File doesn&#39;t exist!<br><br>✓ With Arc:<br>Thread A: Get key from KeyDir, clone Arc (count=2)<br>Thread B: Compact file 0, swap, mark for deletion<br>Thread B: Wait... count=2 (Thread A still reading)<br>Thread A: Read from file 0 (Arc keeps file alive)<br>Thread A: Done, drop Arc (count=1)<br>Thread B: Count=1, safe to delete!<br>Thread B: Delete file 0</pre><p>4.Memory Overhead</p><ul><li>Each Arc is 16 bytes (pointer + counters)</li><li>Small cost for safe concurrent access</li><li>Alternative: use explicit reader tracking with mutexes</li></ul><p>5.Alternative: Epoch-Based Reclamation</p><pre>struct FileRegistry {<br>    current_epoch: AtomicU64,<br>    readers: Vec&lt;(FileId, Epoch)&gt;,<br>    pending_deletes: Vec&lt;(FileId, Epoch)&gt;,<br>}<br><br>// Reader marks epoch when starting<br>fn start_read() -&gt; Epoch {<br>    registry.current_epoch.load(Ordering::Acquire)<br>}<br><br>// Compaction marks file for deletion with current epoch<br>fn mark_for_delete(file_id: FileId) {<br>    let epoch = registry.current_epoch.fetch_add(1);<br>    registry.pending_deletes.push((file_id, epoch));<br>}<br><br>// Background thread deletes files older than all active readers<br>fn cleanup() {<br>    let min_active_epoch = registry.readers.iter()<br>        .map(|(_, epoch)| epoch)<br>        .min();<br><br>    registry.pending_deletes.retain(|(file_id, epoch)| {<br>        if epoch &lt; min_active_epoch {<br>            delete_file(file_id);<br>            false  // Remove from pending<br>        } else {<br>            true   // Keep waiting<br>        }<br>    });<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=241d06263998" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[toyDB: Memory Storage Engine Deep Dive]]></title>
            <link>https://medium.com/@wudiheroback/toydb-memory-storage-engine-deep-dive-310cf32d5ec8?source=rss-83005aa59123------2</link>
            <guid isPermaLink="false">https://medium.com/p/310cf32d5ec8</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Stan Hsu]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 14:34:02 GMT</pubDate>
            <atom:updated>2025-10-07T14:34:02.398Z</atom:updated>
            <content:encoded><![CDATA[<p>This article provides an in-depth analysis of toyDB’s Memory storage engine, demonstrating how to implement a complete key-value store in the simplest way possible.</p><p>The Memory engine is one of toyDB’s two storage implementations, using a pure in-memory B-tree structure. With less than 100 lines of code, it fully implements all Engine trait functionality. This implementation serves not only as a testing baseline but also as the best example for understanding the essence of storage engines.</p><p><a href="https://github.com/erikgrinaker/toydb/blob/main/src/storage/memory.rs">Full source code</a></p><h3>Core Structure Design</h3><p>The Memory engine structure is extremely concise:</p><pre>#[derive(Default)]<br>pub struct Memory(BTreeMap&lt;Vec&lt;u8&gt;, Vec&lt;u8&gt;&gt;);</pre><p>This is a newtype pattern that wraps the standard library’s BTreeMap. Why choose BTreeMap?</p><p><strong>Key Features of BTreeMap</strong></p><ol><li>Ordering: Keys are sorted in lexicographic order, which is the foundation for implementing scan</li><li>Efficient Range Queries: Supports the range() method, directly corresponding to Engine::scan()</li><li>Stable Performance: O(log n) read/write performance, predictable</li><li>Standard Library Implementation: Thoroughly tested and highly reliable</li></ol><h3>Implementation Details</h3><h4>Basic Operations</h4><p><strong>Creating the Engine</strong></p><pre>impl Memory {<br>    pub fn new() -&gt; Self {<br>        Self::default()<br>    }<br>}</pre><p>Using #[derive(Default)], the compiler automatically generates code to create an empty BTreeMap. new() is just a more explicit entry point.</p><p><strong>Reading Data — get</strong></p><pre>fn get(&amp;mut self, key: &amp;[u8]) -&gt; Result&lt;Option&lt;Vec&lt;u8&gt;&gt;&gt; {<br>    Ok(self.0.get(key).cloned())<br>}</pre><p>Key points:</p><ul><li>self.0.get(key) returns Option&lt;&amp;Vec&lt;u8&gt;&gt; (borrowed)</li><li>.cloned() copies the value, returning Option&lt;Vec&lt;u8&gt;&gt; (owned)</li><li>Why copy? To avoid borrow checker issues and give the caller full ownership of the data</li></ul><p><strong>Writing Data — set</strong></p><pre>fn set(&amp;mut self, key: &amp;[u8], value: Vec&lt;u8&gt;) -&gt; Result&lt;()&gt; {<br>    self.0.insert(key.to_vec(), value);<br>    Ok(())<br>}</pre><p>Notes:</p><ul><li>key.to_vec() copies the key because BTreeMap needs to own the key</li><li>value is already Vec&lt;u8&gt;, ownership is directly moved</li><li>insert will overwrite the old value (if it exists)</li></ul><p><strong>Deleting Data — delete</strong></p><pre>fn delete(&amp;mut self, key: &amp;[u8]) -&gt; Result&lt;()&gt; {<br>    self.0.remove(key);<br>    Ok(())<br>}</pre><p>Extremely simple:</p><ul><li>Calls BTreeMap’s remove</li><li>Returns success regardless of whether the key exists</li><li>The return value is discarded (we don’t care about the old value)</li></ul><h4>Range Scanning</h4><p><strong>scan Implementation</strong></p><pre>fn scan(&amp;mut self, range: impl RangeBounds&lt;Vec&lt;u8&gt;&gt;) -&gt; Self::ScanIterator&lt;&#39;_&gt; {<br>    ScanIterator(self.0.range(range))<br>}</pre><p>This demonstrates Rust’s elegance:</p><ul><li>BTreeMap’s range() method perfectly matches our needs</li><li>Directly wraps and returns as ScanIterator</li><li>The compiler automatically monomorphizes for different range types</li></ul><p><strong>ScanIterator Structure</strong></p><pre>pub struct ScanIterator&lt;&#39;a&gt;(Range&lt;&#39;a, Vec&lt;u8&gt;, Vec&lt;u8&gt;&gt;);</pre><p>This is a simple wrapper around BTreeMap’s range iterator. The lifetime &#39;a ensures:</p><ul><li>The iterator won’t outlive the BTreeMap</li><li>Prevents modification of underlying data during iteration</li></ul><p><strong>Double-Ended Iterator</strong></p><pre>impl Iterator for ScanIterator&lt;&#39;_&gt; {<br>    type Item = Result&lt;(Vec&lt;u8&gt;, Vec&lt;u8&gt;)&gt;;<br><br>    fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {<br>        self.0.next().map(|(k, v)| Ok((k.clone(), v.clone())))<br>    }<br>}<br><br>impl DoubleEndedIterator for ScanIterator&lt;&#39;_&gt; {<br>    fn next_back(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {<br>        self.0.next_back().map(|(k, v)| Ok((k.clone(), v.clone())))<br>    }<br>}</pre><p>Implementation points:</p><ul><li>Forward Iteration: next() from small to large</li><li>Reverse Iteration: next_back() from large to small</li><li>Data Copying: k.clone(), v.clone() returns owned data</li><li>Error Wrapping: Wrapped with Ok() because Memory engine never fails</li></ul><p>Why copy key and value?</p><ul><li>BTreeMap’s iterator returns references (&amp;K, &amp;V)</li><li>We need to return owned (Vec&lt;u8&gt;, Vec&lt;u8&gt;)</li><li>Maintain interface consistency: BitCask engine also returns owned data</li></ul><p><strong>scan_dyn Implementation</strong></p><pre>fn scan_dyn(<br>    &amp;mut self,<br>    range: (Bound&lt;Vec&lt;u8&gt;&gt;, Bound&lt;Vec&lt;u8&gt;&gt;),<br>) -&gt; Box&lt;dyn super::ScanIterator + &#39;_&gt; {<br>    Box::new(self.scan(range))<br>}</pre><p>This version is provided for dyn Engine:</p><ul><li>Parameter is concrete type (Bound, Bound) rather than generic</li><li>Returns Box&lt;dyn ScanIterator&gt; rather than associated type</li><li>Internally calls scan() directly, then boxes</li></ul><h4>Status Queries</h4><p><strong>status Implementation</strong></p><pre>fn status(&amp;mut self) -&gt; Result&lt;Status&gt; {<br>    Ok(Status {<br>        name: &quot;memory&quot;.to_string(),<br>        keys: self.0.len() as u64,<br>        size: self.0.iter().map(|(k, v)| (k.len() + v.len()) as u64).sum(),<br>        disk_size: 0,<br>        live_disk_size: 0,<br>    })<br>}</pre><p>Field meanings:</p><ul><li>name: Engine name, used for identification</li><li>keys: Number of active keys, directly using BTreeMap’s len()</li><li>size: Logical size, iterating all key-value pairs and summing their lengths</li><li>disk_size: Total disk size, 0 for Memory engine</li><li>live_disk_size: Active disk size, 0 for Memory engine</li></ul><p><strong>size Calculation Details</strong></p><pre>self.0.iter().map(|(k, v)| (k.len() + v.len()) as u64).sum()</pre><p>This line of code:</p><ol><li>iter() iterates all key-value pairs</li><li>map() calculates the total bytes for each pair</li><li>sum() accumulates all lengths</li></ol><p>Note: This only counts the data size of keys and values, not including BTreeMap’s metadata overhead (node pointers, etc.).</p><h4>Persistence Operations</h4><p><strong>flush Implementation</strong></p><pre>fn flush(&amp;mut self) -&gt; Result&lt;()&gt; {<br>    Ok(())<br>}</pre><p>Memory engine doesn’t need persistence:</p><ul><li>Data only exists in memory</li><li>No buffer needs to be flushed</li><li>Returns success directly</li></ul><p>This conforms to the Engine trait design: flush is just a “hint”, not forced to actually do anything.</p><h3>Usage Examples</h3><h4>Basic Operations</h4><pre>use toydb::error::Result;<br>use toydb::storage::engine::Engine;<br>use toydb::storage::memory::Memory;<br><br>fn main() -&gt; Result&lt;()&gt; {<br>    println!(&quot;=== toyDB Memory Engine Usage Example ===\n&quot;);<br><br>    // Create Memory engine<br>    let mut engine = Memory::new();<br>    println!(&quot;✓ Created Memory engine&quot;);<br><br>    // Basic operations: Write<br>    println!(&quot;\n--- Basic Operations: Write ---&quot;);<br>    engine.set(b&quot;name&quot;, b&quot;Alice&quot;.to_vec())?;<br>    engine.set(b&quot;age&quot;, b&quot;25&quot;.to_vec())?;<br>    engine.set(b&quot;city&quot;, b&quot;Taipei&quot;.to_vec())?;<br>    println!(&quot;✓ Wrote 3 key-value pairs&quot;);<br><br>    // Basic operations: Read<br>    println!(&quot;\n--- Basic Operations: Read ---&quot;);<br>    if let Some(name) = engine.get(b&quot;name&quot;)? {<br>        println!(&quot;name = {}&quot;, String::from_utf8_lossy(&amp;name));<br>    }<br>    if let Some(age) = engine.get(b&quot;age&quot;)? {<br>        println!(&quot;age = {}&quot;, String::from_utf8_lossy(&amp;age));<br>    }<br><br>    // Basic operations: Delete<br>    println!(&quot;\n--- Basic Operations: Delete ---&quot;);<br>    engine.delete(b&quot;age&quot;)?;<br>    println!(&quot;✓ Deleted age&quot;);<br><br>    match engine.get(b&quot;age&quot;)? {<br>        Some(_) =&gt; println!(&quot;✗ age still exists&quot;),<br>        None =&gt; println!(&quot;✓ age has been deleted&quot;),<br>    }<br><br>    // Range scan: Prefix scan<br>    println!(&quot;\n--- Range Scan: Prefix Scan ---&quot;);<br>    engine.set(b&quot;user:1&quot;, b&quot;Alice&quot;.to_vec())?;<br>    engine.set(b&quot;user:2&quot;, b&quot;Bob&quot;.to_vec())?;<br>    engine.set(b&quot;user:3&quot;, b&quot;Carol&quot;.to_vec())?;<br>    engine.set(b&quot;admin:1&quot;, b&quot;David&quot;.to_vec())?;<br>    println!(&quot;✓ Wrote user and admin data&quot;);<br><br>    println!(&quot;\nScanning all keys starting with user::&quot;);<br>    for result in engine.scan_prefix(b&quot;user:&quot;) {<br>        let (key, value) = result?;<br>        println!(&quot;  {} = {}&quot;,<br>            String::from_utf8_lossy(&amp;key),<br>            String::from_utf8_lossy(&amp;value)<br>        );<br>    }<br><br>    // Range scan: Specified range<br>    println!(&quot;\n--- Range Scan: Specified Range ---&quot;);<br>    println!(&quot;Scanning [user:1, user:3] range:&quot;);<br>    for result in engine.scan(b&quot;user:1&quot;.to_vec()..=b&quot;user:3&quot;.to_vec()) {<br>        let (key, value) = result?;<br>        println!(&quot;  {} = {}&quot;,<br>            String::from_utf8_lossy(&amp;key),<br>            String::from_utf8_lossy(&amp;value)<br>        );<br>    }<br><br>    // Range scan: Full scan<br>    println!(&quot;\n--- Range Scan: Full Scan ---&quot;);<br>    println!(&quot;Scanning all keys (forward):&quot;);<br>    for result in engine.scan(..) {<br>        let (key, value) = result?;<br>        println!(&quot;  {} = {}&quot;,<br>            String::from_utf8_lossy(&amp;key),<br>            String::from_utf8_lossy(&amp;value)<br>        );<br>    }<br><br>    // Reverse scan<br>    println!(&quot;\n--- Reverse Scan ---&quot;);<br>    println!(&quot;Scanning all keys (reverse):&quot;);<br>    let mut iter = engine.scan(..);<br>    while let Some(result) = iter.next_back() {<br>        let (key, value) = result?;<br>        println!(&quot;  {} = {}&quot;,<br>            String::from_utf8_lossy(&amp;key),<br>            String::from_utf8_lossy(&amp;value)<br>        );<br>    }<br><br>    // Status query<br>    println!(&quot;\n--- Status Query ---&quot;);<br>    let status = engine.status()?;<br>    println!(&quot;Engine name: {}&quot;, status.name);<br>    println!(&quot;Number of keys: {}&quot;, status.keys);<br>    println!(&quot;Logical size: {} bytes&quot;, status.size);<br>    println!(&quot;Disk size: {} bytes (0 for Memory engine)&quot;, status.disk_size);<br><br>    // Persistence operation<br>    println!(&quot;\n--- Persistence Operation ---&quot;);<br>    engine.flush()?;<br>    println!(&quot;✓ flush completed (no-op for Memory engine)&quot;);<br><br>    println!(&quot;\n=== Example Execution Complete ===&quot;);<br>    Ok(())<br>}</pre><p>Example execution output:</p><pre>=== toyDB Memory Engine Usage Example ===<br><br>✓ Created Memory engine<br><br>--- Basic Operations: Write ---<br>✓ Wrote 3 key-value pairs<br><br>--- Basic Operations: Read ---<br>name = Alice<br>age = 25<br><br>--- Basic Operations: Delete ---<br>✓ Deleted age<br>✓ age has been deleted<br><br>--- Range Scan: Prefix Scan ---<br>✓ Wrote user and admin data<br><br>Scanning all keys starting with user::<br>  user:1 = Alice<br>  user:2 = Bob<br>  user:3 = Carol<br><br>--- Range Scan: Specified Range ---<br>Scanning [user:1, user:3] range:<br>  user:1 = Alice<br>  user:2 = Bob<br>  user:3 = Carol<br><br>--- Range Scan: Full Scan ---<br>Scanning all keys (forward):<br>  admin:1 = David<br>  city = Taipei<br>  name = Alice<br>  user:1 = Alice<br>  user:2 = Bob<br>  user:3 = Carol<br><br>--- Reverse Scan ---<br>Scanning all keys (reverse):<br>  user:3 = Carol<br>  user:2 = Bob<br>  user:1 = Alice<br>  name = Alice<br>  city = Taipei<br>  admin:1 = David<br><br>--- Status Query ---<br>Engine name: memory<br>Number of keys: 6<br>Logical size: 62 bytes<br>Disk size: 0 bytes (0 for Memory engine)<br><br>--- Persistence Operation ---<br>✓ flush completed (no-op for Memory engine)<br><br>=== Example Execution Complete ===</pre><h3>Testing Strategy</h3><p>Memory engine tests are divided into two parts:</p><p><strong>Common Engine Tests</strong></p><pre>// Run all tests under src/storage/testscripts/engine<br>test_each_path! { in &quot;src/storage/testscripts/engine&quot; as engine =&gt; test_goldenscript }</pre><p>These tests apply to all engines, verifying basic functionality:</p><ul><li>CRUD operations</li><li>Range scanning</li><li>Edge cases</li></ul><p><strong>Memory-Specific Tests</strong></p><pre>// Run tests under src/storage/testscripts/memory<br>test_each_path! { in &quot;src/storage/testscripts/memory&quot; as scripts =&gt; test_goldenscript }</pre><p>These tests target Memory engine characteristics, such as:</p><ul><li>Order guarantees in memory</li><li>Performance characteristics</li><li>Special edge cases</li></ul><p><strong>Test Runner</strong></p><pre>fn test_goldenscript(path: &amp;Path) {<br>    goldenscript::run(&amp;mut Runner::new(Memory::new()), path)<br>        .expect(&quot;goldenscript failed&quot;)<br>}</pre><p>Using the Goldenscript framework:</p><ul><li>Test scripts are highly readable</li><li>Automatically captures output for regression testing</li><li>Easy to debug and maintain</li></ul><h3>Summary</h3><p>Though small, the Memory engine is a crystallization of toyDB’s storage layer design. It’s not just a working implementation, but also the best example for understanding storage abstraction, test-driven development, and clean design.</p><p>In the next article, we’ll dive deep into the BitCask engine implementation to see how efficient persistent storage is achieved on disk.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=310cf32d5ec8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【知其然，更知其所以然】toyDB：Memory 存儲引擎解析]]></title>
            <link>https://medium.com/@wudiheroback/%E7%9F%A5%E5%85%B6%E7%84%B6-%E6%9B%B4%E7%9F%A5%E5%85%B6%E6%89%80%E4%BB%A5%E7%84%B6-toydb-memory-%E5%AD%98%E5%84%B2%E5%BC%95%E6%93%8E%E8%A7%A3%E6%9E%90-b5ffe90d8443?source=rss-83005aa59123------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5ffe90d8443</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Stan Hsu]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 14:30:05 GMT</pubDate>
            <atom:updated>2025-10-07T14:30:05.891Z</atom:updated>
            <content:encoded><![CDATA[<p>本文深入解析 toyDB 的 Memory 存儲引擎，展示如何用最簡單的方式實現一個完整的 key-value 存儲。</p><p>Memory 引擎是 toyDB 兩種存儲實現之一，使用純內存的 B-tree 結構，代碼不到 100 行，卻完整實現了 Engine trait 的所有功能。這個實現不僅是測試的基準，更是理解存儲引擎本質的最佳範例。</p><p><a href="https://github.com/erikgrinaker/toydb/blob/main/src/storage/memory.rs">完整源碼請查看</a></p><h3>核心結構設計</h3><p>Memory 引擎的結構極其簡潔：</p><pre>#[derive(Default)]<br>pub struct Memory(BTreeMap&lt;Vec&lt;u8&gt;, Vec&lt;u8&gt;&gt;);</pre><p>包裝了標準庫的 BTreeMap。為什麼選擇 BTreeMap？</p><p>BTreeMap 的關鍵特性</p><ol><li>有序性：鍵按字典序排列，這是實現 scan 的基礎</li><li>高效範圍查詢：支援 range() 方法，直接對應 Engine::scan()</li><li>穩定性能：O(log n) 的讀寫性能，可預測</li><li>標準庫實現：經過充分測試，可靠性高</li></ol><h3>實現細節</h3><h4>基本操作</h4><p><strong>創建引擎</strong></p><pre>impl Memory {<br>    pub fn new() -&gt; Self {<br>        Self::default()<br>    }<br>}</pre><p>使用 #[derive(Default)]，讓編譯器自動生成創建空 BTreeMap 的代碼。new() 只是一個更明確的入口。</p><p><strong>讀取數據 — get</strong></p><pre>fn get(&amp;mut self, key: &amp;[u8]) -&gt; Result&lt;Option&lt;Vec&lt;u8&gt;&gt;&gt; {<br>    Ok(self.0.get(key).cloned())<br>}</pre><p>關鍵點：</p><ul><li>self.0.get(key) 返回 Option&lt;&amp;Vec&lt;u8&gt;&gt;（借用）</li><li>.cloned() 複製值，返回 Option&lt;Vec&lt;u8&gt;&gt;（擁有權）</li><li>為什麼要複製？避免借用檢查問題，讓調用者完全擁有數據</li></ul><p><strong>寫入數據 — set</strong></p><pre>fn set(&amp;mut self, key: &amp;[u8], value: Vec&lt;u8&gt;) -&gt; Result&lt;()&gt; {<br>    self.0.insert(key.to_vec(), value);<br>    Ok(())<br>}</pre><p>注意事項：</p><ul><li>key.to_vec() 複製鍵，因為 BTreeMap 需要擁有鍵</li><li>value 已經是 Vec&lt;u8&gt;，直接移動所有權</li><li>insert 會覆蓋舊值（如果存在）</li></ul><p><strong>刪除數據 — delete</strong></p><pre>fn delete(&amp;mut self, key: &amp;[u8]) -&gt; Result&lt;()&gt; {<br>    self.0.remove(key);<br>    Ok(())<br>}</pre><p>極其簡單：</p><ul><li>調用 BTreeMap 的 remove</li><li>不管鍵是否存在，都返回成功</li><li>返回值被丟棄（我們不關心舊值）</li></ul><h3>範圍掃描</h3><p>scan 實現</p><pre>fn scan(&amp;mut self, range: impl RangeBounds&lt;Vec&lt;u8&gt;&gt;) -&gt; Self::ScanIterator&lt;&#39;_&gt; {<br>    ScanIterator(self.0.range(range))<br>}</pre><p>這裡展示了 Rust 的優雅之處：</p><ul><li>BTreeMap 的 range() 方法完美匹配我們的需求</li><li>直接包裝成 ScanIterator 返回</li><li>編譯器會為不同的 range 類型自動單態化</li></ul><p><strong>ScanIterator 結構</strong></p><pre>pub struct ScanIterator&lt;&#39;a&gt;(Range&lt;&#39;a, Vec&lt;u8&gt;, Vec&lt;u8&gt;&gt;);</pre><p>這是對 BTreeMap 範圍迭代器的簡單包裝。生命週期 &#39;a 確保：</p><ul><li>迭代器不會比 BTreeMap 活得更久</li><li>防止迭代期間修改底層數據</li></ul><p><strong>雙向迭代器</strong></p><pre>impl Iterator for ScanIterator&lt;&#39;_&gt; {<br>    type Item = Result&lt;(Vec&lt;u8&gt;, Vec&lt;u8&gt;)&gt;;<br><br>    fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {<br>        self.0.next().map(|(k, v)| Ok((k.clone(), v.clone())))<br>    }<br>}<br><br>impl DoubleEndedIterator for ScanIterator&lt;&#39;_&gt; {<br>    fn next_back(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {<br>        self.0.next_back().map(|(k, v)| Ok((k.clone(), v.clone())))<br>    }<br>}</pre><p>實現要點：</p><ul><li>正向迭代：next() 從小到大</li><li>反向迭代：next_back() 從大到小</li><li>數據複製：k.clone(), v.clone() 返回擁有的數據</li><li>錯誤包裝：用 Ok() 包裝，因為 Memory 引擎不會失敗</li></ul><p>為什麼要複製 key 和 value？</p><ul><li>BTreeMap 的迭代器返回引用 (&amp;K, &amp;V)</li><li>我們需要返回擁有權的 (Vec&lt;u8&gt;, Vec&lt;u8&gt;)</li><li>保持介面一致：BitCask 引擎也返回擁有的數據</li></ul><p><strong>scan_dyn 實現</strong></p><pre>fn scan_dyn(<br>    &amp;mut self,<br>    range: (Bound&lt;Vec&lt;u8&gt;&gt;, Bound&lt;Vec&lt;u8&gt;&gt;),<br>) -&gt; Box&lt;dyn super::ScanIterator + &#39;_&gt; {<br>    Box::new(self.scan(range))<br>}</pre><p>這是為 dyn Engine 提供的版本：</p><ul><li>參數是具體類型 (Bound, Bound) 而非泛型</li><li>返回 Box&lt;dyn ScanIterator&gt; 而非關聯類型</li><li>內部直接調用 scan()，然後裝箱</li></ul><h4>狀態查詢</h4><p><strong>status 實現</strong></p><pre>fn status(&amp;mut self) -&gt; Result&lt;Status&gt; {<br>    Ok(Status {<br>        name: &quot;memory&quot;.to_string(),<br>        keys: self.0.len() as u64,<br>        size: self.0.iter().map(|(k, v)| (k.len() + v.len()) as u64).sum(),<br>        disk_size: 0,<br>        live_disk_size: 0,<br>    })<br>}</pre><p>各欄位含義：</p><ul><li>name：引擎名稱，用於識別</li><li>keys：活躍鍵數量，直接用 BTreeMap 的 len()</li><li>size：邏輯大小，遍歷所有鍵值對累加長度</li><li>disk_size：磁盤總大小，Memory 引擎為 0</li><li>live_disk_size：活躍磁盤大小，Memory 引擎為 0</li></ul><p><strong>size 計算細節</strong></p><pre>self.0.iter().map(|(k, v)| (k.len() + v.len()) as u64).sum()</pre><p>這行代碼：</p><ol><li>iter() 遍歷所有鍵值對</li><li>map() 計算每對的總字節數</li><li>sum() 累加所有長度</li></ol><p>注意：這只計算鍵值的數據大小，不包括 BTreeMap 的元數據開銷（節點指針等）。</p><h4>持久化操作</h4><p><strong>flush 實現</strong></p><pre>fn flush(&amp;mut self) -&gt; Result&lt;()&gt; {<br>    Ok(())<br>}</pre><p>Memory 引擎不需要持久化：</p><ul><li>數據只存在內存中</li><li>沒有緩衝需要刷新</li><li>直接返回成功</li></ul><p>這符合 Engine trait 的設計：flush 只是一個「提示」，不強制要求真的做什麼。</p><h3>使用範例</h3><h4>基本操作</h4><pre>use toydb::error::Result;<br>use toydb::storage::engine::Engine;<br>use toydb::storage::memory::Memory;<br><br>fn main() -&gt; Result&lt;()&gt; {<br>    println!(&quot;=== toyDB Memory 引擎使用範例 ===\n&quot;);<br><br>    // 創建 Memory 引擎<br>    let mut engine = Memory::new();<br>    println!(&quot;✓ 創建 Memory 引擎&quot;);<br><br>    // 基本操作：寫入<br>    println!(&quot;\n--- 基本操作：寫入 ---&quot;);<br>    engine.set(b&quot;name&quot;, b&quot;Alice&quot;.to_vec())?;<br>    engine.set(b&quot;age&quot;, b&quot;25&quot;.to_vec())?;<br>    engine.set(b&quot;city&quot;, b&quot;Taipei&quot;.to_vec())?;<br>    println!(&quot;✓ 寫入 3 個鍵值對&quot;);<br><br>    // 基本操作：讀取<br>    println!(&quot;\n--- 基本操作：讀取 ---&quot;);<br>    if let Some(name) = engine.get(b&quot;name&quot;)? {<br>        println!(&quot;name = {}&quot;, String::from_utf8_lossy(&amp;name));<br>    }<br>    if let Some(age) = engine.get(b&quot;age&quot;)? {<br>        println!(&quot;age = {}&quot;, String::from_utf8_lossy(&amp;age));<br>    }<br><br>    // 基本操作：刪除<br>    println!(&quot;\n--- 基本操作：刪除 ---&quot;);<br>    engine.delete(b&quot;age&quot;)?;<br>    println!(&quot;✓ 刪除 age&quot;);<br><br>    match engine.get(b&quot;age&quot;)? {<br>        Some(_) =&gt; println!(&quot;✗ age 仍然存在&quot;),<br>        None =&gt; println!(&quot;✓ age 已被刪除&quot;),<br>    }<br><br>    // 範圍掃描：前綴掃描<br>    println!(&quot;\n--- 範圍掃描：前綴掃描 ---&quot;);<br>    engine.set(b&quot;user:1&quot;, b&quot;Alice&quot;.to_vec())?;<br>    engine.set(b&quot;user:2&quot;, b&quot;Bob&quot;.to_vec())?;<br>    engine.set(b&quot;user:3&quot;, b&quot;Carol&quot;.to_vec())?;<br>    engine.set(b&quot;admin:1&quot;, b&quot;David&quot;.to_vec())?;<br>    println!(&quot;✓ 寫入 user 和 admin 資料&quot;);<br><br>    println!(&quot;\n掃描所有 user: 開頭的鍵：&quot;);<br>    for result in engine.scan_prefix(b&quot;user:&quot;) {<br>        let (key, value) = result?;<br>        println!(&quot;  {} = {}&quot;,<br>            String::from_utf8_lossy(&amp;key),<br>            String::from_utf8_lossy(&amp;value)<br>        );<br>    }<br><br>    // 範圍掃描：指定範圍<br>    println!(&quot;\n--- 範圍掃描：指定範圍 ---&quot;);<br>    println!(&quot;掃描 [user:1, user:3] 範圍：&quot;);<br>    for result in engine.scan(b&quot;user:1&quot;.to_vec()..=b&quot;user:3&quot;.to_vec()) {<br>        let (key, value) = result?;<br>        println!(&quot;  {} = {}&quot;,<br>            String::from_utf8_lossy(&amp;key),<br>            String::from_utf8_lossy(&amp;value)<br>        );<br>    }<br><br>    // 範圍掃描：完整掃描<br>    println!(&quot;\n--- 範圍掃描：完整掃描 ---&quot;);<br>    println!(&quot;掃描所有鍵（正向）：&quot;);<br>    for result in engine.scan(..) {<br>        let (key, value) = result?;<br>        println!(&quot;  {} = {}&quot;,<br>            String::from_utf8_lossy(&amp;key),<br>            String::from_utf8_lossy(&amp;value)<br>        );<br>    }<br><br>    // 反向掃描<br>    println!(&quot;\n--- 反向掃描 ---&quot;);<br>    println!(&quot;掃描所有鍵（反向）：&quot;);<br>    let mut iter = engine.scan(..);<br>    while let Some(result) = iter.next_back() {<br>        let (key, value) = result?;<br>        println!(&quot;  {} = {}&quot;,<br>            String::from_utf8_lossy(&amp;key),<br>            String::from_utf8_lossy(&amp;value)<br>        );<br>    }<br><br>    // 狀態查詢<br>    println!(&quot;\n--- 狀態查詢 ---&quot;);<br>    let status = engine.status()?;<br>    println!(&quot;引擎名稱: {}&quot;, status.name);<br>    println!(&quot;鍵數量: {}&quot;, status.keys);<br>    println!(&quot;邏輯大小: {} bytes&quot;, status.size);<br>    println!(&quot;磁盤大小: {} bytes (Memory 引擎為 0)&quot;, status.disk_size);<br><br>    // 持久化操作<br>    println!(&quot;\n--- 持久化操作 ---&quot;);<br>    engine.flush()?;<br>    println!(&quot;✓ flush 完成 (Memory 引擎無操作)&quot;);<br><br>    println!(&quot;\n=== 範例執行完成 ===&quot;);<br>    Ok(())<br>}</pre><p>執行範例的輸出：</p><pre>=== toyDB Memory 引擎使用範例 ===<br><br>✓ 創建 Memory 引擎<br><br>--- 基本操作：寫入 ---<br>✓ 寫入 3 個鍵值對<br><br>--- 基本操作：讀取 ---<br>name = Alice<br>age = 25<br><br>--- 基本操作：刪除 ---<br>✓ 刪除 age<br>✓ age 已被刪除<br><br>--- 範圍掃描：前綴掃描 ---<br>✓ 寫入 user 和 admin 資料<br><br>掃描所有 user: 開頭的鍵：<br>  user:1 = Alice<br>  user:2 = Bob<br>  user:3 = Carol<br><br>--- 範圍掃描：指定範圍 ---<br>掃描 [user:1, user:3] 範圍：<br>  user:1 = Alice<br>  user:2 = Bob<br>  user:3 = Carol<br><br>--- 範圍掃描：完整掃描 ---<br>掃描所有鍵（正向）：<br>  admin:1 = David<br>  city = Taipei<br>  name = Alice<br>  user:1 = Alice<br>  user:2 = Bob<br>  user:3 = Carol<br><br>--- 反向掃描 ---<br>掃描所有鍵（反向）：<br>  user:3 = Carol<br>  user:2 = Bob<br>  user:1 = Alice<br>  name = Alice<br>  city = Taipei<br>  admin:1 = David<br><br>--- 狀態查詢 ---<br>引擎名稱: memory<br>鍵數量: 6<br>邏輯大小: 62 bytes<br>磁盤大小: 0 bytes (Memory 引擎為 0)<br><br>--- 持久化操作 ---<br>✓ flush 完成 (Memory 引擎無操作)<br><br>=== 範例執行完成 ===</pre><h3>測試策略</h3><p>Memory 引擎的測試分兩部分：</p><p><strong>通用引擎測試</strong></p><pre>// 運行 src/storage/testscripts/engine 下的所有測試<br>test_each_path! { in &quot;src/storage/testscripts/engine&quot; as engine =&gt; test_goldenscript }</pre><p>這些測試對所有引擎都適用，驗證基本功能：</p><ul><li>CRUD 操作</li><li>範圍掃描</li><li>邊界情況</li></ul><p><strong>Memory 特定測試</strong></p><pre>// 運行 src/storage/testscripts/memory 下的測試<br>test_each_path! { in &quot;src/storage/testscripts/memory&quot; as scripts =&gt; test_goldenscript }</pre><p>這些測試針對 Memory 引擎的特性，例如：</p><ul><li>內存中的順序保證</li><li>性能特徵</li><li>特殊邊界情況</li></ul><p><strong>測試運行器</strong></p><pre>fn test_goldenscript(path: &amp;Path) {<br>    goldenscript::run(&amp;mut Runner::new(Memory::new()), path)<br>        .expect(&quot;goldenscript failed&quot;)<br>}</pre><p>使用 Goldenscript 框架：</p><ul><li>測試腳本可讀性強</li><li>自動捕獲輸出進行回歸測試</li><li>便於調試和維護</li></ul><h3>總結</h3><p>Memory 引擎雖小，卻是 toyDB 存儲層設計的精華體現。它不僅是一個可用的實現，更是理解存儲抽象、測試驅動開發、簡潔設計的最佳範例。</p><p>下一篇文章，我們將深入探討 BitCask 引擎的實現，看看如何在磁盤上實現高效的持久化存儲。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5ffe90d8443" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[toyDB: Detailed Explanation of Storage Engine Features]]></title>
            <link>https://medium.com/@wudiheroback/toydb-detailed-explanation-of-storage-engine-features-81e73be05c8a?source=rss-83005aa59123------2</link>
            <guid isPermaLink="false">https://medium.com/p/81e73be05c8a</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Stan Hsu]]></dc:creator>
            <pubDate>Mon, 06 Oct 2025 09:09:36 GMT</pubDate>
            <atom:updated>2025-10-06T09:09:36.213Z</atom:updated>
            <content:encoded><![CDATA[<p>As a learner on the Rust journey, I document detailed notes on Rust concepts for future reference. Feel free to share suggestions or corrections about Rust or toyDB in the comments below!</p><h3>Series Articles</h3><ul><li><a href="https://medium.com/@wudiheroback/list/toydb-26839ee6d51c">https://medium.com/@wudiheroback/list/toydb-26839ee6d51c</a></li></ul><h3>Common Storage Engine Data Structures</h3><p>Common storage data structures used in databases include:</p><ul><li>LSM-Tree</li><li>B-Tree / B+Tree</li><li>Hash Table</li><li>Log-Structured Storage</li></ul><h4>toyDB’s Choice</h4><p>toyDB implements two storage engines:</p><ol><li>Memory — Pure in-memory storage</li></ol><ul><li>Fastest performance</li><li>Suitable for testing and development</li><li>Demonstrates storage abstraction flexibility</li></ul><p>2. BitCask — Log-based persistent storage</p><ul><li>Suitable for understanding persistence mechanisms</li><li>Relatively simple implementation</li><li>Demonstrates sequential write advantages</li></ul><p>These two implementations were chosen for educational purposes: BitCask is simple enough to understand while showcasing core concepts of persistent storage; Memory provides performance benchmarks and testing convenience.</p><h3>Core Method Details</h3><p><a href="https://github.com/erikgrinaker/toydb/blob/main/src/storage/engine.rs">Please read with the complete source code</a></p><h4>Basic CRUD Operations</h4><p>Engine provides standard CRUD operations: get, set, delete.</p><pre>fn get(&amp;mut self, key: &amp;[u8]) -&gt; Result&lt;Option&lt;Vec&lt;u8&gt;&gt;&gt;;<br><br>fn set(&amp;mut self, key: &amp;[u8], value: Vec&lt;u8&gt;) -&gt; Result&lt;()&gt;;<br><br>fn delete(&amp;mut self, key: &amp;[u8]) -&gt; Result&lt;()&gt;;</pre><h4>Range Scan Operations</h4><p><strong>scan — Range scanning</strong></p><pre>fn scan(&amp;mut self, range: impl RangeBounds&lt;Vec&lt;u8&gt;&gt;) -&gt; Self::ScanIterator&lt;&#39;_&gt;<br>where<br>    Self: Sized;</pre><p>This is a powerful method that supports Rust’s standard range syntax:</p><pre>// Usage examples<br>engine.scan(b&quot;a&quot;.to_vec()..b&quot;z&quot;.to_vec());      // [a, z)<br>engine.scan(b&quot;a&quot;.to_vec()..=b&quot;z&quot;.to_vec());     // [a, z]<br>engine.scan(..);                                 // all keys<br>engine.scan(b&quot;prefix&quot;.to_vec()..);              // &gt;= prefix</pre><p>Key points:</p><ul><li>Uses impl RangeBounds&lt;Vec&lt;u8&gt;&gt;, very flexible</li><li>Returns custom iterator type</li><li>Iterator is bidirectional (DoubleEndedIterator), supports reverse traversal</li></ul><pre>/// A scan iterator over key/value pairs, returned by [`Engine::scan()`].<br>pub trait ScanIterator: DoubleEndedIterator&lt;Item = Result&lt;(Vec&lt;u8&gt;, Vec&lt;u8&gt;)&gt;&gt; {}<br><br>/// Blanket implementation for all iterators that can act as a scan iterator.<br>impl&lt;I: DoubleEndedIterator&lt;Item = Result&lt;(Vec&lt;u8&gt;, Vec&lt;u8&gt;)&gt;&gt;&gt; ScanIterator for I {}</pre><p><strong>scan_prefix — Prefix scanning</strong></p><pre>fn scan_prefix(&amp;mut self, prefix: &amp;[u8]) -&gt; Self::ScanIterator&lt;&#39;_&gt;<br>where<br>    Self: Sized,<br>{<br>    self.scan(keycode::prefix_range(prefix))<br>}</pre><p>This is a convenience method for scan, used to scan all keys with the same prefix. The key implementation is the keycode::prefix_range function.</p><p><strong>Implementation and Principles of prefix_range</strong></p><pre>pub fn prefix_range(prefix: &amp;[u8]) -&gt; (Bound&lt;Vec&lt;u8&gt;&gt;, Bound&lt;Vec&lt;u8&gt;&gt;) {<br>    // 1. Start point: directly include prefix<br>    let start = Bound::Included(prefix.to_vec());<br>    // 2. End point construction<br>    let end = match prefix.iter().rposition(|&amp;b| b != 0xff) {<br>        // Found position i, construct end point<br>        Some(i) =&gt; Bound::Excluded(<br>            prefix.iter()<br>                .take(i) // Take first i bytes<br>                .copied()<br>                .chain(std::iter::once(prefix[i] + 1)) // Append &quot;i-th byte + 1&quot;<br>                .collect(),<br>        ),<br>        None =&gt; Bound::Unbounded, // All 0xff, no upper bound<br>    };<br>    (start, end)<br>}</pre><p>This function is very clever. Let’s break it down step by step. The core idea is to find all keys starting with prefix by constructing a range: the start point is prefix itself, and the end point is the smallest value greater than prefix.</p><p>Here’s an explanation using actual string examples:</p><pre>// Suppose we want to find all keys starting with &quot;user:&quot;<br>prefix = b&quot;user:&quot;  // In bytes: [0x75, 0x73, 0x65, 0x72, 0x3a]<br>                   //              u     s     e     r     :<br><br><br>// Start point: includes &quot;user:&quot;<br>start = Included(b&quot;user:&quot;)<br>// End point: find rightmost byte (0x3a, which is &#39;:&#39;)<br>// Add 1 to get 0x3b (which is &#39;;&#39; character)<br>end = Excluded(b&quot;user;&quot;)<br>// Result range: &quot;user:&quot; ..&lt; &quot;user;&quot;<br>// Included keys:<br>//   &quot;user:&quot;          ✓<br>//   &quot;user:1&quot;         ✓<br>//   &quot;user:100&quot;       ✓<br>//   &quot;user:alice&quot;     ✓<br>//   &quot;user:zzz&quot;       ✓<br>// Excluded keys:<br>//   &quot;user;&quot;          ✗ (excluded by Excluded)<br>//   &quot;users&quot;          ✗ (already &gt;= &quot;user;&quot;</pre><p>Why are “user:” bytes these values?</p><p>Each character has a corresponding ASCII encoding (a number from 0–127):</p><pre>&#39;u&#39; = 117 (decimal) = 0x75 (hexadecimal)<br>&#39;s&#39; = 115 (decimal) = 0x73 (hexadecimal)<br>&#39;e&#39; = 101 (decimal) = 0x65 (hexadecimal)<br>&#39;r&#39; = 114 (decimal) = 0x72 (hexadecimal)<br>&#39;:&#39; = 58  (decimal) = 0x3a (hexadecimal)</pre><p>Verify in Rust:</p><pre>let s = b&quot;user:&quot;;<br>println!(&quot;{:?}&quot;, s);  // Output: [117, 115, 101, 114, 58]<br>println!(&quot;{:#x?}&quot;, s); // Output: [0x75, 0x73, 0x65, 0x72, 0x3a]</pre><p>What is 0xff?</p><p>Think of a byte as a number box that can only store 0–255:</p><pre>Minimum: 0x00 = 0   (decimal)<br>Maximum: 0xff = 255 (decimal)</pre><p>Problem: If the last byte is already 255, then 255 + 1 = 256 will overflow (exceed the range a byte can store)! In databases/key-value stores (like RocksDB, BTreeMap), strings are not treated as “strings” directly but as a series of bytes (u8 array) for sorting.</p><pre>&quot;ua&quot; -&gt; [117, 97]       // &#39;u&#39; = 117, &#39;a&#39; = 97<br>&quot;ub&quot; -&gt; [117, 98]<br>&quot;uc&quot; -&gt; [117, 99]<br>&quot;v&quot;  -&gt; [118]</pre><p>You want to query: “all keys starting with ‘u’” Theoretically:</p><pre>[&quot;ua&quot;, &quot;ub&quot;, &quot;uc&quot;, ...]</pre><p>How to represent the “range”? Because bytes can’t be larger than 255: [117, 255] + 1 -&gt; overflow So we “carry”: ‘u’ (117) + 1 = ‘v’ (118) Get [118] = “v” So the range is:</p><pre>start = Included([&#39;u&#39;])  // Start from &quot;u&quot;<br>end   = Excluded([&#39;v&#39;])  // End before &quot;v&quot;</pre><p>This covers all strings starting with ‘u’.</p><p><strong>Why search from right to left</strong></p><p>We use the prefix “user” ([117,115,101,114]) as an example to explain why we must use right-to-left logic to calculate the range’s end point.</p><p>Wrong logic: Left to Right (L-R)</p><pre>Search from left to right (L-R) for first non-0xff byte:<br>  - i=0, prefix[0]=117<br>  - 117+1=118, which is character &#39;v&#39;<br>  - End point becomes [118] = &quot;v&quot;<br>Problem: What does range [&quot;user&quot;, &quot;v&quot;) contain?<br>  - &quot;user&quot;     ✓ (should include)<br>  - &quot;userABC&quot;  ✓ (should include)<br>  - &quot;useless&quot;  ✗ (should not include! But wrongly included)<br>Because in lexicographical order:<br>    &quot;user&quot;    [117, 115, 101, 114]<br>    &quot;usez&quot;    [117, 115, 101, 122]  &gt; &quot;user&quot; ✓<br>    &quot;v&quot;       [118]                 &gt; &quot;usez&quot; ✓<br>  So &quot;user&quot; &lt; &quot;usez&quot; &lt; &quot;v&quot;, &quot;usez&quot; is wrongly in range!</pre><p>Correct logic: Right to Left (R-L)</p><pre>Search from right to left (R-L) for first non-0xff byte:<br>  - Scan right to left: i=3, prefix[3] = 114 (character &#39;r&#39;)<br>  - 114 + 1 = 115, which is character &#39;s&#39;<br>  - Keep first 3 bytes [117, 115, 101] + append 115<br>  - End point becomes [117, 115, 101, 115] = &quot;uses&quot;<br>Now what does range [&quot;user&quot;, &quot;uses&quot;) contain?<br>  - &quot;user&quot;     ✓ (should include)<br>  - &quot;userABC&quot;  ✓ (should include)<br>  - &quot;usez&quot;     ✗ (correctly excluded!)<br>Because in lexicographical order:<br>    &quot;user&quot;    [117, 115, 101, 114]<br>    &quot;usez&quot;    [117, 115, 101, 122]  &gt; &quot;user&quot; ✓<br>    &quot;uses&quot;    [117, 115, 101, 115]  &lt; &quot;usez&quot; ✗</pre><h4>scan_dyn — Dynamic Dispatch Version</h4><p><strong>Why does scan use generics?</strong></p><p>Goal: Best performance, good interface</p><p>The scan method uses impl RangeBounds&lt;_&gt; + associated return type (Self::ScanIterator&lt;&#39;_&gt;) design:</p><p><strong>Generic parameters (impl RangeBounds&lt;_&gt;)</strong></p><ul><li>Callers can use any range type: .., a.., ..b, a..b, a..=b, with full expressiveness</li><li>Compiler performs monomorphization and inlining for each call form, achieving zero-cost abstraction and fastest speed</li></ul><p><strong>Associated return type (Self::ScanIterator&lt;’_&gt;)</strong></p><ul><li>Each engine implementer can return their most suitable iterator type (e.g., with caching, prefetching, direction control, etc.)</li><li>Associated types can also be monomorphized, no Box needed, no vtable needed, most resource-efficient</li></ul><p><strong>Trade-off: Not object-safe</strong></p><ul><li>Both points are not object-safe, meaning they cannot be called on dyn Engine</li><li>So scan is marked with where Self: Sized, indicating &quot;this API can only be used on concrete types&quot;</li></ul><p><strong>Why does scan_dyn use concrete type parameters + Box&lt;dyn …&gt; return?</strong></p><p>Goal: Support dyn Engine (swappable implementations)</p><p>If you want dyn Engine, the method signature must fit in the vtable. The vtable (virtual table) needs to determine &quot;parameter/return signatures&quot; at compile time, so:</p><ul><li>Parameters cannot be generic methods (cannot use impl Trait)</li><li>Return cannot depend on Self’s associated types (because dyn can’t see concrete Self)</li></ul><p>Therefore scan_dyn changes to:</p><pre>fn scan_dyn(<br>  &amp;mut self,<br>  range: (Bound&lt;Vec&lt;u8&gt;&gt;, Bound&lt;Vec&lt;u8&gt;&gt;) // Concrete, fixed signature, can hold all RangeBounds cases<br>) -&gt; Box&lt;dyn ScanIterator + &#39;_&gt;;          // Returns unified boxed iterator trait object</pre><p><strong>Why can Box hold all ScanIterator?</strong></p><p>Because Box&lt;dyn ScanIterator&gt; is a fixed-size fat pointer. No matter what the concrete iterator type is, it&#39;s a fixed &quot;one pointer&quot; size in the vtable.</p><p>Trade-off:</p><ul><li>One indirect jump (vtable lookup, slightly slower than static dispatch)</li><li>One heap allocation (Box the iterator), and dynamic dispatch iterator stepping cost</li></ul><p>Simple rule: To use vtable ⇒ parameters/return must be fixed; if they can’t be fixed, wrap them in Box to fix the shape.</p><h4>Persistence and State Queries</h4><p><strong>flush — Flush buffer</strong></p><pre>fn flush(&amp;mut self) -&gt; Result&lt;()&gt;;</pre><p>Important persistence guarantee:</p><blockquote><em>Writes are only guaranteed durable after calling [</em><em>Engine::flush()].</em></blockquote><p>This means:</p><ul><li>set and delete may only write to memory buffer</li><li>Must call flush to ensure data is persisted to disk</li><li>This is a trade-off between performance and durability</li></ul><p><strong>status — Engine status</strong></p><pre>fn status(&amp;mut self) -&gt; Result&lt;Status&gt;;</pre><p>Returns Status struct:</p><pre>pub struct Status {<br>    pub name: String,           // Engine name (e.g., &quot;bitcask&quot;, &quot;memory&quot;)<br>    pub keys: u64,              // Number of active keys<br>    pub size: u64,              // Logical size of key-value pairs<br>    pub disk_size: u64,         // Total disk size (including garbage)<br>    pub live_disk_size: u64,    // Disk size of active data<br>}</pre><p>Useful calculation methods:</p><pre>impl Status {<br>    pub fn garbage_disk_size(&amp;self) -&gt; u64 {<br>        self.disk_size - self.live_disk_size<br>    }</pre><pre>    pub fn garbage_disk_percent(&amp;self) -&gt; f64 {<br>        if self.disk_size == 0 {<br>            return 0.0;<br>        }<br>        self.garbage_disk_size() as f64 / self.disk_size as f64 * 100.0<br>    }<br>}</pre><p>This is useful for monitoring storage engine health, especially:</p><ul><li>Triggering compaction timing</li><li>Estimating storage space usage</li><li>Performance debugging</li></ul><h3>ScanIterator and Associated Types</h3><h4>ScanIterator Trait</h4><pre>pub trait ScanIterator: DoubleEndedIterator&lt;Item = Result&lt;(Vec&lt;u8&gt;, Vec&lt;u8&gt;)&gt;&gt; {}</pre><p>This is a marker trait indicating scan iterator requirements. It supports bidirectional traversal:</p><pre>let mut iter = engine.scan(..);<br>iter.next();       // Forward<br>iter.next_back();  // Backward</pre><p>Each element is Result&lt;(Vec&lt;u8&gt;, Vec&lt;u8&gt;)&gt;, allowing errors during iteration (like I/O errors), returning (key, value) tuples.</p><p>Blanket Implementation</p><pre>impl&lt;I: DoubleEndedIterator&lt;Item = Result&lt;(Vec&lt;u8&gt;, Vec&lt;u8&gt;)&gt;&gt;&gt; ScanIterator for I {}</pre><p>This is Rust’s blanket implementation, meaning: any type that already implements DoubleEndedIterator&lt;Item = Result&lt;(Vec&lt;u8&gt;, Vec&lt;u8&gt;)&gt;&gt; automatically gets the ScanIterator implementation.</p><p><strong>Why is ScanIterator empty?</strong></p><p>ScanIterator itself defines no methods; it&#39;s just a marker trait, used for:</p><ol><li>Semantic clarity: Using ScanIterator better expresses &quot;this is an iterator for scanning&quot; than directly using DoubleEndedIterator&lt;Item = ...&gt;</li><li>Future extensibility: If specific methods need to be added to scan iterators later, they can be directly added to the ScanIterator trait</li><li>Avoid repetition: No need to manually implement ScanIterator for each iterator type; types that meet the conditions automatically get it</li></ol><p>In short: ScanIterator is a &quot;semantic type alias&quot; that makes code more readable and maintainable.</p><h4><strong>Associated Type Design</strong></h4><pre>type ScanIterator&lt;&#39;a&gt;: ScanIterator + &#39;a<br>where<br>    Self: Sized + &#39;a;</pre><p>Why use associated types instead of generics?</p><p>Advantages:</p><ul><li>Each implementation has only one iterator type</li><li>Callers don’t need to specify the iterator type</li><li>Clearer API</li></ul><p>The role of where Self: Sized:</p><ul><li>Allows omitting this method in trait objects (dyn Engine)</li><li>scan and scan_prefix cannot be called through trait objects</li><li>But scan_dyn can, because it doesn&#39;t depend on associated types</li></ul><h4>Byte Strings as Keys and Values</h4><pre>fn set(&amp;mut self, key: &amp;[u8], value: Vec&lt;u8&gt;) -&gt; Result&lt;()&gt;;<br>fn get(&amp;mut self, key: &amp;[u8]) -&gt; Result&lt;Option&lt;Vec&lt;u8&gt;&gt;&gt;;</pre><p>You might wonder: Why not directly use String or other concrete types, but use raw bytes &amp;[u8]?</p><p>This is a clever design decision. Let’s explain with actual examples:</p><p>What if we used concrete types?</p><p>Suppose we define:</p><pre>fn set(&amp;mut self, key: String, value: String) -&gt; Result&lt;()&gt;;</pre><p>Looks simple, but problems arise:</p><ol><li>How to store SQL table data?</li></ol><p>A row has multiple fields: {id: 1, name: &quot;Alice&quot;, age: 25}.You can’t represent such complex structure with one String</p><p>2. How to store numbers?</p><p>If converting number 12345 to string &quot;12345&quot; for storage. Sorting would be wrong: &quot;2&quot; would come after &quot;10&quot; (string sorting), but we want numeric sorting: 2 &lt; 10</p><p>3. How to store Raft logs?</p><p>Log entries contain index, term, command, and other complex structures. Forcing String is too limiting</p><p><strong>Benefits of using bytes</strong></p><p>The Engine layer is completely unaware of key-value semantics; it only handles raw bytes &amp;[u8]. This design:</p><p>1. Maintains storage layer generality</p><p>No matter what you want to store, ultimately it’s bytes:</p><pre>// Store string<br>let name = &quot;Alice&quot;;<br>engine.set(b&quot;name&quot;, name.as_bytes().to_vec());<br><br>// Store number<br>let id: u64 = 12345;<br>let bytes = id.to_be_bytes().to_vec();  // Convert to bytes<br>engine.set(b&quot;id&quot;, bytes);<br>// Store complex JSON data<br>let json = r#&quot;{&quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 25}&quot;#;<br>engine.set(b&quot;user:1&quot;, json.as_bytes().to_vec());</pre><p>2. Allows upper layers freedom in encoding</p><p>Different scenarios can use different encoding methods:</p><ul><li>SQL layer: May use Bincode to serialize structs</li><li>MVCC layer: May use special encoding to maintain version order</li><li>Raft layer: May use custom formats to optimize performance</li></ul><p>The storage engine doesn’t need to know these details; it only handles storing and retrieving bytes.</p><p>3. Flexibility and extensibility</p><p>If new data types need to be supported in the future:</p><ul><li>Storage engine code doesn’t need changes</li><li>Just implement new encoding methods in upper layers</li></ul><h3>Summary</h3><p>Through deep understanding of Engine trait design, we see how toyDB balances simplicity and functionality. These design decisions apply not only to toyDB but also provide valuable experience for designing other storage systems.</p><p>In the next article, we’ll dive deep into the concrete implementation of the Memory storage engine.</p><h3>Notes</h3><p>Some Rust details, can be skipped</p><h4>Monomorphization</h4><p>Generating “specialized” machine code for each actual type at compile time from generic functions.</p><p>You write a generic interface (like impl RangeBounds&lt;_&gt;), and the compiler expands it into concrete versions when seeing different call types.</p><p><strong>Benefits</strong>: Zero-cost abstraction (no runtime cost, no vtable), can perform more aggressive optimizations for types.</p><p><strong>Trade-off</strong>: May increase binary size.</p><p>Example:</p><pre>fn sum&lt;T: Copy + std::ops::Add&lt;Output = T&gt;&gt;(a: T, b: T) -&gt; T { a + b }<br><br>let x = sum(1i32, 2i32);   // Generates sum_i32 version<br>let y = sum(1.0f64, 2.0);  // Generates sum_f64 version</pre><p>Example: scan method monomorphization</p><pre>fn scan&lt;R&gt;(&amp;mut self, range: R) -&gt; Self::ScanIterator&lt;&#39;_&gt;<br>where R: RangeBounds&lt;&amp;[u8]&gt;;</pre><p>Callers might pass: .. (RangeFull), a.. (RangeFrom), ..b (RangeTo), a..b (Range), a..=b (RangeInclusive)</p><p>The compiler generates specialized versions of scan for each R actually used, so there’s no “determining which range type” runtime overhead.</p><h4>Inlining</h4><p>Directly “expanding function body” into the call site at compile time. Reduces function call overhead (one less call/ret), and more importantly, allows subsequent optimizations across function boundaries (constant propagation, dead code elimination, loop optimization, etc.).</p><p>Compiler decision; #[inline] / #[inline(always)] are just suggestions, not guaranteed.</p><p>Example:</p><pre>#[inline]              // Suggest inlining<br>fn inc(x: u32) -&gt; u32 { x + 1 }<br><br>fn foo(mut n: u32) -&gt; u32 {<br>    // May be expanded to: n = n + 1;<br>    n = inc(n);<br>    n<br>}</pre><p>After expansion, inc’s body is directly pasted into foo, then LLVM can optimize it together with surrounding operations.</p><h4>Object Safety</h4><p>Object safety is Rust’s rule for traits: when you make a trait into dyn Trait (trait object), only object-safe methods are allowed to make dynamic calls through vtable.</p><p><strong>What is dyn Engine?</strong></p><p>dyn Engine is a trait object, allowing you to dynamically choose which concrete Engine implementation to use at runtime.</p><pre>// Static dispatch: known at compile time to be Memory<br>let engine: Memory = Memory::new();<br>engine.get(b&quot;key&quot;);  // Directly call Memory::get<br><br>// Dynamic dispatch: known at runtime which implementation<br>let engine: Box&lt;dyn Engine&gt; = if use_memory {<br>    Box::new(Memory::new())<br>} else {<br>    Box::new(BitCask::new(path)?)<br>};<br>engine.get(b&quot;key&quot;);  // Indirect call through vtable</pre><p>Benefits of using dyn Engine:</p><ul><li>Swappable: Can choose different storage engines at runtime</li><li>Unified interface: Same code can handle different implementations</li><li>Flexibility: For example, switching engines in tests, or dynamically choosing based on configuration</li></ul><p>Trade-off:</p><ul><li>Indirect calls: Need to look up function pointer through vtable, slightly slower than direct calls</li><li>Cannot inline: Compiler cannot inline optimize</li><li>More restrictions: Can only use object-safe methods</li></ul><p>Why this rule? Because trait object method calls go through vtable (virtual table). The vtable needs to know at compile time <strong>“the final function signature (parameter types, return types, calling convention)”;</strong> if a method’s type cannot be fixed at compile time (e.g., has generic parameters or depends on implementer’s associated types), it can’t be put in the vtable, and such methods are not object-safe.</p><p><strong>vtable structure</strong></p><p>vtable is a “fixed-shape” function pointer table; each entry’s parameter types and return types must be determined at compile time, so the call site knows how to pass parameters, how much stack space to reserve, and how to drop.</p><p>&amp;dyn Engine / Box&lt;dyn Engine&gt; is a fat pointer, containing:</p><ul><li>A pointer to data (data ptr)</li><li>A pointer to vtable (vtbl ptr)</li></ul><p>Conceptual structure:</p><pre>struct EngineVTable {<br>    delete:   fn(*mut (), *const u8, usize) -&gt; Result&lt;()&gt;,<br>    flush:    fn(*mut ()) -&gt; Result&lt;()&gt;,<br>    get:      fn(*mut (), *const u8, usize) -&gt; Result&lt;Option&lt;Vec&lt;u8&gt;&gt;&gt;,<br>    scan_dyn: fn(*mut (), (Bound&lt;Vec&lt;u8&gt;&gt;, Bound&lt;Vec&lt;u8&gt;&gt;)) -&gt; Box&lt;dyn ScanIterator&gt;,<br>    // Each entry here must have &quot;fixed signature&quot; for parameters/return<br>}</pre><p>When you call engine.delete(b&quot;key&quot;), the compiler: extracts the vtable pointer from engine, gets the corresponding function pointer from vtable, jumps using fixed calling convention.</p><p>Because the call site needs to decide at compile time how to move parameters (register/stack layout), how big the return value is (how much stack space to reserve), how to drop return value (needs concrete type), so vtable can only hold methods with “completely determined signatures”.</p><p><strong>Why can’t scan fit in vtable?</strong></p><p>It hits two “signature not fixed” landmines:</p><p>1. Generic method (impl Trait)</p><p>impl RangeBounds&lt;_&gt; is equivalent to introducing an implicit type parameter R. vtable must hold a single function pointer, but generic methods need to generate separate versions for &quot;each R&quot; (monomorphization). vtable cannot prepare entries for unknown and potentially infinite Rs.</p><p>2. Return associated type</p><p>Self::ScanIterator&lt;&#39;_&gt; for dyn Engine, Self is type-erased, the call site doesn&#39;t know this associated type&#39;s concrete type and size. The call site can&#39;t even figure out &quot;how much stack space to reserve&quot; or &quot;how to drop&quot;.</p><p>Conclusion: scan is not object-safe, so marked with where Self: Sized, indicating &quot;this method is omitted on trait objects, can only be used on concrete types&quot;.</p><p><strong>Why </strong><strong>where Self: Sized = can only be used on concrete types?</strong></p><p>Sized trait means &quot;this type&#39;s size is known at compile time&quot;. The key is:</p><pre>// Concrete types are Sized<br>Memory               // ✓ Size known at compile time<br>BitCask              // ✓ Size known at compile time<br><br>// trait object is not Sized<br>dyn Engine           // ✗ Size not known at compile time (could be Memory or BitCask)</pre><p>When you write where Self: Sized, you&#39;re actually saying: &quot;this method can only be used when Self&#39;s size is known&quot;.</p><pre>trait Engine {<br>    fn scan(&amp;mut self, ...) -&gt; Self::ScanIterator&lt;&#39;_&gt;<br>    where<br>        Self: Sized;  // Requires Self&#39;s size known at compile time<br>}<br><br>// Can use: concrete types satisfy Sized<br>let mut engine = Memory::new();<br>engine.scan(..);  // ✓ Memory is Sized<br>// Cannot use: trait object doesn&#39;t satisfy Sized<br>let mut engine: Box&lt;dyn Engine&gt; = Box::new(Memory::new());<br>engine.scan(..);  // ✗ Compile error: dyn Engine is not Sized</pre><p>The clever design:</p><ul><li>Concrete types (Memory, BitCask) can use scan (static dispatch, best performance)</li><li>trait object (dyn Engine) can only use scan_dyn (dynamic dispatch, but object-safe)</li></ul><p>This is Rust’s balance between “flexibility” and “performance”.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81e73be05c8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【知其然，更知其所以然】toyDB：storage engine trait 詳解]]></title>
            <link>https://medium.com/@wudiheroback/%E7%9F%A5%E5%85%B6%E7%84%B6-%E6%9B%B4%E7%9F%A5%E5%85%B6%E6%89%80%E4%BB%A5%E7%84%B6-toydb-storage-engine-trait-%E8%A9%B3%E8%A7%A3-aa969ef9ca29?source=rss-83005aa59123------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa969ef9ca29</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Stan Hsu]]></dc:creator>
            <pubDate>Mon, 06 Oct 2025 08:41:57 GMT</pubDate>
            <atom:updated>2025-10-06T09:08:14.110Z</atom:updated>
            <content:encoded><![CDATA[<p>由於筆者也在學習 Rust 的路上，會針對一些 Rust 概念做一些詳細的紀錄，方便日後回顧。歡迎有任何對於 Rust 或 toyDB 的建議與指正在文章底下交流!</p><h3><strong>系列文章</strong></h3><ul><li><a href="https://medium.com/@wudiheroback/list/toydb-26839ee6d51c">https://medium.com/@wudiheroback/list/toydb-26839ee6d51c</a></li></ul><h3>常見的存儲引擎數據結構</h3><p>資料庫常用的存儲數據結構包括：</p><ul><li>LSM-Tree</li><li>B-Tree / B+Tree</li><li>Hash Table</li><li>Log-Structured Storage</li></ul><h4>toyDB 的選擇</h4><p>toyDB 實現了兩種存儲引擎：</p><ol><li>Memory — 純內存存儲</li></ol><ul><li>最快的性能</li><li>適合測試和開發</li><li>展示了存儲抽象的靈活性</li></ul><p>2. BitCask — 基於日誌的持久化存儲</p><ul><li>適合理解持久化機制</li><li>實現相對簡單</li><li>展示了順序寫入的優勢</li></ul><p>選擇這兩種實現是出於教育目的：BitCask 足夠簡單易懂，但又展示了實際持久化存儲的核心概念；Memory 則提供了性能基準和測試便利。</p><h3>核心方法詳解</h3><p><a href="https://github.com/erikgrinaker/toydb/blob/main/src/storage/engine.rs">請搭配完整源碼閱讀</a></p><h4>基本 CRUD 操作</h4><p>Engine 提供標準的 CRUD 操作：get、set、delete。</p><pre>fn get(&amp;mut self, key: &amp;[u8]) -&gt; Result&lt;Option&lt;Vec&lt;u8&gt;&gt;&gt;;<br><br>fn set(&amp;mut self, key: &amp;[u8], value: Vec&lt;u8&gt;) -&gt; Result&lt;()&gt;;<br><br>fn delete(&amp;mut self, key: &amp;[u8]) -&gt; Result&lt;()&gt;;</pre><h4>範圍掃描操作</h4><p><strong>scan - 範圍掃描</strong></p><pre>fn scan(&amp;mut self, range: impl RangeBounds&lt;Vec&lt;u8&gt;&gt;) -&gt; Self::ScanIterator&lt;&#39;_&gt;<br>where<br>    Self: Sized;</pre><p>這是一個強大的方法，支持 Rust 標準的範圍語法：</p><pre>// 使用示例<br>engine.scan(b&quot;a&quot;.to_vec()..b&quot;z&quot;.to_vec());      // [a, z)<br>engine.scan(b&quot;a&quot;.to_vec()..=b&quot;z&quot;.to_vec());     // [a, z]<br>engine.scan(..);                                 // 所有鍵<br>engine.scan(b&quot;prefix&quot;.to_vec()..);              // &gt;= prefix</pre><p>關鍵點：</p><ul><li>使用 impl RangeBounds&lt;Vec&lt;u8&gt;&gt;，非常靈活</li><li>返回自定義的迭代器類型</li><li>迭代器是雙向的（DoubleEndedIterator），支持反向遍歷</li></ul><pre>/// A scan iterator over key/value pairs, returned by [`Engine::scan()`].<br>pub trait ScanIterator: DoubleEndedIterator&lt;Item = Result&lt;(Vec&lt;u8&gt;, Vec&lt;u8&gt;)&gt;&gt; {}<br><br>/// Blanket implementation for all iterators that can act as a scan iterator.<br>impl&lt;I: DoubleEndedIterator&lt;Item = Result&lt;(Vec&lt;u8&gt;, Vec&lt;u8&gt;)&gt;&gt;&gt; ScanIterator for I {}</pre><p><strong>scan_prefix - 前綴掃描</strong></p><pre>fn scan_prefix(&amp;mut self, prefix: &amp;[u8]) -&gt; Self::ScanIterator&lt;&#39;_&gt;<br>where<br>    Self: Sized,<br>{<br>    self.scan(keycode::prefix_range(prefix))<br>}</pre><p>這是 scan 的便捷方法，用於掃描具有相同前綴的所有鍵。實現的關鍵在於 keycode::prefix_range 函數。</p><p><strong>prefix_range 的實現與原理</strong></p><pre>pub fn prefix_range(prefix: &amp;[u8]) -&gt; (Bound&lt;Vec&lt;u8&gt;&gt;, Bound&lt;Vec&lt;u8&gt;&gt;) {<br>    // 1. 起始點：直接包含 prefix<br>    let start = Bound::Included(prefix.to_vec());<br>    // 2. 結束點的構造<br>    let end = match prefix.iter().rposition(|&amp;b| b != 0xff) {<br>        // 找到了位置 i，構造結束點<br>        Some(i) =&gt; Bound::Excluded(<br>            prefix.iter()<br>                .take(i) // 取前 i 個字節<br>                .copied()<br>                .chain(std::iter::once(prefix[i] + 1)) // 接上「第 i 個字節+1」<br>                .collect(),<br>        ),<br>        None =&gt; Bound::Unbounded, // 全是 0xff，沒有上界<br>    };<br>    (start, end)<br>}</pre><p>這個函數非常巧妙，讓我們逐步拆解。核心思路是要找到所有以 prefix 開頭的鍵，需要構造一個範圍：起始點就是 prefix 本身，結束點是比 prefix 大的最小值。</p><p>下面通過實際字符串範例來說明：</p><pre>// 假設我們要找所有 &quot;user:&quot; 開頭的鍵<br>prefix = b&quot;user:&quot;  // 在字節表示是 [0x75, 0x73, 0x65, 0x72, 0x3a]<br>                   //                  u     s     e     r     :<br>// 起始點：包含 &quot;user:&quot;<br>start = Included(b&quot;user:&quot;)<br>// 結束點：找最右邊的字節（0x3a，也就是 &#39;:&#39;）<br>// 將它 +1 得到 0x3b（也就是 &#39;;&#39; 字符）<br>end = Excluded(b&quot;user;&quot;)<br>// 結果範圍：&quot;user:&quot; ..&lt; &quot;user;&quot;<br>// 包含的鍵：<br>//   &quot;user:&quot;          ✓<br>//   &quot;user:1&quot;         ✓<br>//   &quot;user:100&quot;       ✓<br>//   &quot;user:alice&quot;     ✓<br>//   &quot;user:zzz&quot;       ✓<br>// 不包含的鍵：<br>//   &quot;user;&quot;          ✗ (被 Excluded 排除)<br>//   &quot;users&quot;          ✗ (已經 &gt;= &quot;user;&quot;)</pre><p>為什麼 “user:” 的字節是這些值？</p><p>每個字符都有對應的 ASCII 編碼（一個 0–127 的數字）：</p><pre>&#39;u&#39; = 117 (十進制) = 0x75 (十六進制)<br>&#39;s&#39; = 115 (十進制) = 0x73 (十六進制)<br>&#39;e&#39; = 101 (十進制) = 0x65 (十六進制)<br>&#39;r&#39; = 114 (十進制) = 0x72 (十六進制)<br>&#39;:&#39; = 58  (十進制) = 0x3a (十六進制)</pre><p>在 Rust 中驗證：</p><pre>let s = b&quot;user:&quot;;<br>println!(&quot;{:?}&quot;, s);  // 輸出: [117, 115, 101, 114, 58]<br>println!(&quot;{:#x?}&quot;, s); // 輸出: [0x75, 0x73, 0x65, 0x72, 0x3a]</pre><p>什麼是 0xff？</p><p>想像字節就像一個只能存 0–255 的數字格子：</p><pre>最小值: 0x00 = 0   (十進制)<br>最大值: 0xff = 255 (十進制)</pre><p>問題：如果最後一個字節已經是 255，那 255 + 1 = 256 會溢出（超出字節能存的範圍）！ 在 資料庫 / key-value store (例如 RocksDB, BTreeMap) 裡，字串不是直接當「字串」，而是當 一串 bytes (u8 陣列) 來排序。</p><p>你想查詢：「所有以 ‘u’ 開頭的 key」 理論上就是：</p><pre>[&quot;ua&quot;, &quot;ub&quot;, &quot;uc&quot;, ...]</pre><p>怎麼表示「範圍」呢？因為 byte 不能比 255 大： [117, 255] + 1 -&gt; 爆掉 所以我們「借位」： ‘u’ (117) + 1 = ‘v’ (118) 得到 [118] = “v” 所以區間就是：</p><pre>start = Included([&#39;u&#39;])  // 從 &quot;u&quot; 開始<br>end   = Excluded([&#39;v&#39;])  // 到 &quot;v&quot; 之前結束</pre><p>這樣就能涵蓋 所有以 ‘u’ 開頭的字串。</p><p><strong>為什麼要從右往左找</strong></p><p>我們用前綴 “user” ([117,115,101,114]) 這個例子，來整理總結為什麼必須使用從右到左的邏輯來計算範圍的結束點。</p><p>錯誤的邏輯：從左到右 (L-R)</p><pre>從左到右（L-R）找到第一個非 0xff 的字節：<br>  - i=0，prefix[0]=117<br>  - 117+1=118，即字元 &#39;v&#39;<br>  - 結束點變成 [118] = &quot;v&quot;<br>問題：範圍 [&quot;user&quot;, &quot;v&quot;) 包含了什麼？<br>  - &quot;user&quot;     ✓ (應該包含)<br>  - &quot;userABC&quot;  ✓ (應該包含)<br>  - &quot;useless&quot;  ✗ (不應該包含！但被錯誤包含了)<br><br>  因為字典序比較：<br>    &quot;user&quot;    [117, 115, 101, 114]<br>    &quot;usez&quot;    [117, 115, 101, 122]  &gt; &quot;user&quot; ✓<br>    &quot;v&quot;       [118]                 &gt; &quot;usez&quot; ✓<br><br>  所以 &quot;user&quot; &lt; &quot;usez&quot; &lt; &quot;v&quot;，&quot;usez&quot; 錯誤地落在範圍內！</pre><p>正確的邏輯：從右到左 (R-L)</p><pre>從右到左（R-L）找到第一個非 0xff 的字節：<br>  - 從右往左掃描：i=3，prefix[3] = 114 (字元 &#39;r&#39;)<br>  - 114 + 1 = 115，即字元 &#39;s&#39;<br>  - 保留前 3 個字節 [117, 115, 101] + 接上 115<br>  - 結束點變成 [117, 115, 101, 115] = &quot;uses&quot;<br><br>現在範圍 [&quot;user&quot;, &quot;uses&quot;) 包含了什麼？<br>  - &quot;user&quot;     ✓ (應該包含)<br>  - &quot;userABC&quot;  ✓ (應該包含)<br>  - &quot;usez&quot;     ✗ (正確排除！)<br><br>因為字典序比較：<br>    &quot;user&quot;    [117, 115, 101, 114]<br>    &quot;usez&quot;    [117, 115, 101, 122]  &gt; &quot;user&quot; ✓<br>    &quot;uses&quot;    [117, 115, 101, 115]  &lt; &quot;usez&quot; ✗</pre><h4>scan_dyn - 動態分發版本</h4><p><strong>為什麼 scan 用泛型？</strong></p><p>目標：效能最好、介面好用</p><p>scan 方法用 impl RangeBounds&lt;_&gt; + 關聯回傳型別（Self::ScanIterator&lt;&#39;_&gt;）的設計：</p><p><strong>參數用泛型（impl RangeBounds&lt;_&gt;）</strong></p><ul><li>呼叫端可以用 ..、a..、..b、a..b、a..=b 任一種 range 型別，表達力完整</li><li>編譯器對每種呼叫形態做單態化（monomorphization）與內聯，達成零成本抽象、跑最快</li></ul><p><strong>回傳用關聯型別（Self::ScanIterator&lt;’_&gt;）</strong></p><ul><li>每個引擎實作者可回傳自己最合適的迭代器型別（例如包了快取、預取、方向控制等）</li><li>關聯型別一樣能單態化，不需要 Box、不需要 vtable，也最省資源</li></ul><p><strong>代價：不物件安全</strong></p><ul><li>這兩點都不物件安全（object safety），也就是不能在 dyn Engine 上呼叫</li><li>所以在 scan 上標 where Self: Sized，表示「這個 API 只能用在具體型別上」</li></ul><p><strong>為什麼 scan_dyn 要用具體型別參數 + Box&lt;dyn …&gt; 回傳？</strong></p><p>目標：支援 dyn Engine（可抽換實作）</p><p>只要你要 dyn Engine，方法簽名就必須能塞進 vtable。vtable 在編譯期就要定好「參數/回傳長相」，所以：</p><ul><li>參數不能是泛型方法（不能 impl Trait）</li><li>回傳不能依賴 Self 的關聯型別（因為 dyn 看不到具體 Self）</li></ul><p>因此 scan_dyn 改成：</p><pre>fn scan_dyn(<br>  &amp;mut self,<br>  range: (Bound&lt;Vec&lt;u8&gt;&gt;, Bound&lt;Vec&lt;u8&gt;&gt;) // 具體、固定長相，能裝下所有 RangeBounds 情況<br>) -&gt; Box&lt;dyn ScanIterator + &#39;_&gt;;          // 回傳統一裝箱後的迭代器 trait object</pre><p><strong>為什麼 Box 就能裝下所有 ScanIterator？</strong></p><p>因為 Box&lt;dyn ScanIterator&gt; 是一個固定大小的胖指標，不管具體的迭代器型別是什麼，在 vtable 中都是固定的「一個指標」大小。</p><p>代價：</p><ul><li>一次間接跳轉（vtable lookup，較靜態派發慢一點點）</li><li>一次 heap 配置（Box 住迭代器），以及動態派發的迭代器步進成本</li></ul><p>簡單記： 要能走 vtable ⇒ 參數/回傳都得固定；固定不了就用 Box 包起來固定外形。</p><h4>持久化與狀態查詢</h4><p><strong>flush — 刷新緩衝</strong></p><pre>fn flush(&amp;mut self) -&gt; Result&lt;()&gt;;</pre><p>重要的持久化保證：</p><blockquote><em>Writes are only guaranteed durable after calling [</em><em>Engine::flush()].</em></blockquote><p>這意味著：</p><ul><li>set 和 delete 可能只寫入內存緩衝</li><li>必須調用 flush 才能確保數據持久化到磁盤</li><li>這是性能和持久性之間的權衡</li></ul><p><strong>status — 引擎狀態</strong></p><pre>fn status(&amp;mut self) -&gt; Result&lt;Status&gt;;</pre><p>返回 Status 結構體：</p><pre>pub struct Status {<br>    pub name: String,           // 引擎名稱 (如 &quot;bitcask&quot;, &quot;memory&quot;)<br>    pub keys: u64,              // 活躍鍵數量<br>    pub size: u64,              // 鍵值對的邏輯大小<br>    pub disk_size: u64,         // 磁盤總大小（包含垃圾）<br>    pub live_disk_size: u64,    // 活躍數據的磁盤大小<br>}</pre><p>有用的計算方法：</p><pre>impl Status {<br>    pub fn garbage_disk_size(&amp;self) -&gt; u64 {<br>        self.disk_size - self.live_disk_size<br>    }<br><br>    pub fn garbage_disk_percent(&amp;self) -&gt; f64 {<br>        if self.disk_size == 0 {<br>            return 0.0;<br>        }<br>        self.garbage_disk_size() as f64 / self.disk_size as f64 * 100.0<br>    }<br>}</pre><p>這對於監控存儲引擎健康狀況很有用，特別是：</p><ul><li>觸發壓縮（compaction）的時機</li><li>估算存儲空間使用</li><li>性能調試</li></ul><h3>ScanIterator 與關聯類型</h3><h3>ScanIterator Trait</h3><pre>pub trait ScanIterator: DoubleEndedIterator&lt;Item = Result&lt;(Vec&lt;u8&gt;, Vec&lt;u8&gt;)&gt;&gt; {}</pre><p>這是一個標記 trait，表示掃描迭代器的要求。它支持雙向遍歷：</p><pre>let mut iter = engine.scan(..);<br>iter.next();       // 從前往後<br>iter.next_back();  // 從後往前r</pre><p>每個元素是 Result&lt;(Vec&lt;u8&gt;, Vec&lt;u8&gt;)&gt;，允許迭代過程中發生錯誤（如 I/O 錯誤），返回 (key, value) 元組。</p><p><strong>Blanket Implementation（一攬子實現）</strong></p><pre>impl&lt;I: DoubleEndedIterator&lt;Item = Result&lt;(Vec&lt;u8&gt;, Vec&lt;u8&gt;)&gt;&gt;&gt; ScanIterator for I {}</pre><p>這是 Rust 的 blanket implementation，意思是：任何已經實現了 DoubleEndedIterator&lt;Item = Result&lt;(Vec&lt;u8&gt;, Vec&lt;u8&gt;)&gt;&gt; 的類型，都自動獲得 ScanIterator 的實現。</p><p><strong>為什麼 ScanIterator 是空的？</strong></p><ol><li>語義清晰：使用 ScanIterator 比直接用 DoubleEndedIterator&lt;Item = ...&gt; 更能表達「這是用於掃描的迭代器」</li><li>未來擴展性：如果以後需要給掃描迭代器添加特定方法，可以直接加到 ScanIterator trait 裡</li><li>避免重複：不用為每個迭代器類型都手動實現 ScanIterator，只要滿足條件就自動獲得</li></ol><p>簡單說：ScanIterator 就是「帶有語義的類型別名」，讓代碼更易讀、更好維護</p><h4>關聯類型設計</h4><pre>type ScanIterator&lt;&#39;a&gt;: ScanIterator + &#39;a<br>where<br>    Self: Sized + &#39;a;</pre><p>為什麼使用關聯類型而不是泛型？</p><p>優點：</p><ul><li>每個實現只有一種迭代器類型</li><li>調用者不需要指定迭代器類型</li><li>更清晰的 API</li></ul><p>where Self: Sized 的作用：</p><ul><li>允許在 trait object (dyn Engine) 中省略這個方法</li><li>scan 和 scan_prefix 無法通過 trait object 調用</li><li>但 scan_dyn 可以，因為它不依賴關聯類型</li></ul><h4>字節字符串作為鍵值</h4><pre>fn set(&amp;mut self, key: &amp;[u8], value: Vec&lt;u8&gt;) -&gt; Result&lt;()&gt;;<br>fn get(&amp;mut self, key: &amp;[u8]) -&gt; Result&lt;Option&lt;Vec&lt;u8&gt;&gt;&gt;;</pre><p>你可能會疑惑：為什麼不直接用 String 或其他具體類型，而要用 &amp;[u8] 這種原始字節？</p><p>這是一個精妙的設計決策。讓我們用實際例子說明：</p><p>如果使用具體類型會怎樣？</p><p>假設我們定義：</p><pre>fn set(&amp;mut self, key: String, value: String) -&gt; Result&lt;()&gt;;</pre><p>看起來很簡單，但問題來了：</p><ol><li><strong>SQL 表的數據怎麼存？</strong></li></ol><p>一行數據有多個欄位：{id: 1, name: &quot;Alice&quot;, age: 25}，你無法用一個 String 表示這麼複雜的結構</p><p>2. 數字怎麼存？</p><p>如果把數字 12345 轉成字符串 &quot;12345&quot; 存儲，排序就錯了：&quot;2&quot; 會排在 &quot;10&quot; 後面（字符串排序），但我們要的是數字排序：2 &lt; 10</p><p>3. Raft 日誌怎麼存？</p><p>日誌條目包含索引、任期、命令等複雜結構，強制用 String 太局限</p><p><strong>使用字節的好處</strong></p><p>Engine 層面完全不知道鍵值的語義，它只處理原始字節 &amp;[u8]。這樣設計：</p><p><strong>1. 保持存儲層的通用性</strong></p><p>不管你要存什麼，最終都是字節：</p><pre>// 存儲字符串<br>let name = &quot;Alice&quot;;<br>engine.set(b&quot;name&quot;, name.as_bytes().to_vec());<br><br>// 存儲數字<br>let id: u64 = 12345;<br>let bytes = id.to_be_bytes().to_vec();  // 轉成字節<br>engine.set(b&quot;id&quot;, bytes);<br><br>// 存儲複雜的 JSON 數據<br>let json = r#&quot;{&quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 25}&quot;#;<br>engine.set(b&quot;user:1&quot;, json.as_bytes().to_vec());</pre><p><strong>2. 允許上層自由編碼</strong></p><p>不同場景可以用不同編碼方式：</p><ul><li>SQL 層：可能用 Bincode 序列化結構體</li><li>MVCC 層：可能用特殊編碼來保持版本順序</li><li>Raft 層：可能用自定義格式來優化性能</li></ul><p>存儲引擎不需要知道這些細節，它只負責存取字節。</p><p><strong>3. 靈活性與擴展性</strong></p><p>未來如果要支持新的數據類型：</p><ul><li>存儲引擎代碼不用改</li><li>只需要在上層實現新的編碼方式</li></ul><h3>總結</h3><p>通過深入理解 `Engine` trait 的設計，我們看到了 toyDB 如何在簡潔性和功能性之間取得平衡。這些設計決策不僅適用於 toyDB，也為我們設計其他存儲系統提供了寶貴的經驗。</p><p>下一篇文章，我們將深入探討 Memory 存儲引擎的具體實現。</p><h3>備註</h3><p>Rust 的一些細節，可跳過</p><h4><strong>單態化（monomorphization）</strong></h4><p>把「泛型函式」在編譯期為每種實際型別，產生一份「專屬」機器碼。</p><p>你寫的是一個泛型介面（例如 impl RangeBounds&lt;_&gt;），編譯器看到不同呼叫型別時，會各自展開成具體版本。</p><p><strong>好處：</strong> 零成本抽象（沒有執行期成本、沒有 vtable），可針對型別做更狠的最佳化。</p><p><strong>代價：</strong> 可增加 binary 大小。</p><p><strong>範例：</strong></p><pre>fn sum&lt;T: Copy + std::ops::Add&lt;Output = T&gt;&gt;(a: T, b: T) -&gt; T { a + b }<br><br>let x = sum(1i32, 2i32);   // 產生 sum_i32 版本<br>let y = sum(1.0f64, 2.0);  // 產生 sum_f64 版本</pre><p><strong>範例：scan 方法的單態化</strong></p><pre>fn scan&lt;R&gt;(&amp;mut self, range: R) -&gt; Self::ScanIterator&lt;&#39;_&gt;<br>where R: RangeBounds&lt;&amp;[u8]&gt;;</pre><p>呼叫端可能傳：..（RangeFull）、a..（RangeFrom）、..b（RangeTo）、a..b（Range）、a..=b（RangeInclusive）</p><p>編譯器會針對實際用到的這些 R，各自產生專屬版本的 scan，所以沒有「判斷是哪種 range」的執行期開銷。</p><h4><strong>內聯（inlining）</strong></h4><p>把「函式呼叫」在編譯時直接「展開成函式本體」貼到呼叫點。減少函式呼叫的開銷（少一次 call/ret），更重要的是讓後續最佳化能跨函式進行（常數傳遞、死程式碼刪除、循環優化等）。</p><p>編譯器決策；#[inline] / #[inline(always)] 只是建議，不一定保證。</p><p>範例：</p><pre>#[inline]              // 建議內聯<br>fn inc(x: u32) -&gt; u32 { x + 1 }<br><br>fn foo(mut n: u32) -&gt; u32 {<br>    // 可能被展開為：n = n + 1;<br>    n = inc(n);<br>    n<br>}</pre><p>展開後，inc 的本體直接貼進 foo，接著 LLVM 能把它和周圍的運算一起最佳化。</p><h4><strong>物件安全（object safety）</strong></h4><p>物件安全是 Rust 對 trait 的一條規則：當你把某個 trait 做成 dyn Trait（trait object）來用時，只有物件安全的方法才允許透過 vtable 做動態呼叫。</p><p><strong>什麼是 dyn Engine？</strong></p><p>dyn Engine 是 trait object（特徵物件），讓你可以在執行期動態選擇使用哪個具體的 Engine 實現。</p><pre>// 靜態派發：編譯期就知道是 Memory<br>let engine: Memory = Memory::new();<br>engine.get(b&quot;key&quot;);  // 直接呼叫 Memory::get<br><br>// 動態派發：執行期才知道是哪個實現<br>let engine: Box&lt;dyn Engine&gt; = if use_memory {<br>    Box::new(Memory::new())<br>} else {<br>    Box::new(BitCask::new(path)?)<br>};<br>engine.get(b&quot;key&quot;);  // 透過 vtable 間接呼叫</pre><p>使用 dyn Engine 的好處：</p><ul><li>可抽換：可以在執行期選擇不同的存儲引擎</li><li>統一介面：相同的代碼可以處理不同的實現</li><li>靈活性：例如在測試中切換引擎，或根據配置動態選擇</li></ul><p>代價：</p><ul><li>間接呼叫：需要透過 vtable 查找函式指標，比直接呼叫慢一點</li><li>無法內聯：編譯器無法內聯優化</li><li>限制更多：只能使用物件安全的方法</li></ul><p>為什麼需要這條規則？因為 trait object 的方法呼叫要走 vtable（虛表）。vtable 需要在編譯期就知道「方法的最終函式簽名（參數型別、回傳型別、呼叫約定）」；如果某個方法的型別在編譯期無法固定（例如有泛型參數或依賴實作者的關聯型別），就沒法把它放進 vtable，這樣的方法就不物件安全。</p><p><strong>vtable 的結構</strong></p><p>vtable 是一張「固定形狀」的函式指標表；每個項目的參數型別與回傳型別都必須在編譯期確定，這樣呼叫點才知道怎麼傳參、要在棧上留多少空間、怎麼 drop。</p><p>&amp;dyn Engine / Box&lt;dyn Engine&gt; 是 fat pointer，包含：</p><ul><li>一個指向資料的指標（data ptr）</li><li>一個指向 vtable 的指標（vtbl ptr）</li></ul><p>結構概念示意：</p><pre>struct EngineVTable {<br>    delete:   fn(*mut (), *const u8, usize) -&gt; Result&lt;()&gt;,<br>    flush:    fn(*mut ()) -&gt; Result&lt;()&gt;,<br>    get:      fn(*mut (), *const u8, usize) -&gt; Result&lt;Option&lt;Vec&lt;u8&gt;&gt;&gt;,<br>    scan_dyn: fn(*mut (), (Bound&lt;Vec&lt;u8&gt;&gt;, Bound&lt;Vec&lt;u8&gt;&gt;)) -&gt; Box&lt;dyn ScanIterator&gt;,<br>    // 這裡的每個條目，參數/回傳都要「長相固定」<br>}</pre><p>當你呼叫 engine.delete(b&quot;key&quot;)，編譯器做的是：取出 engine 內的 vtable 指標、從 vtable 拿到對應的函式指標、用固定的呼叫約定跳過去。</p><p>因為呼叫點要在編譯期決定參數怎麼搬（寄存器/棧布局）、回傳值多大（要留多少棧空間）、怎麼 drop 回傳值（需知道具體型別），所以 vtable 只能裝「簽名已經完全確定」的方法。</p><p><strong>為什麼 scan 進不了 vtable？</strong></p><p>它踩了兩條「簽名不固定」的大地雷：</p><p><strong>1. 泛型方法（impl Trait）</strong></p><p>impl RangeBounds&lt;_&gt; 等價於引入一個隱含型別參數 R。vtable 必須放單一函式指標，但泛型方法需要對「每個 R」單獨產生版本（單態化）。vtable 不可能替未知且可能無限多的 R 準備條目。</p><p><strong>2. 回傳關聯型別</strong></p><p>Self::ScanIterator&lt;&#39;_&gt; 對 dyn Engine 來說，Self 被型別抹消了，呼叫點不知道這個關聯型別的具體型別與大小。呼叫點連「要在棧上留多少空間」「怎麼 drop」都說不清。</p><p>結論： scan 不物件安全，所以標上 where Self: Sized，表示「這個方法在 trait object 上省略，只能在具體型別上用」。</p><p><strong>為什麼 `where Self: Sized` = 只能在具體型別上用？</strong></p><p>Sized trait 表示「這個類型的大小在編譯期已知」。關鍵在於：</p><pre>// 具體型別是 Sized 的<br>Memory               // ✓ 編譯期知道大小<br>BitCask              // ✓ 編譯期知道大小<br><br>// trait object 不是 Sized 的<br>dyn Engine           // ✗ 編譯期不知道大小（可能是 Memory，也可能是 BitCask）</pre><p>當你寫 where Self: Sized 時，實際上是在說：「這個方法只能在 Self 的大小已知時使用」。</p><pre>trait Engine {<br>    fn scan(&amp;mut self, ...) -&gt; Self::ScanIterator&lt;&#39;_&gt;<br>    where<br>        Self: Sized;  // 要求 Self 的大小在編譯期已知<br>}<br><br>// 可以用：具體型別滿足 Sized<br>let mut engine = Memory::new();<br>engine.scan(..);  // ✓ Memory 是 Sized 的<br><br>// 不能用：trait object 不滿足 Sized<br>let mut engine: Box&lt;dyn Engine&gt; = Box::new(Memory::new());<br>engine.scan(..);  // ✗ 編譯錯誤：dyn Engine 不是 Sized 的</pre><p>這樣設計的巧妙之處：</p><ul><li>具體型別 (Memory, BitCask) 可以使用 scan（靜態派發，性能最佳）</li><li>trait object (dyn Engine) 只能使用 scan_dyn（動態派發，但物件安全）</li></ul><p>這是 Rust 在「靈活性」與「性能」之間找到的平衡點。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa969ef9ca29" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>