bashkit 0.7.2

Awesomely fast virtual sandbox with bash and file system
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
//! VFS / file-operation benchmarks.
//!
//! Today's bench coverage stops at trivial three-line `grep`/`awk`/`sed`
//! cases. This file fills in the workloads users actually hit:
//!
//!   - **Read throughput** — `cat`/`grep` over 1 KB, 1 MB, 50 MB files.
//!     Modeled on `sqlite.rs`'s backend-comparison shape (parametrized
//!     by file size instead of backend).
//!   - **Traversal** — `ls -R`, `find . -name`, and `for f in *` over a
//!     1000-file generated tree.
//!   - **`rg` workloads** — literal, regex, `--no-ignore`, `--multiline`,
//!     recursive over the same tree. Highest-churn builtin right now
//!     (~15 fixes in PRs #1742–#1767) with zero perf guard until this file.
//!   - **`grep -r` vs `rg`** at parity, so regressions in either show up.
//!   - **Glob expansion** — `echo **/*` (interpreter glob path, not a
//!     builtin) over the same tree.
//!
//! The seeded VFS is built once per bench group and shared via
//! `Bash::builder().fs(fs.clone()).build()` for each iteration — same
//! pattern `sqlite.rs` uses for shared-VFS parallel sessions. Iterations
//! pay one `Bash::new()` constant overhead; read paths are what we time.
//!
//! Run with: `cargo bench --bench file_ops`

use bashkit::{Bash, FileSystem, FsLimits, InMemoryFs};
use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main};
use std::path::Path;
use std::sync::Arc;
use tokio::runtime::Runtime;

/// File sizes for read-throughput benches.
/// Tune the "large" entry down (e.g. to 5 MB) if running on memory-constrained
/// CI: criterion's default 100 samples × 50 MB = 5 GB of reads per bench.
const FILE_SIZES: &[(&str, usize)] = &[
    ("1KB", 1024),
    ("1MB", 1024 * 1024),
    ("50MB", 50 * 1024 * 1024),
];

/// Total files in the generated tree, fanned out across `TREE_DIRS` subdirs.
const TREE_FILES: usize = 1000;
const TREE_DIRS: usize = 10;
const TREE_ROOT: &str = "/work";

/// Build a fresh seeded FS containing one `/data/file.txt` of `size` bytes.
/// Pattern is `"abc\n"` repeated — predictable line count so we can
/// sanity-check `wc -l` from a `verify_*` test if needed.
fn seed_single_file(rt: &Runtime, size: usize) -> Arc<InMemoryFs> {
    // Default FsLimits caps individual file size at 10 MB; bench needs 50 MB.
    let fs = Arc::new(InMemoryFs::with_limits(FsLimits::unlimited()));
    rt.block_on(async {
        let fs_dyn: Arc<dyn FileSystem> = fs.clone();
        fs_dyn
            .mkdir(Path::new("/data"), true)
            .await
            .expect("mkdir /data");
        let mut buf = Vec::with_capacity(size);
        let chunk = b"abcdefghij\n"; // 11 bytes, includes newline
        while buf.len() + chunk.len() <= size {
            buf.extend_from_slice(chunk);
        }
        // Pad with zeros (no extra newlines) to hit `size` exactly.
        buf.resize(size, b'.');
        fs_dyn
            .write_file(Path::new("/data/file.txt"), &buf)
            .await
            .expect("write /data/file.txt");
    });
    fs
}

/// Build a 1000-file tree fanned across 10 subdirs. Each file gets the
/// same small body with a per-file marker, so `grep`/`rg` benches have
/// real content to match.
fn seed_tree(rt: &Runtime) -> Arc<InMemoryFs> {
    let fs = Arc::new(InMemoryFs::with_limits(FsLimits::unlimited()));
    rt.block_on(async {
        let fs_dyn: Arc<dyn FileSystem> = fs.clone();
        fs_dyn
            .mkdir(Path::new(TREE_ROOT), true)
            .await
            .expect("mkdir root");
        let per_dir = TREE_FILES / TREE_DIRS;
        for d in 0..TREE_DIRS {
            let dir = format!("{TREE_ROOT}/d{d:02}");
            fs_dyn
                .mkdir(Path::new(&dir), true)
                .await
                .expect("mkdir subdir");
            for f in 0..per_dir {
                let path = format!("{dir}/f{f:03}.txt");
                // ~6 lines per file; one in five carries "needle" so
                // recursive search has a non-trivial hit count.
                let mut body =
                    format!("alpha {d} {f}\nbeta {d} {f}\ngamma\ndelta\nepsilon\nzeta\n");
                if (d * per_dir + f).is_multiple_of(5) {
                    body.push_str("needle here\n");
                }
                fs_dyn
                    .write_file(Path::new(&path), body.as_bytes())
                    .await
                    .expect("write tree file");
            }
        }
    });
    fs
}

