infinite-db 0.1.3

A spatial-graph database using n-dimensional curves and hyperedges for engineering logic.
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
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
//! `InfiniteDb` — the top-level embedded database handle.
//!
//! This is the single entry point for embedded use. It owns:
//!   - A `BlockStore` (NVMe-aware file storage)
//!   - A `WalWriter` (crash-safe append log)
//!   - A `SpaceRegistry` (named dimension spaces)
//!   - A `BranchRegistry` (named branch heads)
//!   - A monotonic revision counter
//!
//! All writes go through the WAL before touching any block. On `open()`,
//! the WAL is replayed to recover any in-flight writes from a prior crash.
//!
//! # Example
//! ```no_run
//! use infinitedb::InfiniteDb;
//! use infinitedb::infinitedb_core::address::{DimensionVector, SpaceId};
//! use infinitedb::infinitedb_core::space::{SpaceConfig, SpaceRegistry};
//!
//! let mut db = InfiniteDb::open("./mydb").unwrap();
//! let space = SpaceId(1);
//! let point = DimensionVector::new(vec![128, 64]);
//! let data  = bincode::encode_to_vec(&42u32, bincode::config::standard()).unwrap();
//! db.insert(space, point, data).unwrap();
//! ```

use std::{
    collections::BTreeMap,
    io,
    path::{Path, PathBuf},
    sync::atomic::{AtomicU64, Ordering},
};
#[cfg(feature = "sync")]
use std::{
    sync::{Arc, Mutex},
    time::Duration,
};

use bincode::{config::standard, decode_from_slice, encode_to_vec};

use crate::infinitedb_core::{
    address::{Address, DimensionVector, RevisionId, SpaceId},
    block::{Block, BlockId, Record},
    branch::{Branch, BranchId, BranchRegistry},
    snapshot::{Snapshot, SnapshotId},
    space::{SpaceConfig, SpaceRegistry},
};
use crate::infinitedb_index::{
    composite::{CompositeKey, Dimension, KeyConfig},
};
use crate::infinitedb_storage::{
    nvme::{compute_checksum, BlockStore},
    wal::{WalEntry, WalWriter},
};
#[cfg(feature = "sync")]
use crate::infinitedb_sync::{
    outbox::{load_outbox, save_outbox, OutboxState, SyncReport},
    transport::{SyncOperation, SyncTransport},
    worker::BackgroundSyncWorker,
};

// ---------------------------------------------------------------------------
// InfiniteDb
// ---------------------------------------------------------------------------

/// The embedded database handle. Not `Send`/`Sync` — create one per thread
/// or wrap in a `Mutex` for multi-threaded access.
pub struct InfiniteDb {
    store: BlockStore,
    wal: WalWriter,
    spaces: SpaceRegistry,
    branches: BranchRegistry,
    /// In-memory write buffer: accumulated records not yet sealed into a block.
    buffer: Vec<Record>,
    /// Monotonic revision counter. Persisted via WAL checkpoints.
    revision: AtomicU64,
    /// Next block ID to assign.
    next_block_id: AtomicU64,
    /// Next snapshot ID to assign.
    next_snapshot_id: AtomicU64,
    /// Next branch ID to assign.
    next_branch_id: AtomicU64,
    /// Active snapshot per space (space_id → snapshot).
    snapshots: BTreeMap<u64, Snapshot>,
    /// Flush threshold: seal a block after this many buffered records.
    flush_threshold: usize,
    #[cfg(feature = "sync")]
    outbox_path: PathBuf,
    #[cfg(feature = "sync")]
    outbox_state: Arc<Mutex<OutboxState>>,
    #[cfg(feature = "sync")]
    sync_worker: Option<BackgroundSyncWorker>,
}

