okc 0.1.0

A local-first tool for AI agents to browse, parse, search, and reason over Open Knowledge Format (OKF) repositories
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
//! Criterion benchmarks for Open Knowledge Catalog core operations.
//!
//! Benchmark groups (each parameterized by corpus size):
//! - scan/fresh: initial full scan
//! - browse/root: browse the root directory
//! - search/*: full-text and filtered search
//! - document/*: get_document and get_section
//! - graph/*: get_links, get_backlinks, traverse
//! - validate: validation pass
//! - stats: get_stats
//! - export: export_to_json
//!
//! Corpora: small (10), medium (50), large (200) documents.

#![allow(
    clippy::default_constructed_unit_structs,
    clippy::expect_used,
    clippy::panic
)]

use std::path::Path;

use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion, SamplingMode};
use tempfile::TempDir;

use okc::config::OkcConfig;
use okc::service::OkcService;

// ---------------------------------------------------------------------------
// Corpus sizes
// ---------------------------------------------------------------------------

const SIZES: &[usize] = &[10, 50, 200, 1000, 10000];

// ---------------------------------------------------------------------------
// Document generation
// ---------------------------------------------------------------------------

fn generate_docs(root: &Path, count: usize) {
    let types = ["Metric", "Policy", "Dataset", "Glossary", "Guide"];
    let tag_sets: &[&[&str]] = &[
        &["finance", "executive"],
        &["security", "compliance"],
        &["engineering", "performance"],
        &["sales", "revenue"],
        &["product", "design"],
    ];
    let words = [
        "metric",
        "revenue",
        "policy",
        "compliance",
        "dataset",
        "glossary",
        "architecture",
        "design",
        "performance",
        "security",
        "optimization",
        "analysis",
        "report",
        "dashboard",
        "workflow",
    ];

    for i in 0..count {
        let ct = types[i % types.len()];
        let tags = tag_sets[i % tag_sets.len()];
        let title = format!("{} {}", ct, i);

        let link_indices: Vec<usize> = (0..3).map(|j| (i + j + 1) % count).collect();

        let mut content = String::new();
        content.push_str("---\n");
        content.push_str(&format!("type: {}\n", ct));
        content.push_str(&format!("title: \"{}\"\n", title));
        content.push_str(&format!(
            "description: \"Auto-generated {} for benchmarking\"\n",
            ct
        ));
        content.push_str("tags:\n");
        for t in tags {
            content.push_str(&format!("  - {}\n", t));
        }
        content.push_str(&format!("priority: \"P{}\"\n", i % 5 + 1));
        content.push_str("---\n\n");
        content.push_str(&format!("# {}\n\n", title));
        content.push_str(&format!("This is the definition of {}. ", ct));
        content.push_str(&format!(
            "Every {} has associated {} metrics and {} analysis. ",
            ct,
            words[i % words.len()],
            words[(i + 1) % words.len()]
        ));
        content.push_str("The values are tracked on the dashboard.\n\n");

        content.push_str("## Key Metrics\n\n");
        for j in 0..3 {
            let idx = (i + j) % words.len();
            content.push_str(&format!(
                "- **{}**: Target value for {} is {} units\n",
                words[idx],
                ct,
                (i * 100 + j * 10)
            ));
        }
        content.push_str("\n## Dependencies\n\n");
        content.push_str("This concept depends on the following:\n\n");

        for &li in &link_indices {
            let lt = types[li % types.len()];
            content.push_str(&format!("- [{} {}](doc_{}.md)\n", lt, li, li));
        }

        content.push_str("\n## Notes\n\n");
        content.push_str(&format!("Additional notes for {}. ", title));
        content.push_str("See the architecture document for more details.\n");

        let filename = format!("doc_{}.md", i);
        std::fs::write(root.join(&filename), content)
            .unwrap_or_else(|e| panic!("write {}: {}", filename, e));
    }
}

