do-memory-mcp 0.1.29

Model Context Protocol (MCP) server for AI agents
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
use crate::patterns::predictive::{
    dbscan::{AdaptiveDBSCAN, DBSCANConfig},
    kdtree::{KDTree, Point},
};
use crate::patterns::statistical::{
    SimpleBOCPD, analysis::types::BOCPDConfig, bocpd_tests::create_changepoint_data,
};
use std::time::Instant;

#[test]
fn benchmark_dbscan_scalability() {
    let sizes = vec![100, 500, 1000, 2000, 5000];

    for size in sizes {
        let values: Vec<f64> = (0..size)
            .map(|i| 10.0 + (i as f64 / size as f64) * 10.0 + (rand::random::<f64>() - 0.5))
            .collect();

        let timestamps: Vec<f64> = (0..values.len()).map(|i| i as f64).collect();

        let mut dbscan = AdaptiveDBSCAN::new(DBSCANConfig::default()).unwrap();

        let start = Instant::now();
        let labels = dbscan.detect_anomalies_dbscan(&values, &timestamps);
        let duration = start.elapsed();

        println!(
            "DBSCAN with {} points: {:?} ({:.2} ms)",
            size,
            duration,
            duration.as_millis() as f64
        );

        assert_eq!(labels.len(), size);
        if size >= 5000 {
            assert!(
                duration.as_secs() < 30,
                "DBSCAN with 5000 points should complete in < 30s"
            );
        }
    }
}

#[test]
fn benchmark_bocpd_scalability() {
    let sizes = vec![100, 500, 1000, 2000, 5000];

    for size in sizes {
        let data = create_changepoint_data(10.0, 20.0, size / 2, size / 2);

        let config = BOCPDConfig {
            buffer_size: size.min(1000),
            ..Default::default()
        };

        let mut bocpd = SimpleBOCPD::new(config);

        let start = Instant::now();
        let results = bocpd.detect_changepoints(&data).unwrap();
        let duration = start.elapsed();

        println!(
            "BOCPD with {} points: {:?} ({:.2} ms, {} detections)",
            size,
            duration,
            duration.as_millis() as f64,
            results.len()
        );

        if size >= 5000 {
            assert!(
                duration.as_secs() < 30,
                "BOCPD with 5000 points should complete in < 30s"
            );
        }
    }
}

#[test]
fn benchmark_kdtree_performance() {
    let sizes = vec![100, 500, 1000, 1500];

    for size in sizes {
        let mut points: Vec<Point> = (0..size)
            .map(|i| Point::new(i, &[i as f64, (i * 2) as f64], None, i as f64))
            .collect();

        use rand::seq::SliceRandom;
        points.shuffle(&mut rand::rng());

        let start = Instant::now();
        let kd_tree = KDTree::build(&points);
        let construction_time = start.elapsed();

        let query_point = vec![size as f64 / 2.0, size as f64];
        let start = Instant::now();
        let _neighbors = kd_tree.find_neighbors(&query_point, 10.0);
        let query_time = start.elapsed();

        println!(
            "KD-tree with {} points: construction {:?}, query {:?}",
            size,
            construction_time.as_micros(),
            query_time.as_micros()
        );

        assert!(
            construction_time.as_millis() < 1000,
            "KD-tree construction should be fast"
        );
        assert!(
            query_time.as_micros() < 10000,
            "KD-tree query should be fast"
        );
    }
}

#[test]
fn benchmark_pattern_extraction() {
    use crate::patterns::predictive::extraction::{ExtractionConfig, PatternExtractor};

    let sizes = vec![10, 50, 100, 500];

    for size in sizes {
        let mut points = Vec::new();
        for i in 0..size {
            points.push(Point::new(i, &[i as f64], None, i as f64));
        }

        let clusters = vec![crate::patterns::predictive::dbscan::Cluster {
            id: 0,
            points: points.clone(),
            centroid: vec![size as f64 / 2.0],
            density: 0.8,
        }];

        let extractor = PatternExtractor::new(ExtractionConfig::default());

        let start = Instant::now();
        let _patterns = extractor.extract_patterns(&clusters, &[], &["test".to_string()]);
        let duration = start.elapsed();

        println!(
            "Pattern extraction with {} points: {:?}",
            size,
            duration.as_micros()
        );

        assert!(
            duration.as_millis() < 100,
            "Pattern extraction should be fast"
        );
    }
}

