txn-db 0.2.0

MVCC transaction engine for Rust storage layers. Snapshot isolation and serializable transactions with multi-version concurrency control, conflict detection, and a durable transaction log on wal-db. The transaction layer for embedded databases and Hive DB.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
<h1 align="center">
    <img width="99" alt="Rust logo" src="https://raw.githubusercontent.com/jamesgober/rust-collection/72baabd71f00e14aa9184efcb16fa3deddda3a0a/assets/rust-logo.svg">
    <br><b>txn-db</b><br>
    <sub><sup>API REFERENCE</sup></sub>
</h1>
<div align="center">
    <sup>
        <a href="../README.md" title="Project Home"><b>HOME</b></a>
        <span>&nbsp;&nbsp;</span>
        <span>API</span>
        <span>&nbsp;&nbsp;</span>
        <a href="../CHANGELOG.md" title="Changelog"><b>CHANGELOG</b></a>
    </sup>
</div>
<br>

> Complete reference for every public item in `txn-db`, with examples.
>
> **Status: pre-1.0.** This document tracks the API surface as it lands across
> the 0.x series. The Tier-1 surface documented here is settled as of `0.2` and
> will not change shape before `1.0`. Sections marked _(planned)_ describe an
> intended surface that has not shipped yet.

<h4 id="example-pointers">Example Pointers</h4>

- Quick start: `examples/quick_start.rs` — open, write two keys, read them back.
- Bank transfer: `examples/bank_transfer.rs` — atomic multi-key update with conflict retries.
- Concurrent counter: `examples/concurrent_counter.rs` — many threads increment one key; no update is lost.
- Snapshot reads: `examples/snapshot_reads.rs` — a snapshot stays stable as the database moves on.
- Custom store: `examples/custom_store.rs` — backing the engine with a custom `VersionStore`.

Run any of them with `cargo run --example <name>`.

## Table of Contents

- [Installation]#installation
- [Overview]#overview
- [The three tiers]#the-three-tiers
- [Quick start]#quick-start
- [Public API]#public-api
  - [`Db`]#db
  - [`Transaction`]#transaction
  - [`Snapshot`]#snapshot
  - [`Timestamp`]#timestamp
  - [`TxnError`]#txnerror
  - [`Result`]#result
  - [`VersionStore`]#versionstore
  - [`MemoryStore`]#memorystore
  - [`WriteEntry`]#writeentry
  - [`prelude`]#prelude
- [Isolation model]#isolation-model
- [Patterns]#patterns
  - [Retrying on conflict]#retrying-on-conflict
  - [Atomic multi-key updates]#atomic-multi-key-updates
  - [Consistent point-in-time reads]#consistent-point-in-time-reads
  - [Implementing a custom store]#implementing-a-custom-store
- [Feature flags]#feature-flags

---

## Installation

```toml
[dependencies]
txn-db = "0.2"
```

MSRV is Rust 1.85 (the 2024 edition). The crate is `forbid(unsafe_code)`.

---

## Overview