impl InfiniteDb {
    /// Open (or create) a database in `dir`. Replays the WAL on first open.
    pub fn open<P: AsRef<Path>>(dir: P) -> io::Result<Self> {
        let root = dir.as_ref().to_path_buf();
        let store = BlockStore::open(root.clone())?;
        let wal_path = store.wal_path();
        #[cfg(feature = "sync")]
        let outbox_path = root.join("meta").join("sync_outbox.bin");

        // Replay WAL to recover in-flight writes.
        let recovered = recover_wal(&wal_path)?;

        let wal = WalWriter::open(wal_path)?;

        // Load persisted metadata (spaces, branches, snapshots) if present.
        let (spaces, branches, snapshots, next_rev, next_block, next_snap) =
            load_meta(&store).unwrap_or_else(default_meta);

        let mut db = Self {
            store,
            wal,
            spaces,
            branches,
            buffer: Vec::new(),
            revision: AtomicU64::new(next_rev),
            next_block_id: AtomicU64::new(next_block),
            next_snapshot_id: AtomicU64::new(next_snap),
            next_branch_id: AtomicU64::new(2), // 1 is reserved for main
            snapshots,
            flush_threshold: 256,
            #[cfg(feature = "sync")]
            outbox_state: Arc::new(Mutex::new(load_outbox(&outbox_path)?)),
            #[cfg(feature = "sync")]
            outbox_path,
            #[cfg(feature = "sync")]
            sync_worker: None,
        };

        // Re-apply recovered WAL entries.
        for entry in recovered {
            db.apply_wal_entry(entry)?;
        }

        // Ensure a `main` branch exists.
        if db.branches.get_by_name("main").is_none() {
            let snap_id = db.alloc_snapshot_id();
            // No spaces yet — main branch starts with no snapshot content.
            let _ = db.branches.insert(Branch {
                id: BranchId(1),
                name: "main".to_string(),
                head: snap_id,
                parent: None,
                forked_at: RevisionId::ZERO,
            });
        }

        Ok(db)
    }

    // -----------------------------------------------------------------------
    // Space management
    // -----------------------------------------------------------------------

    /// Register a new space. Must be called before inserting records into it.
    pub fn register_space(&mut self, config: SpaceConfig) -> Result<(), String> {
        self.spaces.register(config).map_err(|e| format!("{:?}", e))?;
        self.persist_meta().map_err(|e| e.to_string())?;
        Ok(())
    }

    // -----------------------------------------------------------------------
    // Writes
    // -----------------------------------------------------------------------

    /// Insert or update a record. Appends a new revision to the WAL.
    /// The record is buffered in memory; call `flush()` to seal it into a block.
    pub fn insert(
        &mut self,
        space: SpaceId,
        point: DimensionVector,
        data: Vec<u8>,
    ) -> io::Result<RevisionId> {
        let rev = self.next_revision();
        let address = Address::new(space, point);
        let entry = WalEntry::Write {
            address: address.clone(),
            revision: rev,
            data: data.clone(),
        };
        self.wal.append(&entry)?;
        #[cfg(feature = "sync")]
        self.enqueue_sync(SyncOperation::Write {
            address: address.clone(),
            revision: rev,
            data: data.clone(),
        })?;
        self.buffer.push(Record {
            address,
            revision: rev,
            data,
            tombstone: false,
        });
        if self.buffer.len() >= self.flush_threshold {
            self.flush(space)?;
        }
        Ok(rev)
    }

    /// Logically delete a record at `point` in `space`.
    pub fn delete(&mut self, space: SpaceId, point: DimensionVector) -> io::Result<RevisionId> {
        let rev = self.next_revision();
        let address = Address::new(space, point);
        let entry = WalEntry::Tombstone {
            address: address.clone(),
            revision: rev,
        };
        self.wal.append(&entry)?;
        #[cfg(feature = "sync")]
        self.enqueue_sync(SyncOperation::Tombstone {
            address: address.clone(),
            revision: rev,
        })?;
        self.buffer.push(Record {
            address,
            revision: rev,
            data: vec![],
            tombstone: true,
        });
        Ok(rev)
    }

