Skip to content

Cache compiled JSONPaths per thread (depends on #1730 and #1729) - #1732

Open
fcostaoliveira wants to merge 16 commits into
RedisJSON:masterfrom
fcostaoliveira:perf/jsonpath-path-ir-cache
Open

fcostaoliveira wants to merge 16 commits into
RedisJSON:masterfrom
fcostaoliveira:perf/jsonpath-path-ir-cache

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Important

Depends on #1730 (P1, filter lowering) and #1729 (P2, static path scanner). Please review and merge those two first.
This branch contains both of them, merged in, because the cache reuses P1's lowered filter and checks P2's static scanner before its own lookup. Until they land, the diff here includes their commits. Once they are merged into master, only this change's own commits remain in the diff. Every "base" number below is master + #1729 + #1730.

What

A non-static JSONPath (filter, wildcard, .., union, slice) is now lowered into an owned form and kept in a small per-thread cache keyed by the exact path string. A repeated path no longer goes through pest.

  • Owned IR: PathIr { segs: Vec<IrSeg> }, one segment per child of the pest root: FullScan, All, Key, Strings, Indexes, Range and Filter(FastFilter).
    • The lowered filter from Lower JSONPath filters once per container #1730 becomes owned (Box<str> keys, an owned literal) and independent of the document type. The IR and the per-container filter path share it.
    • The IR borrows nothing from the path string, holds no Rc, and is Send + Sync.
  • Lowering: the cache never parses. pest stays the only parser, and lower_path walks pest's tree once. There is no second grammar to keep in step, and every error message is pest's.
  • Evaluation: QueryRoot::Ir(IrPath) is evaluated by calc_ir, which mirrors calc_internal arm for arm (calc_all, calc_literal, calc_strings, calc_indexes, calc_range, calc_full_scan and the lowered-filter arm) with the same path trackers. Its .. arm skips scalar descendants, as calc_full_scan has done since Skip scalar descendants in JSONPath recursive descent #1717. It needs no PathCalculatorData.
  • Query: every lib.rs entry point has an Ir arm, exists included. pop_last and pop_last_object_key shorten a length over the shared IR and never mutate it. is_static and size keep the pest arms' results.
  • Lookup order in compile: the static scanner (Scan static JSONPaths without pest #1729), then the cache, then pest.
  • Not cached: static paths (the scanner is cheaper than a lookup), projections, invalid paths, and paths with a filter the lowering does not cover. These keep the pest tree, unchanged.
  • path_cache_stats() returns the calling thread's hits, misses, inserts, evictions, oversize refusals, rejected paths (no owned form), entries and bytes.

Cache design and declared memory bound

  • Key: the exact path bytes. Two spellings of one path are two entries, so the cache can never change what a string means.
  • Shape: the 64 most recently used paths of the thread, with exact LRU eviction. A lookup scans up to 64 stored 64-bit hashes and compares the bytes of a match.
  • Admission on the second compile, built at the first evaluation:
    • A missed path's hash goes into a ring of the last 64 first-time misses.
    • If the same path misses again while its hash is still in the ring, compile does not build anything. It returns the pest query with a pending-admission mark (Query::admit, the path string).
    • The first evaluation of that query through an entry point that takes the Query by value (calc_once, calc_once_with_paths, visit_once_with_paths, exists) lowers the path, inserts it, and evaluates the owned form in the same call.
    • The pending check is one inline branch; the admission itself is a #[cold] function.
  • Consequences:
    • The first compile of any path costs pest plus one hash and two short scans, and allocates nothing for the cache.
    • A compile that is never evaluated builds nothing. That keeps the cost off the compile-only rows of jsonpath-benchmark: they compile each path twice and never evaluate, and every row stays within +3 % of master (below).
    • A workload whose paths never repeat (a new literal in every filter) builds nothing and evicts nothing.
    • Queries evaluated only by reference (create / calc, create_with_generator / calc_paths) are served from the cache once a path is in it, but never admit a path themselves.
  • Rejected paths: an admitted path with no owned form (a filter the lowering does not cover) or one over the size bound is marked in a bit per ring slot and is not lowered again while its hash stays in the ring.
  • Eviction: the least recently used slot is found with a plain loop that keeps the oldest tick in a register. An iterator min_by_key here was compiled out of line on the cold admission path and carried its minimum through the stack, about 1,000 extra cycles per insert on Neoverse-V2.
  • Bound, enforced by the code:
    • a path longer than 256 bytes is never cached;
    • an entry whose key plus IR requests more than 1,024 heap bytes is never cached;
    • so one thread holds at most 64 × 1,024 B = 64 KiB of keys and IR, plus at most about 3.6 KiB of fixed tables (the miss ring with its bitmap, and two 64-slot tables allocated on the first insert).
  • Nothing is stored per key or per document. Query grows by 16 bytes (the pending path).

Thread safety

  • One cache per thread (thread_local! holding a RefCell): no lock, no shared write, nothing to contend on. Redis runs commands on the main thread, so in practice there is one cache. A thread that compiles paths elsewhere, such as a module calling JSONAPI_pathParse from a worker, gets its own cache with the same bound.
  • The IR is shared through Arc, not Rc. A Query can leave the thread that compiled it (the boxed Query of JSONAPI_pathParse) while it shares a PathIr with the cache entry. The IR is immutable and holds no Rc, so an atomic count is enough. A pending admission is completed on the thread that evaluates the query, into that thread's cache.
  • Thread exit: the cache is dropped with the thread. try_with turns a compile or admission during thread teardown into a plain miss.
  • Two thread-locals: the miss ring and counters live in one without a destructor; the entries, which need one, in another that a thread first touches on its first insert. A thread that never caches a path registers no destructor and allocates nothing.
  • Alternative measured and rejected: one process-wide cache behind a Mutex. It costs 14 ns more per hit uncontended (44.7 against 30.5 ns). With 8 threads compiling at once, it makes the whole command 2.1× slower, while the per-thread cache is flat from 1 to 8 threads.

E2E results: RedisJSON command throughput

Throughput of each benchmarked command. The first table is this PR's own effect (master + #1729 + #1730 vs this branch); the second is all three PRs together against master.

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.

This PR alone: master + #1729 + #1730 → this branch

Command Dataset P1+P2 ops/s P3 ops/s Δ p
JSON.GET k $.[7] jsonsl-1 119,079 115,954 -2.6 % (no significant change) 0.563
JSON.SET k $.[0] '"foo"' jsonsl-1 101,817 96,763 -5.0 % (no significant change) 0.186
JSON.GET k $.businesses[?(@.avg_rating>=4.5)].name yelp 58,774 83,316 +41.8 % 0.013
JSON.GET k $ yelp 22,390 22,345 -0.2 % (no significant change) 0.433
JSON.GET k $..name yelp 34,153 42,119 +23.3 % 0.013
90 % JSON.GET k / 10 % JSON.SET k $ '{"userId":"user-k","organizationId":"org-id","role":"admin",…}' (≈405 B document) session 118,781 117,035 -1.5 % (no significant change) 0.067
JSON.GET k $.items[?(@.qty>5)].name 10-item 75,661 117,563 +55.4 % 0.013
JSON.GET k $.items[*].name $.items[*].qty $.items[*].price $.items[*].attrs.color $.items[*].attrs.size ¹ 10-item 40,639 68,383 +68.3 % 0.013
JSON.TYPE k $.items[*].attrs 10-item 94,359 120,548 +27.8 % 0.013
JSON.OBJLEN k $.items[*].attrs 10-item 84,631 104,344 +23.3 % 0.039
90 % JSON.STRAPPEND k $.items[*].name '"-x"' / 10 % JSON.SET k $.items[*].name '"Item"' 10-item 75,509 80,931 +7.2 % (no significant change) 0.069
50 % JSON.SET k $.items[*].extra [1,2,3,4,5,6,7,8] / 50 % JSON.ARRAPPEND k $.items[*].extra '"tag"' 10-item 63,295 70,342 +11.1 % 0.039

All three PRs (#1729 + #1730 + this one) vs master

Command Dataset master ops/s P3 ops/s Δ p
JSON.GET k $.[7] jsonsl-1 85,531 115,954 +35.6 % 0.013
JSON.SET k $.[0] '"foo"' jsonsl-1 86,142 96,763 +12.3 % 0.013
JSON.GET k $.businesses[?(@.avg_rating>=4.5)].name yelp 46,616 83,316 +78.7 % 0.013
JSON.GET k $ yelp 21,412 22,345 +4.4 % 0.013
JSON.GET k $..name yelp 34,016 42,119 +23.8 % 0.013
90 % JSON.GET k / 10 % JSON.SET k $ '{"userId":"user-k","organizationId":"org-id","role":"admin",…}' (≈405 B document) session 103,188 117,035 +13.4 % (no significant change) 0.069
JSON.GET k $.items[?(@.qty>5)].name 10-item 59,117 117,563 +98.9 % 0.013
JSON.GET k $.items[*].name $.items[*].qty $.items[*].price $.items[*].attrs.color $.items[*].attrs.size ¹ 10-item 40,856 68,383 +67.4 % 0.013
JSON.TYPE k $.items[*].attrs 10-item 97,485 120,548 +23.7 % 0.013
JSON.OBJLEN k $.items[*].attrs 10-item 84,691 104,344 +23.2 % (no significant change) 0.054
90 % JSON.STRAPPEND k $.items[*].name '"-x"' / 10 % JSON.SET k $.items[*].name '"Item"' 10-item 65,899 80,931 +22.8 % ² 0.019
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 70,342 +19.7 % 0.019

¹ 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; this PR adds 3.5–4.7 KB on the path-heavy suites (the per-thread cache), nothing per key.

Why

After #1729 and #1730, pest compilation is most of a filter command's cost. For JSON.GET k $.items[?(@.qty>5)].name:

Wildcard and recursive-descent paths pay the same parse on every command. Their evaluation also clones a Pairs for every node visited.

Results

Measured on master 7ecc513 on one arm64 Neoverse-V2 host (Graviton4). x86-64 was not timed; the instruction-count gate below ran on x86-64.
base = master + #1729 + #1730 (both branch heads merged); patched = base + this change.

json_path micro, steady state (path cached), ns per call, median of 6 interleaved runs, with an A/A control of the base binary:

Row base patched Δ
compile $.items[?(@.qty>5)].name (a cache hit) 3,000 30.9 −99.0 %
GET (compile + calc + serialize), same path, 10-item doc 5,450 1,384 −74.6 %
GET $.businesses[?(@.avg_rating>=4.5)].name, ~30 KB doc 6,933 1,860 −73.2 %
GET $.items[*].name 2,822 959 −66.0 %
GET, 5 wildcard paths 16,396 6,462 −60.6 %
GET $..name, ~30 KB doc 18,159 13,549 −25.4 %
static paths (no code of this change runs) 81–97 82–97 −0.2 … +0.2 %

The A/A control moved every row by at most 1.2 %. This table was taken on the earlier admission rule of this PR (third compile). The hit path is the same code in this head; on the admission benchmark below, a cached filter compile + calc_once costs 762 ns here against 783 ns on that build. $..name gains less than it would on 8.12, because master's #1717 already made its base 2× faster.

Allocations per call (steady state, path cached): GET filter path 28 / 8,824 B → 5 / 456 B; 5 wildcard paths 109 → 29; compile 16 / 7,400 B → 0.

Server, µs of server CPU per request. Redis 8.12.0 (the official image, with each librejson.so mounted in), server pinned to one core, memtier on other cores for 30 s per cell, interleaved runs per build, plus an A/A control (a second copy of the base binary). p-values are from an exact permutation test on the medians. Every cell returned 0 errors.

Benchmark base patched Δ
JSON.GET k $.businesses[?(@.avg_rating>=4.5)].name (20K keys, ~30 KB docs), 6 runs 16.36 10.90 −33.4 % (p 0.013)
JSON.GET k $.items[?(@.qty>5)].name (50K keys, 10-item docs), 4 runs 13.61 8.67 −36.3 %
JSON.GET, 5 wildcard paths (50K keys) † 24.89 14.88 −40.2 % (p < 0.05)
JSON.GET k $..name (20K keys, ~30 KB docs) † 29.08 22.94 −21.1 % (p < 0.05)
JSON.TYPE k $.items[*].attrs † 10.93 8.65 −20.9 %, not significant
JSON.OBJLEN k $.items[*].attrs † 12.12 9.78 −19.3 % (p < 0.05)
JSON.STRAPPEND / JSON.SET on $.items[*].name † 16.53 11.67 −29.4 % (p < 0.05)
JSON.ARRAPPEND / JSON.SET on $.items[*].extra ‡ 16.06 13.57 −15.5 % (p < 0.05)
guard: JSON.GET k $.[7] (static path, same code in both), 4 runs 8.27 8.40 +1.6 %, no significant change

† Measured on the commit before the last two (d4831b3: the same admission rule, with the pending check behind a by-value call and the iterator eviction). Those two commits change only the admitting call and the eviction scan, which these suites run once per server lifetime. ‡ Measured on 90bbdb7 (the in-place pending check, before the eviction loop).

At the server each suite's path is admitted once and then hits on every request (counted with instrumented builds: 2 misses, 1 insert and about 2.1 M hits per 30 s cell).

The host was noisy: an A/A control moved single suites by up to 18 % (not significant), and server system time per request varies by about 1 µs between cells independently of the module. Only rows with p < 0.05 are claimed as significant. Whole-document JSON.GET and a session-caching playbook were run as guards on the earlier build and stayed within the A/A band; no code of this change runs there.

What admission costs. Compile + calc_once of never-seen filter and wildcard paths, ns per op, median over 2,900 blocks of 16 paths, median of 3 interleaved rounds:

n-th compile + evaluation base patched
filter, 1st (a plain miss) 4,779 4,886 (+2.2 %)
filter, 2nd (admits: lowers, inserts, evaluates the owned form) 4,773 5,143 (+7.8 %)
filter, 3rd and later (hits) 4,772 777 (−83.7 %)
wildcard, 2nd (admits) 2,528 2,583 (+2.2 %)
wildcard, 3rd and later (hits) 2,528 848 (−66.5 %)

Compile only, never evaluated (what the compile rows of jsonpath-benchmark see): +2.0 % (filter) and +3.8 % (wildcard) on every compile, because a compile never builds.

Many distinct paths in strict rotation (compile + calc_once while K filter paths rotate, one thread, ns per op):

Distinct paths K base patched Δ hit rate
64 (the capacity) 4,562 774 −83.0 % 100 %
96 4,558 2,730 −40.1 % 50 %
128 4,569 3,469 −24.1 % 32 %
256 4,584 3,688 −19.6 % 23 %

jsonpath-benchmark instruction gate (run_instructions.sh --callgrind-limits='ir=5%' against master, valgrind, x86-64): passes, exit 0. Worst row compile/projection-keys +2.96 %; compile/slice +2.94 %; eval/filter-and −78.16 %. No gate row inserts into a full cache.

Memory:

  • one cached filter path is 332 to 359 B (key + IR) on the benchmark paths;
  • the fuzz corpora never held more than 29,581 B in 64 entries, against the 65,536 B bound;
  • server used_memory grew by 3.5 to 4.0 KiB on the suites whose paths are cached, about 0.001 % of the 265 to 368 MB datasets. Nothing is stored per key.

Alternatives measured

  • Admit and build in compile on the second compile: the fastest for the many-paths rotation, but the admitting compile costs 15 to 23 % more instructions, and it fails the jsonpath-benchmark gate on 14 compile rows (+7.6 to +22.8 %), because those rows measure each path's second compile.
  • Admit and build in compile on the third compile: passes the gate, but a strict rotation over more than 64 paths never admits anything (0 % hits at K = 96, 128, 256), and the admitting compile is +35 % compile-only. This was the previous head of this branch.
  • Build at first evaluation, with min_by_key eviction: the admitting command cost +15.3 % (filter) and +17.1 % (wildcard); the eviction fold, out of line on the cold path, held 27 to 33 % of the backend-stall samples. The plain loop in this head brings it to the numbers above.

Correctness (on this branch, on master 7ecc513 with #1729 and #1730 merged in)

  • Unit tests: cargo test --workspace gives 487 passed and 0 failed. The new tests are:
    • a path is admitted on its second compile and cached when that query is evaluated, and hits after;
    • a path compiled once is never lowered, and a path compiled twice but never evaluated builds nothing;
    • a path without an owned form is lowered once, then keeps its pest tree;
    • static paths, projections, errors and interpreted filters stay out of the cache;
    • ten spellings of one path give ten entries with the same result;
    • 64 paths all stay, more paths evict, and the byte bound holds at every step;
    • long and large paths are not cached;
    • popping a cached query leaves the entry whole;
    • each thread has its own cache, and an IR compiled on one thread evaluates on another;
    • exists answers from the cached form;
    • a trailing .. left by pop_last_object_key skips scalars like the interpreter does (Skip scalar descendants in JSONPath recursive descent #1717).
  • Flow tests: tests/pytest/tests.sh against redis-server 8.12.0 passes 379 of 379 in each of general, --use-aof, --use-slaves and --env oss-cluster (Scan static JSONPaths without pest #1729 and Lower JSONPath filters once per container #1730 add two flow tests to master's 377).
  • Differential test against unpatched master:
    • the two seeded corpora of Scan static JSONPaths without pest #1729 and Lower JSONPath filters once per container #1730 (about 20,500 paths each), with up to four spelling variants added after each path: swapped quotes, added or removed spaces, and dot keys rewritten as bracket keys. That gives about 77,300 paths per corpus, and each variant is cached next to its original;
    • run on 7 documents (serde_json and ijson, typed arrays included), through every public entry point: compile errors, calc_once, calc_once_with_paths, calc_once_paths, visit_once_with_paths, exists, create/calc, create_with_generator/calc_paths, calc_once_projection, is_static, size, the pop_last* sequences and the prefix left after popping;
    • three passes:
      • A, hits: every path admitted and evaluated first, so every evaluation of a cacheable path is served from the cache.
      • B, evictions: a 32-path hot set revisited between strides over the whole corpus (48,286 inserts and 48,222 evictions on one corpus).
      • C, threads: pass B on 4 threads at once. Each thread ends with its own 64 entries, and the main thread's cache is unchanged by them.
    • 0 differences in 6,651,025 checks. The insert, eviction and byte counters after each pass are identical to those of the iterator eviction: the loop picks the same victims.
  • cargo fmt --check and cargo clippy -p json_path --all-targets are clean.

Merge order: #1730 and #1729 first, then this PR.

🤖 Generated with Claude Code


Note

Medium Risk
Large changes to JSONPath compile/eval hot paths require semantic parity with pest; risk is mitigated by bounded thread-local state and extensive differential tests, but regressions in edge cases (filters, .., path popping) would affect all JSON commands using paths.

Overview
Adds a per-thread LRU cache (up to 64 paths, size limits) that stores an owned path IR (PathIr / QueryRoot::Ir) so repeated JSONPath strings can skip pest on compile and walk a dedicated evaluator (calc_ir, calc_static) instead of the parse tree.

Compile path is now three-tiered: a static path byte scanner returns QueryRoot::Static; on a cache hit compilation returns QueryRoot::Ir; otherwise pest runs and may set Query::admit so the owned form is built on the first by-value evaluation (take_admission) and inserted into the cache.

Query handling is extended so pop_last / pop_last_object_key, is_static, and size work across pest, static, and IR roots; lib.rs entry points (calc_once, exists, visit_once_with_paths, etc.) dispatch on QueryRoot and call admission where needed. path_cache_stats is re-exported for observability.

Filter evaluation reuses the existing lowered filter fast path inside IR segments and when scanning multi-candidate containers; paths that cannot be lowered stay on pest and may be rejected from admission.

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

fcostaoliveira and others added 16 commits December 2, 2026 01:43
`$` and chains of `.key`, `[n]`, `.[n]`, `['key']` and `["key"]` are the most
common paths (JSON.GET/JSON.SET on the root or one element), but every
command compiled them through the full pest grammar, costing a dozen
allocations for a path like `$.[7]`.

`compile` now tries `scan_static_path` first. On success the query root is
`QueryRoot::Static(Vec<StaticStep>)`, evaluated by `PathCalculator::calc_static`
with direct lookups (the user path tracker is filled in the same order).
The `lib.rs` entry points, including `exists`, dispatch on `QueryRoot`, and
`pop_last*`, `is_static` and `size` have static arms. A rejected path
allocates nothing and goes through pest unchanged, so error messages stay
the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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>
A non-static path such as `$.items[?(@.qty>5)].name` was parsed by pest on
every command, and the parse was most of the command's cost: about 3 us of
a 5.4 us `JSON.GET`, with 16 allocations.

`compile` now lowers such a path into an owned IR (`PathIr`: a `Vec` of
key, strings, indexes, range, `*`, `..` and lowered-filter segments) and
keeps it in a per-thread cache keyed by the exact path string. The query
root is `QueryRoot::Ir(IrPath)`, evaluated by `calc_ir`, which mirrors
`calc_internal` arm for arm with the same path trackers. The lowered
filter (`FastFilter`) becomes owned, so the IR and the per-container
filter path share it.

- Lookup order: the static scanner, then the cache, then pest.
- Admission: a path is lowered and inserted on its second compile within
  the last 64 first-time misses, so paths that never repeat build nothing.
- Bound: 64 entries per thread, least recently used evicted; a path over
  256 bytes, or an entry over 1,024 heap bytes, is not cached. At most
  64 KiB of keys and IR per thread, plus about 3.6 KiB of fixed tables.
- Thread safety: one cache per thread (`thread_local!`, no lock). The IR
  is immutable and shared through `Arc`, so a `Query` handed to another
  thread (`JSONAPI_pathParse`) stays valid; `try_with` turns a compile
  during thread teardown into a miss.
- Not cached: static paths, projections, invalid paths and paths with a
  filter the lowering does not cover; those keep the pest tree. Error
  messages are pest's.

Every `lib.rs` entry point, `exists` included, and `pop_last*`, `is_static`
and `size` have `Ir` arms. `path_cache_stats()` reports the calling
thread's hits, misses, inserts, evictions and bytes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cover the saturating index parse and the leading-space quoted key that
the scanner leaves to pest, both as unit tests and through the module.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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>
…ir-cache

Keep this branch's owned lowering types and carry over the
single-candidate gate at the per-container lowering call site.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The cache lowered and inserted a path on its second compile, so that compile
paid for pest plus building the owned form. A path is now admitted on its third
compile: a bit per slot of the miss ring marks a path that has missed twice, and
only a miss that finds its bit set is lowered. The first two compiles of a path
cost pest plus one hash and two short scans; a hot path is still lowered once and
served from the cache afterwards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An admitted path whose owned form cannot be built (a filter the lowering does
not cover) or is too large stayed admitted, so every later compile walked the
parse tree and allocated again before giving up. Such a path is now marked in a
bit per slot of the miss ring and keeps its pest tree without another attempt
while its first miss stays in the ring. path_cache_stats() counts these paths
as `rejected`.

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>
…ir-cache

The lowering moved to free functions here, so the filter pre-scan goes at the
start of the free lower_filter, which also covers lower_path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The entries need a destructor, so their thread-local registers one, and
allocates, on its first access. The miss ring, counters and tick now live in a
thread-local without a destructor, and the entries are touched only once the
thread has cached a path. Compiling a path once or twice no longer registers or
allocates anything, which also leaves the allocator's state as it was without
the cache.

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

The compiled-path cache admitted a path on its third compile, so a strict
rotation over more than 64 paths never admitted any. Admit on the second
compile again, but build nothing there: the admitting compile marks its
query, and the first evaluation of that query through an entry point that
takes it by value lowers the path and inserts it. A compile that is never
evaluated costs one hash and two short scans over an uncached compile.
take_admission moved the whole Query through a by-value call on every
evaluation. Check the flag inline and keep the admission itself in a cold
function.
The admission at first evaluation calls path_cache_insert from a cold
path. There the min_by_key fold over the 64 slots is not inlined, and its
accumulator goes through the stack on every slot: a store-to-load chain
that made the admitting command cost about 1,000 cycles more than an
admission inside compile. A loop with the running minimum in locals
keeps it in registers wherever it is compiled. Same victim: the first
slot with the smallest last-use tick.
@codecov

codecov Bot commented Dec 2, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.62159% with 86 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.72%. Comparing base (7ecc513) to head (ad11f77).

Files with missing lines Patch % Lines
json_path/src/json_path.rs 90.44% 81 Missing ⚠️
json_path/src/lib.rs 92.75% 5 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1732      +/-   ##
==========================================
+ Coverage   88.24%   88.72%   +0.48%     
==========================================
  Files          18       18              
  Lines        6871     7708     +837     
==========================================
+ Hits         6063     6839     +776     
- Misses        808      869      +61     

☔ 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.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit ad11f77. Configure here.

projection: None,
admit: None,
});
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Static paths skip depth limit

Medium Severity

compile returns immediately when scan_static_path succeeds, before max_bracket_depth runs. A valid-looking static path whose bracket nesting exceeds 128 therefore compiles successfully and is evaluated via calc_static, while the same shape would return JSONPath nesting too deep on the pest path.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit ad11f77. Configure here.

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