term-guard 0.0.2

A Rust data validation library providing Deequ-like capabilities without Spark dependencies
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
//! Tests for incremental computation framework.

use super::*;
use crate::analyzers::basic::{CompletenessAnalyzer, MeanAnalyzer, SizeAnalyzer};
use crate::analyzers::MetricValue;
use crate::core::ValidationContext;
use datafusion::arrow::array::{Float64Array, Int64Array, StringArray};
use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::prelude::*;
use std::sync::Arc;
use tempfile::TempDir;

/// Creates a test session context with sample data.
async fn create_test_context(rows: Vec<(i64, Option<f64>, Option<String>)>) -> SessionContext {
    let ctx = SessionContext::new();

    let schema = Arc::new(Schema::new(vec![
        Field::new("id", DataType::Int64, false),
        Field::new("value", DataType::Float64, true),
        Field::new("category", DataType::Utf8, true),
    ]));

    let mut id_values = Vec::new();
    let mut value_values = Vec::new();
    let mut category_values = Vec::new();

    for (id, value, category) in rows {
        id_values.push(id);
        value_values.push(value);
        category_values.push(category);
    }

    let batch = RecordBatch::try_new(
        schema,
        vec![
            Arc::new(Int64Array::from(id_values)),
            Arc::new(Float64Array::from(value_values)),
            Arc::new(StringArray::from(category_values)),
        ],
    )
    .unwrap();

    ctx.register_batch("data", batch).unwrap();
    ctx
}

#[tokio::test]
async fn test_incremental_runner_single_partition() {
    use crate::core::CURRENT_CONTEXT;

    // Set up validation context
    let validation_ctx = ValidationContext::new("data");

    CURRENT_CONTEXT
        .scope(validation_ctx, async {
            // Create temporary directory for state storage
            let temp_dir = TempDir::new().unwrap();
            let state_store = FileSystemStateStore::new(temp_dir.path()).unwrap();

            // Create runner with size analyzer
            let runner = IncrementalAnalysisRunner::new(Box::new(state_store))
                .add_analyzer(SizeAnalyzer::new());

            // Create context with initial data
            let ctx = create_test_context(vec![
                (1, Some(10.0), Some("A".to_string())),
                (2, Some(20.0), Some("B".to_string())),
                (3, None, Some("A".to_string())),
            ])
            .await;

            // Analyze first partition
            let result = runner.analyze_partition(&ctx, "2024-01-01").await.unwrap();

            // Verify size metric
            let size_metric = result.get_metric("size").expect("Size metric not found");
            if let MetricValue::Long(size) = size_metric {
                assert_eq!(*size, 3);
            } else {
                panic!("Expected Long metric for size");
            }

            // Verify state was persisted
            let partitions = runner.list_partitions().await.unwrap();
            assert_eq!(partitions.len(), 1);
            assert_eq!(partitions[0], "2024-01-01");
        })
        .await;
}

#[tokio::test]
async fn test_incremental_runner_merge_states() {
    use crate::core::CURRENT_CONTEXT;

    // Set up validation context
    let validation_ctx = ValidationContext::new("data");

    CURRENT_CONTEXT
        .scope(validation_ctx, async {
            // Create temporary directory for state storage
            let temp_dir = TempDir::new().unwrap();
            let state_store = FileSystemStateStore::new(temp_dir.path()).unwrap();

            // Create runner with multiple analyzers
            let runner = IncrementalAnalysisRunner::new(Box::new(state_store))
                .add_analyzer(SizeAnalyzer::new())
                .add_analyzer(MeanAnalyzer::new("value"));

            // Analyze first partition
            let ctx1 = create_test_context(vec![
                (1, Some(10.0), Some("A".to_string())),
                (2, Some(20.0), Some("B".to_string())),
            ])
            .await;
            runner.analyze_partition(&ctx1, "2024-01-01").await.unwrap();

            // Analyze second partition
            let ctx2 = create_test_context(vec![
                (3, Some(30.0), Some("A".to_string())),
                (4, Some(40.0), Some("C".to_string())),
            ])
            .await;
            runner.analyze_partition(&ctx2, "2024-01-02").await.unwrap();

            // Merge partitions
            let partitions = vec!["2024-01-01".to_string(), "2024-01-02".to_string()];
            let merged_result = runner.analyze_partitions(&partitions).await.unwrap();

            // Verify merged size
            let size_metric = merged_result
                .get_metric("size")
                .expect("Size metric not found");
            if let MetricValue::Long(size) = size_metric {
                assert_eq!(*size, 4); // Total of 4 rows across both partitions
            } else {
                panic!("Expected Long metric for size");
            }

            // Verify merged mean
            let mean_metric = merged_result
                .get_metric("mean.value")
                .expect("Mean metric not found");
            if let MetricValue::Double(mean) = mean_metric {
                assert!((mean - 25.0).abs() < 0.001); // (10+20+30+40)/4 = 25
            } else {
                panic!("Expected Double metric for mean");
            }
        })
        .await;
}

