linkrs-storage 0.1.0

Storage engine with CSR and memory-mapped containers
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
//! Freeze Statistics Collector
//!
//! Collects metrics about single-segment CSR compaction ("freeze")
//! operations and provides configuration for freeze decision-making.
//!
//! Does NOT execute freezing — that's handled by GraphStorageContext
//! via trigger_background_freeze() method.
//!
//! ## Design
//!
//! BackgroundFreezeManager provides:
//! - Decision support via FreezeDecisionEngine (threshold-based should_freeze)
//! - Statistics collection (record_freeze, record_delta_size)
//!
//! Actual freezing is triggered by:
//! - GraphStorageContext::trigger_background_freeze() during maintenance
//! - Checkpoint operations before persistence
//! - HTTP API endpoint for manual triggering
//!
//! ## Example
//!
//! ```ignore
//! let config = FreezeConfig::production_small();
//! let manager = BackgroundFreezeManager::from_config(config);
//!
//! let input = FreezeDecisionInput {
//!     delta_edge_count: table.delta_edge_count(),
//!     delta_memory_bytes: table.used_memory_size() as u64,
//!     deletion_ratio: table.deletion_stats().deletion_ratio(),
//! };
//!
//! if manager.should_freeze_with_stats(&input) {
//!     // Call trigger_background_freeze() externally
//! }
//! ```

use std::sync::Arc;
use std::time::Instant;

use parking_lot::Mutex;

use super::config::{FreezeConfig, FreezeDecisionEngine, FreezeDecisionInput};

/// Automatic freeze statistics recording guard
///
/// When dropped, automatically records freeze completion in the manager.
/// Prevents missed statistics and ensures consistent tracking.
///
/// ## Example
///
/// ```ignore
/// let guard = FreezeGuard::new(manager.clone());
/// let edges_frozen = perform_freeze().await?;
/// guard.record_edges(edges_frozen);
/// // On drop, automatically records the freeze
/// ```
pub struct FreezeGuard {
    manager: Arc<BackgroundFreezeManager>,
    start_time: Instant,
    edges_frozen: u64,
    completed: bool,
}

impl FreezeGuard {
    /// Create a new freeze guard that will record statistics when dropped
    pub fn new(manager: Arc<BackgroundFreezeManager>) -> Self {
        Self {
            manager,
            start_time: Instant::now(),
            edges_frozen: 0,
            completed: false,
        }
    }

    /// Record the number of edges that were frozen
    pub fn record_edges(&mut self, count: u64) {
        self.edges_frozen = count;
        self.completed = true;
    }

    /// Manually complete the freeze (called automatically on drop)
    pub fn finish(&mut self) {
        if self.completed {
            let duration_ms = self.start_time.elapsed().as_millis() as u64;
            self.manager.record_freeze(self.edges_frozen, duration_ms);
            log::info!(
                "Freeze completed: {} edges in {}ms",
                self.edges_frozen,
                duration_ms
            );
        }
    }
}

impl Drop for FreezeGuard {
    fn drop(&mut self) {
        self.finish();
    }
}

/// Statistics about freeze operations
#[derive(Debug, Clone, Copy, Default)]
pub struct FreezeStats {
    /// Total number of freeze operations completed
    pub freeze_count: u64,
    /// Total edges frozen across all operations
    pub total_frozen_edges: u64,
    /// Duration of last freeze operation in milliseconds
    pub last_freeze_duration_ms: u64,
    /// Current mutable delta edges (unfrozen)
    pub current_delta_edges: u64,
}

/// Freeze decision information
#[derive(Debug, Clone)]
pub struct FreezeDecision {
    pub should_freeze: bool,
    pub current_delta_edges: u64,
    pub edge_threshold: u64,
    pub current_delta_memory_bytes: u64,
    pub memory_threshold_bytes: u64,
    pub freeze_reason: FreezeReason,
}

