Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions crates/bashkit/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,11 @@ harness = false
name = "awk_regex"
harness = false

[[bench]]
name = "jq"
harness = false
required-features = ["jq"]

[[bench]]
name = "snapshot_history"
harness = false
Expand Down
107 changes: 107 additions & 0 deletions crates/bashkit/benches/jq.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
//! Measure Bashkit's `jq` builtin through `Bash::exec` on a fresh execution.
//!
//! Repeated, interleaved, and distinct filters exercise cache hits and churn.
//! The single-call and larger JSON cases cover workloads without reuse.
//! Run with `cargo bench -p bashkit --features jq --bench jq`.

use std::fmt::Write as _;
use std::hint::black_box;

use bashkit::Bash;
use criterion::{BatchSize, Criterion, Throughput, criterion_group, criterion_main};
use tokio::runtime::Builder;

const CALLS: usize = 64;
const ROWS: usize = 4096;
const INPUT: &str = r#"{"name":"widget","qty":4}"#;
const LOOKUP: &str = r#"jq -r '.name' <<< '{"name":"widget","qty":4}'"#;

fn lookup_script(filters: impl IntoIterator<Item = (String, &'static str)>) -> (String, String) {
let mut script = String::new();
let mut expected = String::new();
for (filter, output) in filters {
writeln!(script, "jq -r '{filter}' <<< '{INPUT}'").unwrap();
writeln!(expected, "{output}").unwrap();
}
(script, expected)
}

fn large_input_script() -> String {
let rows = vec![r#"{"name":"widget","qty":4}"#; ROWS].join(",");
format!("jq 'map(.qty) | add' <<< '[{rows}]'")
}

fn bench_jq(c: &mut Criterion) {
let rt = Builder::new_current_thread().enable_all().build().unwrap();
let mut group = c.benchmark_group("jq");
let interleaved = [
(".name", "widget"),
(".qty", "4"),
(".name | length", "6"),
(".qty > 0", "true"),
];
let cases = [
(
"single_lookup",
(LOOKUP.to_string(), "widget\n".to_string()),
1,
),
(
"repeated_filter",
lookup_script((0..CALLS).map(|_| (".name # 00".to_string(), "widget"))),
CALLS,
),
(
"interleaved_filters",
lookup_script(
interleaved
.into_iter()
.cycle()
.take(CALLS)
.map(|(filter, output)| (filter.to_string(), output)),
),
CALLS,
),
(
"hot_and_unique_filters",
lookup_script((0..CALLS).map(|index| {
if index % 2 == 0 {
(".name".to_string(), "widget")
} else {
(format!(".qty # {index:02}"), "4")
}
})),
CALLS,
),
(
"distinct_filters",
lookup_script((0..CALLS).map(|index| (format!(".name # {index:02}"), "widget"))),
CALLS,
),
(
"aggregate_4096_rows",
(large_input_script(), format!("{}\n", 4 * ROWS)),
1,
),
];
for (name, (script, expected), calls) in &cases {
group.throughput(Throughput::Elements(*calls as u64));
group.bench_function(*name, |b| {
b.to_async(&rt).iter_batched(
Bash::new,
|mut bash| async move {
let output = bash.exec(black_box(script)).await.unwrap();
assert_eq!(output.exit_code, 0, "{}", output.stderr);
assert!(output.stderr.is_empty());
assert_eq!(output.stdout, expected.as_str());
black_box(output);
},
BatchSize::PerIteration,
);
});
}
group.finish();
}

criterion_group!(benches, bench_jq);
criterion_main!(benches);
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Criterion jq Builtin Benchmark

The benchmark measures jq through `Bash::exec`. Each iteration starts a new
execution in a warmed process. The repeated and distinct cases each run 64
commands over the same small input. Only the distinct case varies the filter
source. The aggregate case processes 4,096 JSON objects in one command.

Run with `cargo bench --locked -p bashkit --features jq --bench jq`.

## Initial comparison

Baseline `290ebb01` plus the benchmark harness, compared with request-local
compiled-filter reuse and process-wide reuse of the parsed jaq library
prelude. Both builds used Rust 1.100.0, thin LTO, and eight codegen units.
The Linux x86-64 runner used one pinned Xeon Platinum 8370C CPU, a one-second
warmup, a three-second measurement target, and 30 Criterion samples per case.
Times are the Criterion point estimate per script.

| Benchmark | Before | After | Change |
|---|---:|---:|---:|
| `jq/single_lookup` | 1.061 ms | 0.802 ms | -24.5% |
| `jq/repeated_filter` | 60.564 ms | 2.801 ms | -95.4% |
| `jq/distinct_filters` | 62.478 ms | 48.727 ms | -22.0% |
| `jq/aggregate_4096_rows` | 13.435 ms | 12.964 ms | -3.5% |

Criterion detected a change in the first three workloads. The 4,096-row
aggregate was within measurement noise (`p = 0.30`).

## Inventory fan-out

The archived warehouse fan-out script ran unchanged with in-process fixture
tools and 100 warehouses. The same CPU ran both builds in alternating order
with 100 timed samples per build per round across three rounds. Every run
matched the expected stdout and returned zero with empty stderr.

The median fell from 107.88 ms to 9.48 ms
(11.4×). The 95th percentile fell from
123.13 ms to 11.12 ms. The baseline interpreter
binary was built from `c30c8ba4`, which has the same Bashkit crate and lockfile
as `290ebb01`. Both fan-out binaries used the bench runner's release profile
with 16 codegen units.
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Criterion jq LRU and Filter Compilation Benchmark

Compares the one-entry compiled-filter cache with a four-entry LRU and with
that LRU plus pre-parsed Bashkit compatibility definitions. Each script runs
through `Bash::exec` in a warmed process and asserts the exact output.
The interleaved case cycles through four distinct filters. The mixed case
alternates one hot filter with new filter source on every other call.

Run with `cargo bench --locked -p bashkit --features jq --bench jq`.

## Results

All three builds used Rust 1.100.0 with thin LTO and eight codegen units on
Linux x86-64. The benchmark process ran on the same pinned Xeon Platinum
8370C CPU with a one-second warmup, a three-second measurement target, and
30 Criterion samples per workload. Times are Criterion point estimates per
script. The baseline already reused the parsed jaq library definitions.

| Benchmark | One entry | Four-entry LRU | After | Change |
|---|---:|---:|---:|---:|
| `jq/single_lookup` | 0.879 ms | 0.797 ms | 0.618 ms | -29.7% |
| `jq/repeated_filter` | 2.710 ms | 2.613 ms | 2.318 ms | -14.5% |
| `jq/interleaved_filters` | 48.320 ms | 4.532 ms | 3.969 ms | -91.8% |
| `jq/hot_and_unique_filters` | 51.333 ms | 25.442 ms | 20.265 ms | -60.5% |
| `jq/distinct_filters` | 50.599 ms | 49.472 ms | 37.086 ms | -26.7% |
| `jq/aggregate_4096_rows` | 15.054 ms | 12.710 ms | 13.622 ms | -9.5% |

The first 4,096-row run showed a 7.2% slowdown against the LRU-only build.
Two isolated reruns with reversed ordering gave 13.99 to 13.77 ms and 13.07
to 12.55 ms. Each rerun used 40 Criterion samples per build. Both reruns
favored the pre-parsed build.

## Cache-miss profile

The distinct-filter workload collected 10,584 user-space CPU samples from
the LRU-only build. Named jaq compiler and compiled-graph code accounted for
32% of samples, and the lexer and parser accounted for 11%. Pre-parsing the
fixed compatibility definitions cut the distinct-filter benchmark by 25%.
The follow-up profile collected 4,601 samples from the combined build, with
1.2% in the lexer and parser and 40% in compiler and compiled-graph code.
Each miss still rebuilds jaq's compiled program graph.

## Inventory fan-out

The archived 100-warehouse script ran unchanged with the same in-process
fixture tools. Each comparison alternated the builds across three rounds,
with 100 timed samples per build per round. Every run returned zero with
empty stderr and matched the expected output.

The one-entry and four-entry builds had medians of 9.30 and 9.15 ms.
In a separate run the four-entry build took 9.09 ms and the combined
build took 8.78 ms. The script reuses one main filter in its loop, so
it sees more of the compile-path improvement than the LRU expansion.
34 changes: 17 additions & 17 deletions crates/bashkit/src/builtins/jq/compat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,8 @@ pub(super) const LINENO_VAR_NAME: &str = "$__bashkit_lineno__";
/// `$ARGS` global, populated from `--args` / `--jsonargs` / `--arg` / `--argjson`.
pub(super) const ARGS_VAR_NAME: &str = "$ARGS";

/// Compat definitions prepended to every user filter. Order matters: each
/// def must precede any other def that references it (jaq resolves
/// top-down). The trailing `;` after every def is required.
/// Compatibility definitions appended to jaq's prelude. Each definition
/// comes before the ones that use it because jaq resolves in source order.
pub(super) const JQ_COMPAT_DEFS: &str = r#"
def setpath(p; v):
p as $p | v as $v |
Expand Down Expand Up @@ -192,12 +191,13 @@ def @csv:
] | join(",");
"#;

/// Build the prepended-defs prefix that wires `env`, `$ENV`,
/// `input_filename`, and `input_line_number` to internal globals.
pub(super) fn build_compat_prefix() -> String {
/// Start the main expression with the helpers that read invocation globals.
/// Keeping a definition prefix also preserves the existing grammar for user
/// filters. `module`, `include`, and `import` directives can only occur
/// before the definitions in jaq's parser.
pub(super) fn build_global_defs() -> String {
format!(
"{JQ_COMPAT_DEFS}\n\
def env: {ENV_VAR_NAME};\n\
"def env: {ENV_VAR_NAME};\n\
def input_filename: {FILENAME_VAR_NAME};\n\
def input_line_number: {LINENO_VAR_NAME};\n"
)
Expand All @@ -208,26 +208,26 @@ mod tests {
use super::*;

#[test]
fn build_compat_prefix_includes_setpath() {
let prefix = build_compat_prefix();
assert!(prefix.contains("def setpath"));
fn prelude_includes_setpath() {
let defs = jaq_core::load::parse(JQ_COMPAT_DEFS, |parser| parser.defs()).unwrap();
assert!(defs.iter().any(|def| def.name == "setpath"));
}

#[test]
fn build_compat_prefix_includes_env_def() {
let prefix = build_compat_prefix();
fn build_global_defs_includes_env_def() {
let prefix = build_global_defs();
assert!(prefix.contains("def env: $__bashkit_env__"));
}

#[test]
fn build_compat_prefix_includes_filename_def() {
let prefix = build_compat_prefix();
fn build_global_defs_includes_filename_def() {
let prefix = build_global_defs();
assert!(prefix.contains("def input_filename: $__bashkit_filename__"));
}

#[test]
fn build_compat_prefix_includes_lineno_def() {
let prefix = build_compat_prefix();
fn build_global_defs_includes_lineno_def() {
let prefix = build_global_defs();
assert!(prefix.contains("def input_line_number: $__bashkit_lineno__"));
}

Expand Down
Loading
Loading