/// Generate large technical documents with tables, code blocks, and complex structures.
fn generate_technical_docs(root: &Path, count: usize) {
    let types = [
        "API Reference",
        "Architecture Decision",
        "Technical Specification",
        "Data Model",
        "Integration Guide",
    ];
    let tag_sets: &[&[&str]] = &[
        &["api", "reference", "rest"],
        &["architecture", "decision", "adr"],
        &["specification", "technical", "design"],
        &["data", "model", "schema"],
        &["integration", "guide", "webhook"],
    ];

    let words = [
        "metric",
        "optimization",
        "pipeline",
        "schema",
        "query",
        "index",
        "throughput",
        "latency",
        "cache",
        "buffer",
    ];

    for i in 0..count {
        let ct = types[i % types.len()];
        let tags = tag_sets[i % tag_sets.len()];
        let title = format!("{} {}", ct, i);

        let mut content = String::new();
        content.push_str("---\n");
        content.push_str(&format!("type: {}\n", ct));
        content.push_str(&format!("title: \"{}\"\n", title));
        content.push_str("description: \"Large technical document for benchmarking\"\n");
        content.push_str("tags:\n");
        for t in tags {
            content.push_str(&format!("  - {}\n", t));
        }
        content.push_str("---\n\n");
        content.push_str(&format!("# {}\n\n", title));

        // Add multiple sections with tables and code blocks
        for section in 0..5 {
            content.push_str(&format!(
                "## Section {}: {}\n\n",
                section + 1,
                words[(i + section) % words.len()]
            ));
            content.push_str("This section contains detailed technical information.\n\n");

            // Add a table
            content.push_str("### Data Table\n\n");
            content.push_str("| Column A | Column B | Column C | Column D |\n");
            content.push_str("|----------|----------|----------|----------|\n");
            for row in 0..20 {
                content.push_str(&format!(
                    "| Value {} | Value {} | Value {} | Value {} |\n",
                    row,
                    row + 1,
                    row + 2,
                    row + 3
                ));
            }
            content.push('\n');

            // Add a code block
            content.push_str("### Code Example\n\n");
            content.push_str("```rust\n");
            content.push_str(&format!("// Example {} for {}\n", section, ct));
            content.push_str("fn example() -> Result<(), Error> {\n");
            content.push_str("    let data = fetch_data()?;\n");
            content.push_str("    process(data)?;\n");
            content.push_str("    Ok(())\n");
            content.push_str("}\n");
            content.push_str("```\n\n");

            // Add a list
            content.push_str("### Key Points\n\n");
            for point in 0..10 {
                content.push_str(&format!(
                    "- Point {}: Important detail about {}\n",
                    point,
                    words[(i + point) % words.len()]
                ));
            }
            content.push('\n');
        }

        // Add cross-references
        content.push_str("## Related Documents\n\n");
        for j in 0..3 {
            let idx = (i + j + 1) % count;
            let lt = types[idx % types.len()];
            content.push_str(&format!("- [{} {}](tech_{}.md)\n", lt, idx, idx));
        }

        let filename = format!("tech_{}.md", i);
        std::fs::write(root.join(&filename), content)
            .unwrap_or_else(|e| panic!("write {}: {}", filename, e));
    }
}

fn bench_config(root: &Path) -> OkcConfig {
    OkcConfig {
        roots: vec![root.to_path_buf()],
        ..OkcConfig::default()
    }
}

// ---------------------------------------------------------------------------
// Build a single-sized corpus directory and return the config + scanned service
// ---------------------------------------------------------------------------

struct BenchSetup {
    #[allow(dead_code)]
    dir: TempDir,
    /// First document path for graph / document benchmarks
    first_doc: String,
    service: OkcService,
}

fn setup_scanned(count: usize) -> BenchSetup {
    let dir = TempDir::new().expect("temp dir");
    generate_docs(dir.path(), count);
    let config = bench_config(dir.path());
    let mut service = OkcService::open_in_memory(&config).expect("open");
    service.scan().expect("scan");
    let first_doc = if count > 0 {
        format!("doc_{}.md", 0)
    } else {
        String::new()
    };
    BenchSetup {
        dir,
        first_doc,
        service,
    }
}

// ---------------------------------------------------------------------------
// Benchmark functions
// ---------------------------------------------------------------------------

