oxirs-tdb 0.3.1

Apache Jena TDB/TDB2 compatible RDF storage engine with B+Tree indexes
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
//! Group commit optimization for WAL
//!
//! This module implements group commit, a technique that batches multiple
//! transaction commits together to reduce the number of fsync() operations.
//!
//! Benefits:
//! - Reduces disk I/O overhead by batching fsync calls
//! - Improves throughput for write-heavy workloads
//! - Maintains durability guarantees (all commits are written before ack)

use super::wal::{Lsn, TxnId, WriteAheadLog};
use crate::error::Result;
use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};

/// Configuration for group commit
#[derive(Debug, Clone)]
pub struct GroupCommitConfig {
    /// Maximum number of commits to batch together
    pub max_batch_size: usize,
    /// Maximum time to wait before flushing (even if batch not full)
    pub max_wait_time: Duration,
    /// Whether group commit is enabled
    pub enabled: bool,
}

impl Default for GroupCommitConfig {
    fn default() -> Self {
        Self {
            max_batch_size: 100,
            max_wait_time: Duration::from_millis(10),
            enabled: true,
        }
    }
}

/// Pending commit request
#[derive(Debug)]
struct PendingCommit {
    /// Transaction ID
    txn_id: TxnId,
    /// LSN of commit record
    commit_lsn: Lsn,
    /// Time when commit was requested
    requested_at: Instant,
}

/// Group commit coordinator
///
/// Batches multiple transaction commits together to reduce fsync overhead.
/// When a transaction wants to commit:
/// 1. It adds itself to the pending queue
/// 2. It waits on the condition variable
/// 3. When batch is full or timeout expires, a flush occurs
/// 4. All transactions in the batch are notified
pub struct GroupCommitCoordinator {
    /// Configuration
    config: GroupCommitConfig,
    /// Write-ahead log
    wal: Arc<WriteAheadLog>,
    /// Pending commits
    pending: Arc<Mutex<PendingCommitQueue>>,
    /// Condition variable for commit notifications
    commit_cv: Arc<Condvar>,
    /// Statistics
    stats: Arc<Mutex<GroupCommitStats>>,
}

/// Queue of pending commits
struct PendingCommitQueue {
    /// List of pending commits
    commits: Vec<PendingCommit>,
    /// Last flush time
    last_flush: Instant,
    /// Last flushed LSN
    last_flushed_lsn: Lsn,
}

impl PendingCommitQueue {
    fn new() -> Self {
        Self {
            commits: Vec::new(),
            last_flush: Instant::now(),
            last_flushed_lsn: Lsn::ZERO,
        }
    }

    fn is_empty(&self) -> bool {
        self.commits.is_empty()
    }

    fn len(&self) -> usize {
        self.commits.len()
    }

    fn should_flush(&self, config: &GroupCommitConfig) -> bool {
        if self.commits.is_empty() {
            return false;
        }

        // Flush if batch is full
        if self.commits.len() >= config.max_batch_size {
            return true;
        }

        // Flush if oldest commit has waited too long
        if let Some(oldest) = self.commits.first() {
            if oldest.requested_at.elapsed() >= config.max_wait_time {
                return true;
            }
        }

        false
    }

    fn drain_batch(&mut self) -> Vec<PendingCommit> {
        std::mem::take(&mut self.commits)
    }
}

/// Group commit statistics
#[derive(Debug, Default)]
pub struct GroupCommitStats {
    /// Total number of commits processed
    pub total_commits: u64,
    /// Total number of flush operations
    pub total_flushes: u64,
    /// Average batch size
    pub avg_batch_size: f64,
    /// Total wait time across all commits (microseconds)
    pub total_wait_time_us: u64,
    /// Maximum wait time seen (microseconds)
    pub max_wait_time_us: u64,
}

impl GroupCommitCoordinator {
    /// Create a new group commit coordinator
    pub fn new(wal: Arc<WriteAheadLog>, config: GroupCommitConfig) -> Self {
        Self {
            config,
            wal,
            pending: Arc::new(Mutex::new(PendingCommitQueue::new())),
            commit_cv: Arc::new(Condvar::new()),
            stats: Arc::new(Mutex::new(GroupCommitStats::default())),
        }
    }