#[test]
fn benchmark_compatibility_assessment() {
    use crate::patterns::compatibility::{AssessmentConfig, CompatibilityAssessor, PatternContext};

    let is_ci = std::env::var("CI").is_ok();
    let max_ms = if is_ci { 3000 } else { 200 };
    let tool_counts = vec![1, 5, 10, 20];
    let known_tools = [
        "query_memory",
        "analyze_patterns",
        "advanced_pattern_analysis",
    ];

    let assessor = CompatibilityAssessor::new(AssessmentConfig::default());

    for tool_name in &known_tools {
        let result = assessor.assess_compatibility(
            "test_pattern",
            tool_name,
            &PatternContext {
                domain: "test".to_string(),
                data_quality: 0.8,
                occurrences: 10,
                temporal_stability: 0.9,
                available_memory_mb: 200,
                complexity: 0.5,
            },
        );
        assert!(
            result.is_ok(),
            "Tool {} should be properly registered",
            tool_name
        );
    }

    for count in tool_counts {
        let tools: Vec<String> = known_tools
            .iter()
            .cycle()
            .take(count)
            .map(|tool| (*tool).to_string())
            .collect();

        let context = PatternContext {
            domain: "test".to_string(),
            data_quality: 0.8,
            occurrences: 10,
            temporal_stability: 0.9,
            available_memory_mb: 200,
            complexity: 0.5,
        };

        if count == 1 {
            let _warmup = assessor.batch_assess("warmup", &tools, &context);
        }

        let start = Instant::now();
        let assessments = assessor.batch_assess("test_pattern", &tools, &context);

        let assessments = match assessments {
            Ok(a) => a,
            Err(e) => {
                panic!("Batch assessment failed for {} tools: {:?}", count, e);
            }
        };

        let duration = start.elapsed();
        assert_eq!(
            assessments.len(),
            tools.len(),
            "Should get one assessment per tool"
        );

        println!(
            "Compatibility assessment for {} tools: {:?} ({} assessments)",
            count,
            duration.as_micros(),
            assessments.len()
        );

        assert!(
            duration.as_millis() < max_ms,
            "Compatibility assessment should be fast: got {}ms, max allowed {}ms",
            duration.as_millis(),
            max_ms
        );
    }
}

#[test]
fn benchmark_memory_usage() {
    let is_ci = std::env::var("CI").is_ok();
    let size = if is_ci { 2000 } else { 10000 };

    let values: Vec<f64> = (0..size)
        .map(|i| 10.0 + (i as f64 / size as f64) * 10.0)
        .collect();
    let timestamps: Vec<f64> = (0..size).map(|i| i as f64).collect();

    use rand::seq::SliceRandom;
    let mut indexed_values: Vec<(f64, f64)> = values.into_iter().zip(timestamps).collect();
    indexed_values.shuffle(&mut rand::rng());

    let values: Vec<f64> = indexed_values.iter().map(|(v, _)| *v).collect();
    let timestamps: Vec<f64> = indexed_values.iter().map(|(_, t)| *t).collect();
    let values_capacity_mb =
        (values.capacity() * std::mem::size_of::<f64>()) as f64 / (1024.0 * 1024.0);
    let timestamps_capacity_mb =
        (timestamps.capacity() * std::mem::size_of::<f64>()) as f64 / (1024.0 * 1024.0);

    let start = Instant::now();
    let mut dbscan = AdaptiveDBSCAN::new(DBSCANConfig::default()).unwrap();
    let _labels = dbscan.detect_anomalies_dbscan(&values, &timestamps);
    let duration = start.elapsed();

    let estimated_mb = values_capacity_mb + timestamps_capacity_mb + 10.0;

    println!(
        "DBSCAN with {} points: input data {:.2} MB, completed in {:?}",
        size, estimated_mb, duration
    );

    // CI uses smaller dataset (2000 points) with 60s budget
    // Local testing uses larger dataset (10000 points) with 120s budget
    // to accommodate more thorough performance validation
    let max_secs = if is_ci { 60 } else { 120 };
    assert!(
        duration.as_secs() < max_secs,
        "DBSCAN should complete within the time budget ({}s for {} points)",
        max_secs,
        size
    );
    assert!(estimated_mb < 500.0, "Memory usage should be reasonable");
}