impl FreezeDecision {
    /// Get a human-readable summary of the decision, including threshold comparisons.
    pub fn summary(&self) -> String {
        let edge_pct = if self.edge_threshold > 0 {
            (self.current_delta_edges as f64 / self.edge_threshold as f64 * 100.0) as u64
        } else {
            0
        };
        let mem_pct = if self.memory_threshold_bytes > 0 {
            (self.current_delta_memory_bytes as f64 / self.memory_threshold_bytes as f64 * 100.0)
                as u64
        } else {
            0
        };
        format!(
            "FreezeDecision {{ should_freeze: {}, edges: {} ({}/{} = {}%), memory: {}MB ({}/{}MB = {}%), reason: {:?} }}",
            self.should_freeze,
            self.current_delta_edges,
            self.current_delta_edges,
            self.edge_threshold,
            edge_pct,
            self.current_delta_memory_bytes / (1024 * 1024),
            self.current_delta_memory_bytes / (1024 * 1024),
            self.memory_threshold_bytes / (1024 * 1024),
            mem_pct,
            self.freeze_reason,
        )
    }
}

/// Reason why freeze was triggered
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FreezeReason {
    None,
    EdgeCountExceeded,
    MemoryExceeded,
    DeletionExceeded,
    Both,
}

/// Freeze statistics collector and decision maker
///
/// Uses FreezeDecisionEngine for threshold-based decision making.
/// Provides decision support and metrics collection for single-segment
/// CSR compaction ("freeze") operations.
pub struct BackgroundFreezeManager {
    /// Decision engine (no trait overhead)
    decision_engine: FreezeDecisionEngine,
    /// Statistics (thread-safe for concurrent reads)
    stats: Arc<Mutex<FreezeStats>>,
}

impl BackgroundFreezeManager {
    /// Create a new freeze manager from FreezeConfig
    pub fn from_config(config: FreezeConfig) -> Self {
        let decision_engine = FreezeDecisionEngine::new(config);
        Self {
            decision_engine,
            stats: Arc::new(Mutex::new(FreezeStats::default())),
        }
    }

    /// Check if freezing should be triggered with full statistics
    pub fn should_freeze_with_stats(&self, input: &FreezeDecisionInput) -> bool {
        self.decision_engine.should_freeze(input)
    }

    /// Get detailed freeze decision
    pub fn get_freeze_decision_with_stats(&self, input: &FreezeDecisionInput) -> FreezeDecision {
        let edge_exceeded =
            input.delta_edge_count >= self.decision_engine.config.delta_edge_threshold;
        let memory_exceeded =
            input.delta_memory_bytes >= self.decision_engine.config.delta_memory_threshold_bytes;
        let deletion_exceeded =
            input.deletion_ratio >= self.decision_engine.config.deletion_threshold;

        // Deletion-driven compaction is the most informative signal: it is
        // the only trigger that fires on churn rather than size.
        let freeze_reason = if deletion_exceeded {
            FreezeReason::DeletionExceeded
        } else {
            match (edge_exceeded, memory_exceeded) {
                (true, true) => FreezeReason::Both,
                (true, false) => FreezeReason::EdgeCountExceeded,
                (false, true) => FreezeReason::MemoryExceeded,
                (false, false) => FreezeReason::None,
            }
        };

        FreezeDecision {
            should_freeze: self.should_freeze_with_stats(input),
            current_delta_edges: input.delta_edge_count,
            edge_threshold: self.decision_engine.config.delta_edge_threshold,
            current_delta_memory_bytes: input.delta_memory_bytes,
            memory_threshold_bytes: self.decision_engine.config.delta_memory_threshold_bytes,
            freeze_reason,
        }
    }

    /// Get current freeze statistics (snapshot)
    pub fn get_stats(&self) -> FreezeStats {
        *self.stats.lock()
    }

    /// Record a freeze event (called by GraphStorageContext after freezing)
    pub(crate) fn record_freeze(&self, edges_frozen: u64, duration_ms: u64) {
        let mut stats = self.stats.lock();
        stats.freeze_count += 1;
        stats.total_frozen_edges += edges_frozen;
        stats.last_freeze_duration_ms = duration_ms;
    }

