kitedb 0.2.18

High-performance embedded graph database
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
//! Transaction management for SingleFileDB
//!
//! Handles begin, commit, and rollback operations.

use crate::core::wal::record::{
  build_begin_payload, build_commit_payload, build_rollback_payload, WalRecord,
};
use crate::error::{KiteError, Result};
use crate::replication::primary::PrimaryReplicationStatus;
use crate::replication::types::CommitToken;
use crate::types::*;
use parking_lot::Mutex;
use std::marker::PhantomData;
use std::rc::Rc;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::time::Duration;
#[cfg(feature = "bench-profile")]
use std::time::Instant;

use super::open::SyncMode;
use super::{SingleFileDB, SingleFileTxState};

/// RAII transaction guard for SingleFileDB.
/// Rolls back the transaction on drop unless committed or rolled back.
pub struct SingleFileTxGuard<'db> {
  db: &'db SingleFileDB,
  txid: TxId,
  active: bool,
  _nosend: PhantomData<Rc<()>>,
}

impl<'db> SingleFileTxGuard<'db> {
  fn new(db: &'db SingleFileDB, txid: TxId) -> Self {
    Self {
      db,
      txid,
      active: true,
      _nosend: PhantomData,
    }
  }

  pub fn txid(&self) -> TxId {
    self.txid
  }

  pub fn commit(mut self) -> Result<()> {
    self.active = false;
    self.db.commit()
  }

  pub fn rollback(mut self) -> Result<()> {
    self.active = false;
    self.db.rollback()
  }
}

impl Drop for SingleFileTxGuard<'_> {
  fn drop(&mut self) {
    if !self.active {
      return;
    }
    self.active = false;
    if self.db.current_txid() != Some(self.txid) {
      return;
    }
    let _ = self.db.rollback();
  }
}

impl SingleFileDB {
  fn begin_with_mode(&self, read_only: bool, bulk_load: bool) -> Result<TxId> {
    if self.read_only && !read_only {
      return Err(KiteError::ReadOnly);
    }
    if bulk_load && read_only {
      return Err(KiteError::ReadOnly);
    }
    if bulk_load && self.mvcc.is_some() {
      return Err(KiteError::Internal(
        "bulk load requires MVCC disabled".to_string(),
      ));
    }

    let tid = std::thread::current().id();
    {
      let current_tx = self.current_tx.lock();
      if current_tx.contains_key(&tid) {
        return Err(KiteError::TransactionInProgress);
      }
    }

    let (txid, snapshot_ts) = if let Some(mvcc) = self.mvcc.as_ref() {
      let (txid, snapshot_ts) = {
        let mut tx_mgr = mvcc.tx_manager.lock();
        tx_mgr.begin_tx()
      };
      self
        .next_tx_id
        .store(txid.saturating_add(1), std::sync::atomic::Ordering::SeqCst);
      (txid, snapshot_ts)
    } else {
      (self.alloc_tx_id(), 0)
    };

    // Write BEGIN record to WAL (for write transactions)
    if !read_only && !bulk_load {
      let record = WalRecord::new(WalRecordType::Begin, txid, build_begin_payload());
      let mut pager = self.pager.lock();
      let mut wal = self.wal_buffer.lock();
      wal.write_record(&record, &mut pager)?;
    }

    let tx_state = Arc::new(Mutex::new(SingleFileTxState::new(
      txid,
      read_only,
      snapshot_ts,
      bulk_load,
    )));

    self.current_tx.lock().insert(tid, tx_state);
    if !read_only {
      self.active_writers.fetch_add(1, Ordering::SeqCst);
    }
    Ok(txid)
  }

  pub(crate) fn current_tx_handle(&self) -> Option<Arc<Mutex<SingleFileTxState>>> {
    let tid = std::thread::current().id();
    let current_tx = self.current_tx.lock();
    current_tx.get(&tid).cloned()
  }

  pub(crate) fn require_write_tx_handle(&self) -> Result<(TxId, Arc<Mutex<SingleFileTxState>>)> {
    let handle = self.current_tx_handle().ok_or(KiteError::NoTransaction)?;
    let txid = {
      let tx = handle.lock();
      if tx.read_only {
        return Err(KiteError::ReadOnly);
      }
      tx.txid
    };
    Ok((txid, handle))
  }

  /// Begin a new transaction
  pub fn begin(&self, read_only: bool) -> Result<TxId> {
    self.begin_with_mode(read_only, false)
  }

