Skip to content

Lower JSONPath filters once per container - #1730

Open
fcostaoliveira wants to merge 3 commits into
RedisJSON:masterfrom
fcostaoliveira:perf/jsonpath-filter-lowering
Open

fcostaoliveira wants to merge 3 commits into
RedisJSON:masterfrom
fcostaoliveira:perf/jsonpath-filter-lowering

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

What

JSONPath filters such as $.items[?(@.qty>5)].name are now lowered once per container, not interpreted from the pest tree for every candidate element.

lower_filter turns the filter into a FastFilter:

  • Structure: OR-of-AND groups of tests, with parenthesized groups and ! negation.
  • A test is operand, operator, operand, with an operator from > >= < <= == !=.
  • An operand is either:
    • an @-relative singular path (@, @.k, @.a.b, @[n], @['k']), resolved with direct get_key / get_index; or
    • a literal (number, string, true/false/null), parsed once.
  • Evaluation: fast_filter evaluates each candidate with the existing TermEvaluationResult comparisons, so ordering, type and number semantics are unchanged.
  • Fallback: anything outside that subset returns None and runs through the existing interpreter. That covers functions, regex =~, in/nin/subsetof and the like, $-rooted or non-singular operands, and arithmetic.

E2E results: RedisJSON command throughput

Throughput of each benchmarked command, master vs this PR.

Graviton4 (arm64 Neoverse-V2, AWS m8g.4xlarge). The official redis:8.12.0 server is pinned to one core and loads the RedisJSON module built from master 7ecc513 (ijson 379dadf) or from the PR head. memtier_benchmark runs on 14 other cores with pipeline 1: 8 connections × 2 threads for jsonsl-1 and yelp, 25 × 4 for 10-item, 25 × 8 for session. Each run lasts 30 s; every build gets 6 interleaved runs, and the table shows the median ops/s. p is an exact permutation test (6 vs 6). The server core was saturated (0.99 cores) in every cell except some multipath-5 cells (0.96). A byte-identical copy of master ran as an A/A control. Δ = patched / base − 1; bold means p < 0.05. k is the key.

Datasets:

  • jsonsl-1: 200,000 keys, one 946 B array each.
  • yelp: 20,000 keys, one 38,034 B object each (10 businesses).
  • 10-item: 50,000 keys, one 2,875 B object each (items array of 10 objects).
  • session: 100,000 keys, one 447 B session object each, Zipfian key popularity.
Command Dataset master ops/s P1 ops/s Δ p
JSON.GET k $.[7] jsonsl-1 85,531 85,619 +0.1 % (no significant change) 0.864
JSON.SET k $.[0] '"foo"' jsonsl-1 86,142 81,857 -5.0 % (no significant change) 0.489
JSON.GET k $.businesses[?(@.avg_rating>=4.5)].name yelp 46,616 52,867 +13.4 % 0.013
JSON.GET k $ yelp 21,412 21,380 -0.1 % (no significant change) 0.823
JSON.GET k $..name yelp 34,016 35,690 +4.9 % 0.013
90 % JSON.GET k / 10 % JSON.SET k $ '{"userId":"user-k","organizationId":"org-id","role":"admin",…}' (≈405 B document) session 103,188 104,408 +1.2 % (no significant change) 0.491
JSON.GET k $.items[?(@.qty>5)].name 10-item 59,117 75,457 +27.6 % 0.019
JSON.GET k $.items[*].name $.items[*].qty $.items[*].price $.items[*].attrs.color $.items[*].attrs.size ¹ 10-item 40,856 40,518 -0.8 % (no significant change) 0.076
JSON.TYPE k $.items[*].attrs 10-item 97,485 94,794 -2.8 % (no significant change) 0.567
JSON.OBJLEN k $.items[*].attrs 10-item 84,691 82,520 -2.6 % (no significant change) 0.567
90 % JSON.STRAPPEND k $.items[*].name '"-x"' / 10 % JSON.SET k $.items[*].name '"Item"' 10-item 65,899 71,083 +7.9 % ² 0.394
50 % JSON.SET k $.items[*].extra [1,2,3,4,5,6,7,8] / 50 % JSON.ARRAPPEND k $.items[*].extra '"tag"' 10-item 58,789 61,862 +5.2 % (no significant change) 0.407

¹ multipath-5: 8 of 36 cells ran at 0.96 server cores (3 master, 3 P2, 2 P1+P2), so the base side of this row may be slightly client-limited (up to about 4 %).

² Not usable against master: on this suite the A/A control (master vs its byte-identical copy) moved +12.1 % (p 0.019). master's six runs split into two groups (57–62k and 70–74k ops/s) from per-run server system time, while user CPU per request was flat.

A/A control (master vs its copy): every suite moved by at most ±6.5 % with p ≥ 0.076, except the STRAPPEND/SET suite (+12.1 %, p 0.019).

used_memory stayed within 0.1 % of master on every suite.

Why

For each candidate element, the interpreter:

  • re-walked the filter's Pairs;
  • re-parsed the literal;
  • built a fresh PathCalculatorData and result Vec for every @ operand.

On a 10-item document this costs more than the path compile itself.

Results

The benchmarks ran on RedisJSON v8.12.0 with and without this patch on one arm64 Neoverse-V2 host (Graviton4). The rebase onto master was checked for correctness (below); the timings were not re-run on master.

json_path micro (ns per call, median of 6):