    /// Seal all buffered records for `space` into a new block on disk.
    pub fn flush(&mut self, space: SpaceId) -> io::Result<()> {
        if self.buffer.is_empty() {
            return Ok(());
        }

        // Partition: take only records for this space; keep the rest in the buffer.
        let mut remaining = Vec::new();
        let mut records: Vec<Record> = Vec::new();
        for record in self.buffer.drain(..) {
            if record.address.space == space {
                records.push(record);
            } else {
                remaining.push(record);
            }
        }
        self.buffer = remaining;

        if records.is_empty() {
            return Ok(());
        }

        // Sort by Hilbert key then revision.
        records.sort_by_key(|r| {
            let key = hilbert_key_for(&r.address.point);
            (key, r.revision.0)
        });

        let min_rev = records.iter().map(|r| r.revision).min().unwrap_or(RevisionId::ZERO);
        let max_rev = records.iter().map(|r| r.revision).max().unwrap_or(RevisionId::ZERO);
        let block_id = self.alloc_block_id();

        let mut block = Block {
            id: block_id,
            space,
            records,
            min_revision: min_rev,
            max_revision: max_rev,
            checksum: [0u8; 32],
        };
        block.checksum = compute_checksum(&block)?;

        // Write block to NVMe store.
        self.store.write_block(&block)?;

        // Record block seal in WAL.
        let snap_id = self.alloc_snapshot_id();
        self.wal.append(&WalEntry::BlockSealed {
            block_id,
            space,
            snapshot: snap_id,
        })?;

        // Advance the space's active snapshot.
        let snapshot = self.snapshots.entry(space.0).or_insert_with(|| {
            Snapshot::root(snap_id, space)
        });
        let hilbert_min = block
            .records
            .first()
            .map(|r| hilbert_key_for(&r.address.point))
            .unwrap_or(0);
        snapshot.blocks.insert(hilbert_min, block_id);
        snapshot.revision = max_rev;

        self.persist_meta()?;
        Ok(())
    }

    // -----------------------------------------------------------------------
    // Reads
    // -----------------------------------------------------------------------

    /// Return the current snapshot ID for `space`.
    pub fn current_snapshot(&self, space: SpaceId) -> Option<SnapshotId> {
        self.snapshots.get(&space.0).map(|s| s.id)
    }

    /// Scan all live records in `space`, optionally capped at `as_of`.
    /// Full-space scan — no spatial filtering. Use `query_bbox` to filter by coordinates.
    pub fn query(
        &mut self,
        space: SpaceId,
        as_of: Option<RevisionId>,
    ) -> io::Result<Vec<Record>> {
        self.query_inner(space, None, as_of)
    }

    /// Bounding-box query in N dimensions.
    ///
    /// Returns every live record in `space` whose point satisfies
    /// `min[i] <= point[i] <= max[i]` on **every** axis simultaneously.
    ///
    /// Works correctly for any dimensionality (1–16 dims). A Hilbert-key
    /// interval is used to prune candidate blocks at the block level; an
    /// exact `within()` check per record eliminates any false positives caused
    /// by the Hilbert curve mapping a bounding box to many disjoint intervals.
    ///
    /// `min` and `max` must have the same number of coordinates as the points
    /// stored in the space.
    pub fn query_bbox(
        &mut self,
        space: SpaceId,
        min: DimensionVector,
        max: DimensionVector,
        as_of: Option<RevisionId>,
    ) -> io::Result<Vec<Record>> {
        assert_eq!(min.dims(), max.dims(), "min and max must have equal dimensions");
        // Compute Hilbert keys for both bounding corners and use the interval
        // as a block-level pre-filter (over-approximation — false positives OK).
        let k_min = hilbert_key_for(&min);
        let k_max = hilbert_key_for(&max);
        let (lo, hi) = if k_min <= k_max { (k_min, k_max) } else { (k_max, k_min) };
        let mut results = self.query_inner(space, Some((lo, hi)), as_of)?;
        // Exact per-record coordinate filter removes all Hilbert false positives.
        results.retain(|r| r.address.point.within(&min, &max));
        Ok(results)
    }

