-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmod.rs
More file actions
3743 lines (3135 loc) · 110 KB
/
Copy pathmod.rs
File metadata and controls
3743 lines (3135 loc) · 110 KB
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
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Lance Zero-Copy Integration
//!
//! This module provides zero-copy access to Lance storage by sharing
//! the same address space. No serialization boundaries, no copies.
//!
//! # Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────┐
//! │ UNIFIED ADDRESS SPACE │
//! ├─────────────────────────────────────────────────────────────────┤
//! │ │
//! │ HOT (BindSpace) WARM (Lance mmap) COLD (Lance file) │
//! │ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ │
//! │ │ Array[32K] │ │ mmap region │ │ Parquet file │ │
//! │ │ Direct access │ │ OS page cache │ │ Compressed │ │
//! │ └───────┬───────┘ └───────┬───────┘ └───────┬───────┘ │
//! │ │ │ │ │
//! │ │◀──── BUBBLE UP ───│◀──── BUBBLE UP ─────│ │
//! │ │ (ptr move) │ (page fault) │ │
//! │ │ │ │ │
//! │ │──── SINK DOWN ───▶│──── SINK DOWN ─────▶│ │
//! │ │ (ptr move) │ (OS evict) │ │
//! │ │
//! │ SCENT INDEX: Awareness layer - tracks where everything lives │
//! │ │
//! └─────────────────────────────────────────────────────────────────┘
//! ```
//!
//! # Key Principles
//!
//! 1. **No Serialization Boundary**: Lance and Ladybug share memory
//! 2. **Scent as Awareness**: Index knows where data lives without copying
//! 3. **Bubbling Without Copy**: Promote/demote by updating pointers
//! 4. **Arrow Native**: Fingerprints stored as Arrow FixedSizeList
use std::path::PathBuf;
use std::sync::Arc;
use arrow_array::{Array, ArrayRef, FixedSizeListArray, UInt64Array};
use arrow_buffer::Buffer;
use arrow_data::ArrayDataBuilder;
use arrow_schema::{DataType, Field};
use super::bind_space::FINGERPRINT_WORDS;
// =============================================================================
// ARROW ZERO-COPY BRIDGE
// =============================================================================
/// Zero-copy fingerprint buffer backed by Arrow
///
/// This struct provides direct access to fingerprint data stored in Arrow format
/// without any copying. The underlying data lives in an Arrow Buffer which may
/// be backed by mmap'd memory from Lance storage.
pub struct FingerprintBuffer {
/// The Arrow buffer containing raw u64 data
buffer: Buffer,
/// Number of fingerprints in this buffer
len: usize,
}
impl FingerprintBuffer {
/// Create from raw u64 data (zero-copy via ownership transfer)
///
/// Uses `Buffer::from_vec()` which takes ownership of the Vec
/// without copying data.
pub fn from_vec(data: Vec<u64>, num_fingerprints: usize) -> Self {
let expected_len = num_fingerprints * FINGERPRINT_WORDS;
let buffer = if data.len() >= expected_len {
Buffer::from_vec(data)
} else {
// Fallback: copy if size doesn't match
Buffer::from_slice_ref(&data)
};
Self {
buffer,
len: num_fingerprints,
}
}
/// Create from raw bytes slice (copies data)
///
/// Use `from_vec` when possible to avoid copies.
pub fn from_bytes(bytes: &[u8], num_fingerprints: usize) -> Self {
let buffer = Buffer::from_slice_ref(bytes);
Self {
buffer,
len: num_fingerprints,
}
}
/// Create from an existing Arrow buffer (always zero-copy)
pub fn from_buffer(buffer: Buffer, num_fingerprints: usize) -> Self {
Self {
buffer,
len: num_fingerprints,
}
}
/// Create from a FixedSizeListArray (zero-copy)
///
/// The FixedSizeListArray should contain UInt64 elements with
/// list size = FINGERPRINT_WORDS (156).
pub fn from_fixed_size_list(array: &FixedSizeListArray) -> Option<Self> {
// Verify the array structure
if array.value_length() != FINGERPRINT_WORDS as i32 {
return None;
}
// Get the inner values array
let values = array.values();
let u64_array = values.as_any().downcast_ref::<UInt64Array>()?;
// Get the underlying buffer (zero-copy)
let buffer = u64_array.values().inner().clone();
Some(Self {
buffer,
len: array.len(),
})
}
/// Get raw pointer to fingerprint data
///
/// # Safety
/// The returned pointer is valid for the lifetime of this FingerprintBuffer.
#[inline]
pub fn as_ptr(&self) -> *const u64 {
self.buffer.as_ptr() as *const u64
}
/// Get fingerprint at index as slice (zero-copy)
#[inline]
pub fn get(&self, index: usize) -> Option<&[u64; FINGERPRINT_WORDS]> {
if index >= self.len {
return None;
}
let offset = index * FINGERPRINT_WORDS;
let ptr = self.as_ptr();
// Safety: We checked bounds above
unsafe {
let slice_ptr = ptr.add(offset) as *const [u64; FINGERPRINT_WORDS];
Some(&*slice_ptr)
}
}
/// Get fingerprint at index without bounds checking
///
/// # Safety
/// Caller must ensure index < self.len()
#[inline]
pub unsafe fn get_unchecked(&self, index: usize) -> &[u64; FINGERPRINT_WORDS] {
let ptr = self.as_ptr().add(index * FINGERPRINT_WORDS) as *const [u64; FINGERPRINT_WORDS];
&*ptr
}
/// Number of fingerprints
#[inline]
pub fn len(&self) -> usize {
self.len
}
/// Is empty?
#[inline]
pub fn is_empty(&self) -> bool {
self.len == 0
}
/// Get underlying Arrow buffer (for sharing with other Arrow operations)
pub fn buffer(&self) -> &Buffer {
&self.buffer
}
/// Convert back to FixedSizeListArray (zero-copy)
pub fn to_fixed_size_list(&self) -> ArrayRef {
// Create UInt64Array from buffer
let u64_data = ArrayDataBuilder::new(DataType::UInt64)
.len(self.len * FINGERPRINT_WORDS)
.add_buffer(self.buffer.clone())
.build()
.expect("valid array data");
let u64_array = UInt64Array::from(u64_data);
// Wrap in FixedSizeListArray
let field = Arc::new(Field::new("item", DataType::UInt64, false));
Arc::new(FixedSizeListArray::new(
field,
FINGERPRINT_WORDS as i32,
Arc::new(u64_array),
None,
))
}
/// Iterate over fingerprints (zero-copy)
pub fn iter(&self) -> FingerprintIter<'_> {
FingerprintIter {
buffer: self,
index: 0,
}
}
}
/// Iterator over fingerprints in a FingerprintBuffer
pub struct FingerprintIter<'a> {
buffer: &'a FingerprintBuffer,
index: usize,
}
impl<'a> Iterator for FingerprintIter<'a> {
type Item = &'a [u64; FINGERPRINT_WORDS];
fn next(&mut self) -> Option<Self::Item> {
if self.index >= self.buffer.len {
return None;
}
// Safety: we just checked bounds
let fp = unsafe { self.buffer.get_unchecked(self.index) };
self.index += 1;
Some(fp)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let remaining = self.buffer.len - self.index;
(remaining, Some(remaining))
}
}
impl<'a> ExactSizeIterator for FingerprintIter<'a> {}
// =============================================================================
// ARROW ZERO-COPY MANAGER
// =============================================================================
/// Manager for zero-copy Arrow integration
///
/// Handles conversion between Ladybug fingerprints and Arrow format,
/// maintaining zero-copy semantics throughout the pipeline.
pub struct ArrowZeroCopy {
/// Currently loaded fingerprint buffers
buffers: Vec<FingerprintBuffer>,
/// Scent awareness for temperature tracking
scent: ScentAwareness,
}
impl ArrowZeroCopy {
/// Create new manager
pub fn new() -> Self {
Self {
buffers: Vec::new(),
scent: ScentAwareness::new(),
}
}
/// Load fingerprints from Vec<u64> (zero-copy via ownership transfer)
pub fn load_from_vec(&mut self, data: Vec<u64>, num_fingerprints: usize) -> usize {
let buffer = FingerprintBuffer::from_vec(data, num_fingerprints);
let id = self.buffers.len();
self.buffers.push(buffer);
id
}
/// Load fingerprints from bytes slice (copies data)
pub fn load_from_bytes(&mut self, bytes: &[u8], num_fingerprints: usize) -> usize {
let buffer = FingerprintBuffer::from_bytes(bytes, num_fingerprints);
let id = self.buffers.len();
self.buffers.push(buffer);
id
}
/// Load fingerprints from Arrow array (zero-copy)
pub fn load_from_arrow(&mut self, array: &FixedSizeListArray) -> Option<usize> {
let buffer = FingerprintBuffer::from_fixed_size_list(array)?;
let id = self.buffers.len();
self.buffers.push(buffer);
Some(id)
}
/// Get fingerprint by buffer ID and index
pub fn get(&self, buffer_id: usize, index: usize) -> Option<&[u64; FINGERPRINT_WORDS]> {
self.buffers.get(buffer_id)?.get(index)
}
/// Touch for temperature tracking
pub fn touch(&mut self, buffer_id: usize, index: usize) {
// Encode buffer_id and index into a single u32
let combined = ((buffer_id as u32) << 24) | (index as u32 & 0xFFFFFF);
self.scent.touch(combined);
}
/// Get buffer by ID
pub fn buffer(&self, id: usize) -> Option<&FingerprintBuffer> {
self.buffers.get(id)
}
/// Get scent awareness
pub fn scent(&self) -> &ScentAwareness {
&self.scent
}
/// Get mutable scent awareness
pub fn scent_mut(&mut self) -> &mut ScentAwareness {
&mut self.scent
}
/// Total fingerprints across all buffers
pub fn total_fingerprints(&self) -> usize {
self.buffers.iter().map(|b| b.len()).sum()
}
}
impl Default for ArrowZeroCopy {
fn default() -> Self {
Self::new()
}
}
// =============================================================================
// ADJACENCY SORTING (locality-preserving order)
// =============================================================================
/// Locality-preserving fingerprint ordering
///
/// Since Lance row operations are cheap, we can sort fingerprints by
/// adjacency (similar fingerprints near each other) for better cache
/// locality during search.
///
/// Uses a simple LSH-style bucket assignment based on the first few bits
/// of each fingerprint word, creating a coarse-grained spatial ordering.
///
/// # IMPORTANT: Codebook Index Preservation
///
/// This index does NOT invalidate codebook addressing. The 8+8 address model
/// (prefix:slot) always uses the ORIGINAL index for lookup:
///
/// ```text
/// Address 0x42:0x0F → original_index = lookup(0x42, 0x0F) → fingerprint
/// ↓
/// AdjacencyIndex::sorted_position(original_index)
/// ↓
/// (only used for cache-friendly iteration)
/// ```
///
/// - Direct lookups by address: use original_index (preserves codebook)
/// - Batch scanning: use iter_sorted() for cache locality
/// - Similarity search: use locality_range() then original_index for results
pub struct AdjacencyIndex {
/// Bucket assignments for each fingerprint
/// bucket[i] = locality hash for fingerprint i
buckets: Vec<u32>,
/// Sorted indices: sorted_order[i] = original index
/// Fingerprints are sorted by bucket, so similar ones are adjacent
sorted_order: Vec<u32>,
/// Reverse map: reverse[original_index] = position in sorted order
reverse: Vec<u32>,
}
impl AdjacencyIndex {
/// Create adjacency index for fingerprints
///
/// Computes a locality-sensitive hash for each fingerprint and
/// creates a sorted order that clusters similar fingerprints together.
pub fn build(fingerprints: &FingerprintBuffer) -> Self {
let n = fingerprints.len();
// Compute locality hash for each fingerprint
// Uses first 4 bits from first 8 words = 32-bit locality hash
let buckets: Vec<u32> = (0..n)
.map(|i| {
let fp = fingerprints.get(i).unwrap();
Self::locality_hash(fp)
})
.collect();
// Create sorted indices
let mut sorted_order: Vec<u32> = (0..n as u32).collect();
sorted_order.sort_by_key(|&i| buckets[i as usize]);
// Create reverse mapping
let mut reverse = vec![0u32; n];
for (pos, &orig) in sorted_order.iter().enumerate() {
reverse[orig as usize] = pos as u32;
}
Self {
buckets,
sorted_order,
reverse,
}
}
/// Locality-sensitive hash
///
/// Takes first 4 bits from first 8 words of fingerprint,
/// creating a 32-bit locality hash that groups similar
/// fingerprints together.
#[inline]
fn locality_hash(fp: &[u64; FINGERPRINT_WORDS]) -> u32 {
let mut hash = 0u32;
for i in 0..8 {
// Take top 4 bits from each of first 8 words
let bits = ((fp[i] >> 60) & 0xF) as u32;
hash |= bits << (i * 4);
}
hash
}
/// Get original index from sorted position
#[inline]
pub fn original_index(&self, sorted_pos: usize) -> Option<u32> {
self.sorted_order.get(sorted_pos).copied()
}
/// Get sorted position from original index
#[inline]
pub fn sorted_position(&self, original_idx: usize) -> Option<u32> {
self.reverse.get(original_idx).copied()
}
/// Get locality bucket for original index
#[inline]
pub fn bucket(&self, original_idx: usize) -> Option<u32> {
self.buckets.get(original_idx).copied()
}
/// Find range of sorted indices that might contain similar fingerprints
///
/// Given a query fingerprint, returns a range of sorted positions
/// that are likely to contain similar fingerprints (same locality bucket).
pub fn locality_range(&self, query: &[u64; FINGERPRINT_WORDS]) -> std::ops::Range<usize> {
let query_bucket = Self::locality_hash(query);
// Binary search for first index with this bucket
let start = self.sorted_order
.partition_point(|&i| self.buckets[i as usize] < query_bucket);
// Binary search for first index past this bucket
let end = self.sorted_order
.partition_point(|&i| self.buckets[i as usize] <= query_bucket);
start..end
}
/// Iterate over original indices in sorted (locality-preserving) order
pub fn iter_sorted(&self) -> impl Iterator<Item = u32> + '_ {
self.sorted_order.iter().copied()
}
/// Number of fingerprints
pub fn len(&self) -> usize {
self.sorted_order.len()
}
/// Is empty?
pub fn is_empty(&self) -> bool {
self.sorted_order.is_empty()
}
}
// =============================================================================
// SAFETY: WAL + CONCURRENCY + ACID
// =============================================================================
use std::collections::VecDeque;
use std::sync::atomic::{AtomicU64, AtomicBool, Ordering};
use parking_lot::{RwLock, Mutex};
/// Write-Ahead Log entry for crash recovery
#[derive(Debug, Clone)]
pub struct WalEntry {
/// Monotonic sequence number
pub lsn: u64,
/// Operation type
pub op: WalOp,
/// Timestamp (epoch millis)
pub timestamp: u64,
/// Checksum for integrity
pub checksum: u32,
}
/// WAL operation types
#[derive(Debug, Clone)]
pub enum WalOp {
/// Insert fingerprint at index
Insert { index: u32, fingerprint: Box<[u64; FINGERPRINT_WORDS]> },
/// Update fingerprint at index
Update { index: u32, old: Box<[u64; FINGERPRINT_WORDS]>, new: Box<[u64; FINGERPRINT_WORDS]> },
/// Delete fingerprint at index
Delete { index: u32, fingerprint: Box<[u64; FINGERPRINT_WORDS]> },
/// Temperature change (for scent tracking)
TempChange { index: u32, from: Temperature, to: Temperature },
/// Checkpoint marker (safe recovery point)
Checkpoint { version: u64 },
/// Transaction begin
TxnBegin { txn_id: u64 },
/// Transaction commit
TxnCommit { txn_id: u64 },
/// Transaction abort
TxnAbort { txn_id: u64 },
}
impl WalEntry {
/// Create new WAL entry
pub fn new(lsn: u64, op: WalOp) -> Self {
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64;
let mut entry = Self {
lsn,
op,
timestamp,
checksum: 0,
};
entry.checksum = entry.compute_checksum();
entry
}
/// Compute CRC32-style checksum
fn compute_checksum(&self) -> u32 {
// Simple checksum: XOR of lsn, timestamp, and op discriminant
let op_tag = match &self.op {
WalOp::Insert { .. } => 1u32,
WalOp::Update { .. } => 2,
WalOp::Delete { .. } => 3,
WalOp::TempChange { .. } => 4,
WalOp::Checkpoint { .. } => 5,
WalOp::TxnBegin { .. } => 6,
WalOp::TxnCommit { .. } => 7,
WalOp::TxnAbort { .. } => 8,
};
(self.lsn as u32) ^ (self.timestamp as u32) ^ op_tag
}
/// Verify entry integrity
pub fn verify(&self) -> bool {
self.checksum == self.compute_checksum()
}
}
/// Write-Ahead Log for durability
pub struct WriteAheadLog {
/// Current LSN (Log Sequence Number)
current_lsn: AtomicU64,
/// In-memory log buffer (flushed to disk periodically)
buffer: Mutex<VecDeque<WalEntry>>,
/// Last flushed LSN
flushed_lsn: AtomicU64,
/// Last checkpoint LSN
checkpoint_lsn: AtomicU64,
/// Maximum buffer size before force flush
max_buffer_size: usize,
/// Path for WAL files
wal_path: PathBuf,
/// Is WAL enabled?
enabled: AtomicBool,
}
impl WriteAheadLog {
/// Create new WAL
pub fn new(wal_path: PathBuf) -> Self {
Self {
current_lsn: AtomicU64::new(1),
buffer: Mutex::new(VecDeque::with_capacity(1024)),
flushed_lsn: AtomicU64::new(0),
checkpoint_lsn: AtomicU64::new(0),
max_buffer_size: 1024,
wal_path,
enabled: AtomicBool::new(true),
}
}
/// Append entry to WAL, returns LSN
pub fn append(&self, op: WalOp) -> u64 {
if !self.enabled.load(Ordering::Relaxed) {
return 0;
}
let lsn = self.current_lsn.fetch_add(1, Ordering::SeqCst);
let entry = WalEntry::new(lsn, op);
let mut buffer = self.buffer.lock();
buffer.push_back(entry);
// Force flush if buffer is full
if buffer.len() >= self.max_buffer_size {
drop(buffer);
self.flush();
}
lsn
}
/// Flush buffer to disk
pub fn flush(&self) -> u64 {
let mut buffer = self.buffer.lock();
if buffer.is_empty() {
return self.flushed_lsn.load(Ordering::Relaxed);
}
// In real implementation, serialize and write to file
// For now, just update flushed_lsn
let max_lsn = buffer.back().map(|e| e.lsn).unwrap_or(0);
buffer.clear();
self.flushed_lsn.store(max_lsn, Ordering::Release);
max_lsn
}
/// Create checkpoint (safe recovery point)
pub fn checkpoint(&self) -> u64 {
let lsn = self.append(WalOp::Checkpoint {
version: self.current_lsn.load(Ordering::Relaxed),
});
self.flush();
self.checkpoint_lsn.store(lsn, Ordering::Release);
lsn
}
/// Get current LSN
pub fn current_lsn(&self) -> u64 {
self.current_lsn.load(Ordering::Relaxed)
}
/// Get last flushed LSN
pub fn flushed_lsn(&self) -> u64 {
self.flushed_lsn.load(Ordering::Relaxed)
}
/// Get last checkpoint LSN
pub fn checkpoint_lsn(&self) -> u64 {
self.checkpoint_lsn.load(Ordering::Relaxed)
}
/// Enable/disable WAL
pub fn set_enabled(&self, enabled: bool) {
self.enabled.store(enabled, Ordering::Relaxed);
}
/// Recover from WAL (replay entries after last checkpoint)
pub fn recover(&self) -> Vec<WalEntry> {
// In real implementation, read WAL file and return entries
// after last checkpoint for replay
Vec::new()
}
}
impl Default for WriteAheadLog {
fn default() -> Self {
Self::new(PathBuf::from("./wal"))
}
}
/// MVCC version for isolation
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Version(pub u64);
impl Version {
pub fn new(v: u64) -> Self {
Self(v)
}
}
/// Versioned fingerprint for MVCC
pub struct VersionedFingerprint {
/// The fingerprint data
pub data: [u64; FINGERPRINT_WORDS],
/// Version when this was written
pub write_version: Version,
/// Version when this was deleted (None if still visible)
pub delete_version: Option<Version>,
}
impl VersionedFingerprint {
/// Check if visible at given version
pub fn visible_at(&self, version: Version) -> bool {
version >= self.write_version
&& self.delete_version.map(|dv| version < dv).unwrap_or(true)
}
}
/// Transaction state
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TxnState {
Active,
Committed,
Aborted,
}
/// Transaction context for ACID
pub struct Transaction {
/// Transaction ID
pub id: u64,
/// Read version (snapshot isolation)
pub read_version: Version,
/// State
pub state: TxnState,
/// WAL entries for this transaction
pub wal_entries: Vec<u64>,
/// Modified indices (for rollback)
pub modified: Vec<u32>,
}
impl Transaction {
/// Create new transaction
pub fn new(id: u64, read_version: Version) -> Self {
Self {
id,
read_version,
state: TxnState::Active,
wal_entries: Vec::new(),
modified: Vec::new(),
}
}
/// Check if transaction is active
pub fn is_active(&self) -> bool {
self.state == TxnState::Active
}
}
/// Concurrent access controller with read-write locking
pub struct ConcurrentAccess<T> {
/// The protected data
data: RwLock<T>,
/// Version counter
version: AtomicU64,
/// WAL reference
wal: Arc<WriteAheadLog>,
/// Active transactions
active_txns: Mutex<Vec<Transaction>>,
/// Next transaction ID
next_txn_id: AtomicU64,
}
impl<T> ConcurrentAccess<T> {
/// Create new concurrent access wrapper
pub fn new(data: T, wal: Arc<WriteAheadLog>) -> Self {
Self {
data: RwLock::new(data),
version: AtomicU64::new(1),
wal,
active_txns: Mutex::new(Vec::new()),
next_txn_id: AtomicU64::new(1),
}
}
/// Read access (shared lock)
pub fn read(&self) -> parking_lot::RwLockReadGuard<'_, T> {
self.data.read()
}
/// Write access (exclusive lock)
pub fn write(&self) -> parking_lot::RwLockWriteGuard<'_, T> {
self.data.write()
}
/// Try read with timeout
pub fn try_read(&self, timeout: std::time::Duration) -> Option<parking_lot::RwLockReadGuard<'_, T>> {
self.data.try_read_for(timeout)
}
/// Try write with timeout
pub fn try_write(&self, timeout: std::time::Duration) -> Option<parking_lot::RwLockWriteGuard<'_, T>> {
self.data.try_write_for(timeout)
}
/// Begin transaction
pub fn begin_txn(&self) -> u64 {
let txn_id = self.next_txn_id.fetch_add(1, Ordering::SeqCst);
let read_version = Version::new(self.version.load(Ordering::Acquire));
let lsn = self.wal.append(WalOp::TxnBegin { txn_id });
let mut txn = Transaction::new(txn_id, read_version);
txn.wal_entries.push(lsn);
self.active_txns.lock().push(txn);
txn_id
}
/// Commit transaction
pub fn commit_txn(&self, txn_id: u64) -> bool {
let mut txns = self.active_txns.lock();
if let Some(pos) = txns.iter().position(|t| t.id == txn_id) {
let mut txn = txns.remove(pos);
if txn.state != TxnState::Active {
return false;
}
txn.state = TxnState::Committed;
self.wal.append(WalOp::TxnCommit { txn_id });
// Bump version
self.version.fetch_add(1, Ordering::Release);
true
} else {
false
}
}
/// Abort transaction
pub fn abort_txn(&self, txn_id: u64) -> bool {
let mut txns = self.active_txns.lock();
if let Some(pos) = txns.iter().position(|t| t.id == txn_id) {
let mut txn = txns.remove(pos);
if txn.state != TxnState::Active {
return false;
}
txn.state = TxnState::Aborted;
self.wal.append(WalOp::TxnAbort { txn_id });
// Rollback would happen here using txn.modified
true
} else {
false
}
}
/// Current version
pub fn version(&self) -> u64 {
self.version.load(Ordering::Acquire)
}
}
/// Thread-safe zero-copy manager with ACID guarantees
pub struct SafeArrowZeroCopy {
/// Inner manager with concurrent access
inner: ConcurrentAccess<ArrowZeroCopy>,
}
impl SafeArrowZeroCopy {
/// Create new thread-safe manager
pub fn new(wal: Arc<WriteAheadLog>) -> Self {
Self {
inner: ConcurrentAccess::new(ArrowZeroCopy::new(), wal),
}
}
/// Load fingerprints with transaction
pub fn load_with_txn(&self, txn_id: u64, data: Vec<u64>, num_fingerprints: usize) -> Option<usize> {
let mut guard = self.inner.write();
let buffer_id = guard.load_from_vec(data, num_fingerprints);
// Record in transaction
let mut txns = self.inner.active_txns.lock();
if let Some(txn) = txns.iter_mut().find(|t| t.id == txn_id) {
txn.modified.push(buffer_id as u32);
}
Some(buffer_id)
}
/// Read fingerprint (shared access)
pub fn get(&self, buffer_id: usize, index: usize) -> Option<[u64; FINGERPRINT_WORDS]> {
let guard = self.inner.read();
guard.get(buffer_id, index).copied()
}
/// Begin transaction
pub fn begin(&self) -> u64 {
self.inner.begin_txn()
}
/// Commit transaction
pub fn commit(&self, txn_id: u64) -> bool {
self.inner.commit_txn(txn_id)
}
/// Abort transaction
pub fn abort(&self, txn_id: u64) -> bool {
self.inner.abort_txn(txn_id)
}
/// Checkpoint (create safe recovery point)
pub fn checkpoint(&self) {
self.inner.wal.checkpoint();
}
/// Force WAL flush
pub fn flush_wal(&self) {
self.inner.wal.flush();
}
}
// =============================================================================
// TRANSPARENT WRITE-THROUGH FOR PREFIX 0x00 (LANCE)
// =============================================================================
/// Prefix constants (mirrored from bind_space for no-dependency)
pub const PREFIX_LANCE: u8 = 0x00;
pub const PREFIX_SURFACE_END: u8 = 0x0F;
/// Storage backend trait for transparent DTO integration
///
/// All query languages (Redis, SQL, Cypher, GQL, NARS) go through this trait.
/// The implementation decides where data actually lives:
/// - Hot: In-memory BindSpace array
/// - Warm: Lance mmap'd buffer
/// - Cold: Lance persistent storage
pub trait StorageBackend: Send + Sync {
/// Read fingerprint at address (prefix:slot)
fn read_fingerprint(&self, prefix: u8, slot: u8) -> Option<[u64; FINGERPRINT_WORDS]>;
/// Write fingerprint to address
fn write_fingerprint(&self, prefix: u8, slot: u8, fp: [u64; FINGERPRINT_WORDS]) -> bool;
/// Delete fingerprint at address
fn delete_fingerprint(&self, prefix: u8, slot: u8) -> bool;
/// Check if address is in Lance prefix (for routing)
fn is_lance_prefix(&self, prefix: u8) -> bool {
prefix == PREFIX_LANCE
}
/// Sync to persistent storage
fn sync(&self) -> bool;
/// Begin transaction
fn begin_transaction(&self) -> u64;
/// Commit transaction
fn commit_transaction(&self, txn_id: u64) -> bool;
/// Abort transaction
fn abort_transaction(&self, txn_id: u64) -> bool;
}
/// Transparent write-through adapter for Lance prefix
///
/// All writes to prefix 0x00 automatically persist to Lance storage.
/// All reads check the hot cache first, then fall through to Lance.
///
/// This achieves the "same control over storage access architecture"
/// without duplicating methods between BindSpace and LanceDB.
pub struct LanceWriteThrough {
/// The zero-copy Lance storage (warm/cold)
lance: SafeArrowZeroCopy,
/// Hot cache: recently accessed fingerprints
/// Key: (slot as u32), Value: fingerprint
hot_cache: RwLock<HashMap<u32, [u64; FINGERPRINT_WORDS]>>,
/// Dirty set: slots modified but not yet synced
dirty: Mutex<Vec<u32>>,
/// Configuration
config: WriteThroughConfig,
}
/// Configuration for write-through behavior
#[derive(Debug, Clone)]
pub struct WriteThroughConfig {
/// Maximum entries in hot cache before eviction
pub max_hot_entries: usize,
/// Sync to Lance after this many writes
pub sync_interval: usize,
/// Enable write-behind (async) instead of write-through (sync)
pub write_behind: bool,
}
impl Default for WriteThroughConfig {
fn default() -> Self {
Self {
max_hot_entries: 1024,
sync_interval: 100,
write_behind: false,
}
}
}
impl LanceWriteThrough {
/// Create new write-through adapter
pub fn new(wal: Arc<WriteAheadLog>, config: WriteThroughConfig) -> Self {
Self {
lance: SafeArrowZeroCopy::new(wal),
hot_cache: RwLock::new(HashMap::with_capacity(config.max_hot_entries)),
dirty: Mutex::new(Vec::new()),
config,
}
}
/// Create with default config
pub fn with_defaults(wal: Arc<WriteAheadLog>) -> Self {
Self::new(wal, WriteThroughConfig::default())
}
/// Read from hot cache or Lance
pub fn read(&self, slot: u8) -> Option<[u64; FINGERPRINT_WORDS]> {
let key = slot as u32;