    /// Record current delta size (for monitoring)
    pub(crate) fn record_delta_size(&self, delta_edges: u64) {
        let mut stats = self.stats.lock();
        stats.current_delta_edges = delta_edges;
    }

    /// Get freeze reason as string
    pub fn get_reason(&self, input: &FreezeDecisionInput) -> String {
        self.decision_engine.get_reason(input)
    }

    /// Get configuration for testing/debugging
    pub fn get_config(&self) -> &FreezeConfig {
        &self.decision_engine.config
    }
}

impl Default for BackgroundFreezeManager {
    fn default() -> Self {
        Self::from_config(FreezeConfig::default())
    }
}

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

    fn test_config() -> FreezeConfig {
        FreezeConfig {
            delta_edge_threshold: 100_000,
            delta_memory_threshold_bytes: 256 * 1024 * 1024,
            deletion_threshold: 0.5,
        }
    }

    fn input(edges: u64, mem_mb: u64, deletion_ratio: f64) -> FreezeDecisionInput {
        FreezeDecisionInput {
            delta_edge_count: edges,
            delta_memory_bytes: mem_mb * 1024 * 1024,
            deletion_ratio,
        }
    }

    #[test]
    fn test_freeze_decision_below_both_thresholds() {
        let manager = BackgroundFreezeManager::from_config(test_config());

        let decision = manager.get_freeze_decision_with_stats(&input(50_000, 100, 0.1));
        assert!(!decision.should_freeze);
        assert_eq!(decision.freeze_reason, FreezeReason::None);
    }

    #[test]
    fn test_freeze_decision_edge_count_exceeded() {
        let manager = BackgroundFreezeManager::from_config(test_config());

        let decision = manager.get_freeze_decision_with_stats(&input(150_000, 100, 0.1));
        assert!(decision.should_freeze);
        assert_eq!(decision.freeze_reason, FreezeReason::EdgeCountExceeded);
    }

    #[test]
    fn test_freeze_decision_memory_exceeded() {
        let manager = BackgroundFreezeManager::from_config(test_config());

        let decision = manager.get_freeze_decision_with_stats(&input(50_000, 300, 0.1));
        assert!(decision.should_freeze);
        assert_eq!(decision.freeze_reason, FreezeReason::MemoryExceeded);
    }

    #[test]
    fn test_freeze_decision_both_exceeded() {
        let manager = BackgroundFreezeManager::from_config(test_config());

        let decision = manager.get_freeze_decision_with_stats(&input(150_000, 300, 0.1));
        assert!(decision.should_freeze);
        assert_eq!(decision.freeze_reason, FreezeReason::Both);
    }

    #[test]
    fn test_freeze_decision_deletion_exceeded() {
        let manager = BackgroundFreezeManager::from_config(test_config());

        let decision = manager.get_freeze_decision_with_stats(&input(50_000, 100, 0.6));
        assert!(decision.should_freeze);
        assert_eq!(decision.freeze_reason, FreezeReason::DeletionExceeded);
    }

    #[test]
    fn test_should_freeze_with_stats_method() {
        let manager = BackgroundFreezeManager::default();

        assert!(!manager.should_freeze_with_stats(&input(50_000, 100, 0.1)));

        // Default config is production_small: 100K edges / 256MB / 0.2 deletions.
        assert!(manager.should_freeze_with_stats(&input(150_000, 100, 0.1)));
        assert!(manager.should_freeze_with_stats(&input(50_000, 100, 0.3)));
    }

    #[test]
    fn test_record_freeze() {
        let manager = BackgroundFreezeManager::default();

        manager.record_freeze(50_000, 100);
        let stats = manager.get_stats();
        assert_eq!(stats.freeze_count, 1);
        assert_eq!(stats.total_frozen_edges, 50_000);
        assert_eq!(stats.last_freeze_duration_ms, 100);

        manager.record_freeze(30_000, 50);
        let stats = manager.get_stats();
        assert_eq!(stats.freeze_count, 2);
        assert_eq!(stats.total_frozen_edges, 80_000);
        assert_eq!(stats.last_freeze_duration_ms, 50);
    }

    #[test]
    fn test_record_delta_size() {
        let manager = BackgroundFreezeManager::default();

        manager.record_delta_size(12_000);
        let stats = manager.get_stats();
        assert_eq!(stats.current_delta_edges, 12_000);

        manager.record_delta_size(25_000);
        let stats = manager.get_stats();
        assert_eq!(stats.current_delta_edges, 25_000);
    }

    #[test]
    fn test_manager_creation_and_stats() {
        let manager = BackgroundFreezeManager::from_config(test_config());

        let stats = manager.get_stats();
        assert_eq!(stats.freeze_count, 0);
        assert_eq!(stats.total_frozen_edges, 0);
        assert_eq!(stats.current_delta_edges, 0);
    }

    #[test]
    fn test_config_access() {
        let config = FreezeConfig::development();
        let manager = BackgroundFreezeManager::from_config(config.clone());

        let retrieved_config = manager.get_config();
        assert_eq!(retrieved_config.delta_edge_threshold, 50_000);
        assert_eq!(
            retrieved_config.delta_memory_threshold_bytes,
            128 * 1024 * 1024
        );
    }

    #[test]
    fn test_default_config() {
        let manager = BackgroundFreezeManager::default();
        let config = manager.get_config();
        assert_eq!(
            config.delta_edge_threshold, 100_000,
            "Default edge threshold should be 100K edges"
        );
        assert_eq!(
            config.delta_memory_threshold_bytes,
            256 * 1024 * 1024,
            "Default memory threshold should be 256MB"
        );
    }

    #[test]
    fn test_freeze_guard_records_automatically() {
        let manager = Arc::new(BackgroundFreezeManager::default());
        let stats_before = manager.get_stats();
        assert_eq!(stats_before.freeze_count, 0);

        // Create and use guard
        {
            let mut guard = FreezeGuard::new(manager.clone());
            guard.record_edges(50_000);
            // Guard automatically records on drop
        }

        // Verify statistics were recorded
        let stats_after = manager.get_stats();
        assert_eq!(stats_after.freeze_count, 1);
        assert_eq!(stats_after.total_frozen_edges, 50_000);
        assert!(stats_after.last_freeze_duration_ms < 1000); // Should be fast
    }

    #[test]
    fn test_freeze_guard_without_edges_does_nothing() {
        let manager = Arc::new(BackgroundFreezeManager::default());

        // Create guard but don't call record_edges
        {
            let _guard = FreezeGuard::new(manager.clone());
            // Just drop without recording
        }

        // Should not record anything if completed=false
        let stats = manager.get_stats();
        assert_eq!(stats.freeze_count, 0);
    }

    #[test]
    fn test_freeze_guard_multiple() {
        let manager = Arc::new(BackgroundFreezeManager::default());

        // First freeze
        {
            let mut guard = FreezeGuard::new(manager.clone());
            guard.record_edges(30_000);
        }

        // Second freeze
        {
            let mut guard = FreezeGuard::new(manager.clone());
            guard.record_edges(40_000);
        }

        // Verify both recorded
        let stats = manager.get_stats();
        assert_eq!(stats.freeze_count, 2);
        assert_eq!(stats.total_frozen_edges, 70_000);
    }

    #[test]
    fn test_freeze_guard_manual_finish() {
        let manager = Arc::new(BackgroundFreezeManager::default());

        let mut guard = FreezeGuard::new(manager.clone());
        guard.record_edges(50_000);
        guard.finish(); // Manual finish
                        // Guard is still dropped after this

        let stats = manager.get_stats();
        assert_eq!(stats.freeze_count, 1);
        assert_eq!(stats.total_frozen_edges, 50_000);
    }
}