    /// Sub-space query: pins the first `parent_coords.len()` dimensions to exact
    /// values and leaves the remaining inner dimensions fully open (0..u32::MAX).
    ///
    /// This is the idiomatic way to retrieve all property records for a specific
    /// parent element in the nested Hilbert design:
    /// ```ignore
    /// // All load properties of element 42:
    /// db.query_subscope(SPACE_LOADS, &[42], None);
    /// ```
    pub fn query_subscope(
        &mut self,
        space: SpaceId,
        parent_coords: &[u32],
        as_of: Option<RevisionId>,
    ) -> io::Result<Vec<Record>> {
        // We need to know the total dims for this space to build the full vectors.
        let dims = self.spaces.get(space)
            .map(|c| c.dims)
            .unwrap_or(parent_coords.len() + 1);
        assert!(
            parent_coords.len() <= dims,
            "parent_coords has more dimensions than the space"
        );
        let inner_dims = dims - parent_coords.len();
        let mut min_coords: Vec<u32> = parent_coords.to_vec();
        let mut max_coords: Vec<u32> = parent_coords.to_vec();
        min_coords.extend(std::iter::repeat(0).take(inner_dims));
        max_coords.extend(std::iter::repeat(u32::MAX).take(inner_dims));
        self.query_bbox(
            space,
            DimensionVector::new(min_coords),
            DimensionVector::new(max_coords),
            as_of,
        )
    }

    // Shared core: reads from sealed blocks + the in-memory write buffer.
    fn query_inner(
        &mut self,
        space: SpaceId,
        key_range: Option<(u128, u128)>,
        as_of: Option<RevisionId>,
    ) -> io::Result<Vec<Record>> {
        let rev_ceiling = as_of.unwrap_or_else(|| {
            RevisionId(self.revision.load(Ordering::Relaxed))
        });

        let mut results: Vec<Record> = Vec::new();

        // Query sealed blocks if a snapshot exists.
        if let Some(snapshot) = self.snapshots.get(&space.0) {
            let block_ids: Vec<BlockId> = match key_range {
                None => snapshot.blocks.values().copied().collect(),
                Some((_, hi)) => {
                    // The snapshot map is keyed by the Hilbert key of each
                    // block's first record. Include all blocks with a start key
                    // <= hi; the within() filter handles exactness.
                    snapshot.blocks.range(..=hi).map(|(_, id)| *id).collect()
                }
            };
            for block_id in block_ids {
                let block = self.store.read_block(block_id)?;
                for record in block.records {
                    if record.revision <= rev_ceiling && !record.tombstone {
                        results.push(record);
                    }
                }
            }
        }

        // Always check the in-memory buffer (records not yet flushed to disk).
        // Collect tombstoned coordinates first so we can suppress stale sealed records.
        let tombstoned: std::collections::HashSet<_> = self
            .buffer
            .iter()
            .filter(|r| r.address.space == space && r.tombstone && r.revision <= rev_ceiling)
            .map(|r| r.address.point.coords.clone())
            .collect();

        results.retain(|r| !tombstoned.contains(&r.address.point.coords));

        for record in &self.buffer {
            if record.address.space == space
                && record.revision <= rev_ceiling
                && !record.tombstone
                && !tombstoned.contains(&record.address.point.coords)
            {
                if let Some((lo, hi)) = key_range {
                    let k = hilbert_key_for(&record.address.point);
                    if k < lo || k > hi {
                        continue;
                    }
                }
                results.push(record.clone());
            }
        }

        Ok(results)
    }

    // -----------------------------------------------------------------------
    // Branch management
    // -----------------------------------------------------------------------

    /// Create a new branch forked from an existing one at the current revision.
    pub fn create_branch(
        &mut self,
        name: impl Into<String>,
        from: BranchId,
    ) -> Result<BranchId, String> {
        let parent = self.branches.get(from).ok_or("Branch not found")?;
        let new_id = BranchId(self.next_branch_id.fetch_add(1, Ordering::Relaxed));
        let rev = RevisionId(self.revision.load(Ordering::Relaxed));
        let branch = Branch {
            id: new_id,
            name: name.into(),
            head: parent.head,
            parent: Some(from),
            forked_at: rev,
        };
        self.branches.insert(branch).map_err(|e| format!("{:?}", e))?;
        Ok(new_id)
    }

