sochdb-storage 2.0.3

SochDB storage engine (WAL, block store, compaction, sync-first I/O)
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
// SPDX-License-Identifier: AGPL-3.0-or-later
// SochDB - LLM-Optimized Embedded Database
// Copyright (C) 2026 Sushanth Reddy Vanagala (https://github.com/sushanthpy)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! Transaction-Scoped Arena with Zero-Copy Key/Value Plumbing
//!
//! This module provides a memory arena that lives for the duration of a transaction,
//! enabling zero-copy key/value handling across multiple bookkeeping structures.
//!
//! ## Problem: Death by Cloning
//!
//! Today's write path clones `Vec<u8>` keys/values across multiple structures:
//! - WAL buffering
//! - MVCC write-set tracking
//! - Ordered index maintenance
//! - Memtable KV storage
//! - Dirty tracking
//!
//! If a key participates in all 5 structures, naive cloning multiplies memory
//! bandwidth and allocator pressure by O(#structures).
//!
//! ## Solution: Copy-Once, Reference Many
//!
//! ```text
//! ┌────────────────────────────────────────────────────────────────┐
//! │                    Transaction Arena                            │
//! │  ┌────────────────────────────────────────────────────────────┐│
//! │  │ Key/Value Bytes Storage (Vec<u8> backing store)            ││
//! │  │ ┌──────────┬──────────┬──────────┬──────────┬────────────┐ ││
//! │  │ │  key1    │  val1    │  key2    │  val2    │   ...      │ ││
//! │  │ └──────────┴──────────┴──────────┴──────────┴────────────┘ ││
//! │  └────────────────────────────────────────────────────────────┘│
//! │                     ↑         ↑         ↑                       │
//! │          BytesRef handles (offset, len) - 8 bytes each         │
//! └────────────────────────────────────────────────────────────────┘
//!                      │         │         │
//!     ┌────────────────┼─────────┼─────────┼────────────────┐
//!     ↓                ↓         ↓         ↓                ↓
//! ┌──────┐        ┌──────┐  ┌──────┐  ┌──────┐        ┌──────┐
//! │ WAL  │        │ MVCC │  │SkipM│  │DashM │        │Dirty │
//! │Buffer│        │WriteS│  │Index│  │Memtab│        │Track │
//! └──────┘        └──────┘  └──────┘  └──────┘        └──────┘
//!
//! Old cost: O(S × (|k|+|v|)) where S = number of structures
//! New cost: O(|k|+|v| + S)   (copy once + O(1) handle copies)
//! ```
//!
//! ## Performance
//!
//! - Bump allocation: ~3ns per key (vs ~50ns for malloc)
//! - Handle copy: 8 bytes (vs full key copy)
//! - Hash computation: Once per key (cached in handle)
//! - Memory locality: All transaction data in contiguous region

use std::cell::UnsafeCell;
use std::hash::{Hash, Hasher};
use std::sync::atomic::{AtomicU32, Ordering};

/// Default arena capacity: 64KB (handles ~1000 typical writes)
const DEFAULT_ARENA_CAPACITY: usize = 64 * 1024;

/// Maximum key+value size that fits inline in BytesRef (24 bytes)
#[allow(dead_code)]
const INLINE_MAX_SIZE: usize = 24;

// ============================================================================
// BytesRef - Lightweight Handle to Arena-Stored Bytes
// ============================================================================

/// A lightweight reference to bytes stored in a TxnArena
///
/// Only 16 bytes: (offset: u32, len: u32, hash: u64)
/// Compared to Vec<u8>: 24 bytes + heap allocation + deallocation
///
/// ## Usage
///
/// ```ignore
/// let arena = TxnArena::new(txn_id);
/// let key_ref = arena.alloc_key(b"users/12345/name");
/// let val_ref = arena.alloc_value(b"Alice");
///
/// // Now use key_ref and val_ref in multiple structures
/// // Each copy is just 16 bytes, not a full clone
/// write_set.insert(key_ref.fingerprint());  // O(1) copy
/// dirty_list.push(key_ref);                  // O(1) copy
/// memtable.insert(key_ref, val_ref);         // O(1) copy
/// ```
#[derive(Clone, Copy, Debug)]
pub struct BytesRef {
    /// Offset into arena's backing store (or inline flag if high bit set)
    offset_or_inline: u32,
    /// Length of the data
    len: u32,
    /// Pre-computed 64-bit hash (FNV-1a) for O(1) hash lookups
    hash: u64,
}