#[tokio::test]
async fn test_incremental_update() {
    use crate::core::CURRENT_CONTEXT;

    // Set up validation context
    let validation_ctx = ValidationContext::new("data");

    CURRENT_CONTEXT
        .scope(validation_ctx, async {
            // Create temporary directory for state storage
            let temp_dir = TempDir::new().unwrap();
            let state_store = FileSystemStateStore::new(temp_dir.path()).unwrap();

            // Create runner with size analyzer
            let runner = IncrementalAnalysisRunner::new(Box::new(state_store))
                .add_analyzer(SizeAnalyzer::new());

            // Initial analysis
            let ctx1 = create_test_context(vec![
                (1, Some(10.0), Some("A".to_string())),
                (2, Some(20.0), Some("B".to_string())),
            ])
            .await;
            runner.analyze_partition(&ctx1, "daily").await.unwrap();

            // Incremental update with new data
            let ctx2 = create_test_context(vec![
                (3, Some(30.0), Some("C".to_string())),
                (4, Some(40.0), Some("D".to_string())),
                (5, None, Some("E".to_string())),
            ])
            .await;
            let updated_result = runner.analyze_incremental(&ctx2, "daily").await.unwrap();

            // Verify updated size includes both old and new data
            let size_metric = updated_result
                .get_metric("size")
                .expect("Size metric not found");
            if let MetricValue::Long(size) = size_metric {
                assert_eq!(*size, 5); // 2 original + 3 new = 5 total
            } else {
                panic!("Expected Long metric for size");
            }
        })
        .await;
}

#[tokio::test]
async fn test_error_handling_with_config() {
    use crate::core::CURRENT_CONTEXT;

    // Set up validation context
    let validation_ctx = ValidationContext::new("data");

    CURRENT_CONTEXT
        .scope(validation_ctx, async {
            // Create temporary directory for state storage
            let temp_dir = TempDir::new().unwrap();
            let state_store = FileSystemStateStore::new(temp_dir.path()).unwrap();

            // Create runner with fail_fast = false
            let config = IncrementalConfig {
                fail_fast: false,
                save_empty_states: false,
                max_merge_batch_size: 100,
            };

            let runner = IncrementalAnalysisRunner::with_config(Box::new(state_store), config)
                .add_analyzer(SizeAnalyzer::new())
                .add_analyzer(CompletenessAnalyzer::new("nonexistent_column")); // This will fail

            let ctx = create_test_context(vec![(1, Some(10.0), Some("A".to_string()))]).await;

            // Should not fail completely due to fail_fast = false
            let result = runner.analyze_partition(&ctx, "test").await.unwrap();

            // Should have size metric
            assert!(result.get_metric("size").is_some());

            // Should have recorded an error for completeness
            assert!(result.has_errors());
            assert_eq!(result.errors().len(), 1);
        })
        .await;
}