/// Spin up a Bash sharing the pre-seeded VFS. One construction per iter
/// (constant overhead) — same pattern as `parallel_execution.rs::single_*`.
fn bash_with(fs: &Arc<InMemoryFs>) -> Bash {
    let fs_dyn: Arc<dyn FileSystem> = fs.clone();
    Bash::builder().fs(fs_dyn).build()
}

// ---------------------------------------------------------------------------
// VFS read throughput: cat + grep over 1 KB / 1 MB / 50 MB.
// ---------------------------------------------------------------------------

fn bench_read_throughput(c: &mut Criterion) {
    let rt = Runtime::new().unwrap();
    let mut g = c.benchmark_group("read_throughput");
    for (label, size) in FILE_SIZES {
        let fs = seed_single_file(&rt, *size);
        g.throughput(Throughput::Bytes(*size as u64));

        g.bench_with_input(BenchmarkId::new("cat", label), &fs, |b, fs| {
            b.to_async(&rt).iter(|| {
                let fs = fs.clone();
                async move {
                    let mut bash = bash_with(&fs);
                    let _ = bash.exec("cat /data/file.txt >/dev/null").await;
                }
            });
        });

        g.bench_with_input(BenchmarkId::new("grep_literal", label), &fs, |b, fs| {
            b.to_async(&rt).iter(|| {
                let fs = fs.clone();
                async move {
                    let mut bash = bash_with(&fs);
                    let _ = bash.exec("grep abcdef /data/file.txt >/dev/null").await;
                }
            });
        });

        g.bench_with_input(BenchmarkId::new("grep_count", label), &fs, |b, fs| {
            b.to_async(&rt).iter(|| {
                let fs = fs.clone();
                async move {
                    let mut bash = bash_with(&fs);
                    let _ = bash.exec("grep -c abc /data/file.txt >/dev/null").await;
                }
            });
        });
    }
    g.finish();
}

// ---------------------------------------------------------------------------
// Tree traversal: ls -R, find, glob expansion.
// ---------------------------------------------------------------------------

fn bench_traversal(c: &mut Criterion) {
    let rt = Runtime::new().unwrap();
    let fs = seed_tree(&rt);
    let mut g = c.benchmark_group("traversal");

    g.bench_function("ls_R_1k_files", |b| {
        b.to_async(&rt).iter(|| {
            let fs = fs.clone();
            async move {
                let mut bash = bash_with(&fs);
                let _ = bash.exec("ls -R /work >/dev/null").await;
            }
        });
    });

    g.bench_function("find_by_name_1k_files", |b| {
        b.to_async(&rt).iter(|| {
            let fs = fs.clone();
            async move {
                let mut bash = bash_with(&fs);
                let _ = bash.exec("find /work -name 'f001.txt' >/dev/null").await;
            }
        });
    });

    g.bench_function("find_no_filter_1k_files", |b| {
        b.to_async(&rt).iter(|| {
            let fs = fs.clone();
            async move {
                let mut bash = bash_with(&fs);
                let _ = bash.exec("find /work >/dev/null").await;
            }
        });
    });

    // Interpreter glob expansion (NOT a builtin). Two shapes:
    //   - shallow `*` glob (one directory level)
    //   - recursive `**/*` glob (globstar shopt)
    g.bench_function("glob_shallow_subdir", |b| {
        b.to_async(&rt).iter(|| {
            let fs = fs.clone();
            async move {
                let mut bash = bash_with(&fs);
                let _ = bash.exec("for f in /work/d00/*; do :; done").await;
            }
        });
    });

    g.bench_function("glob_globstar_1k_files", |b| {
        b.to_async(&rt).iter(|| {
            let fs = fs.clone();
            async move {
                let mut bash = bash_with(&fs);
                let _ = bash
                    .exec("shopt -s globstar; for f in /work/**/*; do :; done")
                    .await;
            }
        });
    });

    // Interpreter glob materialized into a single command's argv.
    g.bench_function("glob_echo_globstar", |b| {
        b.to_async(&rt).iter(|| {
            let fs = fs.clone();
            async move {
                let mut bash = bash_with(&fs);
                let _ = bash
                    .exec("shopt -s globstar; echo /work/**/* >/dev/null")
                    .await;
            }
        });
    });

    g.finish();
}

// ---------------------------------------------------------------------------
// rg workloads — literal, regex, --no-ignore, --multiline, recursive.
// ---------------------------------------------------------------------------