impl BytesRef {
    /// Flag indicating inline storage (high bit of offset)
    const INLINE_FLAG: u32 = 0x8000_0000;

    /// Create a BytesRef from arena offset
    #[inline]
    pub fn from_arena(offset: u32, len: u32, hash: u64) -> Self {
        debug_assert!(offset & Self::INLINE_FLAG == 0, "offset too large");
        Self {
            offset_or_inline: offset,
            len,
            hash,
        }
    }

    /// Create an inline BytesRef for small keys (avoids arena allocation)
    /// Not implemented here - see InlineBytes for that pattern
    #[inline]
    pub fn null() -> Self {
        Self {
            offset_or_inline: 0,
            len: 0,
            hash: 0,
        }
    }

    /// Check if this is a null/empty reference
    #[inline]
    pub fn is_null(&self) -> bool {
        self.len == 0
    }

    /// Get the length of referenced bytes
    #[inline]
    pub fn len(&self) -> usize {
        self.len as usize
    }

    /// Check if empty
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Get the pre-computed hash
    #[inline]
    pub fn hash(&self) -> u64 {
        self.hash
    }

    /// Get 128-bit fingerprint for MVCC write-set tracking
    ///
    /// Uses the pre-computed hash and length to create a 128-bit fingerprint.
    /// Collision probability for 10^5 keys: ~2^-128 (astronomically small)
    #[inline]
    pub fn fingerprint(&self) -> u128 {
        // Combine hash with length and a mixing constant for 128-bit fingerprint
        let upper = self.hash;
        let lower = (self.len as u64) ^ (self.hash.rotate_right(32));
        ((upper as u128) << 64) | (lower as u128)
    }

    /// Get offset in arena
    #[inline]
    pub fn offset(&self) -> u32 {
        self.offset_or_inline & !Self::INLINE_FLAG
    }

    /// Resolve this reference to actual bytes using the arena
    #[inline]
    pub fn resolve<'a>(&self, arena: &'a TxnArena) -> &'a [u8] {
        arena.get_bytes(self.offset(), self.len as usize)
    }
}

impl PartialEq for BytesRef {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        // Fast path: compare hash and length first
        self.hash == other.hash && self.len == other.len
    }
}

impl Eq for BytesRef {}

impl Hash for BytesRef {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        state.write_u64(self.hash);
    }
}

impl PartialOrd for BytesRef {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for BytesRef {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // For ordering, we need to compare by hash (approximate)
        // or the actual bytes if hashes match
        self.hash
            .cmp(&other.hash)
            .then_with(|| self.len.cmp(&other.len))
    }
}

// ============================================================================
// KeyFingerprint - 128-bit Key Identifier for MVCC Write-Set
// ============================================================================

/// 128-bit fingerprint for MVCC write-set tracking
///
/// Replaces `HashSet<Vec<u8>>` with `HashSet<KeyFingerprint>` for:
/// - O(1) memory per entry (16 bytes vs 24 + heap for Vec<u8>)
/// - No allocations in write-set operations
/// - Fast is_disjoint validation (~2^-128 collision probability)
///
/// ## Collision Safety
///
/// For 10^5 keys, collision probability is ~10^5 × 10^5 / 2^128 ≈ 10^-29
/// This is astronomically smaller than hardware bit-flip probability.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct KeyFingerprint(pub u128);

impl KeyFingerprint {
    /// Create from raw bytes
    #[inline]
    pub fn from_bytes(key: &[u8]) -> Self {
        // Use blake3 for high-quality 128-bit hash
        let hash = blake3::hash(key);
        let bytes = hash.as_bytes();
        let upper = u64::from_le_bytes([
            bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
        ]);
        let lower = u64::from_le_bytes([
            bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15],
        ]);
        Self(((upper as u128) << 64) | (lower as u128))
    }

    /// Create from BytesRef
    #[inline]
    pub fn from_bytes_ref(bytes_ref: &BytesRef, arena: &TxnArena) -> Self {
        Self::from_bytes(bytes_ref.resolve(arena))
    }

    /// Get the raw fingerprint value
    #[inline]
    pub fn value(&self) -> u128 {
        self.0
    }
}

