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
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
//! # Compression Benchmarking
//!
//! Measures throughput and compression ratio for different compression algorithms
//! on TSDB-style data (typically sorted integer sequences).
//!
//! ## Usage
//!
//! ```rust
//! use oxirs_tdb::compression::benchmark::{CompressionAlgo, CompressionBenchmark};
//!
//! let data = b"hello world hello world hello world";
//! let result = CompressionBenchmark::benchmark_algorithm(CompressionAlgo::Lz4, data);
//! println!("Ratio: {:.2}, Speed: {:.1} MB/s", result.ratio, result.compress_mb_s);
//! ```

use std::time::{Duration, Instant};

use crate::compression::{
    delta::DeltaEncoder, lz4::Lz4Compressor, run_length::RunLengthEncoder,
    snappy::SnappyCompressor, zstd_compression::ZstdCompressor, CompressionAlgorithm,
};

// ─────────────────────────────────────────────────────────────────────────────
// CompressionAlgo
// ─────────────────────────────────────────────────────────────────────────────

/// Identifies a compression algorithm for benchmarking purposes.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum CompressionAlgo {
    /// Variable-length delta encoding (optimised for sorted integer IDs).
    Delta,
    /// Run-length encoding (optimised for repeated values).
    RunLength,
    /// LZ4 general-purpose compression (very fast).
    Lz4,
    /// Zstandard compression (excellent ratio).
    Zstd,
    /// Snappy compression (fast with good ratio).
    Snappy,
}

impl std::fmt::Display for CompressionAlgo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = match self {
            CompressionAlgo::Delta => "Delta",
            CompressionAlgo::RunLength => "RunLength",
            CompressionAlgo::Lz4 => "LZ4",
            CompressionAlgo::Zstd => "Zstd",
            CompressionAlgo::Snappy => "Snappy",
        };
        write!(f, "{}", name)
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// BenchmarkResult
// ─────────────────────────────────────────────────────────────────────────────

/// Benchmark measurements for a single compression algorithm on a data sample.
#[derive(Debug, Clone)]
pub struct BenchmarkResult {
    /// The algorithm that was benchmarked.
    pub algo: CompressionAlgo,
    /// Compression ratio: `compressed_size / original_size` (lower is better).
    /// A ratio > 1.0 means the data expanded (compression was counter-productive).
    pub ratio: f64,
    /// Compression throughput in MB/s.
    pub compress_mb_s: f64,
    /// Decompression throughput in MB/s.
    pub decompress_mb_s: f64,
    /// Original data size in bytes.
    pub original_size: usize,
    /// Compressed data size in bytes.
    pub compressed_size: usize,
}

impl BenchmarkResult {
    /// Return `true` if compression actually shrinks the data.
    pub fn is_beneficial(&self) -> bool {
        self.ratio < 1.0
    }

    /// Space savings as a percentage (0–100).  Negative means data expanded.
    pub fn space_savings_pct(&self) -> f64 {
        (1.0 - self.ratio) * 100.0
    }
}

impl std::fmt::Display for BenchmarkResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}: ratio={:.3} compress={:.1}MB/s decompress={:.1}MB/s",
            self.algo, self.ratio, self.compress_mb_s, self.decompress_mb_s
        )
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Internal helpers
// ─────────────────────────────────────────────────────────────────────────────

/// Minimum nanoseconds to report (avoids division by zero on very fast ops).
const MIN_NS: u128 = 1;

/// Compute MB/s given `data_bytes` and `elapsed` time.
fn mb_per_second(data_bytes: usize, elapsed: Duration) -> f64 {
    let ns = elapsed.as_nanos().max(MIN_NS);
    (data_bytes as f64 / 1_048_576.0) / (ns as f64 / 1_000_000_000.0)
}

