Skip to main content

oxirs_cluster/
compression_strategy.rs

1//! Compression strategy for cluster data with auto-selection
2//!
3//! This module provides intelligent compression strategies that automatically
4//! select the best compression algorithm based on data characteristics,
5//! access patterns, and system load.
6
7use crate::error::{ClusterError, Result};
8use scirs2_core::profiling::Profiler;
9use serde::{Deserialize, Serialize};
10use std::sync::atomic::{AtomicU64, Ordering};
11use std::sync::Arc;
12
13/// Compression strategy manager with auto-selection capabilities
14pub struct CompressionStrategy {
15    config: CompressionConfig,
16    #[allow(dead_code)]
17    profiler: Arc<Profiler>,
18    metrics: Arc<CompressionMetrics>,
19}
20
21/// Configuration for compression behavior
22#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct CompressionConfig {
24    /// Default compression algorithm to use
25    pub default_algorithm: Algorithm,
26    /// Enable automatic algorithm selection based on data characteristics
27    pub auto_select: bool,
28    /// Minimum data size for compression (smaller data won't be compressed)
29    pub compression_threshold_bytes: usize,
30}
31
32impl Default for CompressionConfig {
33    fn default() -> Self {
34        Self {
35            default_algorithm: Algorithm::Zstd,
36            auto_select: true,
37            compression_threshold_bytes: 1024, // 1KB minimum
38        }
39    }
40}
41
42/// Available compression algorithms
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
44pub enum Algorithm {
45    /// No compression
46    None,
47    /// LZ4: Fast compression (~500 MB/s), ~60% compression ratio
48    Lz4,
49    /// Zstd: Balanced compression (~200 MB/s), ~70% compression ratio
50    Zstd,
51    /// LZMA: High compression (~50 MB/s), ~80% compression ratio
52    Lzma,
53}
54
55impl std::fmt::Display for Algorithm {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        match self {
58            Algorithm::None => write!(f, "none"),
59            Algorithm::Lz4 => write!(f, "lz4"),
60            Algorithm::Zstd => write!(f, "zstd"),
61            Algorithm::Lzma => write!(f, "lzma"),
62        }
63    }
64}
65
66/// Data access patterns for algorithm selection
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum AccessPattern {
69    /// Frequently accessed data - prioritize decompression speed
70    Hot,
71    /// Occasionally accessed data - balance speed and compression
72    Warm,
73    /// Rarely accessed data - prioritize compression ratio
74    Cold,
75}
76
77/// Compressed data container
78#[derive(Debug, Clone, Serialize, Deserialize)]
79pub struct CompressedData {
80    /// Compressed data bytes
81    pub data: Vec<u8>,
82    /// Original uncompressed size
83    pub original_size: usize,
84    /// Algorithm used for compression
85    pub algorithm: Algorithm,
86}
87
88/// Compression performance metrics
89pub struct CompressionMetrics {
90    total_bytes_in: AtomicU64,
91    total_bytes_out: AtomicU64,
92    compression_time_ns: AtomicU64,
93    decompression_time_ns: AtomicU64,
94    compression_count: AtomicU64,
95    decompression_count: AtomicU64,
96}
97
98impl Default for CompressionMetrics {
99    fn default() -> Self {
100        Self::new()
101    }
102}
103
104impl CompressionMetrics {
105    /// Create new metrics tracker
106    pub fn new() -> Self {
107        Self {
108            total_bytes_in: AtomicU64::new(0),
109            total_bytes_out: AtomicU64::new(0),
110            compression_time_ns: AtomicU64::new(0),
111            decompression_time_ns: AtomicU64::new(0),
112            compression_count: AtomicU64::new(0),
113            decompression_count: AtomicU64::new(0),
114        }
115    }
116
117    /// Record compression operation
118    pub fn record_compression(
119        &self,
120        input_size: usize,
121        output_size: usize,
122        _algorithm: Algorithm,
123        elapsed_ns: u64,
124    ) {
125        self.total_bytes_in
126            .fetch_add(input_size as u64, Ordering::Relaxed);
127        self.total_bytes_out
128            .fetch_add(output_size as u64, Ordering::Relaxed);
129        self.compression_time_ns
130            .fetch_add(elapsed_ns, Ordering::Relaxed);
131        self.compression_count.fetch_add(1, Ordering::Relaxed);
132    }
133
134    /// Record decompression operation
135    pub fn record_decompression(&self, elapsed_ns: u64) {
136        self.decompression_time_ns
137            .fetch_add(elapsed_ns, Ordering::Relaxed);
138        self.decompression_count.fetch_add(1, Ordering::Relaxed);
139    }
140
141    /// Get compression ratio
142    pub fn compression_ratio(&self) -> f64 {
143        let bytes_in = self.total_bytes_in.load(Ordering::Relaxed) as f64;
144        let bytes_out = self.total_bytes_out.load(Ordering::Relaxed) as f64;
145        if bytes_in > 0.0 {
146            1.0 - (bytes_out / bytes_in)
147        } else {
148            0.0
149        }
150    }
151
152    /// Get average compression throughput in MB/s
153    pub fn compression_throughput_mbps(&self) -> f64 {
154        let bytes = self.total_bytes_in.load(Ordering::Relaxed) as f64;
155        let time_sec = self.compression_time_ns.load(Ordering::Relaxed) as f64 / 1_000_000_000.0;
156        if time_sec > 0.0 {
157            (bytes / 1_000_000.0) / time_sec
158        } else {
159            0.0
160        }
161    }
162
163    /// Get average decompression throughput in MB/s
164    pub fn decompression_throughput_mbps(&self) -> f64 {
165        let bytes = self.total_bytes_out.load(Ordering::Relaxed) as f64;
166        let time_sec = self.decompression_time_ns.load(Ordering::Relaxed) as f64 / 1_000_000_000.0;
167        if time_sec > 0.0 {
168            (bytes / 1_000_000.0) / time_sec
169        } else {
170            0.0
171        }
172    }
173}
174
175impl CompressionStrategy {
176    /// Create a new compression strategy
177    pub fn new(config: CompressionConfig) -> Self {
178        Self {
179            config,
180            profiler: Arc::new(Profiler::new()),
181            metrics: Arc::new(CompressionMetrics::new()),
182        }
183    }
184
185    /// Auto-select compression algorithm based on data characteristics
186    pub fn select_algorithm(&self, data: &[u8], access_pattern: AccessPattern) -> Algorithm {
187        if !self.config.auto_select {
188            return self.config.default_algorithm;
189        }
190
191        // Criteria 1: Data size - Small data won't benefit from compression
192        if data.len() < self.config.compression_threshold_bytes {
193            return Algorithm::None;
194        }
195
196        // Criteria 2: Compressibility - Random data won't compress well
197        let compressibility = self.estimate_compressibility(data);
198        if compressibility < 0.1 {
199            // Nearly random data, compression won't help
200            return Algorithm::None;
201        }
202
203        // Criteria 3: Access pattern determines priority (speed vs ratio)
204        match access_pattern {
205            AccessPattern::Hot => Algorithm::Lz4,   // Fast decompression
206            AccessPattern::Warm => Algorithm::Zstd, // Balanced
207            AccessPattern::Cold => Algorithm::Lzma, // Best ratio
208        }
209    }
210
211    /// Compress data with selected or auto-selected algorithm
212    pub fn compress(&self, data: &[u8]) -> Result<CompressedData> {
213        self.compress_with_pattern(data, AccessPattern::Warm)
214    }
215
216    /// Compress data with specific access pattern
217    pub fn compress_with_pattern(
218        &self,
219        data: &[u8],
220        access_pattern: AccessPattern,
221    ) -> Result<CompressedData> {
222        let algorithm = self.select_algorithm(data, access_pattern);
223
224        let start = std::time::Instant::now();
225        let compressed = match algorithm {
226            Algorithm::None => data.to_vec(),
227            Algorithm::Lz4 => self.compress_lz4(data)?,
228            Algorithm::Zstd => self.compress_zstd(data)?,
229            Algorithm::Lzma => self.compress_lzma(data)?,
230        };
231        let elapsed_ns = start.elapsed().as_nanos() as u64;
232
233        // Update metrics
234        self.metrics
235            .record_compression(data.len(), compressed.len(), algorithm, elapsed_ns);
236
237        Ok(CompressedData {
238            data: compressed,
239            original_size: data.len(),
240            algorithm,
241        })
242    }
243
244    /// Decompress data
245    pub fn decompress(&self, compressed: &CompressedData) -> Result<Vec<u8>> {
246        let start = std::time::Instant::now();
247
248        let result = match compressed.algorithm {
249            Algorithm::None => Ok(compressed.data.clone()),
250            Algorithm::Lz4 => self.decompress_lz4(&compressed.data, compressed.original_size),
251            Algorithm::Zstd => self.decompress_zstd(&compressed.data, compressed.original_size),
252            Algorithm::Lzma => self.decompress_lzma(&compressed.data),
253        };
254
255        let elapsed_ns = start.elapsed().as_nanos() as u64;
256        self.metrics.record_decompression(elapsed_ns);
257
258        result
259    }
260
261    /// Estimate compressibility using Shannon entropy
262    /// Returns value between 0.0 (random) and 1.0 (highly compressible)
263    pub fn estimate_compressibility(&self, data: &[u8]) -> f64 {
264        if data.is_empty() {
265            return 0.0;
266        }
267
268        // Count byte frequencies
269        let mut counts = [0u32; 256];
270        for &byte in data {
271            counts[byte as usize] += 1;
272        }
273
274        // Calculate Shannon entropy
275        let len = data.len() as f64;
276        let mut entropy = 0.0;
277        for &count in &counts {
278            if count > 0 {
279                let p = count as f64 / len;
280                entropy -= p * p.log2();
281            }
282        }
283
284        // Normalize: 8 bits = random (max entropy), 0 bits = constant (min entropy)
285        // Return compressibility score (inverse of normalized entropy)
286        1.0 - (entropy / 8.0)
287    }
288
289    // LZ4 implementation using oxiarc_lz4
290    fn compress_lz4(&self, data: &[u8]) -> Result<Vec<u8>> {
291        oxiarc_lz4::compress(data)
292            .map_err(|e| ClusterError::Compression(format!("LZ4 compression failed: {e}")))
293    }
294
295    fn decompress_lz4(&self, data: &[u8], _expected_size: usize) -> Result<Vec<u8>> {
296        oxiarc_lz4::decompress(data, 100 * 1024 * 1024)
297            .map_err(|e| ClusterError::Compression(format!("LZ4 decompression failed: {e}")))
298    }
299
300    // Zstd implementation
301    fn compress_zstd(&self, data: &[u8]) -> Result<Vec<u8>> {
302        oxiarc_zstd::encode_all(data, 3)
303            .map_err(|e| ClusterError::Compression(format!("Zstd compression failed: {e}")))
304    }
305
306    fn decompress_zstd(&self, data: &[u8], _expected_size: usize) -> Result<Vec<u8>> {
307        // Use expected_size * 4 as buffer size hint (can grow if needed)
308        oxiarc_zstd::decode_all(data)
309            .map_err(|e| ClusterError::Compression(format!("Zstd decompression failed: {e}")))
310    }
311
312    // LZMA implementation using oxiarc-lzma (Pure Rust, replaces xz2/lzma-sys).
313    // Uses the self-describing LZMA stream (header carries props + dict size +
314    // uncompressed length), so `compress_bytes`/`decompress_bytes` round-trip
315    // without the caller tracking the original size.
316    fn compress_lzma(&self, data: &[u8]) -> Result<Vec<u8>> {
317        oxiarc_lzma::compress_bytes(data)
318            .map_err(|e| ClusterError::Compression(format!("LZMA compression failed: {e}")))
319    }
320
321    fn decompress_lzma(&self, data: &[u8]) -> Result<Vec<u8>> {
322        oxiarc_lzma::decompress_bytes(data)
323            .map_err(|e| ClusterError::Compression(format!("LZMA decompression failed: {e}")))
324    }
325
326    /// Get compression metrics
327    pub fn metrics(&self) -> &Arc<CompressionMetrics> {
328        &self.metrics
329    }
330
331    /// Get configuration
332    pub fn config(&self) -> &CompressionConfig {
333        &self.config
334    }
335}
336
337#[cfg(test)]
338mod tests {
339    use super::*;
340
341    #[test]
342    fn test_compression_strategy_creation() {
343        let config = CompressionConfig::default();
344        let strategy = CompressionStrategy::new(config);
345        assert!(strategy.config().auto_select);
346    }
347
348    #[test]
349    fn test_algorithm_selection_small_data() {
350        let config = CompressionConfig {
351            default_algorithm: Algorithm::Zstd,
352            auto_select: true,
353            compression_threshold_bytes: 1024,
354        };
355        let strategy = CompressionStrategy::new(config);
356
357        // Small data should not be compressed
358        let small_data = vec![0u8; 512];
359        let algorithm = strategy.select_algorithm(&small_data, AccessPattern::Warm);
360        assert_eq!(algorithm, Algorithm::None);
361    }
362
363    #[test]
364    fn test_algorithm_selection_by_pattern() {
365        let config = CompressionConfig::default();
366        let strategy = CompressionStrategy::new(config);
367
368        let data = vec![65u8; 10000]; // Highly compressible data
369
370        let hot_algo = strategy.select_algorithm(&data, AccessPattern::Hot);
371        assert_eq!(hot_algo, Algorithm::Lz4);
372
373        let warm_algo = strategy.select_algorithm(&data, AccessPattern::Warm);
374        assert_eq!(warm_algo, Algorithm::Zstd);
375
376        let cold_algo = strategy.select_algorithm(&data, AccessPattern::Cold);
377        assert_eq!(cold_algo, Algorithm::Lzma);
378    }
379
380    #[test]
381    fn test_compressibility_estimation() {
382        let config = CompressionConfig::default();
383        let strategy = CompressionStrategy::new(config);
384
385        // Highly compressible data (all same byte)
386        let compressible = vec![42u8; 1000];
387        let score1 = strategy.estimate_compressibility(&compressible);
388        assert!(score1 > 0.9, "Expected high compressibility score");
389
390        // Random data (less compressible)
391        use scirs2_core::random::Random;
392        let mut rng = Random::seed(
393            std::time::SystemTime::now()
394                .duration_since(std::time::UNIX_EPOCH)
395                .map_or(0, |d| d.as_secs()),
396        );
397        let random_data: Vec<u8> = (0..1000).map(|_| rng.random_range(0..256) as u8).collect();
398        let score2 = strategy.estimate_compressibility(&random_data);
399        assert!(
400            score2 < 0.2,
401            "Expected low compressibility score for random data"
402        );
403    }
404
405    #[test]
406    fn test_lz4_round_trip() {
407        let config = CompressionConfig {
408            default_algorithm: Algorithm::Lz4,
409            auto_select: false,
410            compression_threshold_bytes: 0,
411        };
412        let strategy = CompressionStrategy::new(config);
413
414        let original = b"Hello, world! This is a test string for LZ4 compression.".repeat(100);
415        let compressed = strategy.compress(&original).expect("Compression failed");
416        assert!(compressed.data.len() < original.len());
417        assert_eq!(compressed.algorithm, Algorithm::Lz4);
418
419        let decompressed = strategy
420            .decompress(&compressed)
421            .expect("Decompression failed");
422        assert_eq!(decompressed, original);
423    }
424
425    #[test]
426    fn test_zstd_round_trip() {
427        let config = CompressionConfig {
428            default_algorithm: Algorithm::Zstd,
429            auto_select: false,
430            compression_threshold_bytes: 0,
431        };
432        let strategy = CompressionStrategy::new(config);
433
434        let original = b"Hello, world! This is a test string for Zstd compression.".repeat(100);
435        let compressed = strategy.compress(&original).expect("Compression failed");
436        assert!(compressed.data.len() < original.len());
437        assert_eq!(compressed.algorithm, Algorithm::Zstd);
438
439        let decompressed = strategy
440            .decompress(&compressed)
441            .expect("Decompression failed");
442        assert_eq!(decompressed, original);
443    }
444
445    #[test]
446    fn test_lzma_round_trip() {
447        let config = CompressionConfig {
448            default_algorithm: Algorithm::Lzma,
449            auto_select: false,
450            compression_threshold_bytes: 0,
451        };
452        let strategy = CompressionStrategy::new(config);
453
454        let original = b"Hello, world! This is a test string for LZMA compression.".repeat(100);
455        let compressed = strategy.compress(&original).expect("Compression failed");
456        assert!(compressed.data.len() < original.len());
457        assert_eq!(compressed.algorithm, Algorithm::Lzma);
458
459        let decompressed = strategy
460            .decompress(&compressed)
461            .expect("Decompression failed");
462        assert_eq!(decompressed, original);
463    }
464
465    // Exercises the Pure Rust oxiarc-lzma path on small/edge-case inputs that
466    // hit different LZMA-stream header branches than the large repetitive case
467    // in `test_lzma_round_trip`.
468    #[test]
469    fn test_lzma_round_trip_small_and_edge_inputs() {
470        let config = CompressionConfig {
471            default_algorithm: Algorithm::Lzma,
472            auto_select: false,
473            compression_threshold_bytes: 0,
474        };
475        let strategy = CompressionStrategy::new(config);
476
477        let cases: &[&[u8]] = &[b"", b"a", b"abc", b"The quick brown fox.", &[0xABu8; 33]];
478        for original in cases {
479            let compressed = strategy
480                .compress(original)
481                .expect("LZMA compression failed");
482            assert_eq!(compressed.algorithm, Algorithm::Lzma);
483            let decompressed = strategy
484                .decompress(&compressed)
485                .expect("LZMA decompression failed");
486            assert_eq!(
487                decompressed.as_slice(),
488                *original,
489                "LZMA round-trip failed for {}-byte input",
490                original.len()
491            );
492        }
493    }
494
495    #[test]
496    fn test_compression_metrics() {
497        let config = CompressionConfig::default();
498        let strategy = CompressionStrategy::new(config);
499
500        let original = b"Test data for metrics".repeat(100);
501        let _compressed = strategy.compress(&original).expect("Compression failed");
502
503        let metrics = strategy.metrics();
504        assert!(metrics.compression_ratio() > 0.0);
505        assert!(metrics.compression_throughput_mbps() > 0.0);
506    }
507
508    #[test]
509    fn test_none_algorithm() {
510        let config = CompressionConfig {
511            default_algorithm: Algorithm::None,
512            auto_select: false,
513            compression_threshold_bytes: 0,
514        };
515        let strategy = CompressionStrategy::new(config);
516
517        let original = b"Test data";
518        let compressed = strategy.compress(original).expect("Compression failed");
519        assert_eq!(compressed.data, original);
520        assert_eq!(compressed.algorithm, Algorithm::None);
521
522        let decompressed = strategy
523            .decompress(&compressed)
524            .expect("Decompression failed");
525        assert_eq!(decompressed, original);
526    }
527}