fn bench_scan(c: &mut Criterion) {
    let mut group = c.benchmark_group("scan");
    group.sampling_mode(SamplingMode::Auto);

    for &size in SIZES {
        let dir = TempDir::new().expect("temp dir");
        generate_docs(dir.path(), size);
        let config = bench_config(dir.path());

        group.bench_with_input(BenchmarkId::new("fresh", size), &size, |b, &_| {
            b.iter(|| {
                let mut service = OkcService::open_in_memory(&config).expect("open");
                black_box(service.scan().expect("scan"));
            });
        });
    }
    group.finish();
}

fn bench_browse(c: &mut Criterion) {
    let mut group = c.benchmark_group("browse");
    group.sampling_mode(SamplingMode::Auto);

    for &size in SIZES {
        let setup = setup_scanned(size);

        group.bench_with_input(BenchmarkId::new("root", size), &size, |b, &_| {
            b.iter(|| {
                black_box(
                    setup
                        .service
                        .browse(black_box(""), black_box(0), black_box(1000))
                        .expect("browse"),
                );
            });
        });

        // Browse with depth=1 (shows subdirectories)
        group.bench_with_input(BenchmarkId::new("root_depth", size), &size, |b, &_| {
            b.iter(|| {
                black_box(
                    setup
                        .service
                        .browse(black_box(""), black_box(1), black_box(1000))
                        .expect("browse"),
                );
            });
        });
    }
    group.finish();
}

fn bench_search(c: &mut Criterion) {
    let mut group = c.benchmark_group("search");
    group.sampling_mode(SamplingMode::Auto);

    for &size in SIZES {
        let setup = setup_scanned(size);

        // Full-text term search -- "dashboard" appears in every doc
        group.bench_with_input(BenchmarkId::new("term_dashboard", size), &size, |b, &_| {
            b.iter(|| {
                black_box(
                    setup
                        .service
                        .search(black_box("dashboard"), None, None, None, black_box(100))
                        .expect("search"),
                );
            });
        });

        // Search with type filter
        let metric = "Metric".to_string();
        let types = vec![metric];
        group.bench_with_input(
            BenchmarkId::new("term_type_filter", size),
            &size,
            |b, &_| {
                b.iter(|| {
                    black_box(
                        setup
                            .service
                            .search(
                                black_box("dashboard"),
                                None,
                                Some(black_box(&types)),
                                None,
                                black_box(100),
                            )
                            .expect("search"),
                    );
                });
            },
        );

        // Search with tag filter
        let tags = vec!["security".to_string(), "compliance".to_string()];
        group.bench_with_input(BenchmarkId::new("term_tag_filter", size), &size, |b, &_| {
            b.iter(|| {
                black_box(
                    setup
                        .service
                        .search(
                            black_box("dashboard"),
                            None,
                            None,
                            Some(black_box(&tags)),
                            black_box(100),
                        )
                        .expect("search"),
                );
            });
        });
    }
    group.finish();
}

fn bench_document(c: &mut Criterion) {
    let mut group = c.benchmark_group("document");
    group.sampling_mode(SamplingMode::Auto);

    for &size in SIZES {
        let setup = setup_scanned(size);
        let doc_path = &setup.first_doc;

        // get_document with metadata + headings only
        let includes: Vec<String> = vec!["metadata".to_string(), "headings".to_string()];
        group.bench_with_input(BenchmarkId::new("get_document", size), &size, |b, &_| {
            b.iter(|| {
                black_box(
                    setup
                        .service
                        .get_document(black_box(doc_path), black_box(&includes), black_box(5000))
                        .expect("get_document"),
                );
            });
        });

        // get_section for "Key Metrics"
        group.bench_with_input(BenchmarkId::new("get_section", size), &size, |b, &_| {
            b.iter(|| {
                black_box(
                    setup
                        .service
                        .get_section(
                            black_box(doc_path),
                            black_box("Key Metrics"),
                            black_box(2000),
                        )
                        .expect("get_section"),
                );
            });
        });
    }
    group.finish();
}