fn bench_rg(c: &mut Criterion) {
    let rt = Runtime::new().unwrap();
    let fs = seed_tree(&rt);
    let mut g = c.benchmark_group("rg");

    g.bench_function("literal_recursive", |b| {
        b.to_async(&rt).iter(|| {
            let fs = fs.clone();
            async move {
                let mut bash = bash_with(&fs);
                let _ = bash.exec("rg needle /work >/dev/null").await;
            }
        });
    });

    g.bench_function("regex_recursive", |b| {
        b.to_async(&rt).iter(|| {
            let fs = fs.clone();
            async move {
                let mut bash = bash_with(&fs);
                let _ = bash.exec(r"rg '\balpha \d+ \d+\b' /work >/dev/null").await;
            }
        });
    });

    // --no-ignore: forces traversal to ignore .gitignore-style rules.
    // No ignore files in the seeded tree, but the flag still exercises
    // a different code path through the ignore stack.
    g.bench_function("no_ignore_recursive", |b| {
        b.to_async(&rt).iter(|| {
            let fs = fs.clone();
            async move {
                let mut bash = bash_with(&fs);
                let _ = bash.exec("rg --no-ignore needle /work >/dev/null").await;
            }
        });
    });

    g.bench_function("multiline_recursive", |b| {
        b.to_async(&rt).iter(|| {
            let fs = fs.clone();
            async move {
                let mut bash = bash_with(&fs);
                let _ = bash
                    .exec(r"rg --multiline 'alpha.*\n.*beta' /work >/dev/null")
                    .await;
            }
        });
    });

    // Single-file rg — separates per-file overhead from traversal cost.
    g.bench_function("literal_single_file", |b| {
        b.to_async(&rt).iter(|| {
            let fs = fs.clone();
            async move {
                let mut bash = bash_with(&fs);
                let _ = bash.exec("rg needle /work/d00/f000.txt >/dev/null").await;
            }
        });
    });

    g.finish();
}

// ---------------------------------------------------------------------------
// grep -r vs rg parity — same query, same tree, different builtins.
// Regressions in either show up as a divergence on the same chart.
// ---------------------------------------------------------------------------

fn bench_grep_rg_parity(c: &mut Criterion) {
    let rt = Runtime::new().unwrap();
    let fs = seed_tree(&rt);
    let mut g = c.benchmark_group("grep_vs_rg");

    g.bench_function("grep_r_literal", |b| {
        b.to_async(&rt).iter(|| {
            let fs = fs.clone();
            async move {
                let mut bash = bash_with(&fs);
                let _ = bash.exec("grep -r needle /work >/dev/null").await;
            }
        });
    });

    g.bench_function("rg_literal", |b| {
        b.to_async(&rt).iter(|| {
            let fs = fs.clone();
            async move {
                let mut bash = bash_with(&fs);
                let _ = bash.exec("rg needle /work >/dev/null").await;
            }
        });
    });

    g.bench_function("grep_r_regex", |b| {
        b.to_async(&rt).iter(|| {
            let fs = fs.clone();
            async move {
                let mut bash = bash_with(&fs);
                let _ = bash
                    .exec(r"grep -rE 'alpha [0-9]+ [0-9]+' /work >/dev/null")
                    .await;
            }
        });
    });

    g.bench_function("rg_regex", |b| {
        b.to_async(&rt).iter(|| {
            let fs = fs.clone();
            async move {
                let mut bash = bash_with(&fs);
                let _ = bash
                    .exec(r"rg 'alpha [0-9]+ [0-9]+' /work >/dev/null")
                    .await;
            }
        });
    });

    g.finish();
}

// ---------------------------------------------------------------------------
// Sanity checks (compile-time-cheap, runs under `cargo test`).
// ---------------------------------------------------------------------------

#[test]
fn verify_seed_single_file() {
    let rt = Runtime::new().unwrap();
    let fs = seed_single_file(&rt, 1024);
    rt.block_on(async {
        let mut bash = bash_with(&fs);
        let res = bash.exec("wc -c </data/file.txt").await.expect("exec wc");
        assert_eq!(res.stdout.trim(), "1024", "expected 1024 bytes");
    });
}

#[test]
fn verify_seed_tree() {
    let rt = Runtime::new().unwrap();
    let fs = seed_tree(&rt);
    rt.block_on(async {
        let mut bash = bash_with(&fs);
        let res = bash
            .exec("find /work -type f | wc -l")
            .await
            .expect("exec find");
        assert_eq!(
            res.stdout.trim(),
            TREE_FILES.to_string(),
            "expected {TREE_FILES} files"
        );
    });
}

criterion_group!(
    benches,
    bench_read_throughput,
    bench_traversal,
    bench_rg,
    bench_grep_rg_parity,
);
criterion_main!(benches);