aptu-coder-core 0.30.0

Multi-language AST analysis library using tree-sitter
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
// SPDX-FileCopyrightText: 2026 aptu-coder contributors
// SPDX-License-Identifier: Apache-2.0

use aptu_coder_core::cache::{CallGraphCache, CallGraphCacheKey};
use aptu_coder_core::graph::StructuralGraph;
use aptu_coder_core::types::SymbolMatchMode;
use criterion::{Criterion, criterion_group, criterion_main};
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use tokio_util::sync::CancellationToken;

fn overview_benchmark(c: &mut Criterion) {
    let mut group = c.benchmark_group("overview");
    group.sample_size(10);

    group.bench_function("analyze_directory_src", |b| {
        b.iter(|| {
            let path = std::hint::black_box(Path::new("src"));
            let entries = aptu_coder_core::traversal::walk_directory(path, None).unwrap();
            let progress = Arc::new(AtomicUsize::new(0));
            let ct = CancellationToken::new();

            aptu_coder_core::analyze::analyze_directory_with_progress(path, entries, progress, ct)
        });
    });

    group.finish();
}

fn file_details_benchmark(c: &mut Criterion) {
    let mut group = c.benchmark_group("file_details");
    group.sample_size(10);

    group.bench_function("analyze_file_lib_rs", |b| {
        b.iter(|| {
            let path = std::hint::black_box("src/lib.rs");
            let ast_recursion_limit = std::hint::black_box(None);

            aptu_coder_core::analyze::analyze_file(path, ast_recursion_limit)
        });
    });

    group.finish();
}

fn symbol_focus_benchmark(c: &mut Criterion) {
    let mut group = c.benchmark_group("symbol_focus");
    group.sample_size(10);

    group.bench_function("analyze_focused_src", |b| {
        b.iter(|| {
            let path = std::hint::black_box(Path::new("src"));
            let focus = std::hint::black_box("analyze_directory".to_string());
            let follow_depth = std::hint::black_box(2);
            let max_depth = std::hint::black_box(None);
            let ast_recursion_limit = std::hint::black_box(None);
            let progress = Arc::new(AtomicUsize::new(0));
            let ct = CancellationToken::new();

            let params = aptu_coder_core::analyze::FocusedAnalysisConfig {
                focus,
                match_mode: SymbolMatchMode::Exact,
                follow_depth,
                max_depth,
                ast_recursion_limit,
                use_summary: false,
                impl_only: None,
                def_use: false,
                parse_timeout_micros: None,
            };

            aptu_coder_core::analyze::analyze_focused_with_progress(path, &params, progress, ct)
        });
    });

    group.finish();
}

fn subtree_count_overhead(c: &mut Criterion) {
    use std::fs;
    use tempfile::TempDir;

    // Create fixture: root/ with 3 levels and 120 files (5 * 4 * 6)
    let dir = TempDir::new().unwrap();
    let root = dir.path();
    for i in 0..5usize {
        for j in 0..4usize {
            let subsub = root.join(format!("sub{}", i)).join(format!("subsub{}", j));
            fs::create_dir_all(&subsub).unwrap();
            for k in 0..6usize {
                fs::write(subsub.join(format!("file{}.rs", k)), b"fn main() {}").unwrap();
            }
        }
    }

    let mut group = c.benchmark_group("subtree_count_overhead");
    group.sample_size(10);

    group.bench_function("baseline_walk_only", |b| {
        b.iter(|| {
            let entries = aptu_coder_core::traversal::walk_directory(
                std::hint::black_box(root),
                std::hint::black_box(None),
            )
            .unwrap();
            std::hint::black_box(entries)
        })
    });

    group.bench_function("with_single_walk_and_count", |b| {
        b.iter(|| {
            // Single unbounded walk; compute counts in-memory; filter for bounded subset.
            let all_entries = aptu_coder_core::traversal::walk_directory(
                std::hint::black_box(root),
                std::hint::black_box(None),
            )
            .unwrap();
            let counts = aptu_coder_core::traversal::subtree_counts_from_entries(
                std::hint::black_box(root),
                &all_entries,
            );
            let bounded: Vec<_> = all_entries.into_iter().filter(|e| e.depth <= 2).collect();
            std::hint::black_box((bounded, counts))
        })
    });

    group.finish();
    // Keep dir alive until benchmarks are done
    drop(dir);
}