  /// Begin a new transaction guard (rolls back on drop)
  pub fn begin_guard(&self, read_only: bool) -> Result<SingleFileTxGuard<'_>> {
    let txid = self.begin_with_mode(read_only, false)?;
    Ok(SingleFileTxGuard::new(self, txid))
  }

  /// Begin a bulk-load transaction (fast path, MVCC disabled)
  pub fn begin_bulk(&self) -> Result<TxId> {
    self.begin_with_mode(false, true)
  }

  /// Begin a bulk-load transaction guard (rolls back on drop)
  pub fn begin_bulk_guard(&self) -> Result<SingleFileTxGuard<'_>> {
    let txid = self.begin_with_mode(false, true)?;
    Ok(SingleFileTxGuard::new(self, txid))
  }

  fn apply_mvcc_commit(
    &self,
    commit_ts_for_mvcc: Option<(u64, bool)>,
    txid: TxId,
    pending: &DeltaState,
    delta: &DeltaState,
  ) {
    let Some((commit_ts, has_active_readers)) = commit_ts_for_mvcc else {
      return;
    };
    let Some(mvcc) = self.mvcc.as_ref() else {
      return;
    };
    if !has_active_readers {
      return;
    }

    let snapshot = self.snapshot.read();
    let mut vc = mvcc.version_chain.lock();

    for (&node_id, node_delta) in &pending.created_nodes {
      vc.append_node_version(
        node_id,
        NodeVersionData {
          node_id,
          delta: node_delta.for_version(),
        },
        txid,
        commit_ts,
      );
    }

    for &node_id in &pending.deleted_nodes {
      vc.delete_node_version(node_id, txid, commit_ts);
    }

    for (&src, patches) in &pending.out_add {
      for patch in patches {
        vc.append_edge_version(src, patch.etype, patch.other, true, txid, commit_ts);
      }
    }

    for (&src, patches) in &pending.out_del {
      for patch in patches {
        vc.append_edge_version(src, patch.etype, patch.other, false, txid, commit_ts);
      }
    }

    let old_node_prop = |node_id: NodeId, key_id: PropKeyId| -> Option<PropValue> {
      if delta.is_node_deleted(node_id) {
        return None;
      }
      if let Some(value_opt) = delta.node_prop(node_id, key_id) {
        return value_opt.cloned();
      }
      if let Some(ref snap) = *snapshot {
        if let Some(phys) = snap.phys_node(node_id) {
          return snap.node_prop(phys, key_id);
        }
      }
      None
    };

    let old_edge_prop = |src: NodeId, etype: ETypeId, dst: NodeId, key_id: PropKeyId| {
      if delta.is_node_deleted(src) || delta.is_node_deleted(dst) {
        return None;
      }
      if delta.is_edge_deleted(src, etype, dst) {
        return None;
      }
      if let Some(value_opt) = delta.edge_prop(src, etype, dst, key_id) {
        return value_opt.cloned();
      }
      if let Some(ref snap) = *snapshot {
        if let (Some(src_phys), Some(dst_phys)) = (snap.phys_node(src), snap.phys_node(dst)) {
          if let Some(edge_idx) = snap.find_edge_index(src_phys, etype, dst_phys) {
            if let Some(snapshot_props) = snap.edge_props(edge_idx) {
              return snapshot_props.get(&key_id).cloned();
            }
          }
        }
      }
      None
    };

    let old_node_label = |node_id: NodeId, label_id: LabelId| -> bool {
      if delta.is_node_deleted(node_id) {
        return false;
      }
      if let Some(node_delta) = delta.node_delta(node_id) {
        if node_delta
          .labels_deleted
          .as_ref()
          .is_some_and(|labels| labels.contains(&label_id))
        {
          return false;
        }
        if node_delta
          .labels
          .as_ref()
          .is_some_and(|labels| labels.contains(&label_id))
        {
          return true;
        }
      }
      if let Some(ref snap) = *snapshot {
        if let Some(phys) = snap.phys_node(node_id) {
          if let Some(labels) = snap.node_labels(phys) {
            return labels.contains(&label_id);
          }
        }
      }
      false
    };

    for (node_id, node_delta) in pending
      .created_nodes
      .iter()
      .chain(pending.modified_nodes.iter())
    {
      if pending.deleted_nodes.contains(node_id) {
        continue;
      }

      if let Some(after_map) = node_delta.props.as_ref() {
        for (key_id, after_value) in after_map {
          let mut before_value = old_node_prop(*node_id, *key_id);
          if before_value.as_ref() == after_value.as_deref() {
            continue;
          }
          if vc.node_prop_version(*node_id, *key_id).is_none() {
            let before_shared = before_value.take().map(std::sync::Arc::new);
            vc.append_node_prop_version(*node_id, *key_id, before_shared, 0, 0);
          }
          vc.append_node_prop_version(*node_id, *key_id, after_value.clone(), txid, commit_ts);
        }
      }

      if let Some(added_labels) = node_delta.labels.as_ref() {
        for label_id in added_labels {
          let before_value = old_node_label(*node_id, *label_id);
          if before_value {
            continue;
          }
          if vc.node_label_version(*node_id, *label_id).is_none() {
            vc.append_node_label_version(
              *node_id,
              *label_id,
              if before_value { Some(true) } else { None },
              0,
              0,
            );
          }
          vc.append_node_label_version(*node_id, *label_id, Some(true), txid, commit_ts);
        }
      }

      if let Some(removed_labels) = node_delta.labels_deleted.as_ref() {
        for label_id in removed_labels {
          let before_value = old_node_label(*node_id, *label_id);
          if !before_value {
            continue;
          }
          if vc.node_label_version(*node_id, *label_id).is_none() {
            vc.append_node_label_version(
              *node_id,
              *label_id,
              if before_value { Some(true) } else { None },
              0,
              0,
            );
          }
          vc.append_node_label_version(*node_id, *label_id, None, txid, commit_ts);
        }
      }
    }

    for (edge_key, after_props) in &pending.edge_props {
      for (key_id, after_value) in after_props {
        let (src, etype, dst) = *edge_key;
        let mut before_value = old_edge_prop(src, etype, dst, *key_id);
        if before_value.as_ref() == after_value.as_deref() {
          continue;
        }
        if vc.edge_prop_version(src, etype, dst, *key_id).is_none() {
          let before_shared = before_value.take().map(std::sync::Arc::new);
          vc.append_edge_prop_version(src, etype, dst, *key_id, before_shared, 0, 0);
        }
        vc.append_edge_prop_version(
          src,
          etype,
          dst,
          *key_id,
          after_value.clone(),
          txid,
          commit_ts,
        );
      }
    }
  }

  /// Commit the current transaction
  pub fn commit(&self) -> Result<()> {
    self.commit_with_token().map(|_| ())
  }

  /// Commit the current transaction and return replication commit token if enabled.
  pub fn commit_with_token(&self) -> Result<Option<CommitToken>> {
    let tx_handle = {
      let tid = std::thread::current().id();
      let mut current_tx = self.current_tx.lock();
      current_tx.remove(&tid).ok_or(KiteError::NoTransaction)?
    };

    let (txid, read_only, bulk_load, pending, pending_wal) = {
      let mut tx = tx_handle.lock();
      let pending = std::mem::take(&mut tx.pending);
      let pending_wal = std::mem::take(&mut tx.pending_wal);
      (tx.txid, tx.read_only, tx.bulk_load, pending, pending_wal)
    };

    if read_only {
      // Read-only transactions don't need WAL
      if let Some(mvcc) = self.mvcc.as_ref() {
        let mut tx_mgr = mvcc.tx_manager.lock();
        tx_mgr.abort_tx(txid);
      }
      return Ok(None);
    }
    let prev_writers = self.active_writers.fetch_sub(1, Ordering::SeqCst);
    debug_assert!(prev_writers > 0, "active_writers underflow in commit");

    let mut commit_ts_for_mvcc = None;
    if let Some(mvcc) = self.mvcc.as_ref() {
      let mut tx_mgr = mvcc.tx_manager.lock();
      if let Err(err) = mvcc.conflict_detector.validate_commit(&tx_mgr, txid) {
        tx_mgr.abort_tx(txid);
        return Err(KiteError::Conflict {
          txid: err.txid,
          keys: err.conflicting_keys,
        });
      }

      let commit_ts = tx_mgr
        .commit_tx(txid)
        .map_err(|e| KiteError::Internal(e.to_string()))?;
      commit_ts_for_mvcc = Some((commit_ts, tx_mgr.active_count() > 0));
    }

    let replication_enabled = self.primary_replication.is_some();
    let group_commit_active =
      self.group_commit_enabled && self.sync_mode == SyncMode::Normal && !replication_enabled;
    let mut group_commit_seq = 0u64;
    let mut commit_token = None;

    {
      // Serialize commit to preserve WAL ordering without holding the delta lock during I/O.
      #[cfg(feature = "bench-profile")]
      let commit_lock_start = Instant::now();
      let _commit_guard = self.commit_lock.lock();
      #[cfg(feature = "bench-profile")]
      self.commit_lock_wait_ns.fetch_add(
        commit_lock_start.elapsed().as_nanos() as u64,
        Ordering::Relaxed,
      );

      let mut pager = self.pager.lock();
      let mut wal = self.wal_buffer.lock();
      if bulk_load {
        let begin_record = WalRecord::new(WalRecordType::Begin, txid, build_begin_payload());
        wal.write_record(&begin_record, &mut pager)?;
        if !pending_wal.is_empty() {
          wal.write_record_bytes_batch(&pending_wal, &mut pager)?;
        }
        let commit_record = WalRecord::new(WalRecordType::Commit, txid, build_commit_payload());
        wal.write_record(&commit_record, &mut pager)?;
      } else {
        // Write COMMIT record to WAL
        let record = WalRecord::new(WalRecordType::Commit, txid, build_commit_payload());
        wal.write_record(&record, &mut pager)?;
      }

      // Flush WAL to disk based on sync mode
      let should_flush = matches!(self.sync_mode, SyncMode::Full | SyncMode::Normal);
      if should_flush && !group_commit_active {
        #[cfg(feature = "bench-profile")]
        let flush_start = Instant::now();
        wal.flush(&mut pager)?;
        #[cfg(feature = "bench-profile")]
        self
          .wal_flush_ns
          .fetch_add(flush_start.elapsed().as_nanos() as u64, Ordering::Relaxed);
      }

      // Update header with current WAL state and commit metadata
      let mut header = self.header.write();
      header.wal_head = wal.head();
      header.wal_tail = wal.tail();
      header.wal_primary_head = wal.primary_head();
      header.wal_secondary_head = wal.secondary_head();
      header.active_wal_region = wal.active_region();
      header.max_node_id = self
        .next_node_id
        .load(std::sync::atomic::Ordering::SeqCst)
        .saturating_sub(1);
      header.next_tx_id = self.next_tx_id.load(std::sync::atomic::Ordering::SeqCst);
      header.last_commit_ts = if let Some((commit_ts, _)) = commit_ts_for_mvcc {
        commit_ts
      } else {
        std::time::SystemTime::now()
          .duration_since(std::time::UNIX_EPOCH)
          .map(|d| d.as_millis() as u64)
          .unwrap_or(0)
      };
      header.change_counter += 1;

      // Persist header based on sync mode
      if self.sync_mode != SyncMode::Off {
        let header_bytes = header.serialize_to_page();
        pager.write_page(0, &header_bytes)?;

        if self.sync_mode == SyncMode::Full {
          #[cfg(feature = "bench-profile")]
          let sync_start = Instant::now();
          // Full durability: fsync after WAL + header updates
          pager.sync()?;
          #[cfg(feature = "bench-profile")]
          self
            .wal_flush_ns
            .fetch_add(sync_start.elapsed().as_nanos() as u64, Ordering::Relaxed);
        }
      }

      if group_commit_active {
        let mut state = self.group_commit_state.lock();
        state.next_seq = state.next_seq.saturating_add(1);
        group_commit_seq = state.next_seq;
      }

      if let Some(replication) = self.primary_replication.as_ref() {
        commit_token = Some(replication.append_commit_wal_frame(txid, pending_wal)?);
      }
    }

    if group_commit_active {
      self.wait_for_group_commit(group_commit_seq)?;
    }

    let mut delta = self.delta.write();

    self.apply_mvcc_commit(commit_ts_for_mvcc, txid, &pending, &delta);

    // Apply pending vector operations
    self.apply_pending_vectors(&pending.pending_vectors)?;

    merge_pending_delta(&mut delta, pending);
    if bulk_load {
      self.cache_clear();
    }
    drop(delta);

    // Check if auto-checkpoint should be triggered
    // Note: We release all locks above first to avoid deadlock during checkpoint
    if self.auto_checkpoint && self.should_checkpoint(self.checkpoint_threshold) {
      // Don't trigger if checkpoint is already running
      if !self.is_checkpoint_running() {
        // Use background or blocking checkpoint based on config
        let result = if self.background_checkpoint {
          self.background_checkpoint()
        } else {
          self.checkpoint()
        };

        // Log errors but don't fail the commit
        if let Err(e) = result {
          eprintln!("Warning: Auto-checkpoint failed: {e}");
        }
      }
    }

    Ok(commit_token)
  }

  /// Rollback the current transaction
  pub fn rollback(&self) -> Result<()> {
    let tx_handle = {
      let tid = std::thread::current().id();
      let mut current_tx = self.current_tx.lock();
      current_tx.remove(&tid).ok_or(KiteError::NoTransaction)?
    };
    let (txid, read_only, bulk_load) = {
      let tx = tx_handle.lock();
      (tx.txid, tx.read_only, tx.bulk_load)
    };

    if read_only {
      // Read-only transactions don't need WAL
      if let Some(mvcc) = self.mvcc.as_ref() {
        let mut tx_mgr = mvcc.tx_manager.lock();
        tx_mgr.abort_tx(txid);
      }
      return Ok(());
    }
    let prev_writers = self.active_writers.fetch_sub(1, Ordering::SeqCst);
    debug_assert!(prev_writers > 0, "active_writers underflow in rollback");

    if let Some(mvcc) = self.mvcc.as_ref() {
      let mut tx_mgr = mvcc.tx_manager.lock();
      tx_mgr.abort_tx(txid);
    }

    if !bulk_load {
      // Write ROLLBACK record to WAL
      let record = WalRecord::new(WalRecordType::Rollback, txid, build_rollback_payload());
      let mut pager = self.pager.lock();
      let mut wal = self.wal_buffer.lock();
      wal.write_record(&record, &mut pager)?;
    }

    Ok(())
  }

  /// Check if there's an active transaction
  pub fn has_transaction(&self) -> bool {
    self.current_tx_handle().is_some()
  }

  pub(crate) fn has_any_transaction(&self) -> bool {
    !self.current_tx.lock().is_empty()
  }

  /// Get the current transaction ID (if any)
  pub fn current_txid(&self) -> Option<TxId> {
    self.current_tx_handle().as_ref().map(|tx| tx.lock().txid)
  }

  /// Get the most recently emitted commit token from primary replication.
  pub fn last_commit_token(&self) -> Option<CommitToken> {
    self
      .primary_replication
      .as_ref()
      .and_then(|replication| replication.last_token())
  }

  /// Get primary replication status when replication role is `primary`.
  pub fn primary_replication_status(&self) -> Option<PrimaryReplicationStatus> {
    self
      .primary_replication
      .as_ref()
      .map(|replication| replication.status())
  }

  /// Write a WAL record (internal helper)
  pub(crate) fn write_wal(&self, record: WalRecord) -> Result<()> {
    let mut pager = self.pager.lock();
    let mut wal = self.wal_buffer.lock();
    wal.write_record(&record, &mut pager)?;
    Ok(())
  }

  pub(crate) fn write_wal_tx(
    &self,
    tx_handle: &Arc<Mutex<SingleFileTxState>>,
    record: WalRecord,
  ) -> Result<()> {
    let mut tx = tx_handle.lock();
    let record_bytes = record.build();
    if tx.bulk_load {
      tx.pending_wal.extend_from_slice(&record_bytes);
      Ok(())
    } else {
      drop(tx);
      self.write_wal(record)?;
      let mut tx = tx_handle.lock();
      tx.pending_wal.extend_from_slice(&record_bytes);
      Ok(())
    }
  }

  fn wait_for_group_commit(&self, seq: u64) -> Result<()> {
    let window_ms = self.group_commit_window_ms;

    {
      let mut state = self.group_commit_state.lock();
      if state.flushing {
        while state.flushed_seq < seq && state.last_error_seq < seq {
          self.group_commit_cv.wait(&mut state);
        }
        if state.last_error_seq >= seq {
          let message = state
            .last_error
            .as_deref()
            .unwrap_or("group commit flush failed");
          return Err(KiteError::Internal(message.to_string()));
        }
        return Ok(());
      }
      state.flushing = true;
    }

    if window_ms > 0 && self.active_writers.load(Ordering::SeqCst) > 0 {
      std::thread::sleep(Duration::from_millis(window_ms));
    }

    #[cfg(feature = "bench-profile")]
    let flush_start = Instant::now();
    let flush_result = {
      let mut pager = self.pager.lock();
      let mut wal = self.wal_buffer.lock();
      wal.flush(&mut pager)
    };
    #[cfg(feature = "bench-profile")]
    self
      .wal_flush_ns
      .fetch_add(flush_start.elapsed().as_nanos() as u64, Ordering::Relaxed);

    let mut state = self.group_commit_state.lock();
    state.flushed_seq = state.next_seq;
    state.flushing = false;
    match &flush_result {
      Ok(_) => {
        state.last_error_seq = 0;
        state.last_error = None;
      }
      Err(err) => {
        state.last_error_seq = state.next_seq;
        state.last_error = Some(err.to_string());
      }
    }
    self.group_commit_cv.notify_all();

    flush_result
  }

  /// Get current transaction ID or error
  pub(crate) fn require_write_tx(&self) -> Result<TxId> {
    let (txid, _) = self.require_write_tx_handle()?;
    Ok(txid)
  }
}

