microscope-memory 1.2.0

Pure binary cognitive memory engine with REST API bridge for LLM integration. Zero-JSON core, mmap-based, hierarchical, sub-microsecond search.
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
//! Criterion benchmarks for the Microscope Memory pipeline.

use criterion::{black_box, criterion_group, criterion_main, Criterion};
use std::path::Path;

/// Create a temporary test environment with config pointing to fixture data.
fn setup_test_env() -> (tempfile::TempDir, microscope_memory::config::Config) {
    let tmp = tempfile::tempdir().expect("create temp dir");
    let output_dir = tmp.path().join("output");
    std::fs::create_dir_all(&output_dir).unwrap();

    let manifest_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    let fixtures = manifest_dir.join("tests").join("fixtures");
    let layers_dir = fixtures.join("layers");

    let mut config = microscope_memory::config::Config::default();
    config.paths.layers_dir = layers_dir.to_string_lossy().to_string();
    config.paths.output_dir = output_dir.to_string_lossy().to_string();
    config.paths.temp_dir = tmp.path().join("tmp").to_string_lossy().to_string();
    config.memory_layers.layers = vec!["long_term".to_string(), "short_term".to_string()];
    config.embedding.provider = "mock".to_string();
    config.embedding.dim = 128;
    config.embedding.max_depth = 4;

    (tmp, config)
}

/// Build the index once and return the temp dir, config, and reader for reuse.
fn setup_built_env() -> (
    tempfile::TempDir,
    microscope_memory::config::Config,
    microscope_memory::MicroscopeReader,
) {
    let (tmp, config) = setup_test_env();
    microscope_memory::build::build(&config, true, true).expect("build");
    let reader = microscope_memory::MicroscopeReader::open(&config).expect("open reader");
    (tmp, config, reader)
}

// ─── Build pipeline ──────────────────────────────────────

fn bench_build_pipeline(c: &mut Criterion) {
    c.bench_function("build_pipeline", |b| {
        b.iter_with_setup(setup_test_env, |(_tmp, config)| {
            microscope_memory::build::build(black_box(&config), true, true).expect("build");
        });
    });
}

// ─── Text search (find_text) ─────────────────────────────

fn bench_find_text(c: &mut Criterion) {
    let (_tmp, _config, reader) = setup_built_env();

    let mut group = c.benchmark_group("find_text");
    group.bench_function("existing_term", |b| {
        b.iter(|| reader.find_text(black_box("Rust"), black_box(10)));
    });
    group.bench_function("missing_term", |b| {
        b.iter(|| reader.find_text(black_box("xyznonexistent123"), black_box(10)));
    });
    group.finish();
}

// ─── Spatial lookup (reader.look) ────────────────────────

fn bench_look(c: &mut Criterion) {
    let (_tmp, config, reader) = setup_built_env();

    let mut group = c.benchmark_group("spatial_look");
    for depth in [1u8, 2, 3] {
        group.bench_function(format!("depth_{}", depth), |b| {
            b.iter(|| {
                reader.look(
                    black_box(&config),
                    black_box(0.5),
                    black_box(0.5),
                    black_box(0.5),
                    black_box(depth),
                    black_box(5),
                )
            });
        });
    }
    group.finish();
}

// ─── MQL query (parse + execute) ─────────────────────────

fn bench_mql_query(c: &mut Criterion) {
    let (_tmp, config, reader) = setup_built_env();
    let append_path = Path::new(&config.paths.output_dir).join("append.bin");
    let appended = microscope_memory::read_append_log(&append_path);

    let mut group = c.benchmark_group("mql_query");
    group.bench_function("keyword_search", |b| {
        b.iter(|| {
            let q = microscope_memory::query::parse(black_box("\"Rust\""));
            microscope_memory::query::execute(&q, black_box(&reader), black_box(&appended))
        });
    });
    group.bench_function("depth_filter", |b| {
        b.iter(|| {
            let q = microscope_memory::query::parse(black_box("depth:3 \"memory\""));
            microscope_memory::query::execute(&q, black_box(&reader), black_box(&appended))
        });
    });
    group.finish();
}

// ─── CRC16 computation ──────────────────────────────────

fn bench_crc16(c: &mut Criterion) {
    let short_data = b"hello world";
    let medium_data = vec![0xABu8; 256];
    let long_data = vec![0xCDu8; 4096];

    let mut group = c.benchmark_group("crc16_ccitt");
    group.bench_function("short_11b", |b| {
        b.iter(|| microscope_memory::crc16_ccitt(black_box(short_data)));
    });
    group.bench_function("medium_256b", |b| {
        b.iter(|| microscope_memory::crc16_ccitt(black_box(&medium_data)));
    });
    group.bench_function("long_4096b", |b| {
        b.iter(|| microscope_memory::crc16_ccitt(black_box(&long_data)));
    });
    group.finish();
}

// ─── Content coords ─────────────────────────────────────