    /// Request a commit (blocking until commit is durable)
    ///
    /// This method adds the transaction to the pending queue and waits
    /// until the WAL is flushed. Multiple transactions may be flushed
    /// together in a single batch.
    pub fn commit(&self, txn_id: TxnId, commit_lsn: Lsn) -> Result<()> {
        let requested_at = Instant::now();

        if !self.config.enabled {
            // Group commit disabled - flush immediately
            self.wal.flush()?;

            // Still update stats
            let wait_time_us = requested_at.elapsed().as_micros() as u64;
            let mut stats = self.stats.lock().expect("lock poisoned");
            stats.total_commits += 1;
            stats.total_flushes += 1; // Each commit flushes immediately when disabled
            stats.total_wait_time_us += wait_time_us;
            stats.max_wait_time_us = stats.max_wait_time_us.max(wait_time_us);

            return Ok(());
        }

        // Add to pending queue
        {
            let mut pending = self.pending.lock().expect("lock poisoned");
            pending.commits.push(PendingCommit {
                txn_id,
                commit_lsn,
                requested_at,
            });
        }

        // Try to flush if conditions are met
        self.try_flush()?;

        // Wait for flush (with timeout to prevent deadlock)
        let timeout = self.config.max_wait_time * 2; // Safety margin
        self.wait_for_flush(commit_lsn, timeout)?;

        // Record wait time
        let wait_time_us = requested_at.elapsed().as_micros() as u64;
        let mut stats = self.stats.lock().expect("lock poisoned");
        stats.total_commits += 1;
        stats.total_wait_time_us += wait_time_us;
        stats.max_wait_time_us = stats.max_wait_time_us.max(wait_time_us);

        Ok(())
    }

    /// Try to flush pending commits if conditions are met
    fn try_flush(&self) -> Result<()> {
        let mut pending = self.pending.lock().expect("lock poisoned");

        if !pending.should_flush(&self.config) {
            return Ok(());
        }

        // Take the batch
        let batch = pending.drain_batch();
        let batch_size = batch.len();

        // Record flush time
        pending.last_flush = Instant::now();

        // Find highest LSN in batch
        let max_lsn = batch
            .iter()
            .map(|c| c.commit_lsn)
            .max()
            .unwrap_or(Lsn::ZERO);

        // Release lock before flushing (don't hold lock during I/O)
        drop(pending);

        // Flush WAL to disk
        self.wal.flush()?;

        // Update flushed LSN and notify waiters
        {
            let mut pending = self.pending.lock().expect("lock poisoned");
            pending.last_flushed_lsn = max_lsn;
        }

        // Notify all waiting transactions
        self.commit_cv.notify_all();

        // Update statistics
        {
            let mut stats = self.stats.lock().expect("lock poisoned");
            stats.total_flushes += 1;
            let total_commits = stats.total_commits as f64;
            stats.avg_batch_size = (stats.avg_batch_size * (total_commits - batch_size as f64)
                + batch_size as f64)
                / total_commits.max(1.0);
        }

        Ok(())
    }

    /// Wait for a specific LSN to be flushed
    fn wait_for_flush(&self, target_lsn: Lsn, timeout: Duration) -> Result<()> {
        let deadline = Instant::now() + timeout;

        let mut pending = self.pending.lock().expect("lock poisoned");

        loop {
            // Check if already flushed
            if pending.last_flushed_lsn >= target_lsn {
                return Ok(());
            }

            // Wait with timeout
            let now = Instant::now();
            if now >= deadline {
                // Timeout - force flush
                drop(pending);
                self.force_flush()?;
                return Ok(());
            }

            let remaining = deadline.duration_since(now);
            let (guard, timeout_result) = self
                .commit_cv
                .wait_timeout(pending, remaining)
                .expect("lock poisoned");
            pending = guard;

            if timeout_result.timed_out() {
                // Timeout - force flush
                drop(pending);
                self.force_flush()?;
                return Ok(());
            }
        }
    }

    /// Force an immediate flush of pending commits
    pub fn force_flush(&self) -> Result<()> {
        let mut pending = self.pending.lock().expect("lock poisoned");

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

        let batch = pending.drain_batch();
        let batch_size = batch.len();

        let max_lsn = batch
            .iter()
            .map(|c| c.commit_lsn)
            .max()
            .unwrap_or(Lsn::ZERO);

        pending.last_flush = Instant::now();

        drop(pending);

        // Flush WAL
        self.wal.flush()?;

        // Update flushed LSN
        {
            let mut pending = self.pending.lock().expect("lock poisoned");
            pending.last_flushed_lsn = max_lsn;
        }

        // Notify waiters
        self.commit_cv.notify_all();

        // Update stats
        {
            let mut stats = self.stats.lock().expect("lock poisoned");
            stats.total_flushes += 1;
            let total_commits = stats.total_commits as f64;
            stats.avg_batch_size = (stats.avg_batch_size * (total_commits - batch_size as f64)
                + batch_size as f64)
                / total_commits.max(1.0);
        }

        Ok(())
    }