fn bench_graph(c: &mut Criterion) {
    let mut group = c.benchmark_group("graph");
    group.sampling_mode(SamplingMode::Auto);

    for &size in SIZES {
        let setup = setup_scanned(size);
        let doc_path = &setup.first_doc;

        // get_links
        group.bench_with_input(BenchmarkId::new("get_links", size), &size, |b, &_| {
            b.iter(|| {
                black_box(
                    setup
                        .service
                        .get_links(black_box(doc_path))
                        .expect("get_links"),
                );
            });
        });

        // get_backlinks
        group.bench_with_input(BenchmarkId::new("get_backlinks", size), &size, |b, &_| {
            b.iter(|| {
                black_box(
                    setup
                        .service
                        .get_backlinks(black_box(doc_path), black_box(50))
                        .expect("get_backlinks"),
                );
            });
        });

        // traverse_graph with default relations
        let relations: Vec<String> = vec!["*".to_string()];
        group.bench_with_input(BenchmarkId::new("traverse", size), &size, |b, &_| {
            b.iter(|| {
                black_box(
                    setup
                        .service
                        .traverse(
                            black_box(doc_path),
                            black_box(&relations),
                            black_box(3),
                            black_box(50),
                        )
                        .expect("traverse"),
                );
            });
        });
    }
    group.finish();
}

fn bench_validate(c: &mut Criterion) {
    let mut group = c.benchmark_group("validate");
    group.sampling_mode(SamplingMode::Auto);

    for &size in SIZES {
        let setup = setup_scanned(size);

        group.bench_with_input(BenchmarkId::new("all", size), &size, |b, &_| {
            b.iter(|| {
                black_box(setup.service.validate().expect("validate"));
            });
        });
    }
    group.finish();
}

fn bench_stats(c: &mut Criterion) {
    let mut group = c.benchmark_group("stats");
    group.sampling_mode(SamplingMode::Auto);

    for &size in SIZES {
        let setup = setup_scanned(size);

        group.bench_with_input(BenchmarkId::new("get_stats", size), &size, |b, &_| {
            b.iter(|| {
                black_box(setup.service.get_stats().expect("get_stats"));
            });
        });
    }
    group.finish();
}

fn bench_export(c: &mut Criterion) {
    let mut group = c.benchmark_group("export");
    group.sampling_mode(SamplingMode::Auto);

    for &size in SIZES {
        let setup = setup_scanned(size);

        group.bench_with_input(BenchmarkId::new("export_to_json", size), &size, |b, &_| {
            b.iter(|| {
                black_box(setup.service.export_to_json().expect("export"));
            });
        });
    }
    group.finish();
}

fn bench_technical_docs(c: &mut Criterion) {
    let mut group = c.benchmark_group("technical_docs");
    group.sampling_mode(SamplingMode::Auto);

    // Use smaller sizes for technical docs since they're larger
    let tech_sizes = [10, 50, 100];

    for size in tech_sizes {
        let dir = TempDir::new().expect("temp dir");
        generate_technical_docs(dir.path(), size);
        let config = bench_config(dir.path());

        // Benchmark full scan of technical documents
        group.bench_with_input(BenchmarkId::new("scan", size), &size, |b, &_| {
            b.iter(|| {
                let mut service = OkcService::open_in_memory(&config).expect("open");
                black_box(service.scan().expect("scan"));
            });
        });

        // Benchmark incremental scan (re-scan after initial)
        let mut service = OkcService::open_in_memory(&config).expect("open");
        service.scan().expect("initial scan");

        group.bench_with_input(
            BenchmarkId::new("incremental_scan", size),
            &size,
            |b, &_| {
                b.iter(|| {
                    black_box(service.scan().expect("incremental scan"));
                });
            },
        );

        // Benchmark search on technical content
        group.bench_with_input(BenchmarkId::new("search", size), &size, |b, &_| {
            b.iter(|| {
                black_box(
                    service
                        .search(black_box("function"), None, None, None, black_box(100))
                        .expect("search"),
                );
            });
        });
    }
    group.finish();
}

// ---------------------------------------------------------------------------
// Criterion harness
// ---------------------------------------------------------------------------

criterion_group!(
    benches,
    bench_scan,
    bench_browse,
    bench_search,
    bench_document,
    bench_graph,
    bench_validate,
    bench_stats,
    bench_export,
    bench_technical_docs,
);
criterion_main!(benches);