fn bench_content_coords(c: &mut Criterion) {
    let mut group = c.benchmark_group("content_coords");
    group.bench_function("hash_only", |b| {
        b.iter(|| {
            microscope_memory::content_coords(
                black_box("Rust memory system benchmark test"),
                black_box("long_term"),
            )
        });
    });
    group.bench_function("blended_w0.5", |b| {
        b.iter(|| {
            microscope_memory::content_coords_blended(
                black_box("Rust memory system benchmark test"),
                black_box("long_term"),
                black_box(0.5),
            )
        });
    });
    group.bench_function("blended_w0.0", |b| {
        b.iter(|| {
            microscope_memory::content_coords_blended(
                black_box("Rust memory system benchmark test"),
                black_box("long_term"),
                black_box(0.0),
            )
        });
    });
    group.finish();
}

// ─── Append log read/write ──────────────────────────────

fn bench_append_log(c: &mut Criterion) {
    let mut group = c.benchmark_group("append_log");

    group.bench_function("store_and_read_cycle", |b| {
        b.iter_with_setup(
            || {
                let (tmp, config) = setup_test_env();
                microscope_memory::build::build(&config, true, true).expect("build");
                (tmp, config)
            },
            |(_tmp, config)| {
                microscope_memory::store_memory(
                    black_box(&config),
                    black_box("Benchmark test memory entry about quantum computing"),
                    black_box("long_term"),
                    black_box(5),
                )
                .expect("store");
                let append_path = Path::new(&config.paths.output_dir).join("append.bin");
                let entries = microscope_memory::read_append_log(black_box(&append_path));
                assert!(!entries.is_empty());
            },
        );
    });

    group.bench_function("read_existing", |b| {
        // Setup: build and store one entry, then benchmark reads only
        let (_tmp, config) = setup_test_env();
        microscope_memory::build::build(&config, true, true).expect("build");
        microscope_memory::store_memory(
            &config,
            "Benchmark pre-stored memory entry",
            "long_term",
            5,
        )
        .expect("store");
        let append_path = Path::new(&config.paths.output_dir).join("append.bin");

        b.iter(|| {
            let entries = microscope_memory::read_append_log(black_box(&append_path));
            assert!(!entries.is_empty());
        });
    });

    group.finish();
}

// ─── Candle embedding device selection ─────────────────

#[cfg(all(not(target_arch = "wasm32"), feature = "embeddings"))]
fn bench_embedding_device(c: &mut Criterion) {
    use candle_core::Device;

    let mut group = c.benchmark_group("embedding_device");

    group.bench_function("cpu_explicit", |b| {
        b.iter(|| {
            let _device = black_box(Device::Cpu);
        });
    });

    group.bench_function("cuda_if_available_false", |b| {
        b.iter(|| {
            let _device = black_box(Device::cuda_if_available(0).unwrap_or(Device::Cpu));
        });
    });

    group.bench_function("cuda_lazy_with_gpu_request", |b| {
        b.iter(|| {
            // This mirrors the lazy GPU activation in embeddings.rs:
            // if use_gpu is true, try CUDA(0); fall back to CPU.
            let device = if let Ok(d) = Device::cuda_if_available(0) {
                d
            } else {
                Device::Cpu
            };
            let _ = black_box(device);
        });
    });

    group.finish();
}

#[cfg(not(all(not(target_arch = "wasm32"), feature = "embeddings")))]
fn bench_embedding_device(_c: &mut Criterion) {}

criterion_group!(
    benches,
    bench_build_pipeline,
    bench_find_text,
    bench_look,
    bench_mql_query,
    bench_crc16,
    bench_content_coords,
    bench_append_log,
);
criterion_main!(benches, cognitive_benches);

// ─── Morphogenesis benchmarks ────────────────────────────

fn bench_morphogenesis_growth(c: &mut Criterion) {
    use microscope_memory::morphogenesis::*;

    let mut group = c.benchmark_group("morphogenesis");

    group.bench_function("mycelium_growth", |b| {
        b.iter(|| {
            let seed = Seed::new("bench", 0.0, 0.0, 0.0, "service");
            let field = MorphogenField::new();
            let config = GrowthConfig::mycelium_default();
            let org = mycelium_growth(black_box(&seed), black_box(&field), black_box(&config));
            black_box(org.nodes.len());
        });
    });

    group.bench_function("capillary_growth", |b| {
        b.iter(|| {
            let seed = Seed::new("bench", 0.0, 0.0, 0.0, "gateway");
            let field = MorphogenField::new();
            let config = GrowthConfig::capillary_default();
            let org = capillary_growth(black_box(&seed), black_box(&field), black_box(&config));
            black_box(org.nodes.len());
        });
    });

    group.bench_function("fractal_growth", |b| {
        b.iter(|| {
            let seed = Seed::new("bench", 0.0, 0.0, 0.0, "service");
            let field = MorphogenField::new();
            let config = GrowthConfig::fractal_lsystem_default();
            let org = fractal_growth(black_box(&seed), black_box(&field), black_box(&config));
            black_box(org.nodes.len());
        });
    });

    group.bench_function("slime_mold_growth", |b| {
        b.iter(|| {
            let seed = Seed::new("bench", 0.0, 0.0, 0.0, "router");
            let field = MorphogenField::new();
            let config = GrowthConfig::slime_mold_default();
            let org = slime_mold_growth(black_box(&seed), black_box(&field), black_box(&config));
            black_box(org.nodes.len());
        });
    });

    group.finish();
}