    /// Get current statistics
    pub fn stats(&self) -> GroupCommitStats {
        let stats = self.stats.lock().expect("lock poisoned");
        GroupCommitStats {
            total_commits: stats.total_commits,
            total_flushes: stats.total_flushes,
            avg_batch_size: stats.avg_batch_size,
            total_wait_time_us: stats.total_wait_time_us,
            max_wait_time_us: stats.max_wait_time_us,
        }
    }

    /// Get average commits per flush
    pub fn avg_commits_per_flush(&self) -> f64 {
        let stats = self.stats.lock().expect("lock poisoned");
        if stats.total_flushes == 0 {
            0.0
        } else {
            stats.total_commits as f64 / stats.total_flushes as f64
        }
    }

    /// Get number of pending commits
    pub fn pending_count(&self) -> usize {
        self.pending.lock().expect("lock poisoned").len()
    }
}

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

    #[test]
    fn test_group_commit_config() {
        let config = GroupCommitConfig::default();
        assert_eq!(config.max_batch_size, 100);
        assert_eq!(config.max_wait_time, Duration::from_millis(10));
        assert!(config.enabled);
    }

    #[test]
    fn test_single_commit() {
        let temp_dir = env::temp_dir().join("oxirs_group_commit_single");
        std::fs::create_dir_all(&temp_dir).unwrap();

        let wal = Arc::new(WriteAheadLog::new(&temp_dir).unwrap());
        let coordinator = GroupCommitCoordinator::new(wal.clone(), GroupCommitConfig::default());

        let lsn = wal
            .append(super::super::wal::LogRecord::Commit {
                txn_id: TxnId::new(1),
            })
            .unwrap();

        coordinator.commit(TxnId::new(1), lsn).unwrap();

        // Explicitly force flush to ensure stats are updated
        coordinator.force_flush().unwrap();

        let stats = coordinator.stats();
        assert_eq!(stats.total_commits, 1);
        assert!(stats.total_flushes >= 1);

        std::fs::remove_dir_all(&temp_dir).ok();
    }

    #[test]
    fn test_batch_commit() {
        let temp_dir = env::temp_dir().join("oxirs_group_commit_batch");
        std::fs::create_dir_all(&temp_dir).unwrap();

        let wal = Arc::new(WriteAheadLog::new(&temp_dir).unwrap());
        let config = GroupCommitConfig {
            max_batch_size: 5,
            max_wait_time: Duration::from_millis(50), // Reduced from 100ms
            enabled: true,
        };
        let coordinator = Arc::new(GroupCommitCoordinator::new(wal.clone(), config));

        // Spawn multiple threads to commit concurrently (reduced for faster tests)
        let mut handles = vec![];
        for i in 0..5 {
            let coordinator = Arc::clone(&coordinator);
            let wal = Arc::clone(&wal);
            let handle = thread::spawn(move || {
                let lsn = wal
                    .append(super::super::wal::LogRecord::Commit {
                        txn_id: TxnId::new(i),
                    })
                    .unwrap();
                coordinator.commit(TxnId::new(i), lsn).unwrap();
            });
            handles.push(handle);
        }

        for handle in handles {
            handle.join().unwrap();
        }

        let stats = coordinator.stats();
        assert_eq!(stats.total_commits, 5);
        // Should have fewer flushes than commits due to batching
        assert!(stats.total_flushes <= 5);
        assert!(stats.avg_batch_size >= 1.0);

        std::fs::remove_dir_all(&temp_dir).ok();
    }

    #[test]
    fn test_force_flush() {
        let temp_dir = env::temp_dir().join("oxirs_group_commit_force");
        std::fs::create_dir_all(&temp_dir).unwrap();

        let wal = Arc::new(WriteAheadLog::new(&temp_dir).unwrap());
        let config = GroupCommitConfig {
            max_batch_size: 100,
            max_wait_time: Duration::from_millis(50), // Short timeout for tests
            enabled: false,                           // Disable to manually control flushing
        };
        let coordinator = Arc::new(GroupCommitCoordinator::new(wal.clone(), config));

        // Do sequential commits instead of concurrent to avoid potential deadlocks
        for i in 0..3 {
            let lsn = wal
                .append(super::super::wal::LogRecord::Commit {
                    txn_id: TxnId::new(i),
                })
                .unwrap();
            // With group commit disabled, each commit flushes immediately
            coordinator.commit(TxnId::new(i), lsn).unwrap();
        }

        let stats = coordinator.stats();
        // With group commit disabled, each commit flushes immediately
        assert_eq!(stats.total_commits, 3);
        assert!(stats.total_flushes >= 1);

        std::fs::remove_dir_all(&temp_dir).ok();
    }

    #[test]
    fn test_disabled_group_commit() {
        let temp_dir = env::temp_dir().join("oxirs_group_commit_disabled");
        std::fs::create_dir_all(&temp_dir).unwrap();

        let wal = Arc::new(WriteAheadLog::new(&temp_dir).unwrap());
        let config = GroupCommitConfig {
            enabled: false,
            ..Default::default()
        };
        let coordinator = GroupCommitCoordinator::new(wal.clone(), config);

        for i in 0..5 {
            let lsn = wal
                .append(super::super::wal::LogRecord::Commit {
                    txn_id: TxnId::new(i),
                })
                .unwrap();
            coordinator.commit(TxnId::new(i), lsn).unwrap();
        }

        let stats = coordinator.stats();
        assert_eq!(stats.total_commits, 5);
        // With group commit disabled, each commit should flush immediately
        assert_eq!(stats.avg_batch_size, 0.0);

        std::fs::remove_dir_all(&temp_dir).ok();
    }

    #[test]
    #[ignore] // Timing-dependent test, not suitable for CI
    fn test_timeout_flush() {
        let temp_dir = env::temp_dir().join("oxirs_group_commit_timeout");
        std::fs::create_dir_all(&temp_dir).unwrap();

        let wal = Arc::new(WriteAheadLog::new(&temp_dir).unwrap());
        let config = GroupCommitConfig {
            max_batch_size: 100,
            max_wait_time: Duration::from_millis(50), // Short timeout
            enabled: true,
        };
        let coordinator = Arc::new(GroupCommitCoordinator::new(wal.clone(), config));

        // Single commit should timeout and flush
        let lsn = wal
            .append(super::super::wal::LogRecord::Commit {
                txn_id: TxnId::new(1),
            })
            .unwrap();

        coordinator.commit(TxnId::new(1), lsn).unwrap();

        let stats = coordinator.stats();
        assert_eq!(stats.total_commits, 1);
        assert!(stats.max_wait_time_us > 0);

        std::fs::remove_dir_all(&temp_dir).ok();
    }

    #[test]
    fn test_concurrent_commits() {
        let temp_dir = env::temp_dir().join("oxirs_group_commit_concurrent");
        std::fs::create_dir_all(&temp_dir).unwrap();

        let wal = Arc::new(WriteAheadLog::new(&temp_dir).unwrap());
        let config = GroupCommitConfig {
            max_batch_size: 10,
            max_wait_time: Duration::from_millis(50), // Reduced from 100ms
            enabled: true,
        };
        let coordinator = Arc::new(GroupCommitCoordinator::new(wal.clone(), config));

        // Concurrent commits (reduced to 5 for faster tests)
        let mut handles = vec![];
        for i in 0..5 {
            let coordinator = Arc::clone(&coordinator);
            let wal = Arc::clone(&wal);
            let handle = thread::spawn(move || {
                let lsn = wal
                    .append(super::super::wal::LogRecord::Commit {
                        txn_id: TxnId::new(i),
                    })
                    .unwrap();
                coordinator.commit(TxnId::new(i), lsn).unwrap();
            });
            handles.push(handle);
        }

        for handle in handles {
            handle.join().unwrap();
        }

        let stats = coordinator.stats();
        assert_eq!(stats.total_commits, 5);
        // With batch size of 10 and 5 commits, batching may or may not occur
        assert!(stats.total_flushes <= 5); // Should not exceed total commits

        std::fs::remove_dir_all(&temp_dir).ok();
    }
}