impl From<&[u8]> for KeyFingerprint {
    fn from(bytes: &[u8]) -> Self {
        Self::from_bytes(bytes)
    }
}

// ============================================================================
// TxnArena - Transaction-Scoped Memory Arena
// ============================================================================

/// Transaction-scoped memory arena for zero-copy key/value handling
///
/// ## Design
///
/// - Single contiguous allocation per transaction
/// - Bump-pointer allocation (O(1) per key/value)
/// - Automatic cleanup when transaction completes
/// - Pre-computes hashes at allocation time
///
/// ## Thread Safety
///
/// TxnArena is designed for single-thread use within a transaction.
/// Multiple threads should each have their own TxnArena.
pub struct TxnArena {
    /// Transaction ID this arena belongs to
    txn_id: u64,
    /// Backing store for all keys and values
    data: UnsafeCell<Vec<u8>>,
    /// Current write offset (bump pointer)
    offset: AtomicU32,
    /// Number of keys allocated
    key_count: AtomicU32,
    /// Number of values allocated
    value_count: AtomicU32,
}

// Safety: TxnArena is Send because the UnsafeCell is only accessed
// through &self methods with proper synchronization via AtomicU32
unsafe impl Send for TxnArena {}

impl TxnArena {
    /// Create a new transaction arena with default capacity
    #[inline]
    pub fn new(txn_id: u64) -> Self {
        Self::with_capacity(txn_id, DEFAULT_ARENA_CAPACITY)
    }

    /// Create with specific capacity
    pub fn with_capacity(txn_id: u64, capacity: usize) -> Self {
        Self {
            txn_id,
            data: UnsafeCell::new(Vec::with_capacity(capacity)),
            offset: AtomicU32::new(0),
            key_count: AtomicU32::new(0),
            value_count: AtomicU32::new(0),
        }
    }

    /// Get the transaction ID
    #[inline]
    pub fn txn_id(&self) -> u64 {
        self.txn_id
    }

    /// Allocate a key in the arena and return a BytesRef handle
    ///
    /// The hash is computed once here and cached in the BytesRef.
    #[inline]
    pub fn alloc_key(&self, key: &[u8]) -> BytesRef {
        let hash = Self::compute_hash(key);
        let (offset, len) = self.alloc_raw(key);
        self.key_count.fetch_add(1, Ordering::Relaxed);
        BytesRef::from_arena(offset, len as u32, hash)
    }

    /// Allocate a value in the arena and return a BytesRef handle
    #[inline]
    pub fn alloc_value(&self, value: &[u8]) -> BytesRef {
        let hash = Self::compute_hash(value);
        let (offset, len) = self.alloc_raw(value);
        self.value_count.fetch_add(1, Ordering::Relaxed);
        BytesRef::from_arena(offset, len as u32, hash)
    }

    /// Allocate a key-value pair and return handles to both
    #[inline]
    pub fn alloc_kv(&self, key: &[u8], value: &[u8]) -> (BytesRef, BytesRef) {
        (self.alloc_key(key), self.alloc_value(value))
    }

    /// Raw allocation into the arena (bump pointer)
    fn alloc_raw(&self, data: &[u8]) -> (u32, usize) {
        let len = data.len();
        if len == 0 {
            return (0, 0);
        }

        // Get current offset and reserve space atomically
        let offset = self.offset.fetch_add(len as u32, Ordering::Relaxed);

        // Safety: We're the only writer to this offset range
        let vec = unsafe { &mut *self.data.get() };

        // Ensure capacity
        if vec.len() < (offset as usize + len) {
            vec.resize(offset as usize + len, 0);
        }

        // Copy data
        vec[offset as usize..offset as usize + len].copy_from_slice(data);

        (offset, len)
    }