#[cfg_attr(not(feature = "streaming-impl"), ignore)]
#[test]
fn benchmark_streaming_performance() {
    let is_ci = std::env::var("CI").is_ok();
    let window_sizes = if is_ci {
        vec![100, 500]
    } else {
        vec![100, 500, 1000, 2000]
    };

    for window_size in window_sizes {
        let num_points = match window_size {
            _ if is_ci && window_size >= 1000 => 500,
            _ if is_ci => 1000,
            _ => 10000,
        };

        let mut dbscan = AdaptiveDBSCAN::new(DBSCANConfig {
            window_size,
            ..Default::default()
        })
        .unwrap();

        let start = Instant::now();

        for i in 0..num_points {
            let point = Point::new(i, &[i as f64], None, i as f64);
            dbscan.update_streaming_clusters(point);
        }

        let duration = start.elapsed();
        let throughput = (num_points as f64) / duration.as_secs_f64();

        println!(
            "Streaming DBSCAN (window={}): {} points in {:?} ({:.0} points/sec)",
            window_size, num_points, duration, throughput
        );

        let min_throughput = if is_ci { 3.0 } else { 10.0 };
        assert!(
            throughput > min_throughput,
            "Streaming performance degraded: got {:.0} pts/sec, min {} pts/sec. \
             See ADR-026 for handling strategy.",
            throughput,
            min_throughput
        );
    }
}

#[test]
fn benchmark_concurrent_analysis() {
    use std::thread;

    let num_threads = vec![1, 2, 4];

    for threads in num_threads {
        let start = Instant::now();

        let handles: Vec<_> = (0..threads)
            .map(|_| {
                thread::spawn(|| {
                    let mut dbscan = AdaptiveDBSCAN::new(DBSCANConfig::default()).unwrap();
                    let values: Vec<f64> = (0..1000).map(|i| i as f64).collect();
                    let timestamps: Vec<f64> = (0..1000).map(|i| i as f64).collect();
                    dbscan.detect_anomalies_dbscan(&values, &timestamps)
                })
            })
            .collect();

        for handle in handles {
            handle.join().unwrap();
        }

        let duration = start.elapsed();

        println!(
            "Concurrent analysis ({} threads): {:?}",
            threads,
            duration.as_millis()
        );
    }
}

#[test]
fn benchmark_real_world_workload() {
    let mut dbscan = AdaptiveDBSCAN::new(DBSCANConfig::default()).unwrap();

    let num_batches = 100;
    let points_per_batch = 50;

    let start = Instant::now();

    for batch in 0..num_batches {
        let values: Vec<f64> = (0..points_per_batch)
            .map(|_i| {
                let base = 10.0;
                if rand::random::<f64>() < 0.05 {
                    base + 50.0
                } else {
                    base + (rand::random::<f64>() - 0.5) * 2.0
                }
            })
            .collect();

        let timestamps: Vec<f64> = (0..points_per_batch)
            .map(|i| (batch * points_per_batch + i) as f64)
            .collect();

        let _labels = dbscan.detect_anomalies_dbscan(&values, &timestamps);
    }

    let duration = start.elapsed();
    let total_points = num_batches * points_per_batch;
    let throughput = total_points as f64 / duration.as_secs_f64();

    println!(
        "Real-world workload: {} points in {:?} ({:.0} points/sec)",
        total_points, duration, throughput
    );

    assert!(
        throughput > 100.0,
        "Real-time processing should handle at least 100 points/sec"
    );
}

#[test]
fn benchmark_accuracy_performance_tradeoff() {
    let configs = vec![(0.1, 2, 1000), (0.5, 5, 500), (1.0, 10, 200)];

    for (density, min_samples, max_distance) in configs {
        let config = DBSCANConfig {
            density,
            min_cluster_size: min_samples,
            max_distance: max_distance as f64,
            window_size: 1000,
        };

        let mut dbscan = AdaptiveDBSCAN::new(config).unwrap();

        let values: Vec<f64> = (0..1000)
            .map(|i| {
                if i == 100 || i == 500 || i == 900 {
                    50.0
                } else {
                    10.0 + (rand::random::<f64>() - 0.5) * 2.0
                }
            })
            .collect();

        let timestamps: Vec<f64> = (0..values.len()).map(|i| i as f64).collect();

        let start = Instant::now();
        let labels = dbscan.detect_anomalies_dbscan(&values, &timestamps);
        let duration = start.elapsed();

        let detected_outliers = labels
            .iter()
            .filter(|&l| matches!(l, crate::patterns::predictive::dbscan::ClusterLabel::Noise))
            .count();

        println!(
            "Config (density={}, min_samples={}, max_distance={}): {:?}, detected {} outliers",
            density, min_samples, max_distance, duration, detected_outliers
        );
    }
}