/// Produce a [`BenchmarkResult`] where compression was not available.
///
/// Uses original data as compressed data, giving ratio = 1.0 and max speed.
fn unavailable_result(algo: CompressionAlgo, data: &[u8]) -> BenchmarkResult {
    BenchmarkResult {
        algo,
        ratio: 1.0,
        compress_mb_s: 0.0,
        decompress_mb_s: 0.0,
        original_size: data.len(),
        compressed_size: data.len(),
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// CompressionBenchmark
// ─────────────────────────────────────────────────────────────────────────────

/// Measures compression throughput and ratio for different algorithms.
///
/// All benchmarks are single-shot (not averaged); for statistical precision
/// use the `benchmarking` feature with multiple iterations.
pub struct CompressionBenchmark;

impl CompressionBenchmark {
    /// Create a new `CompressionBenchmark` instance (stateless).
    pub fn new() -> Self {
        Self
    }

    /// Benchmark a single algorithm on the given data.
    ///
    /// Returns a [`BenchmarkResult`] regardless of whether compression succeeds:
    /// on error, ratio is set to `1.0` and throughputs to `0.0`.
    pub fn benchmark_algorithm(algo: CompressionAlgo, data: &[u8]) -> BenchmarkResult {
        if data.is_empty() {
            return BenchmarkResult {
                algo,
                ratio: 1.0,
                compress_mb_s: 0.0,
                decompress_mb_s: 0.0,
                original_size: 0,
                compressed_size: 0,
            };
        }

        match &algo {
            CompressionAlgo::Delta => Self::bench_delta(data),
            CompressionAlgo::RunLength => Self::bench_run_length(data),
            CompressionAlgo::Lz4 => Self::bench_lz4(data),
            CompressionAlgo::Zstd => Self::bench_zstd(data),
            CompressionAlgo::Snappy => Self::bench_snappy(data),
        }
    }

    /// Benchmark all supported algorithms on the given data.
    ///
    /// Results are returned in algorithm order (Delta, RunLength, LZ4, Zstd, Snappy).
    pub fn benchmark_all(data: &[u8]) -> Vec<BenchmarkResult> {
        vec![
            Self::benchmark_algorithm(CompressionAlgo::Delta, data),
            Self::benchmark_algorithm(CompressionAlgo::RunLength, data),
            Self::benchmark_algorithm(CompressionAlgo::Lz4, data),
            Self::benchmark_algorithm(CompressionAlgo::Zstd, data),
            Self::benchmark_algorithm(CompressionAlgo::Snappy, data),
        ]
    }

    /// Return the result with the best compression ratio (lowest ratio value).
    pub fn best_ratio(results: &[BenchmarkResult]) -> Option<&BenchmarkResult> {
        results.iter().min_by(|a, b| {
            a.ratio
                .partial_cmp(&b.ratio)
                .unwrap_or(std::cmp::Ordering::Equal)
        })
    }

    /// Return the result with the highest compression throughput (MB/s).
    pub fn best_compress_speed(results: &[BenchmarkResult]) -> Option<&BenchmarkResult> {
        results.iter().max_by(|a, b| {
            a.compress_mb_s
                .partial_cmp(&b.compress_mb_s)
                .unwrap_or(std::cmp::Ordering::Equal)
        })
    }

    /// Return the result with the highest decompression throughput (MB/s).
    pub fn best_decompress_speed(results: &[BenchmarkResult]) -> Option<&BenchmarkResult> {
        results.iter().max_by(|a, b| {
            a.decompress_mb_s
                .partial_cmp(&b.decompress_mb_s)
                .unwrap_or(std::cmp::Ordering::Equal)
        })
    }

    // ── Private per-algorithm benchmarks ─────────────────────────────────────

    fn bench_delta(data: &[u8]) -> BenchmarkResult {
        // Treat raw bytes as u64 sequence (chunked by 8 bytes).
        let values: Vec<u64> = data
            .chunks_exact(8)
            .map(|c| u64::from_le_bytes([c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7]]))
            .collect();

        if values.is_empty() {
            // Data too small for u64 chunking; fall back to byte-level encoding
            let t0 = Instant::now();
            let enc = DeltaEncoder::encode_byte_sequence(data);
            let compress_elapsed = t0.elapsed();

            let compressed = match enc {
                Ok(c) => c,
                Err(_) => return unavailable_result(CompressionAlgo::Delta, data),
            };

            let t1 = Instant::now();
            let _ = DeltaEncoder::decode_byte_sequence(&compressed);
            let decompress_elapsed = t1.elapsed();

            let ratio = compressed.len() as f64 / data.len() as f64;
            return BenchmarkResult {
                algo: CompressionAlgo::Delta,
                ratio,
                compress_mb_s: mb_per_second(data.len(), compress_elapsed),
                decompress_mb_s: mb_per_second(data.len(), decompress_elapsed),
                original_size: data.len(),
                compressed_size: compressed.len(),
            };
        }

        let t0 = Instant::now();
        let encoded = DeltaEncoder::encode(&values);
        let compress_elapsed = t0.elapsed();

        let t1 = Instant::now();
        let _ = DeltaEncoder::decode(&encoded);
        let decompress_elapsed = t1.elapsed();

        let ratio = encoded.len() as f64 / data.len() as f64;
        BenchmarkResult {
            algo: CompressionAlgo::Delta,
            ratio,
            compress_mb_s: mb_per_second(data.len(), compress_elapsed),
            decompress_mb_s: mb_per_second(data.len(), decompress_elapsed),
            original_size: data.len(),
            compressed_size: encoded.len(),
        }
    }

    fn bench_run_length(data: &[u8]) -> BenchmarkResult {
        let t0 = Instant::now();
        let enc = RunLengthEncoder::encode(data);
        let compress_elapsed = t0.elapsed();

        let compressed = match enc {
            Ok(c) => c,
            Err(_) => return unavailable_result(CompressionAlgo::RunLength, data),
        };

        let t1 = Instant::now();
        let _ = RunLengthEncoder::decode(&compressed);
        let decompress_elapsed = t1.elapsed();

        let ratio = if data.is_empty() {
            1.0
        } else {
            compressed.len() as f64 / data.len() as f64
        };

        BenchmarkResult {
            algo: CompressionAlgo::RunLength,
            ratio,
            compress_mb_s: mb_per_second(data.len(), compress_elapsed),
            decompress_mb_s: mb_per_second(data.len(), decompress_elapsed),
            original_size: data.len(),
            compressed_size: compressed.len(),
        }
    }

    fn bench_lz4(data: &[u8]) -> BenchmarkResult {
        let compressor = Lz4Compressor::new();

        let t0 = Instant::now();
        let compressed_data = compressor.compress(data);
        let compress_elapsed = t0.elapsed();

        let compressed_data = match compressed_data {
            Ok(c) => c,
            Err(_) => return unavailable_result(CompressionAlgo::Lz4, data),
        };

        let t1 = Instant::now();
        let _ = compressor.decompress(&compressed_data);
        let decompress_elapsed = t1.elapsed();

        let ratio = compressed_data.data.len() as f64 / data.len() as f64;
        BenchmarkResult {
            algo: CompressionAlgo::Lz4,
            ratio,
            compress_mb_s: mb_per_second(data.len(), compress_elapsed),
            decompress_mb_s: mb_per_second(data.len(), decompress_elapsed),
            original_size: data.len(),
            compressed_size: compressed_data.data.len(),
        }
    }

    fn bench_zstd(data: &[u8]) -> BenchmarkResult {
        let compressor = ZstdCompressor::new();

        let t0 = Instant::now();
        let compressed_data = compressor.compress(data);
        let compress_elapsed = t0.elapsed();

        let compressed_data = match compressed_data {
            Ok(c) => c,
            Err(_) => return unavailable_result(CompressionAlgo::Zstd, data),
        };

        let t1 = Instant::now();
        let _ = compressor.decompress(&compressed_data);
        let decompress_elapsed = t1.elapsed();

        let ratio = compressed_data.data.len() as f64 / data.len() as f64;
        BenchmarkResult {
            algo: CompressionAlgo::Zstd,
            ratio,
            compress_mb_s: mb_per_second(data.len(), compress_elapsed),
            decompress_mb_s: mb_per_second(data.len(), decompress_elapsed),
            original_size: data.len(),
            compressed_size: compressed_data.data.len(),
        }
    }

    fn bench_snappy(data: &[u8]) -> BenchmarkResult {
        let compressor = SnappyCompressor::new();

        let t0 = Instant::now();
        let compressed_data = compressor.compress(data);
        let compress_elapsed = t0.elapsed();

        let compressed_data = match compressed_data {
            Ok(c) => c,
            Err(_) => return unavailable_result(CompressionAlgo::Snappy, data),
        };

        let t1 = Instant::now();
        let _ = compressor.decompress(&compressed_data);
        let decompress_elapsed = t1.elapsed();

        let ratio = compressed_data.data.len() as f64 / data.len() as f64;
        BenchmarkResult {
            algo: CompressionAlgo::Snappy,
            ratio,
            compress_mb_s: mb_per_second(data.len(), compress_elapsed),
            decompress_mb_s: mb_per_second(data.len(), decompress_elapsed),
            original_size: data.len(),
            compressed_size: compressed_data.data.len(),
        }
    }
}

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

// ─────────────────────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────────────────────

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

    /// Build a repetitive u64 sequence and flatten to bytes for benchmarking.
    fn repetitive_u64_data(count: usize) -> Vec<u8> {
        let values: Vec<u64> = (0..count as u64).map(|i| i / 10).collect();
        values.iter().flat_map(|v| v.to_le_bytes()).collect()
    }

    /// Build a sorted ascending u64 sequence as bytes.
    fn sorted_u64_data(count: usize) -> Vec<u8> {
        let values: Vec<u64> = (0..count as u64).collect();
        values.iter().flat_map(|v| v.to_le_bytes()).collect()
    }

    // ── Individual algorithm benchmarks ──────────────────────────────────────

    #[test]
    fn test_benchmark_delta_valid_result() {
        let data = sorted_u64_data(100);
        let result = CompressionBenchmark::benchmark_algorithm(CompressionAlgo::Delta, &data);
        assert_eq!(result.algo, CompressionAlgo::Delta);
        assert!(result.original_size > 0);
        assert!(result.ratio >= 0.0);
        assert!(result.compress_mb_s >= 0.0);
        assert!(result.decompress_mb_s >= 0.0);
    }

    #[test]
    fn test_benchmark_run_length_valid_result() {
        let data = repetitive_u64_data(100);
        let result = CompressionBenchmark::benchmark_algorithm(CompressionAlgo::RunLength, &data);
        assert_eq!(result.algo, CompressionAlgo::RunLength);
        assert!(result.original_size > 0);
        assert!(result.ratio >= 0.0);
    }

    #[test]
    fn test_benchmark_lz4_valid_result() {
        let data = b"hello world hello world hello world hello world".to_vec();
        let result = CompressionBenchmark::benchmark_algorithm(CompressionAlgo::Lz4, &data);
        assert_eq!(result.algo, CompressionAlgo::Lz4);
        assert!(result.original_size == data.len());
        assert!(result.ratio >= 0.0);
    }

    #[test]
    fn test_benchmark_zstd_valid_result() {
        let data = b"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_vec();
        let result = CompressionBenchmark::benchmark_algorithm(CompressionAlgo::Zstd, &data);
        assert_eq!(result.algo, CompressionAlgo::Zstd);
        assert!(result.ratio >= 0.0);
    }

    #[test]
    fn test_benchmark_snappy_valid_result() {
        let data = b"snappy snappy snappy snappy snappy".to_vec();
        let result = CompressionBenchmark::benchmark_algorithm(CompressionAlgo::Snappy, &data);
        assert_eq!(result.algo, CompressionAlgo::Snappy);
        assert!(result.ratio >= 0.0);
    }

    // ── benchmark_all ─────────────────────────────────────────────────────────

    #[test]
    fn test_benchmark_all_returns_five_results() {
        let data = b"test data for benchmarking all algorithms".to_vec();
        let results = CompressionBenchmark::benchmark_all(&data);
        assert_eq!(results.len(), 5);
    }

    #[test]
    fn test_benchmark_all_all_algos_present() {
        let data = sorted_u64_data(50);
        let results = CompressionBenchmark::benchmark_all(&data);
        let algos: Vec<&CompressionAlgo> = results.iter().map(|r| &r.algo).collect();
        assert!(algos.contains(&&CompressionAlgo::Delta));
        assert!(algos.contains(&&CompressionAlgo::RunLength));
        assert!(algos.contains(&&CompressionAlgo::Lz4));
        assert!(algos.contains(&&CompressionAlgo::Zstd));
        assert!(algos.contains(&&CompressionAlgo::Snappy));
    }

    // ── best_ratio ────────────────────────────────────────────────────────────

    #[test]
    fn test_best_ratio_returns_minimum() {
        let data = repetitive_u64_data(100);
        let results = CompressionBenchmark::benchmark_all(&data);
        let best = CompressionBenchmark::best_ratio(&results);
        assert!(best.is_some());
        let best = best.unwrap();
        // Verify it really is the minimum
        for r in &results {
            assert!(best.ratio <= r.ratio + f64::EPSILON);
        }
    }

    #[test]
    fn test_best_ratio_empty_returns_none() {
        let result = CompressionBenchmark::best_ratio(&[]);
        assert!(result.is_none());
    }

    // ── best_compress_speed ───────────────────────────────────────────────────

    #[test]
    fn test_best_compress_speed_returns_maximum() {
        let data = sorted_u64_data(100);
        let results = CompressionBenchmark::benchmark_all(&data);
        let best = CompressionBenchmark::best_compress_speed(&results);
        assert!(best.is_some());
        let best = best.unwrap();
        for r in &results {
            assert!(best.compress_mb_s >= r.compress_mb_s - f64::EPSILON);
        }
    }

    #[test]
    fn test_best_compress_speed_empty_returns_none() {
        let result = CompressionBenchmark::best_compress_speed(&[]);
        assert!(result.is_none());
    }

    // ── best_decompress_speed ─────────────────────────────────────────────────

    #[test]
    fn test_best_decompress_speed_returns_maximum() {
        let data = sorted_u64_data(100);
        let results = CompressionBenchmark::benchmark_all(&data);
        let best = CompressionBenchmark::best_decompress_speed(&results);
        assert!(best.is_some());
    }

    // ── BenchmarkResult helpers ───────────────────────────────────────────────

    #[test]
    fn test_benchmark_result_ratio_beneficial() {
        let r = BenchmarkResult {
            algo: CompressionAlgo::Lz4,
            ratio: 0.5,
            compress_mb_s: 100.0,
            decompress_mb_s: 200.0,
            original_size: 1000,
            compressed_size: 500,
        };
        assert!(r.is_beneficial());
        assert!((r.space_savings_pct() - 50.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_benchmark_result_ratio_not_beneficial() {
        let r = BenchmarkResult {
            algo: CompressionAlgo::RunLength,
            ratio: 1.5,
            compress_mb_s: 50.0,
            decompress_mb_s: 80.0,
            original_size: 100,
            compressed_size: 150,
        };
        assert!(!r.is_beneficial());
        assert!(r.space_savings_pct() < 0.0);
    }

    #[test]
    fn test_benchmark_empty_data() {
        let result = CompressionBenchmark::benchmark_algorithm(CompressionAlgo::Lz4, &[]);
        assert_eq!(result.original_size, 0);
        assert_eq!(result.compressed_size, 0);
    }

    #[test]
    fn test_benchmark_result_display() {
        let r = BenchmarkResult {
            algo: CompressionAlgo::Zstd,
            ratio: 0.3,
            compress_mb_s: 120.0,
            decompress_mb_s: 400.0,
            original_size: 1000,
            compressed_size: 300,
        };
        let s = r.to_string();
        assert!(s.contains("Zstd"));
        assert!(s.contains("0.300"));
    }

    #[test]
    fn test_compression_algo_display() {
        assert_eq!(CompressionAlgo::Delta.to_string(), "Delta");
        assert_eq!(CompressionAlgo::RunLength.to_string(), "RunLength");
        assert_eq!(CompressionAlgo::Lz4.to_string(), "LZ4");
        assert_eq!(CompressionAlgo::Zstd.to_string(), "Zstd");
        assert_eq!(CompressionAlgo::Snappy.to_string(), "Snappy");
    }

    #[test]
    fn test_delta_compresses_sorted_ids_efficiently() {
        // Sorted triple IDs with small deltas should compress well
        let data = sorted_u64_data(200);
        let result = CompressionBenchmark::benchmark_algorithm(CompressionAlgo::Delta, &data);
        // Expect better than 50% ratio for sequential IDs (delta=1 → 1 byte via LEB128)
        assert!(
            result.ratio < 0.5,
            "Expected ratio < 0.5, got {}",
            result.ratio
        );
    }

    #[test]
    fn test_rle_compresses_repetitive_ids_efficiently() {
        // Highly repetitive data should compress well with RLE
        let data = vec![42u8; 1000];
        let result = CompressionBenchmark::benchmark_algorithm(CompressionAlgo::RunLength, &data);
        assert!(
            result.ratio < 0.1,
            "Expected ratio < 0.1 for repetitive data, got {}",
            result.ratio
        );
    }
}