#[tokio::test]
async fn test_empty_state_handling() {
    use crate::core::CURRENT_CONTEXT;

    // Set up validation context
    let validation_ctx = ValidationContext::new("data");

    CURRENT_CONTEXT
        .scope(validation_ctx, async {
            // Create temporary directory for state storage
            let temp_dir = TempDir::new().unwrap();
            let state_store = FileSystemStateStore::new(temp_dir.path()).unwrap();

            // Create runner with save_empty_states = true
            let config = IncrementalConfig {
                fail_fast: true,
                save_empty_states: true,
                max_merge_batch_size: 100,
            };

            let runner = IncrementalAnalysisRunner::with_config(Box::new(state_store), config)
                .add_analyzer(SizeAnalyzer::new());

            // Analyze empty dataset
            let ctx = create_test_context(vec![]).await;
            let result = runner.analyze_partition(&ctx, "empty").await.unwrap();

            // Should have size metric of 0
            let size_metric = result.get_metric("size").expect("Size metric not found");
            if let MetricValue::Long(size) = size_metric {
                assert_eq!(*size, 0);
            }

            // State should be saved even though it's empty
            let partitions = runner.list_partitions().await.unwrap();
            assert_eq!(partitions.len(), 1);
        })
        .await;
}

#[tokio::test]
async fn test_batch_processing() {
    use crate::core::CURRENT_CONTEXT;

    // Set up validation context
    let validation_ctx = ValidationContext::new("data");

    CURRENT_CONTEXT
        .scope(validation_ctx, async {
            // Create temporary directory for state storage
            let temp_dir = TempDir::new().unwrap();
            let state_store = FileSystemStateStore::new(temp_dir.path()).unwrap();

            // Create runner with small batch size
            let config = IncrementalConfig {
                fail_fast: true,
                save_empty_states: false,
                max_merge_batch_size: 2, // Process only 2 partitions at a time
            };

            let runner = IncrementalAnalysisRunner::with_config(Box::new(state_store), config)
                .add_analyzer(SizeAnalyzer::new());

            // Create multiple partitions
            for i in 1..=5 {
                let ctx =
                    create_test_context(vec![(i, Some(i as f64 * 10.0), Some("A".to_string()))])
                        .await;
                runner
                    .analyze_partition(&ctx, &format!("partition-{i}"))
                    .await
                    .unwrap();
            }

            // Merge all partitions (should be processed in batches of 2)
            let partitions: Vec<String> = (1..=5).map(|i| format!("partition-{i}")).collect();
            let merged_result = runner.analyze_partitions(&partitions).await.unwrap();

            // Verify total size
            let size_metric = merged_result
                .get_metric("size")
                .expect("Size metric not found");
            if let MetricValue::Long(size) = size_metric {
                assert_eq!(*size, 5); // Total of 5 rows (one per partition)
            }
        })
        .await;
}

#[tokio::test]
async fn test_partition_management() {
    use crate::core::CURRENT_CONTEXT;

    // Set up validation context
    let validation_ctx = ValidationContext::new("data");

    CURRENT_CONTEXT
        .scope(validation_ctx, async {
            // Create temporary directory for state storage
            let temp_dir = TempDir::new().unwrap();
            let state_store = FileSystemStateStore::new(temp_dir.path()).unwrap();

            let runner = IncrementalAnalysisRunner::new(Box::new(state_store))
                .add_analyzer(SizeAnalyzer::new());

            // Create partitions
            for i in 1..=3 {
                let ctx =
                    create_test_context(vec![(i, Some(i as f64), Some("A".to_string()))]).await;
                runner
                    .analyze_partition(&ctx, &format!("2024-01-{i:02}"))
                    .await
                    .unwrap();
            }

            // List partitions
            let partitions = runner.list_partitions().await.unwrap();
            assert_eq!(partitions.len(), 3);
            assert_eq!(partitions[0], "2024-01-01");
            assert_eq!(partitions[1], "2024-01-02");
            assert_eq!(partitions[2], "2024-01-03");

            // Delete a partition
            runner.delete_partition("2024-01-02").await.unwrap();

            // Verify deletion
            let remaining = runner.list_partitions().await.unwrap();
            assert_eq!(remaining.len(), 2);
            assert!(!remaining.contains(&"2024-01-02".to_string()));
        })
        .await;
}