Row base patched Δ
calc $.items[?(@.qty>5)].name, 10-item doc 5,339 2,055 −61.5 %
GET (compile + calc + serialize), same 8,647 5,352 −38.1 %
GET $.businesses[?(@.avg_rating>=4.5)].name, ~30 KB doc 10,223 6,892 −32.6 %
non-filter paths (static, wildcard, recursive descent, multipath) within ±1 % (one multipath row −3.4 %)

Allocations per filter GET: 34 → 28 (8,968 → 8,824 B).

Server, µs of server CPU per request. Redis 8.12.0, server pinned to one core, 6 interleaved runs, plus an A/A control. p-values are from a permutation test.

Benchmark base patched Δ
JSON.GET k $.items[?(@.qty>5)].name (50K keys, 10-item docs) 16.72 13.79 −17.5 % (p 0.013)
guards: $.[7], $, session playbook, multipath, recursive descent, wildcard JSON.TYPE no significant change

With #1729 the filter GET is −19.9 %. The two patches are independent and apply in either order.

Correctness (on this branch, rebased on master 7ecc513)

  • Unit tests: cargo test --workspace gives 453 passed and 0 failed, the same as master.
  • Flow tests: tests/pytest/tests.sh against redis-server 8.12.0 passes 377 of 377 in each of general, --use-aof, --use-slaves and --env oss-cluster, the same as master.
  • Differential test against unpatched master:
    • two seeded corpora of about 20,000 paths each: the JSONPath literals in this repo's sources and tests, plus random filters over every operator, literal type, type mismatch, missing key, nested @ path, &&/||/!/parentheses, and syntax errors;
    • run on 7 documents, including typed arrays (serde_json and ijson);
    • compared through every public entry point: values, paths, order, exists, the pop_last* sequences, and so on;
    • 0 differences in 534,716 checks, with about 2,470 paths per corpus hitting a lowered filter.
  • cargo fmt --check and cargo clippy -p json_path are clean.

🤖 Generated with Claude Code


Note

Medium Risk
Changes core filter evaluation for a common query shape; unsupported constructs must fall back identically, and differential tests cover parity but edge cases around lowering eligibility matter.

Overview
Adds a filter fast path for JSONPath: when an array/object has more than one child, eligible filters are lowered once into a FastFilter (OR-of-AND groups of comparisons, existence tests, negation, and parentheses) instead of re-walking the pest parse tree for every candidate.

Lowering only covers singular @ paths (single key/index steps) plus scalar literals compared with > >= < <= == !=. A lightweight filter_needs_interpreter text scan skips lowering early for $, ~, and function-call patterns. Anything else—including regex, arithmetic, $ operands, wildcards, and ..—falls back to the existing evaluate_filter interpreter unchanged.

Per-candidate evaluation on the fast path uses direct key/index resolution and the same TermEvaluationResult comparison helpers, so semantics should match the interpreter for the supported subset. Single-element containers skip lowering (cost/benefit).

Also extracts TermEvaluationResult::parse_decimal for shared literal parsing, and adds Rust/pytest tests that fast-path and interpreter paths agree (plus pre-scan unit tests).

Reviewed by Cursor Bugbot for commit d77885f. Bugbot is set up for automated code reviews on this repo. Configure here.

A filter such as `$.items[?(@.qty>5)].name` was interpreted from the pest
tree for every candidate element: the operands, the operator and the literal
were re-read and the literal re-parsed per element, and each candidate built
its own PathCalculatorData and result Vec.

`lower_filter` now turns a filter into a `FastFilter` once per container:
OR-of-AND groups of tests (operand, operator, operand), with parenthesized
groups and negation. Operands are `@`-relative singular paths, resolved with
direct `get_key` / `get_index`, or literals parsed once. Comparisons reuse
`TermEvaluationResult`, so semantics are unchanged. Anything outside that
subset (functions, regex, non-singular operands, arithmetic) returns `None`
and runs through the existing interpreter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.08612% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.84%. Comparing base (7ecc513) to head (d77885f).

Files with missing lines Patch % Lines
json_path/src/json_path.rs 98.08% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1730      +/-   ##
==========================================
+ Coverage   88.24%   88.84%   +0.60%     
==========================================
  Files          18       18              
  Lines        6871     7066     +195     
==========================================
+ Hits         6063     6278     +215     
+ Misses        808      788      -20     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

fcostaoliveira and others added 2 commits December 2, 2026 05:20
Lowering walks the filter's parse tree about as far as interpreting one
candidate does, so on a container with one candidate it is pure
overhead: the jsonpath benchmark row root-single-candidate rose from
6,685 to 9,037 instructions (+35%). Lower only when the container has
at least two candidates, the same condition that enables the root
operand cache.

Fold the existence and comparison forms of a lowered test into one
enum, share the decimal literal parse with the interpreter, and test
each lowered shape against the general evaluator, in json_path and
through the module.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A filter that references `$`, uses `~` (regex or keys) or calls a function or
method was still lowered on each container of two or more candidates, and the
attempt allocated before failing: about 2.3k instructions per container, +21%
on a two-row array with `$`. A scan of the filter's text, which skips quoted
strings, now sends these filters straight to the interpreter. The scan only
rejects: a filter it lets through is lowered as before, and a filter it rejects
needlessly (an unquoted `$` in a field name) is evaluated by the interpreter,
which handles every filter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant