llm-optimizer-processor 0.1.1

Data processing and transformation pipeline
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
//! Integration tests for Enterprise Redis Backend
//!
//! These tests require a running Redis instance on localhost:6379
//! Run with: cargo test --test redis_enterprise_integration -- --ignored

use processor::state::{
    BackendStats, CompressionAlgorithm, EnterpriseRedisBackend, EnterpriseRedisConfig,
    RedisMode, StateBackend,
};
use std::time::Duration;
use tokio::time::sleep;

/// Helper to create test backend
async fn create_test_backend(compression: CompressionAlgorithm) -> Option<EnterpriseRedisBackend> {
    let config = EnterpriseRedisConfig::builder()
        .mode(RedisMode::Standalone {
            url: "redis://localhost:6379".to_string(),
        })
        .key_prefix("test:enterprise:")
        .compression(compression)
        .compression_threshold(100)
        .enable_metrics(true)
        .enable_circuit_breaker(true)
        .slow_query_log(true, Duration::from_millis(50))
        .build()
        .ok()?;

    match EnterpriseRedisBackend::new(config).await {
        Ok(backend) => {
            // Clean up any existing test data
            let _ = backend.clear().await;
            Some(backend)
        }
        Err(e) => {
            eprintln!("Failed to create backend: {}", e);
            None
        }
    }
}

#[tokio::test]
#[ignore]
async fn test_basic_crud_operations() {
    let backend = create_test_backend(CompressionAlgorithm::None)
        .await
        .expect("Redis not available");

    // Create
    backend.put(b"test_key", b"test_value").await.unwrap();

    // Read
    let value = backend.get(b"test_key").await.unwrap();
    assert_eq!(value, Some(b"test_value".to_vec()));

    // Update
    backend.put(b"test_key", b"new_value").await.unwrap();
    let value = backend.get(b"test_key").await.unwrap();
    assert_eq!(value, Some(b"new_value".to_vec()));

    // Delete
    backend.delete(b"test_key").await.unwrap();
    let value = backend.get(b"test_key").await.unwrap();
    assert_eq!(value, None);
}

#[tokio::test]
#[ignore]
async fn test_lz4_compression() {
    let backend = create_test_backend(CompressionAlgorithm::Lz4)
        .await
        .expect("Redis not available");

    // Create large data that will benefit from compression
    let large_value = vec![b'x'; 10000];
    backend.put(b"large_key", &large_value).await.unwrap();

    // Verify we can retrieve it correctly
    let retrieved = backend.get(b"large_key").await.unwrap().unwrap();
    assert_eq!(retrieved, large_value);

    // Check compression stats
    let stats = backend.stats().await;
    assert!(stats.bytes_compressed > 0);
    assert!(stats.bytes_compressed < stats.bytes_written);

    println!("Compression ratio: {:.2}x",
        stats.bytes_written as f64 / stats.bytes_compressed as f64);
}

#[tokio::test]
#[ignore]
async fn test_snappy_compression() {
    let backend = create_test_backend(CompressionAlgorithm::Snappy)
        .await
        .expect("Redis not available");

    let data = b"Hello, World! ".repeat(100);
    backend.put(b"snappy_key", &data).await.unwrap();

    let retrieved = backend.get(b"snappy_key").await.unwrap().unwrap();
    assert_eq!(retrieved, data);
}

#[tokio::test]
#[ignore]
async fn test_zstd_compression() {
    let backend = create_test_backend(CompressionAlgorithm::Zstd)
        .await
        .expect("Redis not available");

    let data = b"Zstandard compression test data. ".repeat(100);
    backend.put(b"zstd_key", &data).await.unwrap();

    let retrieved = backend.get(b"zstd_key").await.unwrap().unwrap();
    assert_eq!(retrieved, data);
}

#[tokio::test]
#[ignore]
async fn test_batch_operations_performance() {
    let backend = create_test_backend(CompressionAlgorithm::None)
        .await
        .expect("Redis not available");

    let start = std::time::Instant::now();

    // Batch write 1000 items
    let mut pairs = Vec::new();
    for i in 0..1000 {
        let key = format!("batch_key_{}", i);
        let value = format!("batch_value_{}", i);
        pairs.push((key.as_bytes().to_vec(), value.as_bytes().to_vec()));
    }

    let pair_refs: Vec<(&[u8], &[u8])> = pairs
        .iter()
        .map(|(k, v)| (k.as_slice(), v.as_slice()))
        .collect();

    backend.batch_put_optimized(&pair_refs).await.unwrap();

    let batch_write_time = start.elapsed();
    println!("Batch write 1000 items: {:?}", batch_write_time);

    // Batch read
    let start = std::time::Instant::now();
    let keys: Vec<&[u8]> = pairs.iter().map(|(k, _)| k.as_slice()).collect();
    let values = backend.batch_get_optimized(&keys).await.unwrap();
    let batch_read_time = start.elapsed();

    println!("Batch read 1000 items: {:?}", batch_read_time);

    assert_eq!(values.len(), 1000);
    assert!(values.iter().all(|v| v.is_some()));

    // Verify performance improvement over individual operations
    assert!(batch_write_time < Duration::from_secs(2));
    assert!(batch_read_time < Duration::from_secs(2));
}

#[tokio::test]
#[ignore]
async fn test_distributed_locking() {
    let backend = create_test_backend(CompressionAlgorithm::None)
        .await
        .expect("Redis not available");

    let resource = "test_resource";

    // Acquire lock
    let guard1 = backend
        .acquire_lock(resource, Duration::from_secs(5))
        .await
        .unwrap();

    // Try to acquire same lock should fail
    let guard2 = backend
        .try_acquire_lock(resource, Duration::from_secs(5))
        .await
        .unwrap();
    assert!(guard2.is_none());

    // Release first lock
    drop(guard1);
    sleep(Duration::from_millis(100)).await;

    // Now we should be able to acquire
    let guard3 = backend
        .try_acquire_lock(resource, Duration::from_secs(5))
        .await
        .unwrap();
    assert!(guard3.is_some());
}

#[tokio::test]
#[ignore]
async fn test_concurrent_lock_acquisition() {
    use std::sync::Arc;
    use tokio::task;

    let backend = Arc::new(
        create_test_backend(CompressionAlgorithm::None)
            .await
            .expect("Redis not available"),
    );

    let resource = "concurrent_resource";
    let mut handles = vec![];

    // Spawn 10 tasks trying to acquire the same lock
    for i in 0..10 {
        let backend = backend.clone();
        let resource = resource.to_string();

        let handle = task::spawn(async move {
            match backend
                .try_acquire_lock(&resource, Duration::from_secs(1))
                .await
            {
                Ok(Some(guard)) => {
                    println!("Task {} acquired lock", i);
                    sleep(Duration::from_millis(100)).await;
                    drop(guard);
                    Some(i)
                }
                Ok(None) => {
                    println!("Task {} failed to acquire lock", i);
                    None
                }
                Err(e) => {
                    eprintln!("Task {} error: {}", i, e);
                    None
                }
            }
        });

        handles.push(handle);
    }

    // Collect results
    let mut successful = 0;
    for handle in handles {
        if let Ok(Some(_)) = handle.await {
            successful += 1;
        }
    }

    // At least one should succeed
    assert!(successful >= 1);
    println!("{} tasks successfully acquired lock", successful);
}

#[tokio::test]
#[ignore]
async fn test_health_check() {
    let backend = create_test_backend(CompressionAlgorithm::None)
        .await
        .expect("Redis not available");

    let healthy = backend.health_check().await.unwrap();
    assert!(healthy);
}

#[tokio::test]
#[ignore]
async fn test_statistics_tracking() {
    let backend = create_test_backend(CompressionAlgorithm::Lz4)
        .await
        .expect("Redis not available");

    // Perform various operations
    backend.put(b"stats_key1", b"value1").await.unwrap();
    backend.put(b"stats_key2", b"value2").await.unwrap();

    backend.get(b"stats_key1").await.unwrap(); // Hit
    backend.get(b"stats_key1").await.unwrap(); // Hit
    backend.get(b"nonexistent").await.unwrap(); // Miss

    backend.delete(b"stats_key1").await.unwrap();

    // Get stats
    let stats = backend.stats().await;

    println!("Statistics: {:?}", stats);

    assert_eq!(stats.cache_hits, 2);
    assert_eq!(stats.cache_misses, 1);
    assert!(stats.operations_success > 0);
    assert!(stats.bytes_written > 0);
    assert!(stats.avg_latency_us > 0);
}

#[tokio::test]
#[ignore]
async fn test_list_keys_with_prefix() {
    let backend = create_test_backend(CompressionAlgorithm::None)
        .await
        .expect("Redis not available");

    // Create keys with different prefixes
    backend.put(b"user:1:name", b"Alice").await.unwrap();
    backend.put(b"user:2:name", b"Bob").await.unwrap();
    backend.put(b"user:3:name", b"Charlie").await.unwrap();
    backend.put(b"product:1:name", b"Widget").await.unwrap();

    // List keys with prefix
    let user_keys = backend.list_keys(b"user:").await.unwrap();

    assert_eq!(user_keys.len(), 3);
    assert!(user_keys
        .iter()
        .all(|k| k.starts_with(b"user:")));

    // List all keys
    let all_keys = backend.list_keys(b"").await.unwrap();
    assert_eq!(all_keys.len(), 4);
}

#[tokio::test]
#[ignore]
async fn test_count_operations() {
    let backend = create_test_backend(CompressionAlgorithm::None)
        .await
        .expect("Redis not available");

    backend.clear().await.unwrap();

    for i in 0..10 {
        let key = format!("count_key_{}", i);
        backend.put(key.as_bytes(), b"value").await.unwrap();
    }

    let count = backend.count().await.unwrap();
    assert_eq!(count, 10);
}

#[tokio::test]
#[ignore]
async fn test_contains_operation() {
    let backend = create_test_backend(CompressionAlgorithm::None)
        .await
        .expect("Redis not available");

    backend.put(b"exists_key", b"value").await.unwrap();

    assert!(backend.contains(b"exists_key").await.unwrap());
    assert!(!backend.contains(b"nonexistent_key").await.unwrap());
}

#[tokio::test]
#[ignore]
async fn test_retry_logic() {
    let backend = create_test_backend(CompressionAlgorithm::None)
        .await
        .expect("Redis not available");

    // Normal operation should work
    backend.put(b"retry_key", b"value").await.unwrap();
    let value = backend.get(b"retry_key").await.unwrap();
    assert_eq!(value, Some(b"value".to_vec()));

    // The backend will automatically retry on transient failures
    // This is tested by the internal retry mechanism
}

#[tokio::test]
#[ignore]
async fn test_compression_threshold() {
    let backend = create_test_backend(CompressionAlgorithm::Lz4)
        .await
        .expect("Redis not available");

    // Small data below threshold shouldn't be compressed
    let small_data = b"small";
    backend.put(b"small_key", small_data).await.unwrap();

    // Large data above threshold should be compressed
    let large_data = vec![b'x'; 10000];
    backend.put(b"large_key", &large_data).await.unwrap();

    // Both should be retrieved correctly
    assert_eq!(
        backend.get(b"small_key").await.unwrap(),
        Some(small_data.to_vec())
    );
    assert_eq!(
        backend.get(b"large_key").await.unwrap(),
        Some(large_data)
    );
}

#[tokio::test]
#[ignore]
async fn test_metrics_collection() {
    let backend = create_test_backend(CompressionAlgorithm::Lz4)
        .await
        .expect("Redis not available");

    // Verify metrics are enabled
    assert!(backend.metrics().is_some());

    // Perform operations
    backend.put(b"metric_key", b"value").await.unwrap();
    backend.get(b"metric_key").await.unwrap();

    // Metrics should be updated
    let stats = backend.stats().await;
    assert!(stats.operations_total > 0);
}

#[tokio::test]
#[ignore]
async fn test_clear_all_keys() {
    let backend = create_test_backend(CompressionAlgorithm::None)
        .await
        .expect("Redis not available");

    // Add multiple keys
    for i in 0..50 {
        let key = format!("clear_key_{}", i);
        backend.put(key.as_bytes(), b"value").await.unwrap();
    }

    let count_before = backend.count().await.unwrap();
    assert_eq!(count_before, 50);

    // Clear all
    backend.clear().await.unwrap();

    let count_after = backend.count().await.unwrap();
    assert_eq!(count_after, 0);
}

#[tokio::test]
#[ignore]
async fn test_stress_test() {
    use std::sync::Arc;
    use tokio::task;

    let backend = Arc::new(
        create_test_backend(CompressionAlgorithm::Lz4)
            .await
            .expect("Redis not available"),
    );

    let mut handles = vec![];

    // Spawn 20 concurrent tasks
    for task_id in 0..20 {
        let backend = backend.clone();

        let handle = task::spawn(async move {
            for i in 0..50 {
                let key = format!("stress_{}_{}", task_id, i);
                let value = format!("value_{}_{}", task_id, i);

                backend.put(key.as_bytes(), value.as_bytes()).await.unwrap();

                if i % 10 == 0 {
                    let retrieved = backend.get(key.as_bytes()).await.unwrap();
                    assert_eq!(retrieved, Some(value.as_bytes().to_vec()));
                }
            }
        });

        handles.push(handle);
    }

    // Wait for all tasks
    for handle in handles {
        handle.await.unwrap();
    }

    // Verify we have 1000 keys (20 * 50)
    let count = backend.count().await.unwrap();
    assert_eq!(count, 1000);

    let stats = backend.stats().await;
    println!("Stress test stats: {:?}", stats);
    assert!(stats.operations_success >= 1000);
}