fn bench_morphogenesis_evaluate_fitness(c: &mut Criterion) {
    use microscope_memory::morphogenesis::*;

    let seed = Seed::new("bench", 0.0, 0.0, 0.0, "service");
    let field = MorphogenField::new();
    let config = GrowthConfig::mycelium_default();
    let organism = mycelium_growth(&seed, &field, &config);

    c.bench_function("evaluate_fitness", |b| {
        b.iter(|| {
            let result =
                evaluate_fitness(black_box(&organism), black_box(&FitnessObjective::Balanced));
            black_box(result.score);
        });
    });
}

// ─── Executive benchmarks ────────────────────────────────

fn bench_executive_schedule(c: &mut Criterion) {
    use microscope_memory::executive::Executive;

    let exec = Executive::new();
    exec.register_module("test1", "Test Module 1", 100, 0.5, vec![]);
    exec.register_module("test2", "Test Module 2", 200, 0.3, vec![]);
    exec.register_module("test3", "Test Module 3", 50, 0.8, vec![]);

    c.bench_function("executive_schedule", |b| {
        b.iter(|| {
            let plan = exec.schedule();
            black_box(plan.module_order.len());
        });
    });

    c.bench_function("executive_cycle", |b| {
        b.iter(|| {
            let executed = exec.cycle();
            black_box(executed.len());
        });
    });
}

// ─── Pattern Recognition benchmarks ──────────────────────

fn bench_pattern_recognition(c: &mut Criterion) {
    use microscope_memory::pattern_recognition::*;

    let recognizer = PatternRecognizer::new();

    let elements: Vec<String> = (0..100).map(|i| format!("word_{}", i % 20)).collect();

    c.bench_function("find_sequences", |b| {
        b.iter(|| {
            let patterns = recognizer.find_sequences(black_box(&elements), black_box("bench"));
            black_box(patterns.len());
        });
    });

    // Structural motifs
    let edges: Vec<(String, String, f64)> = (0..50)
        .map(|i| {
            (
                format!("node_{}", i),
                format!("node_{}", (i + 1) % 50),
                rand::random::<f64>(),
            )
        })
        .collect();

    c.bench_function("find_motifs", |b| {
        b.iter(|| {
            let patterns = recognizer.find_motifs(black_box(&edges), black_box("bench"));
            black_box(patterns.len());
        });
    });
}

// ─── Planner benchmarks ──────────────────────────────────

fn bench_planning(c: &mut Criterion) {
    use microscope_memory::planning::Planner;

    let planner = Planner::new();
    let goal_id = planner.add_goal("learn", "Learn about Rust", 100, None);

    c.bench_function("decompose_goal", |b| {
        b.iter(|| {
            let subs = planner.decompose_goal(black_box(goal_id));
            black_box(subs.len());
        });
    });

    c.bench_function("create_plan", |b| {
        b.iter(|| {
            let plan = planner.create_plan(black_box(goal_id));
            black_box(plan.actions.len());
        });
    });
}

// ─── Autopoiesis benchmarks ──────────────────────────────

fn bench_autopoiesis(c: &mut Criterion) {
    use microscope_memory::autopoiesis::AutopoiesisEngine;

    let engine = AutopoiesisEngine::new();
    engine.register_template(
        "test_tmpl",
        "test_module",
        "fn hello() { println!(\"{{name}}\"); }",
        vec!["name".to_string()],
        "Test template",
    );

    c.bench_function("autopoiesis_generate_template", |b| {
        b.iter(|| {
            let mut vars = std::collections::HashMap::new();
            vars.insert("name".to_string(), "world".to_string());
            let code = engine.generate_from_template(black_box("test_tmpl"), black_box(&vars));
            black_box(code);
        });
    });

    c.bench_function("autopoiesis_propose_mutation", |b| {
        b.iter(|| {
            let id = engine.propose_mutation(
                black_box("bench_mut"),
                black_box(microscope_memory::autopoiesis::MutationType::Modification),
                black_box("test_module"),
                black_box("fn test() {}"),
                black_box("benchmark"),
                black_box("system"),
            );
            black_box(id);
        });
    });
}

criterion_group!(
    cognitive_benches,
    bench_morphogenesis_growth,
    bench_embedding_device,
    bench_morphogenesis_evaluate_fitness,
    bench_executive_schedule,
    bench_pattern_recognition,
    bench_planning,
    bench_autopoiesis,
);