    /// Get bytes at the given offset and length
    #[inline]
    pub fn get_bytes(&self, offset: u32, len: usize) -> &[u8] {
        let vec = unsafe { &*self.data.get() };
        &vec[offset as usize..offset as usize + len]
    }

    /// Compute FNV-1a hash for a byte slice
    #[inline]
    fn compute_hash(data: &[u8]) -> u64 {
        const FNV_OFFSET_BASIS: u64 = 0xcbf29ce484222325;
        const FNV_PRIME: u64 = 0x00000100000001B3;

        let mut h = FNV_OFFSET_BASIS;
        for &b in data {
            h ^= b as u64;
            h = h.wrapping_mul(FNV_PRIME);
        }
        h
    }

    /// Get total bytes allocated
    #[inline]
    pub fn bytes_used(&self) -> usize {
        self.offset.load(Ordering::Relaxed) as usize
    }

    /// Get number of keys allocated
    #[inline]
    pub fn key_count(&self) -> usize {
        self.key_count.load(Ordering::Relaxed) as usize
    }

    /// Get number of values allocated
    #[inline]
    pub fn value_count(&self) -> usize {
        self.value_count.load(Ordering::Relaxed) as usize
    }

    /// Reset the arena for reuse (O(1) operation)
    ///
    /// Does not deallocate memory, just resets the write pointer.
    #[inline]
    pub fn reset(&self) {
        self.offset.store(0, Ordering::Relaxed);
        self.key_count.store(0, Ordering::Relaxed);
        self.value_count.store(0, Ordering::Relaxed);
    }

    /// Create a KeyFingerprint from a BytesRef
    #[inline]
    pub fn fingerprint(&self, bytes_ref: &BytesRef) -> KeyFingerprint {
        KeyFingerprint::from_bytes(bytes_ref.resolve(self))
    }
}

impl Drop for TxnArena {
    fn drop(&mut self) {
        // All memory is automatically freed when the Vec is dropped
    }
}

// ============================================================================
// ArenaWriteSet - MVCC Write-Set Using Fingerprints
// ============================================================================

use std::collections::HashSet;

/// MVCC write-set using 128-bit fingerprints instead of Vec<u8>
///
/// ## Memory Comparison
///
/// | Structure              | Per-entry Memory | 1000 entries |
/// |------------------------|------------------|--------------|
/// | HashSet<Vec<u8>>       | 24 + heap (~50B) | ~74 KB       |
/// | HashSet<KeyFingerprint>| 16 bytes         | 16 KB        |
/// | Savings                | ~70%             | ~58 KB       |
///
/// ## Operations
///
/// - Insert: O(1) with no allocation
/// - Contains: O(1) with pre-computed hash
/// - is_disjoint: O(min(n,m)) where n,m are set sizes
pub struct ArenaWriteSet {
    /// Fingerprints of keys in the write set
    fingerprints: HashSet<KeyFingerprint>,
}

impl ArenaWriteSet {
    /// Create a new empty write set
    #[inline]
    pub fn new() -> Self {
        Self {
            fingerprints: HashSet::new(),
        }
    }

    /// Create with expected capacity
    #[inline]
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            fingerprints: HashSet::with_capacity(capacity),
        }
    }

    /// Insert a key fingerprint
    #[inline]
    pub fn insert(&mut self, fingerprint: KeyFingerprint) -> bool {
        self.fingerprints.insert(fingerprint)
    }

    /// Insert from raw bytes
    #[inline]
    pub fn insert_bytes(&mut self, key: &[u8]) -> bool {
        self.fingerprints.insert(KeyFingerprint::from_bytes(key))
    }

    /// Check if a key is in the write set
    #[inline]
    pub fn contains(&self, fingerprint: &KeyFingerprint) -> bool {
        self.fingerprints.contains(fingerprint)
    }

    /// Check if write set contains key by bytes
    #[inline]
    pub fn contains_bytes(&self, key: &[u8]) -> bool {
        self.fingerprints.contains(&KeyFingerprint::from_bytes(key))
    }

    /// Check if two write sets are disjoint (no common keys)
    #[inline]
    pub fn is_disjoint(&self, other: &ArenaWriteSet) -> bool {
        self.fingerprints.is_disjoint(&other.fingerprints)
    }

    /// Get the number of keys in the write set
    #[inline]
    pub fn len(&self) -> usize {
        self.fingerprints.len()
    }

    /// Check if the write set is empty
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.fingerprints.is_empty()
    }

    /// Iterate over fingerprints
    #[inline]
    pub fn iter(&self) -> impl Iterator<Item = &KeyFingerprint> {
        self.fingerprints.iter()
    }

    /// Clear the write set
    #[inline]
    pub fn clear(&mut self) {
        self.fingerprints.clear();
    }
}

