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
use crossbeam_channel::{Receiver, Sender, unbounded};
use simd_json::OwnedValue as Value;
use std::sync::Arc;
use std::thread::{self, JoinHandle};
use crate::error::FilterError;
use crate::filter;
/// Maximum number of values to cache. Caching large intermediate results
/// doubles memory usage, so we skip caching when results exceed this threshold.
const CACHE_SIZE_LIMIT: usize = 1_000_000;
pub struct EvalRequest {
pub id: u64,
pub filter_text: String,
pub inputs: Arc<Vec<Value>>,
pub slurp_mode: bool,
}
pub struct EvalResult {
pub id: u64,
pub result: Result<Vec<Value>, FilterError>,
}
/// Cache for intermediate pipe results
struct PipeCache {
filter_text: String,
values: Arc<Vec<Value>>,
slurp_mode: bool,
}
impl PipeCache {
/// Check if new_filter extends cached filter at a pipe boundary.
/// Returns the suffix to evaluate if cache can be used, None otherwise.
fn get_suffix<'a>(&self, new_filter: &'a str, new_slurp: bool) -> Option<&'a str> {
// Input semantics changed - can't use cache
if new_slurp != self.slurp_mode {
return None;
}
// Normalize whitespace for comparison
let cached_trimmed = self.filter_text.trim();
let new_trimmed = new_filter.trim();
// Not a prefix match
if !new_trimmed.starts_with(cached_trimmed) {
return None;
}
let remainder = &new_trimmed[cached_trimmed.len()..];
let trimmed = remainder.trim_start();
if trimmed.is_empty() {
// Exact match - use cache as-is
return Some("");
}
if trimmed.starts_with('|') {
// Valid pipe extension - return the part after the pipe
return Some(trimmed.strip_prefix('|').unwrap().trim_start());
}
// Not at pipe boundary (e.g., ".foo" -> ".foobar")
None
}
}
pub struct Worker {
request_tx: Option<Sender<EvalRequest>>,
result_rx: Receiver<EvalResult>,
handle: Option<JoinHandle<()>>,
}
impl Worker {
pub fn spawn() -> Self {
let (request_tx, request_rx) = unbounded::<EvalRequest>();
let (result_tx, result_rx) = unbounded::<EvalResult>();
let handle = thread::spawn(move || {
let mut cache: Option<PipeCache> = None;
while let Ok(mut req) = request_rx.recv() {
// Drain any newer requests, keeping only the latest.
// This replaces the old TOCTOU-prone is_empty() check.
while let Ok(newer) = request_rx.try_recv() {
req = newer;
}
// Check for cache hit
// error_offset tracks where suffix starts in full filter (for error position adjustment)
let (base_values, filter_to_eval, error_offset) = match &cache {
Some(c) => match c.get_suffix(&req.filter_text, req.slurp_mode) {
Some("") => {
// Exact match - return cached values directly
let _ = result_tx.send(EvalResult {
id: req.id,
result: Ok((*c.values).clone()),
});
continue;
}
Some(suffix) => {
// Pipe extension - evaluate only the suffix on cached values
// Calculate offset: find where suffix starts in full filter
let offset = req.filter_text.len() - suffix.len();
(Arc::clone(&c.values), suffix.to_string(), offset)
}
None => {
// No cache hit - evaluate full filter
(prepare_inputs(&req), req.filter_text.clone(), 0)
}
},
None => {
// No cache - evaluate full filter
(prepare_inputs(&req), req.filter_text.clone(), 0)
}
};
// Evaluate the filter (either full or just the suffix)
let result = filter::evaluate_all(&filter_to_eval, &base_values).map_err(|e| {
// Adjust error position to account for suffix offset
if error_offset > 0 {
match e {
FilterError::Eval(mut eval_err) => {
let pos = eval_err.position();
eval_err.set_position(pos + error_offset);
FilterError::Eval(eval_err)
}
FilterError::Parse(mut parse_err) => {
parse_err.position += error_offset;
FilterError::Parse(parse_err)
}
}
} else {
e
}
});
// Update cache on success (skip if too large to avoid OOM)
if let Ok(ref values) = result {
if values.len() <= CACHE_SIZE_LIMIT {
cache = Some(PipeCache {
filter_text: req.filter_text.clone(),
values: Arc::new(values.clone()),
slurp_mode: req.slurp_mode,
});
} else {
cache = None;
}
}
// Skip sending if newer requests arrived during evaluation.
// The App side also rejects stale results, but this avoids
// unnecessary channel traffic.
if !request_rx.is_empty() {
continue;
}
let _ = result_tx.send(EvalResult { id: req.id, result });
}
});
Worker {
request_tx: Some(request_tx),
result_rx,
handle: Some(handle),
}
}
pub fn send(&self, req: EvalRequest) {
if let Some(tx) = &self.request_tx {
let _ = tx.send(req);
}
}
pub fn try_recv(&self) -> Option<EvalResult> {
self.result_rx.try_recv().ok()
}
}
impl Drop for Worker {
fn drop(&mut self) {
// Drop the sender to signal the worker to exit
self.request_tx.take();
// Wait for the worker thread to finish
if let Some(handle) = self.handle.take() {
let _ = handle.join();
}
}
}
fn prepare_inputs(req: &EvalRequest) -> Arc<Vec<Value>> {
if req.slurp_mode {
Arc::new(vec![Value::Array(Box::new((*req.inputs).clone()))])
} else {
Arc::clone(&req.inputs)
}
}
#[cfg(test)]
mod tests {
use super::*;
use simd_json::json;
use std::time::Duration;
fn make_cache(filter_text: &str, slurp_mode: bool) -> PipeCache {
PipeCache {
filter_text: filter_text.to_string(),
values: Arc::new(vec![]),
slurp_mode,
}
}
// =========================================================================
// PipeCache::get_suffix tests
// =========================================================================
#[test]
fn test_pipe_cache_exact_match() {
let cache = make_cache(".foo", false);
assert_eq!(cache.get_suffix(".foo", false), Some(""));
}
#[test]
fn test_pipe_cache_pipe_extension() {
let cache = make_cache(".foo", false);
assert_eq!(cache.get_suffix(".foo | .bar", false), Some(".bar"));
}
#[test]
fn test_pipe_cache_multiple_pipes() {
let cache = make_cache(".foo | .bar", false);
assert_eq!(cache.get_suffix(".foo | .bar | .baz", false), Some(".baz"));
}
#[test]
fn test_pipe_cache_not_at_pipe_boundary() {
let cache = make_cache(".foo", false);
// ".foobar" is not a pipe extension of ".foo"
assert_eq!(cache.get_suffix(".foobar", false), None);
}
#[test]
fn test_pipe_cache_slurp_mode_mismatch() {
let cache = make_cache(".foo", false);
// Cache was created without slurp, but new request has slurp
assert_eq!(cache.get_suffix(".foo | .bar", true), None);
}
#[test]
fn test_pipe_cache_slurp_mode_match() {
let cache = make_cache(".foo", true);
assert_eq!(cache.get_suffix(".foo | .bar", true), Some(".bar"));
}
#[test]
fn test_pipe_cache_whitespace_normalization() {
let cache = make_cache(" .foo ", false);
// Extra whitespace in new filter should still match
assert_eq!(cache.get_suffix(".foo | .bar", false), Some(".bar"));
}
#[test]
fn test_pipe_cache_whitespace_around_pipe() {
let cache = make_cache(".foo", false);
// Various whitespace around the pipe
assert_eq!(cache.get_suffix(".foo|.bar", false), Some(".bar"));
assert_eq!(cache.get_suffix(".foo |.bar", false), Some(".bar"));
assert_eq!(cache.get_suffix(".foo| .bar", false), Some(".bar"));
assert_eq!(cache.get_suffix(".foo | .bar", false), Some(".bar"));
}
#[test]
fn test_pipe_cache_no_prefix_match() {
let cache = make_cache(".foo", false);
assert_eq!(cache.get_suffix(".bar", false), None);
}
#[test]
fn test_pipe_cache_shorter_filter() {
let cache = make_cache(".foo | .bar", false);
// New filter is shorter - not a valid extension
assert_eq!(cache.get_suffix(".foo", false), None);
}
// =========================================================================
// Integration test
// =========================================================================
/// Test that error positions are correctly adjusted when using pipe cache.
/// When a cached prefix is reused and only the suffix is evaluated,
/// error positions must be offset to point to the correct location
/// in the full filter text.
#[test]
fn test_pipe_cache_error_position_adjustment() {
let worker = Worker::spawn();
// Input data: object with "name" field
let inputs = Arc::new(vec![json!({"name": "alice"})]);
// First request: evaluate a prefix that succeeds and gets cached
// .name returns "alice"
let prefix_filter = ".name".to_string();
worker.send(EvalRequest {
id: 1,
filter_text: prefix_filter.clone(),
inputs: Arc::clone(&inputs),
slurp_mode: false,
});
// Wait for result
let mut result = None;
for _ in 0..100 {
if let Some(r) = worker.try_recv() {
result = Some(r);
break;
}
thread::sleep(Duration::from_millis(10));
}
assert!(result.is_some(), "Should receive result for prefix");
assert!(result.unwrap().result.is_ok(), "Prefix should succeed");
// Second request: extend with a suffix that will error
// sort_by(.x) fails because it receives a string, not an array
let full_filter = ".name | sort_by(.x)".to_string();
worker.send(EvalRequest {
id: 2,
filter_text: full_filter.clone(),
inputs: Arc::clone(&inputs),
slurp_mode: false,
});
// Wait for result
let mut result = None;
for _ in 0..100 {
if let Some(r) = worker.try_recv() {
result = Some(r);
break;
}
thread::sleep(Duration::from_millis(10));
}
assert!(result.is_some(), "Should receive result for full filter");
let err = result
.unwrap()
.result
.expect_err("Full filter should error");
let pos = match &err {
FilterError::Eval(e) => e.position(),
FilterError::Parse(e) => e.position,
};
// sort_by(.x) starts at position 8 in the full filter ".name | sort_by(.x)"
// The error position should point there, not at 0
let error_text = &full_filter[pos..];
assert!(
error_text.starts_with("sort_by"),
"Error position {} should point to 'sort_by', got '{}'",
pos,
error_text
);
}
}