fn subtree_count_overhead_500(c: &mut Criterion) {
    use std::fs;
    use tempfile::TempDir;

    // Create fixture: 3 directory levels deep; files sit at depth 4 (root=0, sub=1, subsub=2, subsubsub=3, file=4).
    // Total: 5 * 5 * 4 * 5 = 500 files.
    let dir = TempDir::new().unwrap();
    let root = dir.path();
    for i in 0..5usize {
        for j in 0..5usize {
            for k in 0..4usize {
                let subdir = root
                    .join(format!("sub{}", i))
                    .join(format!("subsub{}", j))
                    .join(format!("subsubsub{}", k));
                fs::create_dir_all(&subdir).unwrap();
                for m in 0..5usize {
                    fs::write(subdir.join(format!("file{}.rs", m)), b"fn main() {}").unwrap();
                }
            }
        }
    }

    let mut group = c.benchmark_group("subtree_count_overhead_500");
    group.sample_size(10);

    group.bench_function("baseline_walk_only", |b| {
        b.iter(|| {
            let entries = aptu_coder_core::traversal::walk_directory(
                std::hint::black_box(root),
                std::hint::black_box(None),
            )
            .unwrap();
            std::hint::black_box(entries)
        })
    });

    group.bench_function("with_single_walk_and_count", |b| {
        b.iter(|| {
            // Single unbounded walk; compute counts in-memory.
            // Both this and baseline_walk_only do an unbounded walk; the only difference is the counting step.
            let all_entries = aptu_coder_core::traversal::walk_directory(
                std::hint::black_box(root),
                std::hint::black_box(None),
            )
            .unwrap();
            let counts = aptu_coder_core::traversal::subtree_counts_from_entries(
                std::hint::black_box(root),
                &all_entries,
            );
            std::hint::black_box((all_entries, counts))
        })
    });

    group.finish();
    // Keep dir alive until benchmarks are done
    drop(dir);
}

fn subtree_count_overhead_1000(c: &mut Criterion) {
    use std::fs;
    use tempfile::TempDir;

    // Create fixture: 5 * 5 * 5 * 8 = 1000 files.
    // Directory structure: root/sub{0-4}/subsub{0-4}/subsubsub{0-4}/file{0-7}.rs
    let dir = TempDir::new().unwrap();
    let root = dir.path();
    for i in 0..5usize {
        for j in 0..5usize {
            for k in 0..5usize {
                let subdir = root
                    .join(format!("sub{}", i))
                    .join(format!("subsub{}", j))
                    .join(format!("subsubsub{}", k));
                fs::create_dir_all(&subdir).unwrap();
                for m in 0..8usize {
                    fs::write(subdir.join(format!("file{}.rs", m)), b"fn main() {}").unwrap();
                }
            }
        }
    }

    let mut group = c.benchmark_group("subtree_count_overhead_1000");
    group.sample_size(10);

    group.bench_function("baseline_walk_only_1000", |b| {
        b.iter(|| {
            let entries = aptu_coder_core::traversal::walk_directory(
                std::hint::black_box(root),
                std::hint::black_box(None),
            )
            .unwrap();
            std::hint::black_box(entries)
        })
    });

    group.bench_function("with_single_walk_and_count_1000", |b| {
        b.iter(|| {
            // Single unbounded walk; compute counts in-memory.
            let all_entries = aptu_coder_core::traversal::walk_directory(
                std::hint::black_box(root),
                std::hint::black_box(None),
            )
            .unwrap();
            let counts = aptu_coder_core::traversal::subtree_counts_from_entries(
                std::hint::black_box(root),
                &all_entries,
            );
            std::hint::black_box((all_entries, counts))
        })
    });

    group.finish();
    // Keep dir alive until benchmarks are done
    drop(dir);
}

fn analyze_module_benchmark(c: &mut Criterion) {
    let mut group = c.benchmark_group("analyze_module");
    group.sample_size(10);

    group.bench_function("analyze_module_file_lib_rs", |b| {
        b.iter(|| {
            let path = std::hint::black_box("src/lib.rs");
            aptu_coder_core::analyze::analyze_module_file(path)
        });
    });

    group.finish();
}

fn analyze_directory_depth_benchmark(c: &mut Criterion) {
    let mut group = c.benchmark_group("analyze_directory_depth");
    group.sample_size(10);

    // Benchmark max_depth=1 at repo root (sync walker path)
    group.bench_function("depth_1_repo_root", |b| {
        b.iter(|| {
            let path = std::hint::black_box(Path::new("."));
            let entries =
                aptu_coder_core::traversal::walk_directory(path, std::hint::black_box(Some(1)))
                    .unwrap();
            let progress = Arc::new(AtomicUsize::new(0));
            let ct = CancellationToken::new();

            aptu_coder_core::analyze::analyze_directory_with_progress(path, entries, progress, ct)
        });
    });

    // Benchmark max_depth=2 at repo root (parallel walker path for comparison)
    group.bench_function("depth_2_repo_root", |b| {
        b.iter(|| {
            let path = std::hint::black_box(Path::new("."));
            let entries =
                aptu_coder_core::traversal::walk_directory(path, std::hint::black_box(Some(2)))
                    .unwrap();
            let progress = Arc::new(AtomicUsize::new(0));
            let ct = CancellationToken::new();

            aptu_coder_core::analyze::analyze_directory_with_progress(path, entries, progress, ct)
        });
    });

    group.finish();
}