`txn-db` is a multi-version concurrency control (MVCC) transaction engine: the
layer that turns a key-value store into a transactional database. Every write
produces a new version tagged with a commit [`Timestamp`](#timestamp), so
readers get a stable snapshot of the data without ever blocking writers, and
writers detect conflicts at commit time instead of holding locks for the
lifetime of a transaction.

It is deliberately a *layer*, not a store: the version store is the
[`VersionStore`](#versionstore) trait, so the engine composes on top of any
backend that can keep timestamped versions of a key. Keys and values are byte
strings (`[u8]`); the engine assigns no meaning to their contents.

---

## The three tiers

The API is organised in three tiers so the common case stays small and the
power stays reachable.

- **Tier 1 — the common case.** [`Db::new`]#db, [`Db::begin`]#db, and the
  [`Transaction`]#transaction methods. No builder, no generics to name.
- **Tier 2 — configuration.** A builder for tuning, arriving in a later phase.
- **Tier 3 — the power path.** The [`VersionStore`]#versionstore trait, the
  seam for custom backends, reached through [`Db::with_store`]#db.

---

## Quick start

```rust
use txn_db::Db;

let db = Db::new();

let mut tx = db.begin();
tx.put(b"k".to_vec(), b"v".to_vec());
tx.commit()?;

let tx = db.begin();
assert_eq!(tx.get(b"k")?.as_deref(), Some(&b"v"[..]));
# Ok::<(), txn_db::TxnError>(())
```

---

## Public API

### `Db`

```rust
pub struct Db<S: VersionStore = MemoryStore> { /* … */ }
```

The database handle and Tier-1 entry point. A `Db` is a cheap, clonable handle
over shared state, like an `Arc`: every clone refers to the same database, so
the idiomatic way to use it across threads is to clone a handle per thread. It
is `Send + Sync` whenever its store is.

The default type parameter is [`MemoryStore`](#memorystore), so the type is
written `Db` with no generics in the common case.

#### Constructors

| Method | Signature | Description |
|--------|-----------|-------------|
| `new` | `fn new() -> Db<MemoryStore>` | An empty in-memory database. The default configuration. |
| `with_store` | `fn with_store(store: S) -> Db<S>` | A database over a custom [`VersionStore`]#versionstore. The Tier-3 seam. |
| `default` | `fn default() -> Db<MemoryStore>` | Equivalent to `Db::new()`. |

#### Methods

| Method | Signature | Description |
|--------|-----------|-------------|
| `begin` | `fn begin(&self) -> Transaction<S>` | Start a read-write transaction over the current snapshot. |
| `snapshot` | `fn snapshot(&self) -> Snapshot<S>` | Take a read-only, point-in-time view. |
| `last_committed` | `fn last_committed(&self) -> Timestamp` | The timestamp of the most recent commit; `Timestamp::ZERO` if none. |
| `clone` | `fn clone(&self) -> Self` | A new handle to the same database. |

`begin` and `snapshot` both capture the current commit high-water mark as their
read timestamp. Commits made after that moment are invisible to the returned
transaction or snapshot.

**Examples**

Open, write, read:

```rust
use txn_db::Db;

let db = Db::new();
let mut tx = db.begin();
tx.put(b"greeting".to_vec(), b"hei".to_vec());
tx.commit()?;

assert_eq!(db.begin().get(b"greeting")?.as_deref(), Some(&b"hei"[..]));
# Ok::<(), txn_db::TxnError>(())
```

Share one database across threads — independent keys never conflict:

```rust
use std::thread;
use txn_db::Db;

let db = Db::new();
let handles: Vec<_> = (0..4u8)
    .map(|i| {
        let db = db.clone();
        thread::spawn(move || {
            let mut tx = db.begin();
            tx.put(vec![i], vec![i]);
            tx.commit().expect("commit");
        })
    })
    .collect();
for h in handles {
    h.join().expect("thread");
}
```

Track commit progress:

```rust
use txn_db::{Db, Timestamp};

let db = Db::new();
assert_eq!(db.last_committed(), Timestamp::ZERO);

let mut tx = db.begin();
tx.put(b"k".to_vec(), b"v".to_vec());
let ts = tx.commit()?;
assert_eq!(db.last_committed(), ts);
# Ok::<(), txn_db::TxnError>(())
```

---

### `Transaction`

```rust
#[must_use = "a transaction buffers writes that are discarded unless it is committed"]
pub struct Transaction<S: VersionStore = MemoryStore> { /* … */ }
```

A read-write unit of work over a consistent snapshot. Created by
[`Db::begin`](#db). Reads come from the snapshot captured at `begin` plus the
transaction's own buffered writes; writes are local until
[`commit`](#transaction) succeeds. Dropping a transaction without committing
discards its writes — the same as [`rollback`](#transaction).

#### Methods

| Method | Signature | Description |
|--------|-----------|-------------|
| `get` | `fn get(&self, key: &[u8]) -> Result<Option<Arc<[u8]>>>` | Read `key` as this transaction sees it. |
| `put` | `fn put(&mut self, key: impl Into<Arc<[u8]>>, value: impl Into<Arc<[u8]>>)` | Buffer a write. |
| `delete` | `fn delete(&mut self, key: impl Into<Arc<[u8]>>)` | Buffer a delete (a tombstone at commit). |
| `commit` | `fn commit(self) -> Result<Timestamp>` | Apply all buffered writes atomically; returns the commit timestamp. |
| `rollback` | `fn rollback(self)` | Discard the transaction and its writes. |
| `read_timestamp` | `fn read_timestamp(&self) -> Timestamp` | The snapshot timestamp this transaction reads at. |

**Parameters**

- `get` takes `key: &[u8]` — borrowed, so reads never allocate a key.
- `put` / `delete` take `impl Into<Arc<[u8]>>`. Passing an owned `Vec<u8>`,
  `Box<[u8]>`, or `Arc<[u8]>` moves it in without copying the bytes; passing a
  `&[u8]` copies once into a fresh `Arc`. Byte-string literals (`b"k"`) are
  fixed-size arrays and do not convert directly — use `b"k".to_vec()` or
  `&b"k"[..]`.

**Return values**

- `get` returns `Ok(Some(value))` for a visible value, `Ok(None)` if the key is
  absent (or the transaction has deleted it), and `Err` only if a custom store
  fails the read. The value is an `Arc<[u8]>`, so cloning it is a reference-count
  bump, not a copy.
- `commit` returns the commit `Timestamp` on success. A transaction that wrote
  nothing commits trivially and returns its snapshot timestamp without
  allocating a new one.

**Errors**

- `commit` returns [`TxnError::Conflict`]#txnerror — retryable — if another
  transaction committed a change to any written key after this transaction's
  snapshot. None of the writes are applied in that case.
- `get` and `commit` return [`TxnError::Store`]#txnerror if the backing store
  fails. The default in-memory store never fails.

**Examples**

Read-your-own-writes:

```rust
use txn_db::Db;

let db = Db::new();
let mut tx = db.begin();

assert_eq!(tx.get(b"k")?, None);                        // absent
tx.put(b"k".to_vec(), b"v".to_vec());
assert_eq!(tx.get(b"k")?.as_deref(), Some(&b"v"[..]));  // its own write
tx.delete(b"k".to_vec());
assert_eq!(tx.get(b"k")?, None);                        // its own delete
# Ok::<(), txn_db::TxnError>(())
```

Atomic multi-key commit:

```rust
use txn_db::Db;

let db = Db::new();
let mut tx = db.begin();
tx.put(b"account:1".to_vec(), 100u64.to_le_bytes().to_vec());
tx.put(b"account:2".to_vec(), 50u64.to_le_bytes().to_vec());
tx.commit()?;  // both land or neither does
# Ok::<(), txn_db::TxnError>(())
```

Explicit rollback:

```rust
use txn_db::Db;

let db = Db::new();
let mut tx = db.begin();
tx.put(b"k".to_vec(), b"v".to_vec());
tx.rollback();
assert_eq!(db.begin().get(b"k")?, None);
# Ok::<(), txn_db::TxnError>(())
```

---

### `Snapshot`

```rust
pub struct Snapshot<S: VersionStore = MemoryStore> { /* … */ }
```

A read-only, point-in-time view created by [`Db::snapshot`](#db). It reads as of
the moment it was taken and never changes, even as other transactions commit. It
has no write buffer and nothing to commit, so it is cheaper than a transaction
when all you need is to read several keys at one consistent instant.

#### Methods

| Method | Signature | Description |
|--------|-----------|-------------|
| `get` | `fn get(&self, key: &[u8]) -> Result<Option<Arc<[u8]>>>` | Read `key` as of this snapshot. |
| `read_timestamp` | `fn read_timestamp(&self) -> Timestamp` | The timestamp this snapshot reads at. |

**Examples**

A snapshot is stable across later commits:

```rust
use txn_db::Db;

let db = Db::new();
let mut tx = db.begin();
tx.put(b"k".to_vec(), b"v1".to_vec());
tx.commit()?;

let snap = db.snapshot();          // capture the current state
let mut tx = db.begin();
tx.put(b"k".to_vec(), b"v2".to_vec());
tx.commit()?;                      // move the database forward

assert_eq!(snap.get(b"k")?.as_deref(), Some(&b"v1"[..]));        // unmoved
assert_eq!(db.snapshot().get(b"k")?.as_deref(), Some(&b"v2"[..]));
# Ok::<(), txn_db::TxnError>(())
```

---

### `Timestamp`

```rust
pub struct Timestamp(/* private */);
```

A logical timestamp marking a point in a database's commit history. Timestamps
are issued by the database as a strictly increasing sequence, are totally
ordered, and are `Copy`. They are *logical*, not wall-clock: visibility never
depends on the system clock.

#### Associated items

| Item | Signature | Description |
|------|-----------|-------------|
| `ZERO` | `const ZERO: Timestamp` | The empty database, before any commit. A snapshot at `ZERO` sees nothing. |
| `from_raw` | `fn from_raw(value: u64) -> Timestamp` | Wrap a raw counter value. |
| `get` | `fn get(self) -> u64` | The raw counter value. |

`Display` formats a timestamp as `@N` (for example `@42`).

**Examples**

```rust
use txn_db::Timestamp;

assert_eq!(Timestamp::ZERO.get(), 0);
assert!(Timestamp::ZERO < Timestamp::from_raw(1));
assert_eq!(Timestamp::from_raw(42).to_string(), "@42");
```

---

### `TxnError`

```rust
#[non_exhaustive]
pub enum TxnError {
    Conflict { key_len: usize },
    Store { context: &'static str, detail: String },
}
```

The crate error type. It implements `std::error::Error`, `Display`, `Clone`,
`PartialEq`, and `error_forge::ForgeError` (so `kind` / `caption` / `is_fatal`
metadata is available to portfolio tooling). It is `#[non_exhaustive]`: a
`match` over it must include a wildcard arm.

#### Variants

| Variant | Meaning | What to do |
|---------|---------|------------|
| `Conflict { key_len }` | A write-write conflict aborted the commit; another transaction committed a change to a written key after this one's snapshot. Only the key length is carried, never its bytes, so the error is safe to log. | Retry: begin a fresh transaction, re-read, re-apply, commit again. |
| `Store { context, detail }` | The backing [`VersionStore`]#versionstore failed a read or apply. The in-memory store never produces this. | Store-specific; inspect the variant. |

#### Methods

| Method | Signature | Description |
|--------|-----------|-------------|
| `is_retryable` | `fn is_retryable(&self) -> bool` | `true` for `Conflict`; the signal to re-run the transaction. |
| `store` | `fn store(context: &'static str, detail: impl Display) -> TxnError` | Build a `Store` error; for custom store implementations. |

**Examples**

```rust
use txn_db::{Db, TxnError};

let db = Db::new();
let mut a = db.begin();
let mut b = db.begin();
a.put(b"k".to_vec(), b"a".to_vec());
b.put(b"k".to_vec(), b"b".to_vec());

a.commit()?;
let err = b.commit().unwrap_err();
assert!(err.is_retryable());
assert!(matches!(err, TxnError::Conflict { .. }));
# Ok::<(), TxnError>(())
```

---

### `Result`

```rust
pub type Result<T, E = TxnError> = core::result::Result<T, E>;
```

The crate result alias, defaulting its error to [`TxnError`](#txnerror). Most
signatures read `Result<T>`.

---

### `VersionStore`

```rust
pub trait VersionStore: Send + Sync {
    fn get(&self, key: &[u8], read_ts: Timestamp) -> Result<Option<Arc<[u8]>>>;
    fn latest_commit_ts(&self, key: &[u8]) -> Result<Option<Timestamp>>;
    fn apply(&self, commit_ts: Timestamp, writes: Vec<WriteEntry>) -> Result<()>;
}
```

The Tier-3 seam: the backend a [`Db`](#db) is built on. The transaction layer
supplies all of the isolation logic; an implementation only has to keep
timestamped versions of keys and answer the snapshot-read query. Implementations
must be `Send + Sync`.

#### Contract

| Method | Obligation |
|--------|------------|
| `get` | Return the newest version of `key` whose commit timestamp is `<= read_ts`. A tombstone at that position reads as `None`. |
| `latest_commit_ts` | Return the timestamp of the most recent version of `key`, accounting for every applied write including tombstones. Used for conflict detection. |
| `apply` | Install a batch of versions at one `commit_ts`. The database calls this with strictly increasing timestamps and never concurrently with itself, so versions arrive in commit order. |

**Errors**: any method may return [`TxnError::Store`](#txnerror) to surface a
backend failure through the engine's `Result`.

**Example** — driving the shipped store directly through the trait:

```rust
use std::sync::Arc;
use txn_db::{MemoryStore, Timestamp, VersionStore};

let store = MemoryStore::new();
let key: Arc<[u8]> = Arc::from(&b"k"[..]);
store.apply(Timestamp::from_raw(1), vec![(key.clone(), Some(Arc::from(&b"v1"[..])))])?;

assert_eq!(store.get(b"k", Timestamp::from_raw(1))?.as_deref(), Some(&b"v1"[..]));
assert_eq!(store.get(b"k", Timestamp::ZERO)?, None);
# Ok::<(), txn_db::TxnError>(())
```

See [Implementing a custom store](#implementing-a-custom-store) for a wrapper
that adds behavior over an inner store.

---

### `MemoryStore`

```rust
pub struct MemoryStore { /* … */ }
```

An in-memory [`VersionStore`](#versionstore) backed by a hash map of version
chains. Each key maps to its versions in ascending commit-timestamp order, so a
snapshot read is a binary search for the newest version at or below the snapshot
timestamp. This is the default store of [`Db::new`](#db) and is well suited to
caches, tests, and workloads that fit in memory. Versions accumulate until
garbage collection lands (a later roadmap phase).

#### Methods

| Method | Signature | Description |
|--------|-----------|-------------|
| `new` | `fn new() -> MemoryStore` | An empty store. |
| `default` | `fn default() -> MemoryStore` | Equivalent to `new()`. |
| `key_count` | `fn key_count(&self) -> usize` | Number of distinct keys ever written (includes keys whose latest version is a tombstone). |

**Example**

```rust
use txn_db::{Db, MemoryStore};

let db = Db::with_store(MemoryStore::new());  // the explicit form of Db::new()
let mut tx = db.begin();
tx.put(b"hello".to_vec(), b"world".to_vec());
tx.commit()?;
# Ok::<(), txn_db::TxnError>(())
```

---

### `WriteEntry`

```rust
pub type WriteEntry = (Arc<[u8]>, Option<Arc<[u8]>>);
```

One entry in a commit batch handed to [`VersionStore::apply`](#versionstore): a
key paired with the value to write (`Some`) or a tombstone marking a delete
(`None`). You only touch this when implementing a custom store.

---

### `prelude`

```rust
pub mod prelude { /* re-exports */ }
```

The crate's common imports in one `use`: `Db`, `Transaction`, `Snapshot`,
`Timestamp`, `TxnError`, `Result`, `VersionStore`, `MemoryStore`, and
`WriteEntry`.

```rust
use txn_db::prelude::*;

let db = Db::new();
let mut tx = db.begin();
tx.put(b"k".to_vec(), b"v".to_vec());
let _ts: Timestamp = tx.commit()?;
# Ok::<(), TxnError>(())
```

---

## Isolation model

`txn-db` provides **snapshot isolation**:

- A transaction reads the database as of the instant it began. Commits by other
  transactions afterward are invisible to it.
- Within a transaction, reads reflect its own buffered writes
  (read-your-own-writes) before commit.
- At commit, the engine applies **first-committer-wins**: if any key the
  transaction wrote was changed by another transaction that committed after this
  one's snapshot, the commit is rejected with a retryable
  [`TxnError::Conflict`]#txnerror and none of its writes are applied. That rule
  is what prevents lost updates.

Snapshot isolation permits write skew (two transactions reading an overlapping
set and writing disjoint keys can both commit). Eliminating write skew requires
serializable isolation (SSI), which is a planned feature.

---

## Patterns

### Retrying on conflict

A write-write conflict is expected under optimistic concurrency; the correct
response is to retry against a fresh snapshot.

```rust
use txn_db::{Db, TxnError};

fn increment(db: &Db, key: &[u8]) -> Result<(), TxnError> {
    loop {
        let mut tx = db.begin();
        let current = tx.get(key)?.map_or(0u64, |v| {
            let mut buf = [0u8; 8];
            buf.copy_from_slice(&v[..8]);
            u64::from_le_bytes(buf)
        });
        tx.put(key.to_vec(), (current + 1).to_le_bytes().to_vec());
        match tx.commit() {
            Ok(_) => return Ok(()),
            Err(e) if e.is_retryable() => continue,
            Err(e) => return Err(e),
        }
    }
}

let db = Db::new();
increment(&db, b"counter")?;
# Ok::<(), TxnError>(())
```

### Atomic multi-key updates

All writes in a transaction land together or not at all.

```rust
use txn_db::Db;

let db = Db::new();
let mut tx = db.begin();
tx.put(b"order:1:status".to_vec(), b"paid".to_vec());
tx.put(b"inventory:sku-9".to_vec(), 41u64.to_le_bytes().to_vec());
tx.commit()?;  // both visible at once
# Ok::<(), txn_db::TxnError>(())
```

### Consistent point-in-time reads

Use a [`Snapshot`](#snapshot) to read many keys as of one instant without
blocking writers.

```rust
use txn_db::Db;

let db = Db::new();
let mut tx = db.begin();
tx.put(b"a".to_vec(), b"1".to_vec());
tx.put(b"b".to_vec(), b"2".to_vec());
tx.commit()?;

let snap = db.snapshot();
let a = snap.get(b"a")?;
let b = snap.get(b"b")?;  // a and b are read as of the same instant
assert!(a.is_some() && b.is_some());
# Ok::<(), txn_db::TxnError>(())
```

### Implementing a custom store

Wrap or replace the backing store through [`VersionStore`](#versionstore). This
instrumented wrapper counts reads while delegating to an inner store:

```rust
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use txn_db::{Db, MemoryStore, Timestamp, TxnError, VersionStore, WriteEntry};

struct Counting {
    inner: MemoryStore,
    reads: AtomicU64,
}

impl VersionStore for Counting {
    fn get(&self, key: &[u8], read_ts: Timestamp) -> Result<Option<Arc<[u8]>>, TxnError> {
        let _ = self.reads.fetch_add(1, Ordering::Relaxed);
        self.inner.get(key, read_ts)
    }
    fn latest_commit_ts(&self, key: &[u8]) -> Result<Option<Timestamp>, TxnError> {
        self.inner.latest_commit_ts(key)
    }
    fn apply(&self, commit_ts: Timestamp, writes: Vec<WriteEntry>) -> Result<(), TxnError> {
        self.inner.apply(commit_ts, writes)
    }
}

let db = Db::with_store(Counting { inner: MemoryStore::new(), reads: AtomicU64::new(0) });
let mut tx = db.begin();
tx.put(b"k".to_vec(), b"v".to_vec());
tx.commit()?;
# Ok::<(), TxnError>(())
```

---

## Feature flags

| Feature | Default | Description |
|---------|---------|-------------|
| `std` | yes | Standard library. Required by the current implementation. |
| `durability` | no | Durable transaction log via `wal-db`. _(planned: 0.4)_ |
| `serializable` | no | Serializable isolation (SSI) on top of snapshot isolation. _(planned: 0.3)_ |

---

<sub>Copyright &copy; 2026 <strong>James Gober</strong>. All rights reserved.</sub>