    // -----------------------------------------------------------------------
    // Diagnostics
    // -----------------------------------------------------------------------

    /// Returns a snapshot of current memory and cache usage.
    pub fn memory_stats(&self) -> MemoryStats {
        let buffer_records = self.buffer.len();
        let buffer_bytes: usize = self.buffer.iter()
            .map(|r| 48 + r.data.len())
            .sum();
        let (cache_bytes, cache_blocks) = self.store.cache_stats();
        let snapshot_entries: usize = self.snapshots.values()
            .map(|s| s.blocks.len())
            .sum();
        MemoryStats {
            buffer_records,
            buffer_bytes,
            cache_bytes,
            cache_blocks,
            snapshot_index_entries: snapshot_entries,
            total_revision: self.revision.load(Ordering::Relaxed),
            sealed_blocks: self.next_block_id.load(Ordering::Relaxed),
        }
    }

    // -----------------------------------------------------------------------
    // Replication sync (offline-first)
    // -----------------------------------------------------------------------

    /// Run one immediate sync pass against the provided transport.
    #[cfg(feature = "sync")]
    pub fn sync_now(
        &mut self,
        transport: &dyn SyncTransport,
        max_batch: usize,
    ) -> io::Result<SyncReport> {
        let mut state = self
            .outbox_state
            .lock()
            .map_err(|_| io::Error::new(io::ErrorKind::Other, "sync outbox lock poisoned"))?;
        let report = state.process_once(transport, max_batch);
        if report.attempted > 0 {
            save_outbox(&self.outbox_path, &state)?;
        }
        Ok(report)
    }

    /// Start a background worker that retries queued outbox writes.
    #[cfg(feature = "sync")]
    pub fn start_background_sync(
        &mut self,
        transport: Arc<dyn SyncTransport>,
        interval: Duration,
        batch_size: usize,
    ) -> io::Result<()> {
        self.stop_background_sync();
        let worker = BackgroundSyncWorker::start(
            Arc::clone(&self.outbox_state),
            self.outbox_path.clone(),
            transport,
            interval,
            batch_size,
        )?;
        self.sync_worker = Some(worker);
        Ok(())
    }

    /// Stop the running background sync worker (if any).
    #[cfg(feature = "sync")]
    pub fn stop_background_sync(&mut self) {
        if let Some(mut worker) = self.sync_worker.take() {
            worker.stop();
        }
    }

    /// Current number of queued operations waiting to sync.
    #[cfg(feature = "sync")]
    pub fn sync_pending_count(&self) -> usize {
        self.outbox_state
            .lock()
            .map(|s| s.pending_count())
            .unwrap_or(0)
    }

    /// Last successful outbox sync timestamp (epoch ms).
    #[cfg(feature = "sync")]
    pub fn last_successful_sync_at_ms(&self) -> Option<u64> {
        self.outbox_state
            .lock()
            .ok()
            .and_then(|s| s.last_success_at_ms)
    }

    /// Last sync error seen by the outbox processor.
    #[cfg(feature = "sync")]
    pub fn last_sync_error(&self) -> Option<String> {
        self.outbox_state
            .lock()
            .ok()
            .and_then(|s| s.last_error.clone())
    }

    // -----------------------------------------------------------------------
    // Internal helpers
    // -----------------------------------------------------------------------

    fn next_revision(&self) -> RevisionId {
        RevisionId(self.revision.fetch_add(1, Ordering::Relaxed) + 1)
    }

    fn alloc_block_id(&self) -> BlockId {
        BlockId(self.next_block_id.fetch_add(1, Ordering::Relaxed))
    }

    fn alloc_snapshot_id(&self) -> SnapshotId {
        SnapshotId(self.next_snapshot_id.fetch_add(1, Ordering::Relaxed))
    }