fn call_graph_cache_benchmark(c: &mut Criterion) {
    let root = Path::new("src");
    let entries = aptu_coder_core::traversal::walk_directory(root, None).unwrap();

    let params = aptu_coder_core::analyze::FocusedAnalysisConfig {
        focus: "analyze_directory".to_string(),
        match_mode: SymbolMatchMode::Exact,
        follow_depth: 2,
        max_depth: None,
        ast_recursion_limit: None,
        use_summary: false,
        impl_only: None,
        def_use: false,
        parse_timeout_micros: None,
    };

    // Pre-compute output and populate cache for warm_hit benchmark
    let precomputed_progress = Arc::new(AtomicUsize::new(0));
    let precomputed_ct = CancellationToken::new();
    let output = aptu_coder_core::analyze::analyze_focused_with_progress_with_entries(
        root,
        &params,
        &precomputed_progress,
        &precomputed_ct,
        &entries,
        None,
    )
    .unwrap();

    let key = CallGraphCacheKey::from_entries(
        root,
        &entries,
        None,
        params.follow_depth,
        &params.match_mode,
        params.impl_only.unwrap_or(false),
        params.ast_recursion_limit,
    );
    let cache = CallGraphCache::new(32);
    cache.put(key.clone(), Arc::new(output));

    let mut group = c.benchmark_group("call_graph_cache");
    group.sample_size(10);

    group.bench_function("cold_miss", |b| {
        b.iter(|| {
            let progress = Arc::new(AtomicUsize::new(0));
            let ct = CancellationToken::new();

            aptu_coder_core::analyze::analyze_focused_with_progress_with_entries(
                std::hint::black_box(root),
                std::hint::black_box(&params),
                std::hint::black_box(&progress),
                std::hint::black_box(&ct),
                std::hint::black_box(&entries),
                None,
            )
        });
    });

    group.bench_function("warm_hit", |b| {
        b.iter(|| cache.get(std::hint::black_box(&key)));
    });

    group.finish();
}

fn structural_graph_benchmark(c: &mut Criterion) {
    use aptu_coder_core::cache::StructuralGraphCache;

    let root = Path::new("src");
    let entries = aptu_coder_core::traversal::walk_directory(root, None).unwrap();

    let file_outputs: Vec<_> = entries
        .iter()
        .filter(|e| !e.is_dir && e.path.extension().is_some_and(|ext| ext == "rs"))
        .map(|e| aptu_coder_core::analyze::analyze_file(e.path.to_str().unwrap(), None).unwrap())
        .collect();

    // Compute cache key from mtimes
    let mut mtimes = Vec::new();
    for e in &entries {
        if !e.is_dir && !e.is_symlink {
            let m = e
                .mtime
                .and_then(|t| {
                    t.duration_since(std::time::SystemTime::UNIX_EPOCH)
                        .ok()
                        .map(|d| d.as_millis() as u64)
                })
                .unwrap_or(0);
            mtimes.push((e.path.clone(), m));
        }
    }
    let cache_key = aptu_coder_core::graph::GraphDiskStore::cache_key(root, &mtimes);

    // Pre-build and populate cache
    let graph = std::sync::Arc::new(StructuralGraph::build_from_analysis(&file_outputs));
    let sg_cache = StructuralGraphCache::new(16);
    sg_cache.put(cache_key.clone(), graph.clone());

    let mut group = c.benchmark_group("structural_graph");
    group.sample_size(10);

    group.bench_function("cold_miss", |b| {
        b.iter(|| StructuralGraph::build_from_analysis(std::hint::black_box(&file_outputs)));
    });

    group.bench_function("warm_hit", |b| {
        b.iter(|| sg_cache.get(std::hint::black_box(&cache_key)));
    });

    group.finish();
}

criterion_group!(
    benches,
    overview_benchmark,
    file_details_benchmark,
    symbol_focus_benchmark,
    subtree_count_overhead,
    subtree_count_overhead_500,
    subtree_count_overhead_1000,
    analyze_module_benchmark,
    analyze_directory_depth_benchmark,
    call_graph_cache_benchmark,
    structural_graph_benchmark
);
criterion_main!(benches);