impl Default for ArenaWriteSet {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// TxnWriteBuffer - Zero-Copy Transaction Write Buffer
// ============================================================================

/// A write operation in the transaction buffer
#[derive(Clone, Copy, Debug)]
pub struct WriteOp {
    /// Key reference
    pub key: BytesRef,
    /// Value reference (null for deletes)
    pub value: BytesRef,
    /// Is this a delete operation?
    pub is_delete: bool,
}

/// Transaction write buffer using arena-backed references
///
/// Collects all writes during a transaction with zero-copy overhead.
/// At commit time, the buffer can be flushed to WAL and memtable
/// while resolving references to actual bytes.
pub struct TxnWriteBuffer {
    /// Transaction ID
    txn_id: u64,
    /// Arena storing all key/value bytes
    arena: TxnArena,
    /// Write operations (references into arena)
    ops: Vec<WriteOp>,
    /// Write set for SSI validation (fingerprints)
    write_set: ArenaWriteSet,
    /// Read set for SSI validation (fingerprints)
    read_set: ArenaWriteSet,
}

impl TxnWriteBuffer {
    /// Create a new transaction write buffer
    #[inline]
    pub fn new(txn_id: u64) -> Self {
        Self {
            txn_id,
            arena: TxnArena::new(txn_id),
            ops: Vec::with_capacity(64),
            write_set: ArenaWriteSet::with_capacity(64),
            read_set: ArenaWriteSet::new(),
        }
    }

    /// Create with expected capacity
    pub fn with_capacity(txn_id: u64, ops_capacity: usize) -> Self {
        Self {
            txn_id,
            arena: TxnArena::with_capacity(txn_id, ops_capacity * 128), // ~128 bytes per op
            ops: Vec::with_capacity(ops_capacity),
            write_set: ArenaWriteSet::with_capacity(ops_capacity),
            read_set: ArenaWriteSet::new(),
        }
    }

    /// Get transaction ID
    #[inline]
    pub fn txn_id(&self) -> u64 {
        self.txn_id
    }

    /// Append a write operation
    ///
    /// Copies key and value into arena ONCE, then stores lightweight references.
    #[inline]
    pub fn put(&mut self, key: &[u8], value: &[u8]) {
        let key_ref = self.arena.alloc_key(key);
        let val_ref = self.arena.alloc_value(value);

        // Track in write set using fingerprint
        self.write_set.insert(KeyFingerprint::from_bytes(key));

        self.ops.push(WriteOp {
            key: key_ref,
            value: val_ref,
            is_delete: false,
        });
    }

    /// Append a delete operation
    #[inline]
    pub fn delete(&mut self, key: &[u8]) {
        let key_ref = self.arena.alloc_key(key);

        // Track in write set using fingerprint
        self.write_set.insert(KeyFingerprint::from_bytes(key));

        self.ops.push(WriteOp {
            key: key_ref,
            value: BytesRef::null(),
            is_delete: true,
        });
    }

    /// Record a read for SSI tracking
    #[inline]
    pub fn record_read(&mut self, key: &[u8]) {
        self.read_set.insert_bytes(key);
    }

    /// Get the number of write operations
    #[inline]
    pub fn len(&self) -> usize {
        self.ops.len()
    }

    /// Check if buffer is empty
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.ops.is_empty()
    }

    /// Get the write set for SSI validation
    #[inline]
    pub fn write_set(&self) -> &ArenaWriteSet {
        &self.write_set
    }

