From d16a5cd3855b062322b88c994b589f7d6ea73bfd Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Sun, 22 Nov 2026 02:00:59 +0000 Subject: [PATCH] perf(jq): reuse compiled filters within an execution --- crates/bashkit/Cargo.toml | 5 + crates/bashkit/benches/jq.rs | 107 +++++++ ...terion-jq-cloud-linux-x86_64-1795241820.md | 41 +++ ...on-jq-lru-cloud-linux-x86_64-1795243168.md | 53 ++++ crates/bashkit/src/builtins/jq/compat.rs | 34 +-- crates/bashkit/src/builtins/jq/filter.rs | 273 ++++++++++++++++++ crates/bashkit/src/builtins/jq/mod.rs | 171 ++--------- crates/bashkit/src/builtins/jq/tests.rs | 60 ++++ crates/bashkit/src/builtins/mod.rs | 2 + crates/bashkit/src/lib.rs | 2 + knowledge/foundations/jq.md | 20 ++ 11 files changed, 612 insertions(+), 156 deletions(-) create mode 100644 crates/bashkit/benches/jq.rs create mode 100644 crates/bashkit/benches/results/criterion-jq-cloud-linux-x86_64-1795241820.md create mode 100644 crates/bashkit/benches/results/criterion-jq-lru-cloud-linux-x86_64-1795243168.md create mode 100644 crates/bashkit/src/builtins/jq/filter.rs diff --git a/crates/bashkit/Cargo.toml b/crates/bashkit/Cargo.toml index 0aa0288d5..ee2540b1b 100644 --- a/crates/bashkit/Cargo.toml +++ b/crates/bashkit/Cargo.toml @@ -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 diff --git a/crates/bashkit/benches/jq.rs b/crates/bashkit/benches/jq.rs new file mode 100644 index 000000000..bd1c4dbb9 --- /dev/null +++ b/crates/bashkit/benches/jq.rs @@ -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) -> (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); diff --git a/crates/bashkit/benches/results/criterion-jq-cloud-linux-x86_64-1795241820.md b/crates/bashkit/benches/results/criterion-jq-cloud-linux-x86_64-1795241820.md new file mode 100644 index 000000000..8b66a68c4 --- /dev/null +++ b/crates/bashkit/benches/results/criterion-jq-cloud-linux-x86_64-1795241820.md @@ -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. diff --git a/crates/bashkit/benches/results/criterion-jq-lru-cloud-linux-x86_64-1795243168.md b/crates/bashkit/benches/results/criterion-jq-lru-cloud-linux-x86_64-1795243168.md new file mode 100644 index 000000000..49e7f9479 --- /dev/null +++ b/crates/bashkit/benches/results/criterion-jq-lru-cloud-linux-x86_64-1795243168.md @@ -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. diff --git a/crates/bashkit/src/builtins/jq/compat.rs b/crates/bashkit/src/builtins/jq/compat.rs index f10cfad16..b9dc98b4b 100644 --- a/crates/bashkit/src/builtins/jq/compat.rs +++ b/crates/bashkit/src/builtins/jq/compat.rs @@ -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 | @@ -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" ) @@ -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__")); } diff --git a/crates/bashkit/src/builtins/jq/filter.rs b/crates/bashkit/src/builtins/jq/filter.rs new file mode 100644 index 000000000..c5a554841 --- /dev/null +++ b/crates/bashkit/src/builtins/jq/filter.rs @@ -0,0 +1,273 @@ +//! Compile jq filters and cache small inline programs within one request. + +use std::sync::{Arc, Mutex, OnceLock}; + +use jaq_core::Compiler; +use jaq_core::load::{Arena, File, Loader}; +use jaq_std::input::HasInputs; + +use super::compat::{ + ARGS_VAR_NAME, ENV_VAR_NAME, FILENAME_VAR_NAME, JQ_COMPAT_DEFS, LINENO_VAR_NAME, + PUBLIC_ENV_VAR_NAME, build_global_defs, +}; +use super::errors::{format_compile_errors, format_load_errors}; +use super::{InputData, Val, altpat, jaq_json, loc, messages, regex_compat}; + +pub(super) type CompiledFilter = jaq_core::Filter>; + +const MAX_CACHED_FILTERS: usize = 4; + +/// Retains up to four compiled plans per execution. The most recently used +/// entry is last. Keys contain inline source and ordered binding names. +#[derive(Default)] +pub(crate) struct JqFilterCache(Mutex>); + +struct CachedFilter { + source: String, + var_names: Vec, + filter: Arc, +} + +impl CachedFilter { + fn matches(&self, source: &str, var_names: &[&str]) -> bool { + self.source == source && self.var_names == var_names + } +} + +impl JqFilterCache { + pub(super) fn accepts(source: &str, var_names: &[&str]) -> bool { + // Bound retained user-controlled source and bindings per entry. + source.len() <= 1024 + && var_names.len() <= 16 + && var_names.iter().map(|name| name.len()).sum::() <= 1024 + } + + pub(super) fn get(&self, source: &str, var_names: &[&str]) -> Option> { + let mut entries = self.0.lock().ok()?; + let index = entries + .iter() + .rposition(|entry| entry.matches(source, var_names))?; + let filter = Arc::clone(&entries[index].filter); + entries[index..].rotate_left(1); + Some(filter) + } + + pub(super) fn insert(&self, source: &str, var_names: &[&str], filter: &Arc) { + let entry = CachedFilter { + source: source.to_owned(), + var_names: var_names.iter().map(|name| (*name).to_owned()).collect(), + filter: Arc::clone(filter), + }; + let Ok(mut entries) = self.0.lock() else { + return; + }; + // Concurrent misses for the same key occupy a single slot. + let evicted = if let Some(index) = entries.iter().position(|e| e.matches(source, var_names)) + { + Some(entries.remove(index)) + } else if entries.len() == MAX_CACHED_FILTERS { + Some(entries.remove(0)) + } else { + None + }; + entries.push(entry); + // Retire the compiled graph after other calls can look up their keys. + drop(entries); + drop(evicted); + } +} + +pub(super) fn compile( + filter_text: &str, + var_names: &[&str], +) -> std::result::Result { + let prefix = build_global_defs(); + let filter_text = loc::expand_loc(filter_text); + let filter_text = altpat::expand_alternatives(&filter_text); + let compat_filter = format!("{prefix}\n{filter_text}"); + let filter_src = compat_filter.as_str(); + + // Only the library's immutable, trusted definitions live across requests. + // The loader still owns and resolves modules separately for every filter. + static PRELUDE: OnceLock>> = OnceLock::new(); + let defs = PRELUDE.get_or_init(|| { + let compat = jaq_core::load::parse(JQ_COMPAT_DEFS, |parser| parser.defs()) + .expect("embedded jq compatibility definitions must parse"); + jaq_core::defs() + .chain(jaq_std::defs()) + .chain(jaq_json::defs()) + .chain(compat) + .collect() + }); + let loader = Loader::new(defs.iter().cloned()); + let arena = Arena::default(); + + let program = File { + code: filter_src, + path: (), + }; + + let modules = match loader.load(&arena, program) { + Ok(m) => m, + Err(errs) => return Err(format_load_errors(errs)), + }; + + // Names of all globals: --arg/--argjson/--slurpfile/--rawfile, then the + // four internal ones (env, ENV, filename, lineno), then $ARGS. + let mut var_names = var_names.to_vec(); + var_names.push(ENV_VAR_NAME); + var_names.push(PUBLIC_ENV_VAR_NAME); + var_names.push(FILENAME_VAR_NAME); + var_names.push(LINENO_VAR_NAME); + var_names.push(ARGS_VAR_NAME); + + type D = InputData; + // jq's `input` fails with "No more inputs" when the stream is + // exhausted; jaq-std's yields nothing. + let input_run: jaq_core::RunPtr = |cv| { + let next = cv.0.data().inputs().next(); + Box::new(std::iter::once(match next { + Some(r) => r.map_err(|e| jaq_core::Exn::from(jaq_core::Error::str(e))), + None => Err(jaq_core::Exn::from(jaq_core::Error::str("No more inputs"))), + })) + }; + let input_funs: Vec> = jaq_std::input::funs::() + .into_vec() + .into_iter() + .filter(|(name, _, _)| *name != "input") + .chain(std::iter::once(( + "input", + jaq_core::native::v(0), + input_run, + ))) + .map(|(name, arity, run)| (name, arity, jaq_core::Native::::new(run))) + .collect(); + // Replace jaq-std's `regex`-crate-backed natives (matches/split_matches/ + // split_) with our fancy-regex backed versions so patterns with + // lookahead/lookbehind/atomic groups/backrefs work. + let regex_funs: Vec> = regex_compat::funs::() + .into_vec() + .into_iter() + .map(|(name, arity, run)| (name, arity, jaq_core::Native::::new(run))) + .collect(); + // SECURITY (TM-INF-023, #1571): jaq-std's `halt` native only raises + // `Exn::halt`; it is `jaq_core::unwrap_valr` that turns that into + // `std::process::exit`. The evaluation loop never calls `unwrap_valr`: + // it ends the jq command with the halt code instead, so `halt` and + // `halt_error` behave like jq without touching the host process. + // + // jaq-std's `stderr_empty`/`debug_empty` write to the host (`log`); + // ours buffer the text for this command's stderr (see `messages`). + let message_funs: Vec> = vec![ + ( + "stderr_empty", + jaq_core::native::v(0), + jaq_core::Native::::new(|cv| { + messages::stderr(&cv.1); + Box::new(std::iter::empty()) + }), + ), + // jq accepts base64 with non-zero trailing bits ("YW" is "a"). + ( + "decode_base64", + jaq_core::native::v(0), + jaq_core::Native::::new(|cv| { + use base64::Engine; + use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig}; + use jaq_std::ValT; + const LENIENT: GeneralPurpose = GeneralPurpose::new( + &base64::alphabet::STANDARD, + GeneralPurposeConfig::new() + .with_decode_allow_trailing_bits(true) + .with_decode_padding_mode(DecodePaddingMode::Indifferent), + ); + jaq_core::native::bome(cv.1.try_as_utf8_bytes().and_then(|s| { + LENIENT + .decode(s) + .map_err(|e| jaq_core::Error::str(e.to_string())) + .map(Val::from_utf8_bytes) + })) + }), + ), + ( + "debug_empty", + jaq_core::native::v(0), + jaq_core::Native::::new(|cv| { + messages::debug(&cv.1); + Box::new(std::iter::empty()) + }), + ), + ]; + let native_funs = jaq_core::funs::() + .chain(jaq_std::funs::().filter(|(name, _, _)| { + !matches!( + *name, + "env" | "stderr_empty" | "debug_empty" | "decode_base64" + ) && !regex_compat::SHADOWED_NATIVE_NAMES.contains(name) + })) + .chain(message_funs) + .chain(input_funs) + .chain(regex_funs) + .chain(jaq_json::funs::()); + + let compiler = Compiler::default() + .with_funs(native_funs) + .with_global_vars(var_names.iter().copied()); + + compiler.compile(modules).map_err(format_compile_errors) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cache_keys_on_source_and_binding_order() { + let cache = JqFilterCache::default(); + let source = "$left, $right"; + let names = ["$left", "$right"]; + let compiled = Arc::new(compile(source, &names).unwrap()); + cache.insert(source, &names, &compiled); + + assert!(Arc::ptr_eq(&cache.get(source, &names).unwrap(), &compiled)); + assert!(cache.get(source, &["$right", "$left"]).is_none()); + assert!(cache.get(source, &["$left"]).is_none()); + assert!(cache.get("$right, $left", &names).is_none()); + + let other = Arc::new(compile(".", &[]).unwrap()); + cache.insert(".", &[], &other); + assert!(Arc::ptr_eq(&cache.get(source, &names).unwrap(), &compiled)); + assert!(Arc::ptr_eq(&cache.get(".", &[]).unwrap(), &other)); + } + + #[test] + fn cache_hits_and_replacements_update_eviction_order() { + let cache = JqFilterCache::default(); + let filter = Arc::new(CompiledFilter::default()); + for index in 0..MAX_CACHED_FILTERS { + cache.insert(&index.to_string(), &[], &filter); + } + + assert!(cache.get("0", &[]).is_some()); + let replacement = Arc::new(CompiledFilter::default()); + let last_key = (MAX_CACHED_FILTERS - 1).to_string(); + cache.insert(&last_key, &[], &replacement); + assert!(cache.get("1", &[]).is_some()); + + cache.insert("new", &[], &filter); + assert!(cache.get("2", &[]).is_none()); + assert!(cache.get("0", &[]).is_some()); + assert!(Arc::ptr_eq( + &cache.get(&last_key, &[]).unwrap(), + &replacement + )); + } + + #[test] + fn cache_admits_only_small_inline_programs_and_binding_names() { + assert!(JqFilterCache::accepts(".", &["$item"])); + assert!(!JqFilterCache::accepts(&"x".repeat(1025), &[])); + assert!(!JqFilterCache::accepts(".", &["$item"; 17])); + assert!(!JqFilterCache::accepts(".", &[&"x".repeat(1025)])); + } +} diff --git a/crates/bashkit/src/builtins/jq/mod.rs b/crates/bashkit/src/builtins/jq/mod.rs index 61933ccf3..b8b39c6a1 100644 --- a/crates/bashkit/src/builtins/jq/mod.rs +++ b/crates/bashkit/src/builtins/jq/mod.rs @@ -8,7 +8,8 @@ //! - `convert`: order-preserving JSON reader -> JqJson <-> jaq Val, depth check //! - `stream`: incremental, metered path events with shared ancestor keys //! - `format`: indent-aware output rendering (custom `--indent N`) -//! - `compat`: prepended jq-compat definitions and global var names +//! - `compat`: jq compatibility definitions and global variable names +//! - `filter`: compile and reuse filters within a request //! - `errors`: jq-style error formatting (no Debug-shape leaks) //! //! Important decisions are documented at the top of each submodule. @@ -21,9 +22,9 @@ use self::jaq_json::Val; use async_trait::async_trait; -use jaq_core::load::{Arena, File, Loader}; -use jaq_core::{Compiler, Ctx, Vars, data}; +use jaq_core::{Ctx, Vars, data}; use jaq_std::input::{HasInputs, Inputs, RcIter}; +use std::sync::Arc; use super::{Builtin, Context, ExecutionDeadline, read_text_file, resolve_path}; use crate::error::Result; @@ -35,6 +36,7 @@ mod args; mod compat; mod convert; mod errors; +mod filter; mod format; mod input; mod loc; @@ -65,12 +67,9 @@ mod stream; mod tests; use args::{FileVarKind, JqArgs, MAX_FILE_VAR_BYTES, ParseOutcome}; -use compat::{ - ARGS_VAR_NAME, ENV_VAR_NAME, FILENAME_VAR_NAME, LINENO_VAR_NAME, PUBLIC_ENV_VAR_NAME, - build_compat_prefix, -}; use convert::{JqJson, jq_to_val, parse_json_stream, val_to_jq_capped}; -use errors::{format_compile_errors, format_load_errors, format_runtime_error_at}; +use errors::format_runtime_error_at; +pub(crate) use filter::JqFilterCache; use format::{render, sort_keys as sort_jq_keys}; /// Custom DataT that holds both the LUT and a shared input iterator. @@ -246,8 +245,6 @@ async fn run_jq(ctx: Context<'_>, parsed: JqArgs<'_>) -> Result { JqJson::Object(map.into_iter().collect()) }; - // Compose the filter: prepend compat defs, the env def, etc. - let prefix = build_compat_prefix(); let filter_text = match parsed.filter_file { Some(file) => { let path = resolve_path(ctx.cwd, file); @@ -266,137 +263,33 @@ async fn run_jq(ctx: Context<'_>, parsed: JqArgs<'_>) -> Result { } None => std::borrow::Cow::Borrowed(parsed.filter), }; - let filter_text = loc::expand_loc(&filter_text); - let filter_text = altpat::expand_alternatives(&filter_text); - let compat_filter = format!("{prefix}\n{filter_text}"); - let filter_src = compat_filter.as_str(); - - // Set up loader. - let defs = jaq_core::defs() - .chain(jaq_std::defs()) - .chain(self::jaq_json::defs()); - let loader = Loader::new(defs); - let arena = Arena::default(); - - let program = File { - code: filter_src, - path: (), - }; - - let modules = match loader.load(&arena, program) { - Ok(m) => m, - Err(errs) => { - return Ok(ExecResult::err(format_load_errors(errs), 3)); - } - }; - - // Names of all globals: --arg/--argjson/--slurpfile/--rawfile, then the - // four internal ones (env, ENV, filename, lineno), then $ARGS. - let mut var_names: Vec<&str> = all_var_bindings.iter().map(|(n, _)| n.as_str()).collect(); - var_names.push(ENV_VAR_NAME); - var_names.push(PUBLIC_ENV_VAR_NAME); - var_names.push(FILENAME_VAR_NAME); - var_names.push(LINENO_VAR_NAME); - var_names.push(ARGS_VAR_NAME); - - type D = InputData; - // jq's `input` fails with "No more inputs" when the stream is - // exhausted; jaq-std's yields nothing. - let input_run: jaq_core::RunPtr = |cv| { - let next = cv.0.data().inputs().next(); - Box::new(std::iter::once(match next { - Some(r) => r.map_err(|e| jaq_core::Exn::from(jaq_core::Error::str(e))), - None => Err(jaq_core::Exn::from(jaq_core::Error::str("No more inputs"))), - })) - }; - let input_funs: Vec> = jaq_std::input::funs::() - .into_vec() - .into_iter() - .filter(|(name, _, _)| *name != "input") - .chain(std::iter::once(( - "input", - jaq_core::native::v(0), - input_run, - ))) - .map(|(name, arity, run)| (name, arity, jaq_core::Native::::new(run))) - .collect(); - // Replace jaq-std's `regex`-crate-backed natives (matches/split_matches/ - // split_) with our fancy-regex backed versions so patterns with - // lookahead/lookbehind/atomic groups/backrefs work. - let regex_funs: Vec> = regex_compat::funs::() - .into_vec() - .into_iter() - .map(|(name, arity, run)| (name, arity, jaq_core::Native::::new(run))) + let var_names: Vec<&str> = all_var_bindings + .iter() + .map(|(name, _)| name.as_str()) .collect(); - // SECURITY (TM-INF-023, #1571): jaq-std's `halt` native only raises - // `Exn::halt`; it is `jaq_core::unwrap_valr` that turns that into - // `std::process::exit`. The run loop below never calls `unwrap_valr`: - // it ends the jq command with the halt code instead, so `halt` and - // `halt_error` behave like jq without touching the host process. - // - // jaq-std's `stderr_empty`/`debug_empty` write to the host (`log`); - // ours buffer the text for this command's stderr (see `messages`). - let message_funs: Vec> = vec![ - ( - "stderr_empty", - jaq_core::native::v(0), - jaq_core::Native::::new(|cv| { - messages::stderr(&cv.1); - Box::new(std::iter::empty()) - }), - ), - // jq accepts base64 with non-zero trailing bits ("YW" is "a"). - ( - "decode_base64", - jaq_core::native::v(0), - jaq_core::Native::::new(|cv| { - use base64::Engine; - use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig}; - use jaq_std::ValT; - const LENIENT: GeneralPurpose = GeneralPurpose::new( - &base64::alphabet::STANDARD, - GeneralPurposeConfig::new() - .with_decode_allow_trailing_bits(true) - .with_decode_padding_mode(DecodePaddingMode::Indifferent), - ); - jaq_core::native::bome(cv.1.try_as_utf8_bytes().and_then(|s| { - LENIENT - .decode(s) - .map_err(|e| jaq_core::Error::str(e.to_string())) - .map(Val::from_utf8_bytes) - })) - }), - ), - ( - "debug_empty", - jaq_core::native::v(0), - jaq_core::Native::::new(|cv| { - messages::debug(&cv.1); - Box::new(std::iter::empty()) - }), - ), - ]; - let native_funs = jaq_core::funs::() - .chain(jaq_std::funs::().filter(|(name, _, _)| { - !matches!( - *name, - "env" | "stderr_empty" | "debug_empty" | "decode_base64" - ) && !regex_compat::SHADOWED_NATIVE_NAMES.contains(name) - })) - .chain(message_funs) - .chain(input_funs) - .chain(regex_funs) - .chain(self::jaq_json::funs::()); - - let compiler = Compiler::default() - .with_funs(native_funs) - .with_global_vars(var_names.iter().copied()); - - let filter = match compiler.compile(modules) { - Ok(f) => f, - Err(errs) => { - return Ok(ExecResult::err(format_compile_errors(errs), 3)); + let cache = if parsed.filter_file.is_none() && JqFilterCache::accepts(&filter_text, &var_names) + { + ctx.execution_extension::() + } else { + None + }; + let cached = cache.as_ref().and_then(|cache| { + cache + .try_with(|cache| cache.get(&filter_text, &var_names)) + .ok() + .flatten() + }); + let filter = if let Some(filter) = cached { + filter + } else { + let filter = match filter::compile(&filter_text, &var_names) { + Ok(filter) => Arc::new(filter), + Err(stderr) => return Ok(ExecResult::err(stderr, 3)), + }; + if let Some(cache) = cache { + let _ = cache.try_with(|cache| cache.insert(&filter_text, &var_names, &filter)); } + filter }; // Keep parsed input trees, not expanded events. Conversion and streaming diff --git a/crates/bashkit/src/builtins/jq/tests.rs b/crates/bashkit/src/builtins/jq/tests.rs index b10b2bb41..127edb92d 100644 --- a/crates/bashkit/src/builtins/jq/tests.rs +++ b/crates/bashkit/src/builtins/jq/tests.rs @@ -13,6 +13,66 @@ use std::collections::HashMap; use std::path::PathBuf; use std::sync::Arc; +#[tokio::test] +async fn jq_compiled_filter_uses_current_values_and_input() { + let mut bash = crate::Bash::new(); + let result = bash + .exec( + r#" + set -e + export BENCH_ENV=first + jq -r --arg x a --arg y b '$x + $y + env.BENCH_ENV + .value' <<< '{"value":"1"}' + export BENCH_ENV=second + jq -r --arg x c --arg y d '$x + $y + env.BENCH_ENV + .value' <<< '{"value":"2"}' + jq -r --arg y e --arg x f '$x + $y + env.BENCH_ENV + .value' <<< '{"value":"3"}' + "#, + ) + .await + .unwrap(); + assert_eq!(result.exit_code, 0, "{}", result.stderr); + assert!(result.stderr.is_empty()); + assert_eq!(result.stdout, "abfirst1\ncdsecond2\nfesecond3\n"); +} + +#[tokio::test] +async fn jq_filter_file_is_read_again_on_each_call() { + let mut bash = crate::Bash::new(); + let result = bash + .exec( + r#" + set -e + printf '%s\n' '.first' > /filter.jq + jq -r -f /filter.jq <<< '{"first":"one","second":"two"}' + printf '%s\n' '.second' > /filter.jq + jq -r -f /filter.jq <<< '{"first":"one","second":"two"}' + "#, + ) + .await + .unwrap(); + assert_eq!(result.exit_code, 0, "{}", result.stderr); + assert!(result.stderr.is_empty()); + assert_eq!(result.stdout, "one\ntwo\n"); +} + +#[tokio::test] +async fn jq_user_definition_can_shadow_a_compatibility_helper() { + let filter = r#"def prior: join("-"); def join($sep): $sep; prior, join("user")"#; + let result = run_jq_result_with_args(&["-r", filter], r#"["a","b"]"#) + .await + .unwrap(); + assert_eq!(result.exit_code, 0, "{}", result.stderr); + assert_eq!(result.stdout, "a-b\nuser\n"); +} + +#[tokio::test] +async fn jq_filter_rejects_module_directives() { + for filter in [r#"include "example"; ."#, r#"import "data" as $x; $x"#] { + let result = run_jq_result(filter, "null").await.unwrap(); + assert_eq!(result.exit_code, 3); + assert!(result.stdout.is_empty()); + } +} + async fn run_jq(filter: &str, input: &str) -> Result { run_jq_with_args(&[filter], input).await } diff --git a/crates/bashkit/src/builtins/mod.rs b/crates/bashkit/src/builtins/mod.rs index d6a2f4197..44d91ac04 100644 --- a/crates/bashkit/src/builtins/mod.rs +++ b/crates/bashkit/src/builtins/mod.rs @@ -224,6 +224,8 @@ pub(crate) use jobctl::signal_name; pub use join::Join; #[cfg(feature = "jq")] pub use jq::Jq; +#[cfg(feature = "jq")] +pub(crate) use jq::JqFilterCache; pub use json::Json; pub use log::Log; pub use ls::{Ls, Rmdir}; diff --git a/crates/bashkit/src/lib.rs b/crates/bashkit/src/lib.rs index 0844cb1bc..4b54d7664 100644 --- a/crates/bashkit/src/lib.rs +++ b/crates/bashkit/src/lib.rs @@ -1047,6 +1047,8 @@ impl Bash { let _ = extensions.insert(active_limits.clone()); let _ = extensions.insert(self.interpreter.execution_budget().clone()); let _ = extensions.insert(builtins::ExecutionDeadline::new(active_limits.timeout)); + #[cfg(feature = "jq")] + let _ = extensions.insert(builtins::JqFilterCache::default()); #[cfg(feature = "python")] let _ = extensions.insert(builtins::PythonInprocessOptIn(self.python_inprocess_opt_in)); #[cfg(feature = "sqlite")] diff --git a/knowledge/foundations/jq.md b/knowledge/foundations/jq.md index 1ed8662f7..d68c0bc90 100644 --- a/knowledge/foundations/jq.md +++ b/knowledge/foundations/jq.md @@ -55,6 +55,26 @@ current normalized size from the live-intermediate budget before allocation; each later five-byte expansion grows that lease before the buffer grows. The lease remains live until strict parsing finishes (TM-DOS-100). +## Filter compilation + +One `Bash::exec` can reuse up to four compiled inline filters. A key combines +the filter source and ordered global binding names because compilation assigns +variable slots in that order. Each call supplies its current inputs, binding +values, environment, and evaluation limits. On insertion at capacity, the +least recently used plan is evicted. Each cached source can contain up to +1 KiB and bind up to 16 names totaling up to 1 KiB. The execution scope +drops the cache when the request completes or is cancelled. File filters +are read and compiled on every call. The cache lock covers only lookup +and replacement. + +The fixed jaq library and Bashkit compatibility definitions are parsed once +per process and cloned into the loader when a filter needs compilation. The +helpers that read invocation globals stay in the main expression, preserving +the grammar that rejects module directives in user filters. The compiler +resolves and compiles each uncached filter independently. Benchmark repeated, +interleaved, distinct, and one-off filters through +`cargo bench -p bashkit --features jq --bench jq`. + ## Verification `builtins::jq::tests` covers all 32 controls, newline/tab/CR, adjacent existing