#[tokio::test]
async fn test_analyzer_count() {
    let temp_dir = TempDir::new().unwrap();
    let state_store = FileSystemStateStore::new(temp_dir.path()).unwrap();

    let runner = IncrementalAnalysisRunner::new(Box::new(state_store))
        .add_analyzer(SizeAnalyzer::new())
        .add_analyzer(MeanAnalyzer::new("value"))
        .add_analyzer(CompletenessAnalyzer::new("value"));

    assert_eq!(runner.analyzer_count(), 3);
}

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

    #[tokio::test]
    async fn test_filesystem_state_store_basic() {
        let temp_dir = TempDir::new().unwrap();
        let store = FileSystemStateStore::new(temp_dir.path()).unwrap();

        // Create test state
        let mut state_map = StateMap::new();
        state_map.insert("analyzer1".to_string(), vec![1, 2, 3]);
        state_map.insert("analyzer2".to_string(), vec![4, 5, 6]);

        // Save state
        store
            .save_state("partition1", state_map.clone())
            .await
            .unwrap();

        // Load state
        let loaded = store.load_state("partition1").await.unwrap();
        assert_eq!(loaded.len(), 2);
        assert_eq!(loaded.get("analyzer1").unwrap(), &vec![1, 2, 3]);
        assert_eq!(loaded.get("analyzer2").unwrap(), &vec![4, 5, 6]);
    }

    #[tokio::test]
    async fn test_filesystem_state_store_batch_load() {
        let temp_dir = TempDir::new().unwrap();
        let store = FileSystemStateStore::new(temp_dir.path()).unwrap();

        // Save states for multiple partitions
        for i in 1..=3 {
            let mut state_map = StateMap::new();
            state_map.insert("analyzer".to_string(), vec![i]);
            store
                .save_state(&format!("partition{i}"), state_map)
                .await
                .unwrap();
        }

        // Batch load
        let partitions = vec![
            "partition1".to_string(),
            "partition2".to_string(),
            "partition3".to_string(),
        ];
        let batch_result = store.load_states_batch(&partitions).await.unwrap();

        assert_eq!(batch_result.len(), 3);
        assert_eq!(
            batch_result
                .get("partition1")
                .unwrap()
                .get("analyzer")
                .unwrap(),
            &vec![1]
        );
        assert_eq!(
            batch_result
                .get("partition2")
                .unwrap()
                .get("analyzer")
                .unwrap(),
            &vec![2]
        );
        assert_eq!(
            batch_result
                .get("partition3")
                .unwrap()
                .get("analyzer")
                .unwrap(),
            &vec![3]
        );
    }

    #[tokio::test]
    async fn test_filesystem_state_store_nonexistent() {
        let temp_dir = TempDir::new().unwrap();
        let store = FileSystemStateStore::new(temp_dir.path()).unwrap();

        // Load nonexistent partition
        let result = store.load_state("nonexistent").await.unwrap();
        assert!(result.is_empty());
    }

    #[tokio::test]
    async fn test_filesystem_state_store_delete() {
        let temp_dir = TempDir::new().unwrap();
        let store = FileSystemStateStore::new(temp_dir.path()).unwrap();

        // Save state
        let mut state_map = StateMap::new();
        state_map.insert("analyzer".to_string(), vec![1, 2, 3]);
        store.save_state("to_delete", state_map).await.unwrap();

        // Verify it exists
        let partitions = store.list_partitions().await.unwrap();
        assert!(partitions.contains(&"to_delete".to_string()));

        // Delete it
        store.delete_partition("to_delete").await.unwrap();

        // Verify deletion
        let partitions = store.list_partitions().await.unwrap();
        assert!(!partitions.contains(&"to_delete".to_string()));
    }
}