    fn apply_wal_entry(&mut self, entry: WalEntry) -> io::Result<()> {
        match entry {
            WalEntry::Write { address, revision, data } => {
                self.buffer.push(Record { address, revision, data, tombstone: false });
            }
            WalEntry::Tombstone { address, revision } => {
                self.buffer.push(Record { address, revision, data: vec![], tombstone: true });
            }
            WalEntry::BlockSealed { .. } | WalEntry::Checkpoint { .. } => {}
        }
        Ok(())
    }

    fn persist_meta(&mut self) -> io::Result<()> {
        // Persist spaces registry.
        let spaces_bytes = encode_to_vec(&self.spaces, standard())
            .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
        self.store.write_meta("spaces.bin", &spaces_bytes)?;

        // Persist revision counters as a simple [u64; 3].
        let counters: [u64; 3] = [
            self.revision.load(Ordering::Relaxed),
            self.next_block_id.load(Ordering::Relaxed),
            self.next_snapshot_id.load(Ordering::Relaxed),
        ];
        let counters_bytes = encode_to_vec(&counters, standard())
            .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
        self.store.write_meta("counters.bin", &counters_bytes)?;

        Ok(())
    }

    #[cfg(feature = "sync")]
    fn enqueue_sync(&mut self, op: SyncOperation) -> io::Result<()> {
        let mut state = self
            .outbox_state
            .lock()
            .map_err(|_| io::Error::new(io::ErrorKind::Other, "sync outbox lock poisoned"))?;
        state.enqueue(op);
        save_outbox(&self.outbox_path, &state)
    }
}

#[cfg(feature = "sync")]
impl Drop for InfiniteDb {
    fn drop(&mut self) {
        self.stop_background_sync();
    }
}

// ---------------------------------------------------------------------------
// WAL recovery
// ---------------------------------------------------------------------------

fn recover_wal(wal_path: &PathBuf) -> io::Result<Vec<WalEntry>> {
    if !wal_path.exists() {
        return Ok(vec![]);
    }
    let mut reader = crate::infinitedb_storage::wal::WalReader::open(wal_path.clone())?;
    reader.entries()
}

// ---------------------------------------------------------------------------
// MemoryStats
// ---------------------------------------------------------------------------

/// Point-in-time snapshot of database memory and cache usage.
#[derive(Debug, Clone)]
pub struct MemoryStats {
    /// Records currently in the in-memory write buffer (not yet flushed).
    pub buffer_records: usize,
    /// Approximate bytes occupied by the write buffer.
    pub buffer_bytes: usize,
    /// Bytes currently resident in the LRU block cache.
    pub cache_bytes: usize,
    /// Number of blocks held in the LRU block cache.
    pub cache_blocks: usize,
    /// Total Hilbert index entries across all active snapshots.
    pub snapshot_index_entries: usize,
    /// Highest revision number issued so far.
    pub total_revision: u64,
    /// Total sealed blocks written (cumulative, not current on-disk count).
    pub sealed_blocks: u64,
}

impl MemoryStats {
    /// Estimated total process-level RAM attributed to the database.
    pub fn total_ram_bytes(&self) -> usize {
        self.buffer_bytes
            + self.cache_bytes
            // Snapshot index: each entry is approx (u128 key + u64 id) = 24 bytes.
            + self.snapshot_index_entries * 24
            // Fixed overhead: registries, atomics, BTreeMap nodes.
            + 4096
    }

    /// Pretty-print the current memory statistics to stdout.
    pub fn print(&self) {
        println!("\n╔═══ InfiniteDb Memory Stats ═══╗");
        println!("║  Write buffer       {:>6} records  ({} bytes)",
            self.buffer_records, fmt_bytes(self.buffer_bytes));
        println!("║  LRU block cache    {:>6} blocks   ({} bytes / 10 MB limit)",
            self.cache_blocks, fmt_bytes(self.cache_bytes));
        println!("║  Snapshot index     {:>6} entries", self.snapshot_index_entries);
        println!("║  Total revisions    {:>6}", self.total_revision);
        println!("║  Sealed blocks      {:>6}", self.sealed_blocks);
        println!("║  ──────────────────────────────────────────────");
        println!("║  Est. total RAM     {}", fmt_bytes(self.total_ram_bytes()));
        println!("╚════════════════════════════════");
    }
}