    /// Get the read set for SSI validation
    #[inline]
    pub fn read_set(&self) -> &ArenaWriteSet {
        &self.read_set
    }

    /// Get bytes used by the arena
    #[inline]
    pub fn bytes_used(&self) -> usize {
        self.arena.bytes_used()
    }

    /// Iterate over write operations
    #[inline]
    pub fn iter(&self) -> impl Iterator<Item = &WriteOp> {
        self.ops.iter()
    }

    /// Iterate over write operations with resolved bytes
    pub fn iter_resolved(&self) -> impl Iterator<Item = (&[u8], Option<&[u8]>, bool)> {
        self.ops.iter().map(move |op| {
            let key = op.key.resolve(&self.arena);
            let value = if op.is_delete {
                None
            } else {
                Some(op.value.resolve(&self.arena))
            };
            (key, value, op.is_delete)
        })
    }

    /// Get the arena for resolving references
    #[inline]
    pub fn arena(&self) -> &TxnArena {
        &self.arena
    }

    /// Clear the buffer for reuse
    pub fn clear(&mut self) {
        self.ops.clear();
        self.write_set.clear();
        self.read_set.clear();
        self.arena.reset();
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_txn_arena_basic() {
        let arena = TxnArena::new(1);

        let key_ref = arena.alloc_key(b"users/12345");
        let val_ref = arena.alloc_value(b"Alice");

        assert_eq!(key_ref.resolve(&arena), b"users/12345");
        assert_eq!(val_ref.resolve(&arena), b"Alice");
        assert_eq!(arena.key_count(), 1);
        assert_eq!(arena.value_count(), 1);
    }

    #[test]
    fn test_bytes_ref_hash() {
        let arena = TxnArena::new(1);

        let key1 = arena.alloc_key(b"test_key");
        let key2 = arena.alloc_key(b"test_key");
        let key3 = arena.alloc_key(b"other_key");

        assert_eq!(key1.hash(), key2.hash());
        assert_ne!(key1.hash(), key3.hash());
    }

    #[test]
    fn test_key_fingerprint() {
        let fp1 = KeyFingerprint::from_bytes(b"test_key");
        let fp2 = KeyFingerprint::from_bytes(b"test_key");
        let fp3 = KeyFingerprint::from_bytes(b"other_key");

        assert_eq!(fp1, fp2);
        assert_ne!(fp1, fp3);
    }

    #[test]
    fn test_arena_write_set() {
        let mut ws1 = ArenaWriteSet::new();
        let mut ws2 = ArenaWriteSet::new();

        ws1.insert_bytes(b"key1");
        ws1.insert_bytes(b"key2");

        ws2.insert_bytes(b"key3");
        ws2.insert_bytes(b"key4");

        assert!(ws1.is_disjoint(&ws2));

        ws2.insert_bytes(b"key1");
        assert!(!ws1.is_disjoint(&ws2));
    }

    #[test]
    fn test_txn_write_buffer() {
        let mut buffer = TxnWriteBuffer::new(42);

        buffer.put(b"key1", b"value1");
        buffer.put(b"key2", b"value2");
        buffer.delete(b"key3");

        assert_eq!(buffer.len(), 3);
        assert_eq!(buffer.write_set().len(), 3);

        let ops: Vec<_> = buffer.iter_resolved().collect();
        assert_eq!(
            ops[0],
            (b"key1".as_slice(), Some(b"value1".as_slice()), false)
        );
        assert_eq!(
            ops[1],
            (b"key2".as_slice(), Some(b"value2".as_slice()), false)
        );
        assert_eq!(ops[2], (b"key3".as_slice(), None, true));
    }

    #[test]
    fn test_arena_reset() {
        let arena = TxnArena::new(1);

        for i in 0..100 {
            let key = format!("key_{}", i);
            arena.alloc_key(key.as_bytes());
        }

        assert_eq!(arena.key_count(), 100);
        let used_before = arena.bytes_used();
        assert!(used_before > 0);

        arena.reset();

        assert_eq!(arena.key_count(), 0);
        assert_eq!(arena.bytes_used(), 0);
    }
}