Repository navigation
Cache compiled JSONPaths per thread (depends on #1730 and #1729) - #1732
fcostaoliveira wants to merge 16 commits into
Conversation
`$` 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 Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit ad11f77. Configure here.
| projection: None, | ||
| admit: None, | ||
| }); | ||
| } |
There was a problem hiding this comment.
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.
Reviewed by Cursor Bugbot for commit ad11f77. Configure here.


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 ismaster+ #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.PathIr { segs: Vec<IrSeg> }, one segment per child of the pestroot:FullScan,All,Key,Strings,Indexes,RangeandFilter(FastFilter).Box<str>keys, an owned literal) and independent of the document type. The IR and the per-container filter path share it.Rc, and isSend + Sync.lower_pathwalks pest's tree once. There is no second grammar to keep in step, and every error message is pest's.QueryRoot::Ir(IrPath)is evaluated bycalc_ir, which mirrorscalc_internalarm for arm (calc_all,calc_literal,calc_strings,calc_indexes,calc_range,calc_full_scanand the lowered-filter arm) with the same path trackers. Its..arm skips scalar descendants, ascalc_full_scanhas done since Skip scalar descendants in JSONPath recursive descent #1717. It needs noPathCalculatorData.Query: everylib.rsentry point has anIrarm,existsincluded.pop_lastandpop_last_object_keyshorten a length over the shared IR and never mutate it.is_staticandsizekeep the pest arms' results.compile: the static scanner (Scan static JSONPaths without pest #1729), then the cache, then pest.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
compiledoes not build anything. It returns the pest query with a pending-admission mark (Query::admit, the path string).Queryby 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.#[cold]function.jsonpath-benchmark: they compile each path twice and never evaluate, and every row stays within +3 % ofmaster(below).create/calc,create_with_generator/calc_paths) are served from the cache once a path is in it, but never admit a path themselves.min_by_keyhere 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.Querygrows by 16 bytes (the pending path).Thread safety
thread_local!holding aRefCell): 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 callingJSONAPI_pathParsefrom a worker, gets its own cache with the same bound.Arc, notRc. AQuerycan leave the thread that compiled it (the boxedQueryofJSONAPI_pathParse) while it shares aPathIrwith the cache entry. The IR is immutable and holds noRc, so an atomic count is enough. A pending admission is completed on the thread that evaluates the query, into that thread's cache.try_withturns a compile or admission during thread teardown into a plain miss.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 againstmaster.Graviton4 (arm64 Neoverse-V2, AWS m8g.4xlarge). The official
redis:8.12.0server is pinned to one core and loads the RedisJSON module built frommaster7ecc513 (ijson379dadf) 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 ofmasterran as an A/A control. Δ = patched / base − 1; bold means p < 0.05.kis the key.Datasets:
itemsarray of 10 objects).This PR alone:
master+ #1729 + #1730 → this branchJSON.GET k $.[7]JSON.SET k $.[0] '"foo"'JSON.GET k $.businesses[?(@.avg_rating>=4.5)].nameJSON.GET k $JSON.GET k $..nameJSON.GET k/ 10 %JSON.SET k $ '{"userId":"user-k","organizationId":"org-id","role":"admin",…}'(≈405 B document)JSON.GET k $.items[?(@.qty>5)].nameJSON.GET k $.items[*].name $.items[*].qty $.items[*].price $.items[*].attrs.color $.items[*].attrs.size¹JSON.TYPE k $.items[*].attrsJSON.OBJLEN k $.items[*].attrsJSON.STRAPPEND k $.items[*].name '"-x"'/ 10 %JSON.SET k $.items[*].name '"Item"'JSON.SET k $.items[*].extra [1,2,3,4,5,6,7,8]/ 50 %JSON.ARRAPPEND k $.items[*].extra '"tag"'All three PRs (#1729 + #1730 + this one) vs
masterJSON.GET k $.[7]JSON.SET k $.[0] '"foo"'JSON.GET k $.businesses[?(@.avg_rating>=4.5)].nameJSON.GET k $JSON.GET k $..nameJSON.GET k/ 10 %JSON.SET k $ '{"userId":"user-k","organizationId":"org-id","role":"admin",…}'(≈405 B document)JSON.GET k $.items[?(@.qty>5)].nameJSON.GET k $.items[*].name $.items[*].qty $.items[*].price $.items[*].attrs.color $.items[*].attrs.size¹JSON.TYPE k $.items[*].attrsJSON.OBJLEN k $.items[*].attrsJSON.STRAPPEND k $.items[*].name '"-x"'/ 10 %JSON.SET k $.items[*].name '"Item"'JSON.SET k $.items[*].extra [1,2,3,4,5,6,7,8]/ 50 %JSON.ARRAPPEND k $.items[*].extra '"tag"'¹ 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 (mastervs 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 (
mastervs 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_memorystayed within 0.1 % ofmasteron 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:master+ Scan static JSONPaths without pest #1729 + Lower JSONPath filters once per container #1730 (micro benchmark below), with 16 allocations (7.4 KB);json_path::compile.Wildcard and recursive-descent paths pay the same parse on every command. Their evaluation also clones a
Pairsfor every node visited.Results
Measured on
master7ecc513 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_pathmicro, steady state (path cached), ns per call, median of 6 interleaved runs, with an A/A control of the base binary:$.items[?(@.qty>5)].name(a cache hit)$.businesses[?(@.avg_rating>=4.5)].name, ~30 KB doc$.items[*].name$..name, ~30 KB docThe 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_oncecosts 762 ns here against 783 ns on that build.$..namegains 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.somounted 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.JSON.GET k $.businesses[?(@.avg_rating>=4.5)].name(20K keys, ~30 KB docs), 6 runsJSON.GET k $.items[?(@.qty>5)].name(50K keys, 10-item docs), 4 runsJSON.GET, 5 wildcard paths (50K keys) †JSON.GET k $..name(20K keys, ~30 KB docs) †JSON.TYPE k $.items[*].attrs†JSON.OBJLEN k $.items[*].attrs†JSON.STRAPPEND/JSON.SETon$.items[*].name†JSON.ARRAPPEND/JSON.SETon$.items[*].extra‡JSON.GET k $.[7](static path, same code in both), 4 runs† 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 on90bbdb7(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.GETand 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_onceof never-seen filter and wildcard paths, ns per op, median over 2,900 blocks of 16 paths, median of 3 interleaved rounds:Compile only, never evaluated (what the compile rows of
jsonpath-benchmarksee): +2.0 % (filter) and +3.8 % (wildcard) on every compile, because a compile never builds.Many distinct paths in strict rotation (compile +
calc_oncewhile K filter paths rotate, one thread, ns per op):jsonpath-benchmarkinstruction gate (run_instructions.sh --callgrind-limits='ir=5%'againstmaster, valgrind, x86-64): passes, exit 0. Worst rowcompile/projection-keys+2.96 %;compile/slice+2.94 %;eval/filter-and−78.16 %. No gate row inserts into a full cache.Memory:
used_memorygrew 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
compileon the second compile: the fastest for the many-paths rotation, but the admitting compile costs 15 to 23 % more instructions, and it fails thejsonpath-benchmarkgate on 14 compile rows (+7.6 to +22.8 %), because those rows measure each path's second compile.compileon 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.min_by_keyeviction: 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
master7ecc513 with #1729 and #1730 merged in)cargo test --workspacegives 487 passed and 0 failed. The new tests are:existsanswers from the cached form;..left bypop_last_object_keyskips scalars like the interpreter does (Skip scalar descendants in JSONPath recursive descent #1717).tests/pytest/tests.shagainstredis-server8.12.0 passes 379 of 379 in each of general,--use-aof,--use-slavesand--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).master:compileerrors,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, thepop_last*sequences and the prefix left after popping;cargo fmt --checkandcargo clippy -p json_path --all-targetsare 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 returnsQueryRoot::Ir; otherwise pest runs and may setQuery::admitso 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, andsizework across pest, static, and IR roots;lib.rsentry points (calc_once,exists,visit_once_with_paths, etc.) dispatch onQueryRootand call admission where needed.path_cache_statsis 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.