fn fmt_bytes(b: usize) -> String {
    if b < 1024 { format!("{} B", b) }
    else if b < 1024 * 1024 { format!("{:.1} KB", b as f64 / 1024.0) }
    else { format!("{:.2} MB", b as f64 / (1024.0 * 1024.0)) }
}

// ---------------------------------------------------------------------------
// Metadata persistence helpers
// ---------------------------------------------------------------------------

/// Load persisted metadata from the block store.
/// Returns defaults when no metadata exists yet.
#[allow(clippy::type_complexity)]
fn load_meta(
    store: &BlockStore,
) -> Option<(SpaceRegistry, BranchRegistry, BTreeMap<u64, Snapshot>, u64, u64, u64)> {
    let counters_bytes = store.read_meta("counters.bin").ok()?;
    let (counters, _): ([u64; 3], _) = decode_from_slice(&counters_bytes, standard()).ok()?;
    let spaces_bytes = store.read_meta("spaces.bin").ok()?;
    let (spaces, _): (SpaceRegistry, _) = decode_from_slice(&spaces_bytes, standard()).ok()?;
    Some((
        spaces,
        BranchRegistry::new(),
        BTreeMap::new(),
        counters[0],
        counters[1],
        counters[2],
    ))
}

/// Default state for a fresh database.
type MetaTuple = (SpaceRegistry, BranchRegistry, BTreeMap<u64, Snapshot>, u64, u64, u64);

fn default_meta() -> MetaTuple {
    (SpaceRegistry::new(), BranchRegistry::new(), BTreeMap::new(), 0, 1, 1)
}