fn merge_pending_delta(target: &mut DeltaState, mut pending: DeltaState) {
  target.new_labels.extend(pending.new_labels.drain());
  target.new_etypes.extend(pending.new_etypes.drain());
  target.new_propkeys.extend(pending.new_propkeys.drain());

  for (node_id, mut node_delta) in pending.created_nodes.drain() {
    target.create_node(node_id, node_delta.key.as_deref());

    if let Some(labels) = node_delta.labels.take() {
      for label_id in labels {
        target.add_node_label(node_id, label_id);
      }
    }
    if let Some(labels_deleted) = node_delta.labels_deleted.take() {
      for label_id in labels_deleted {
        target.remove_node_label(node_id, label_id);
      }
    }
    if let Some(props) = node_delta.props.take() {
      for (key_id, value) in props {
        match value {
          Some(value) => target.set_node_prop_ref(node_id, key_id, value),
          None => target.delete_node_prop(node_id, key_id),
        }
      }
    }
  }

  for node_id in pending.deleted_nodes.drain() {
    target.delete_node(node_id);
  }

  for (node_id, mut node_delta) in pending.modified_nodes.drain() {
    if let Some(labels) = node_delta.labels.take() {
      for label_id in labels {
        target.add_node_label(node_id, label_id);
      }
    }
    if let Some(labels_deleted) = node_delta.labels_deleted.take() {
      for label_id in labels_deleted {
        target.remove_node_label(node_id, label_id);
      }
    }
    if let Some(props) = node_delta.props.take() {
      for (key_id, value) in props {
        match value {
          Some(value) => target.set_node_prop_ref(node_id, key_id, value),
          None => target.delete_node_prop(node_id, key_id),
        }
      }
    }
  }

  for (src, patches) in pending.out_add.drain() {
    for patch in patches {
      target.add_edge(src, patch.etype, patch.other);
    }
  }

  for (src, patches) in pending.out_del.drain() {
    for patch in patches {
      target.delete_edge(src, patch.etype, patch.other);
    }
  }

  for ((src, etype, dst), props) in pending.edge_props.drain() {
    for (key_id, value) in props {
      match value {
        Some(value) => target.set_edge_prop_ref(src, etype, dst, key_id, value),
        None => target.delete_edge_prop(src, etype, dst, key_id),
      }
    }
  }

  target.key_index.extend(pending.key_index.drain());
  target
    .key_index_deleted
    .extend(pending.key_index_deleted.drain());
}

#[cfg(test)]
mod tests {
  use super::*;
  use crate::core::single_file::{close_single_file, open_single_file, SingleFileOpenOptions};
  use std::panic::{catch_unwind, AssertUnwindSafe};
  use tempfile::tempdir;

  #[test]
  fn tx_guard_rolls_back_on_drop() -> Result<()> {
    let temp_dir = tempdir()?;
    let db_path = temp_dir.path().join("tx-guard.kitedb");
    let db = open_single_file(&db_path, SingleFileOpenOptions::new())?;

    let result = catch_unwind(AssertUnwindSafe(|| {
      let _tx = db.begin_guard(false).expect("expected value");
      db.create_node(Some("guarded")).expect("expected value");
      panic!("boom");
    }));

    assert!(result.is_err());
    assert!(!db.has_transaction());

    db.begin(false)?;
    db.commit()?;
    close_single_file(db)?;

    Ok(())
  }
}