/// Compute the Hilbert key for a point using STANDARD 8-bit precision.
/// All dimensions in the point are encoded.
fn hilbert_key_for(point: &DimensionVector) -> u128 {
    if point.coords.is_empty() {
        return 0;
    }
    let mut key = CompositeKey::new(KeyConfig::STANDARD);
    for &c in &point.coords {
        key = key.push(Dimension::new("_", c));
    }
    key.encode()
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;
    use crate::infinitedb_core::address::{DimensionVector, SpaceId};
    use crate::infinitedb_core::branch::BranchId;
    #[cfg(feature = "sync")]
    use std::sync::Arc;
    #[cfg(feature = "sync")]
    use crate::infinitedb_sync::transport::{SyncEnvelope, SyncResult, SyncTransport};

    fn open_tmp() -> (InfiniteDb, TempDir) {
        let dir = TempDir::new().unwrap();
        let db = InfiniteDb::open(dir.path()).unwrap();
        (db, dir)
    }

    #[test]
    fn insert_and_query_unflushed() {
        let (mut db, _dir) = open_tmp();
        let space = SpaceId(1);
        db.insert(space, DimensionVector::new(vec![10, 20]), vec![1, 2, 3]).unwrap();
        let results = db.query(space, None).unwrap();
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn insert_flush_query() {
        let (mut db, _dir) = open_tmp();
        let space = SpaceId(1);
        db.insert(space, DimensionVector::new(vec![5, 5]), vec![42]).unwrap();
        db.flush(space).unwrap();
        let results = db.query(space, None).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].data, vec![42]);
    }

    #[test]
    fn delete_tombstones_record() {
        let (mut db, _dir) = open_tmp();
        let space = SpaceId(1);
        let point = DimensionVector::new(vec![1, 1]);
        db.insert(space, point.clone(), vec![99]).unwrap();
        db.delete(space, point).unwrap();
        let results = db.query(space, None).unwrap();
        // Tombstone suppresses the record in live queries.
        assert!(results.iter().all(|r| !r.tombstone));
    }

    #[test]
    fn as_of_returns_historical_state() {
        let (mut db, _dir) = open_tmp();
        let space = SpaceId(1);
        let rev1 = db.insert(space, DimensionVector::new(vec![1, 0]), vec![1]).unwrap();
        let _rev2 = db.insert(space, DimensionVector::new(vec![2, 0]), vec![2]).unwrap();
        // Query at rev1 should see only the first record.
        let results = db.query(space, Some(rev1)).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].data, vec![1]);
    }

    #[test]
    fn create_branch_succeeds() {
        let (mut db, _dir) = open_tmp();
        let main = BranchId(1);
        let feature = db.create_branch("feature", main).unwrap();
        assert_ne!(feature, main);
    }

    #[cfg(feature = "sync")]
    struct AckTransport;
    #[cfg(feature = "sync")]
    impl SyncTransport for AckTransport {
        fn push_batch(&self, batch: &[SyncEnvelope]) -> Result<Vec<SyncResult>, String> {
            Ok(batch
                .iter()
                .map(|item| SyncResult::Ack { op_id: item.op_id })
                .collect())
        }
    }

    #[cfg(feature = "sync")]
    struct FlakyTransport;
    #[cfg(feature = "sync")]
    impl SyncTransport for FlakyTransport {
        fn push_batch(&self, batch: &[SyncEnvelope]) -> Result<Vec<SyncResult>, String> {
            Ok(batch
                .iter()
                .map(|item| SyncResult::Retry {
                    op_id: item.op_id,
                    error: "offline".to_string(),
                })
                .collect())
        }
    }

    #[cfg(feature = "sync")]
    struct StaleConflictTransport;
    #[cfg(feature = "sync")]
    impl SyncTransport for StaleConflictTransport {
        fn push_batch(&self, batch: &[SyncEnvelope]) -> Result<Vec<SyncResult>, String> {
            Ok(batch
                .iter()
                .map(|item| SyncResult::ConflictStale {
                    op_id: item.op_id,
                    reason: "stale write".to_string(),
                })
                .collect())
        }
    }

    #[cfg(feature = "sync")]
    #[test]
    fn outbox_survives_restart() {
        let dir = TempDir::new().unwrap();
        let space = SpaceId(1);
        {
            let mut db = InfiniteDb::open(dir.path()).unwrap();
            db.insert(space, DimensionVector::new(vec![1, 2]), vec![3]).unwrap();
            assert_eq!(db.sync_pending_count(), 1);
        }
        let db = InfiniteDb::open(dir.path()).unwrap();
        assert_eq!(db.sync_pending_count(), 1);
    }

    #[cfg(feature = "sync")]
    #[test]
    fn offline_queue_then_manual_sync_drains() {
        let (mut db, _dir) = open_tmp();
        let space = SpaceId(1);
        db.insert(space, DimensionVector::new(vec![10, 10]), vec![7]).unwrap();
        let retry_report = db.sync_now(&FlakyTransport, 32).unwrap();
        assert_eq!(retry_report.retried, 1);
        assert_eq!(db.sync_pending_count(), 1);
        std::thread::sleep(Duration::from_millis(2100));
        let ack_report = db.sync_now(&AckTransport, 32).unwrap();
        assert_eq!(ack_report.acked, 1);
        assert_eq!(db.sync_pending_count(), 0);
    }

    #[cfg(feature = "sync")]
    #[test]
    fn stale_conflict_is_dropped_under_lww() {
        let (mut db, _dir) = open_tmp();
        let space = SpaceId(1);
        db.insert(space, DimensionVector::new(vec![11, 11]), vec![8]).unwrap();
        let report = db.sync_now(&StaleConflictTransport, 32).unwrap();
        assert_eq!(report.dropped_stale, 1);
        assert_eq!(db.sync_pending_count(), 0);
    }

    #[cfg(feature = "sync")]
    #[test]
    fn background_worker_retries_and_acks() {
        let (mut db, _dir) = open_tmp();
        let space = SpaceId(1);
        db.insert(space, DimensionVector::new(vec![20, 20]), vec![1]).unwrap();
        db.start_background_sync(
            Arc::new(AckTransport),
            Duration::from_millis(20),
            16,
        )
        .unwrap();
        std::thread::sleep(Duration::from_millis(120));
        db.stop_background_sync();
        assert_eq!(db.sync_pending_count(), 0);
    }
}