Repository navigation
Add criterion microbenchmarks for the RedisJSON call paths, a memory referee, and benchmark docs - #29
Conversation
…ry referee benches/callpaths.rs: eight criterion groups, one per RedisJSON call path (parse, serialise, lookup, mutation, typed arrays, clone/drop, CBOR, memory accounting/defrag), argument shapes taken from RedisJSON's ivalue_manager.rs, formatter.rs, key_value.rs, rdb_persistence.rs and json_path. The string cache is initialised as OSS RedisJSON does (init_shared_string_cache(false)); mutation benchmarks restore their own state so no iter_batched setup clone confounds the measured routine. benches/memory.rs: deterministic retained/peak bytes per fixture and call path through mockalloc, beside IValue::mem_allocated(), plus size_of the core types. examples/mem_attribution.rs: attributes a parsed document's retained bytes to objects, arrays, numbers and unique heap strings and shows the gap to mem_allocated() (the intern table). Fixtures are minified copies of RedisJSON's tests/files and tests/benchmarks/datasets JSON documents. No library code changes.
…act for AI agents Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…section CI runs cargo fmt --check, which the bench files failed. The clone benchmarks now use iter_with_large_drop so the destructor of the cloned tree is not timed (RedisJSON stores the clone on its target; the drop group measures destruction). The ARRTRIM benchmark already returned the array to iter_batched, which drops outputs after the measurement; a comment says so. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…r, occupied-entry merge benchmark - parse/compact-objects, parse/fpha-f32, cbor/decode-yelp and cbor/decode-compressed-yelp hand their value back to criterion (iter_with_large_drop) so destruction is not timed; JSON.SET and RDB load keep the value. - lookup/business-22-* is a table-backed object (28 keys > SMALL_OBJECT_THRESHOLD 8); the comment said otherwise. New lookup/small-8-hit-last and small-8-miss time the linear-scan path on an 8-key object. - mutation/merge-26-into-54-occupied: JSON.MERGE's per-key entry(&str) + overwrite into an object that already holds every key (ivalue_manager.rs merge()). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…ly reference to a freshly parsed document (the string-cache removal the batch drop cannot see)
…ache reinit RedisJSON's defrag_start does defrag-copy-yelp keeps the string cache, so every re-intern is a hit and the old copies stay referenced by the live document: the fresh allocation, the cache's growth from empty and the stale-copy drop are never timed. The new benchmark parses a unique document, empties the cache, and times only the defrag. It runs last in the group because the reinit orphans the live document's cache entries. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…the cache reinit inside the timed section defrag_start runs once per cycle; a change that moves work into reinit_shared_string_cache (presizing the new cache) is charged for it here, not hidden as in defrag-reinit-yelp. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ed mirror benches/fetch-datasets.sh [--dir DIR] [quick|standard|all|FAMILY...] downloads the datasets-v1 release assets of redis-performance/json-agent-workspace into DIR (default benches/datasets, git-ignored), checks each against the pinned list in benches/datasets.sha256 before unpacking, and skips assets already verified on a re-run. quick (default): simdjson-data, extras, floatdata, 165 MB download, 0.57 GB unpacked. GH Archive (public GitHub user data) only with 'all' or by name. Needs curl, zstd and tar; works with GNU and BSD tools. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…r line benches/fixtures/refsnp-unsupported-400.ndjson is lines 1-400 of NCBI dbSNP build 157 refsnp-unsupported.json.bz2 (US government work, public domain; 243,806 bytes). It joins parse, serialise, clone-drop and the memory referee as one IValue per line, the way JSON.SET stores one key per document. The new benchmarks run after the existing ones in each group, so the existing rows are measured in the same state as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
cargo bench --bench corpus reads IJSON_BENCH_DATASETS (default benches/datasets) and, per file and one key per document (per NDJSON line), times parse (deserialize_compact_objects into an empty string cache), drop of the last references, compact serialise and clone, after a memory table of retained bytes (counting allocator, string cache reset per file). Without datasets it prints the fetch command and exits 0. IJSON_BENCH_FILES (paths or * / ? patterns), IJSON_BENCH_MAX_DOCS (1000) and IJSON_BENCH_MAX_BYTES (4 MiB) bound the work; the default eight files take about two minutes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…3% with alignment flags Three-command quick start (fetch, callpaths, corpus) and criterion baselines for two commits; group table brought up to date (small-8 lookups, occupied merge, drop-last-ref, the r7/r8 defrag benchmarks, refsnp-400); the refsnp-400 provenance; the corpus bench's knobs; dataset families with sizes and licence/privacy notes; A/B protocol with Linux pinning, three interleaved pairs, a 3% noise level, the 64-byte code-alignment RUSTFLAGS for placement-free comparisons, and the four platform classes to report on. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
gabsow
left a comment
There was a problem hiding this comment.
Reviewed at 8eec627. The suite builds in both configurations and runs. But four benchmarks don't time the RedisJSON path they stand for, and two of those are one-line fixes.
clone-drop/clonetimes the drop again.- The string cache isn't the one RedisJSON uses.
init_shared_string_cache(false)creates the unlocked cache. RedisJSON at9ca1c88callsinit_ijson_shared_string_cache(true)("Always enable thread-safe cache for ASM support"), so interning or dropping any string longer than 7 bytes takes the mutex.- I ran two interleaved pairs of unlocked and locked on an Apple silicon Mac, with short settings. With the lock,
array-push-pop-heterois 25% slower,business-22-hit18%,object-insert-remove-2214%,wide-128-hit-long-keyandsmall-8-miss13%, andparse/compact-objects/yelp5%.drop/yelpis 18% faster. All of these are well past the README's 2–3% thresholds. - The same call is in
memory.rsandexamples/mem_attribution.rs. The doc comment and the description both sayfalseis what RedisJSON does.
defrag-copy-yelpnever moves a string.- The clone shares every string with
doc, soIString::defrag'sintern_with_allocatorfinds each one in the cache and returns it. - RedisJSON's
defrag_startcallsreinit_shared_string_cache(), so a defrag cycle re-allocates each string. - Calling
reinit_shared_string_cache()in the setup, withBatchSize::PerIteration, would time that. I tried it: the benchmark runs, and goes from about 43 µs, with a wide spread, to 52.4 µs.
- The clone shares every string with
str-appendtimes a cache hit.- After the first iteration the field already holds
city + " (appended)", soIString::from(s)finds that string in the cache. The value it replaces is the same string, so dropping it frees nothing. - RedisJSON's
str_appendinterns a new string on every command and drops the old one. - Alternating between two suffixes would make each iteration insert one string and remove one. I tried that too: it goes from 40 ns to 77 ns.
- After the first iteration the field already holds
Non-blocking:
parse retainedinmemory.rsdepends on fixture order.- It includes the intern table's growth only for the fixture that grows it.
- With
mem_attribution, yelp retains 47,008 bytes when it's the first file and 44,696 when it's second. yahoo2's gap tomem_allocated()goes from 0 to 2,312. - An untimed parse of the same fixture first would leave only the document in the number.
CBOR decode retainedis measured whiledocis alive, so every string is a cache hit. For yelp it's 15,704 bytes, the same as the clone, against 47,008 for the parse. Droppingdocbefore the decode would count the strings an RDB load allocates.array-trim-typed-1024-to-512peaks at 2.2 GB of resident memory at the suite's default settings.object-insert-remove-22peaks at 12 MB.SmallInputkeeps a tenth of each sample's clones alive at once, andLargeInputwould cap that.- Under
thread_safe,mem_attributioncounts short strings as inline.string.rshas no inline form, so yelp's 327 short strings are heap allocations, but the example leaves them out of the unique heap strings. - The README table is missing
small-8-hit-last,small-8-missandmerge-26-into-54-occupied. - The
business-22-*andobject-insert-remove-22names say 22 keys. The business has 28, as the comment above the lookups says. - CI doesn't build the benches.
cargo buildandcargo testskip bench targets, so an API change could break them without failing CI. Acargo bench --no-runstep in both configurations would catch that. - Some comments point to documents outside this repo, such as
docs/USAGE-PATTERN.mdand "harness r4". Stating the reason in the comment would help readers here.
CI is green, though it doesn't build the benches (non-blocking item 7).
I built the benches in both configurations, ran --bench memory and the mem_attribution example, and ran the whole timing suite with short settings. Every benchmark completes.
The datasets-v1 assets are now served from https://s3.amazonaws.com/benchmarks.redislabs/ijson/datasets-v1 (same files, same pinned sha256 list). IJSON_DATASETS_MIRROR still overrides the base URL. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`b.iter` drops each output inside the timed loop, so `clone/*` timed the clone plus the drop of the copy, the cost `drop/*` already measures. The single-document clones now go through `iter_batched` with `LargeInput`, which drops the clones after each batch, outside the timer; `LargeInput` rather than `iter_with_large_drop` (SmallInput) because a tenth of a sample of 8 KB typed-array clones peaked at 2.3 GB of resident memory. The key-per-line clone collects its clones into a vector made in setup and returns it, so they are dropped outside the timer too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
RedisJSON at 9ca1c88 calls `init_ijson_shared_string_cache(true)` at
module load ("Always enable thread-safe cache for ASM support"), which
reaches `ijson::init_shared_string_cache(true)`: the cache behind a
mutex. The benches, the memory referee and `mem_attribution` initialised
it with `false`, the unlocked cache, and said that was RedisJSON's
choice. Interning a heap string and dropping its last reference both
take the mutex in RedisJSON, so every path that interns or frees strings
(parse, drop, mutation, lookups that build keys) was timed on a cheaper
cache than the one RedisJSON runs. All four now pass `true`, and the
comments and README say why.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The copy shares every string with `doc`, so `IString::defrag`'s `intern_with_allocator` found each one in the cache and returned it: the benchmark never moved a string. RedisJSON's `defrag_start` calls `reinit_shared_string_cache()` before a defrag cycle, so each re-intern misses and allocates a new copy. The setup now reinitialises the cache before cloning, with `BatchSize::PerIteration` so each defrag starts from an empty cache. An untracked check confirmed all 922 long-string references move after the change and none before (default build; the `thread_safe` build's `IString::defrag` is the identity). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
After the first iteration the field already held `city + " (appended)"`, so `IString::from` found the string in the cache and the value it replaced was the same string: the benchmark timed a cache hit and a drop that freed nothing. RedisJSON's `str_append` concatenates the field and the argument, interns the result into the field's `IString` and drops the old one, which is the field's last reference. The routine now does the same through `as_string_mut` and `IString::intern`, alternating between two suffixes of equal length, so each iteration inserts one string into the cache and removes one (an untracked allocation count shows 2 allocations and 2 frees per iteration, against 1 and 1 before). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`parse retained` in the memory referee, and `retained` in `mem_attribution`, included the string cache table's growth only for the fixture that grew it, so a fixture's figure depended on what ran before it (yelp: 47,008 bytes first, 44,696 second). Both now parse the fixture once and drop it before the measured parse; in the default build the table keeps its capacity, so the figure is the document alone and equals `mem_allocated()` for every bundled fixture. (The `thread_safe` build's cache shrinks a shard when it empties, so there the table growth stays in, as the comments say.) `CBOR decode retained` was measured while the parsed document was alive, so every decoded string was a cache hit (yelp: 15,704 bytes, the clone's figure). The document and the stream encoder are now dropped first, so the decode allocates its strings as an RDB load does. `mem_attribution` counted strings of up to 7 bytes as inline in both builds, but the `thread_safe` build's `IString` has no inline form: those strings are heap allocations there and now count as unique heap strings. The column is renamed "no heap" (empty and, in the default build, inline strings), and an exact match prints as 0 rather than -0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`SmallInput` keeps a tenth of each sample's setup values and outputs alive at once. `array-trim-typed-1024-to-512` runs in about 2 ns, so a sample holds millions of 8 KB clones: the run peaked at 2.2 GB of resident memory at the default settings. `retag-on-string-push-1024` returns 1025-element heterogeneous arrays and peaked at 318 MB. `LargeInput` keeps a thousandth alive; on an Apple M-series Mac the two runs now peak at 57 MB and 18 MB. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`business-22-{hit,miss}` and `object-insert-remove-22` run on the first
yelp business, which has 28 keys (as the comment above the lookups
already said). They are now `business-28-{hit,miss}` and
`object-insert-remove-28`, both groups assert the key count, and the
comments and README use 28; the merge benchmark's 54 keys are 28 + 26.
The insert/remove comment no longer quotes absolute timings.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`cargo build` and `cargo test` skip bench targets, so an API change that breaks a benchmark would pass CI. The build-and-test job now runs `cargo bench --no-run` with `--no-default-features` (the configuration RedisJSON uses) and with `--features thread_safe`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Some comments pointed to documents that are not in this repository (a usage-pattern document, harness revision numbers): a reader here could not follow them. The callpaths header now lists the groups and the RedisJSON sources their argument shapes come from, the section headings drop their numbering, the Cargo.toml comments say what each bench target is, and the NUMINCRBY and drop comments say why they avoid a setup clone (a clone's layout is set by the clone code, so a change to `clone` would move them). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The mirror now serves every family publicly, so the notes state the licence position (no data licence stated by simdjson-data, float-data and Pison; GH Archive's public GitHub user data) instead of asking users not to publish copies, and keep the advice not to commit GH Archive data to a repository. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… fetch re-checks unpacked files - typed/build-f64-push-1024 and typed/build-i64-try-extend-16k returned the array from b.iter, so its drop was timed with the build. They now use iter_batched with LargeInput, as parse and clone do, so the array is dropped after the batch. - The corpus bench's counting allocator now counts a realloc as an allocation, as mockalloc (used by --bench memory) records it, so the two tables' allocation columns agree. - fetch-datasets.sh: the verification mark now lists the files an asset unpacked, and a re-run downloads the asset again if any is missing. Marks written before this change (sha256 only) also cause a re-fetch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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 81f8ccb. Configure here.
stream-encode-yelp-fresh-encoder and stream-decode-yelp returned only the payload or value, so the StreamEncoder (its string table) and the StreamDecoder (its definition table and the IString references it holds) were dropped inside the timed routine. Both are now handed back with the output and dropped after the batch, as every other output in the suite is. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every pull request now runs .github/scripts/memory-gate.sh: the PR's memory referee (benches/memory.rs) measures the library at the base branch's tip, fetched when the job runs, and the PR, each built in its own target dir. Every retained and peak byte count, ijson_mem_allocated and size_of of the core types is compared per fixture, and the job fails if any grows by more than 5 % (MEMORY_GATE_MAX_PCT). The default build's counts are exact and repeat, so it runs once per side; the thread_safe build's sharded cache takes a random hash seed (up to ~13 % run-to-run on the 1.3 KB fixture), so the gate uses the median of 5 runs per side, which repeats within ~1.5 %. A base that predates the harness takes this checkout's Cargo.toml. Checked: three clean runs against master pass (default build unchanged, thread_safe medians within 1.25 %); an object layout padded by two entries fails with 51 figures above 5 %. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
gabsow
left a comment
There was a problem hiding this comment.
Re-reviewed at 0fc1cd4. Every item from my last review is fixed, and I checked each one. Approving, with some non-blocking notes: three on the new memory gate, and four on the benches.
Fixed, as measured on an Apple silicon Mac:
clone-drop/clonetimes the clone only:clone/yelpis now 15.5 µs, anddrop/yelpis 5.0 µs.- The benches,
memory.rsandmem_attributionall use the locked cache, and the comments say so. defrag-copy-yelpempties the cache in setup, so every string moves. It now takes 55.9 µs.str-appendalternates two suffixes, so each iteration interns one string and frees one. It takes 88 ns.- In the default build,
parse retainedequalsmem_allocated()for every fixture, andmem_attributionprints the same numbers in either file order. CBOR decode retainedfor yelp is now 41,896 bytes, up from 15,704.- The trim benchmark peaks at 57 MB of resident memory, down from 2.2 GB.
- Under
thread_safe,mem_attributioncounts only yelp's 21 empty strings as having no heap allocation. - The README table, the 28-key names, the CI bench builds and the comments are fixed too.
The new code works:
- All 71
callpathsbenchmarks run once in both builds, andcargo fmt --checkpasses. --bench corpusexits 0 without datasets. I also ran it over a local directory of the bundled yelp and RefSNP files, using a glob inIJSON_BENCH_FILESand a duplicate file name. It runs, and it labels the duplicate by its parent directory.- I ran
fetch-datasets.shunder macOS's bash 3.2 against a localfile://mirror, with no arguments and with named families. It fetches and verifies, skips verified assets on a re-run, and re-fetches an asset after one of its files is deleted. - Every asset in
datasets.sha256is on the S3 mirror, and thequickandstandarddownload sizes match the README. - The memory gate passes in CI.
On the memory gate (0fc1cd4):
- It commits
.github/scripts/__pycache__/memory_gate.cpython-313.pyc. That's Python's compiled cache from a local run. Removing it and adding__pycache__/to.gitignorewould keep it out. - It allows 5 % growth in the default build too. Its counts repeat exactly there, and the README's A/B protocol asks for memory to stay identical unless a change declares otherwise. A 0 % limit for the default build, keeping 5 % for
thread_safe, would match that. - It can blame a PR for changes on the base branch.
- It compares HEAD with the base branch's tip at run time. In CI, HEAD is the merge commit, so the two agree until the base moves. A re-run keeps the old merge commit but takes the new tip.
- Run locally, as the README suggests, HEAD is the branch itself. So anything merged into master since the branch point counts for or against it.
- Measuring the base at the commit HEAD was built on would avoid both. In CI that's the merge commit's first parent,
HEAD^1, which needsfetch-depth: 2on the checkout. Locally it'sgit merge-base HEAD origin/$BASE_REF.
On the benches:
parse/compact-objects/*mostly times cache hits.- Within a batch, every parse after the first finds its strings in the cache. A
JSON.SETof new string values takes the miss path instead. - I timed a yelp parse on its own, dropped outside the timer: 58.6 µs with an empty cache, and 47.8 µs with another copy alive.
compact-objects/yelpreads 48.0 µs, so it's the warm case.corpus-parseon the same file reads 59.7 µs. - I missed this last time. It isn't blocking:
corpus-parsecovers the cold path once the datasets are fetched, and keys that share a schema do take the warm path. Still, the README table could say thatparseis the warm case, and a cold variant could sit beside it, asdrop-last-refdoes for drops.
- Within a batch, every parse after the first finds its strings in the cache. A
array-trim-typed-1024-to-512only covers a trim from index 0.- RedisJSON's
arr_trimrotates the slice left bystart, then truncates. Withstartat 0 the rotate does nothing, so the benchmark is a length store and reads 1 ns. - Keeping the middle half instead, with
rotate_left(256)onas_mut_slice()and thentruncate(512), takes 122 ns. Capping an appended list to its last N elements takes that path.
- RedisJSON's
drop-last-ref/floats-1024mostly times the timer. It reads 32 ns, against 15 ns fordrop/floats-1024. A typed array holds no strings, so both do the same work. The gap is most likely the twoInstantcalls per iteration.parse retainedmeans two things. For yelp it's 42,392 bytes in--bench memory, which leaves out the table growth, and 47,008 bytes in the corpus table, which resets the cache per file and so counts it. Different column names would stop anyone comparing the two tables.
CI: every job passes, including the memory gate. Bugbot hadn't finished on this commit when I posted.
.github/scripts/__pycache__/memory_gate.cpython-313.pyc came from a local run of the memory gate. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…d in The gate compared HEAD with the base branch's tip. In CI, HEAD is the merge commit, which a re-run keeps while the tip moves; run locally, HEAD is the branch, so anything merged into the base since the branch point counted for or against it. Both sides are now built from the tip fetched when the gate runs: the tip itself, and the tip with HEAD merged in (no commit), with the merged tree's harness. Changes that reached the base are on both sides, so only HEAD's own changes count, and the comparison is still always against the current tip. The checkout fetches full history for the merge; a HEAD that does not merge cleanly fails the gate with a message to update the branch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…orpus column - parse/compact-objects-cold/*: each parse runs with no other copy alive, so every string is inserted into the cache (the JSON.SET of new string values); only the parse is timed. compact-objects stays as the warm case (within a batch the strings are already cached, as for keys sharing a schema) and the README says so. - mutation/array-trim-typed-1024-middle-512: ARRTRIM keeping the middle half, through arr_trim's rotate_left then truncate. The trim from index 0 only stores a length. - clone-drop/drop-last-ref skips floats-1024: a typed array holds no strings, so its last-reference drop is drop's work, and at ~15 ns the two Instant reads per iteration dominated it. - The corpus memory table's column is 'parse retained incl. string table': it resets the cache per file, so it counts the table growth that --bench memory's 'parse retained' leaves out. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The default build's counts come from a counting allocator and repeat exactly, so any change is real; the A/B protocol asks for memory to stay identical unless a change declares otherwise. Its limit is now 0 % (MEMORY_GATE_MAX_PCT_DEFAULT). The thread_safe build keeps +5 % on the median of 5 runs (MEMORY_GATE_MAX_PCT_TS), since its sharded cache's random hash seed moves its counts between runs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tring-in-register Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…drop-single-probe Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…y-str-without-intern Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…py-table Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…obe-before-intern Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rays-no-boxing Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Summary
Benchmarks only, no library code changes. Adds under
benches/:callpaths.rs: eight criterion groups, one per kind of operation RedisJSON performs onijson, with argument shapes taken from RedisJSON'sivalue_manager.rs,formatter.rs,key_value.rs,rdb_persistence.rs,defrag.rsandjson_path:parse(JSON.SET, compact objects and FPHA float arrays, one key per line for NDJSON),serialise(JSON.GET, compact and indented),lookup(JSONPath steps andget/get_mutby key on the 28-key yelp business, an 8-key small object and a 128-key wide object, with a typed-array control),mutation(member set/delete,MERGEinto occupied entries, array insert/pop/trim,NUMINCRBY,STRAPPEND),typed(homogeneous arrays: build, retag, slice reads),clone-drop(clone, drop, and drop of the last reference),cbor(RDB save/load incl. the streaming codec and compressed variants),mem-defrag(mem_allocated, and defrag afterdefrag_start's cache reinit). The string cache is initialised as RedisJSON does at module load,init_shared_string_cache(true)(the locked cache); mutation benchmarks restore their own state so no setup clone confounds the measured routine, and outputs are dropped outside the timed section unless the drop is what is measured.memory.rs: deterministic retained/peak bytes and allocation counts per fixture and call path throughmockalloc,IValue::mem_allocated()beside the allocator's truth, CBOR payload sizes,size_offor the core types. Markdown or--jsonoutput.corpus.rs: the parse, drop, serialise and clone call paths over real JSON files fetched byfetch-datasets.sh(one key per document, one per line for NDJSON), after a memory table per file. Without datasets it prints the fetch command and exits 0.fetch-datasets.shanddatasets.sha256: download the benchmark corpus from a public S3 mirror, check every asset against its pinned sha256 before unpacking, in presets (quick165 MB download,standard,all) or by family.examples/mem_attribution.rs: attributes a parsed document's retained bytes to objects, arrays, numbers and unique heap strings and shows the gap tomem_allocated().benches/README.md: a quick start, what each group measures and which RedisJSON command it stands for, the datasets and their licences, how to run, the A/B protocol that has held up against code-placement noise on the 15–60 ns routines (same commit/toolchain/machine, interleaved pairs, median delta with the base's spread, 3% noise level and re-run rule, optional 64-byte alignment flags to take placement out, time-and-memory decision, four platform classes), and a "For AI agents" section stating the contract an automated agent must follow when it proposes a change (name the RedisJSON call path, measure on one machine, report time and memory with spread, keep harness and candidate commits apart, confirm end to end in RedisJSON). A short pointer is added to the top-level README.Fixtures are minified copies of RedisJSON's
tests/filesandtests/benchmarks/datasetsdocuments (yelp, yahoo2, a Google Maps place reply, homogeneous integer arrays,parser-0000,pass-100), two arrays generated with a fixed seed, andrefsnp-unsupported-400.ndjson: 400 NCBI dbSNP RefSNP records (build 157, public domain), benchmarked one key per line.Cargo.tomlgainscriterionas a dev-dependency (no default features,cargo_bench_supportonly) and three[[bench]]entries withharness = false. CI builds the benches in both configurations (cargo bench --no-run,--no-default-featuresand--features thread_safe), sincecargo buildandcargo testskip bench targets.New in this revision
clone-drop/drop-last-ref/*(the drop of the only reference, so every string leaves the cache),mem-defrag/defrag-reinit-yelp(defrag of the only copy afterdefrag_start's cache reinit) andmem-defrag/defrag-cycle-yelp(the same with the reinit timed).benches/fetch-datasets.shreads a public S3 mirror, sha256-pinned per asset, withquick/standard/allpresets.refsnp-400, one key per line, inparse,serialise,clone-dropand the memory referee.--bench corpus, RedisJSON's call paths over the fetched files.Memory gatejob fetches the base branch's tip when it runs and measures it, and the same tip with the PR merged in, with this suite's memory referee (so commits that reached the base after the PR branched off are on both sides). It compares every retained and peak byte count,mem_allocatedandsize_of: the default build, whose counts repeat exactly, fails on any growth;thread_safe, whose sharded cache's random hash seed moves small fixtures by up to ~13 % between runs, uses the median of 5 runs per side and fails above +5 %. Script:.github/scripts/memory-gate.sh; table in the job summary.clone-drop/clone/*times the clone only; clones are dropped outside the timer (LargeInputbatches, so 8 KB typed-array clones no longer reach gigabytes of resident memory).mem_attributioninitialise the locked string cache,init_shared_string_cache(true), as RedisJSON does.defrag-copy-yelpreinitialises the string cache in setup (BatchSize::PerIteration), asdefrag_startdoes, so every string moves.str-appendalternates two suffixes, so each iteration interns a new string and drops the old one, asstr_appenddoes.parse retainedandmem_attributionno longer depend on fixture order (a dropped parse of the fixture first);CBOR decode retainedis measured with the parsed document dropped;mem_attributioncounts short strings as heap strings in thethread_safebuild.array-trim-typed-1024-to-512andretag-on-string-push-1024useLargeInput.business-28-{hit,miss}andobject-insert-remove-28(were-22): the yelp business has 28 keys.typed/build-f64-push-1024andtyped/build-i64-try-extend-16kdrop the built array after the batch, outside the timer.reallocas an allocation, asmockallocdoes, so its allocation column agrees with--bench memory.fetch-datasets.shre-downloads an asset when any file it unpacked has been deleted.cbor/stream-encode-yelp-fresh-encoderandcbor/stream-decode-yelpdrop the encoder and decoder after the batch, outside the timer.parse/compact-objects-cold/*beside the warmcompact-objects/*: no other copy alive, so every string is inserted into the cache.mutation/array-trim-typed-1024-middle-512:ARRTRIMkeeping the middle half, througharr_trim's rotate then truncate.clone-drop/drop-last-refcovers documents with strings only (a typed array's last-reference drop isdrop's work, and the timer dominated it).parse retained incl. string table, distinct from--bench memory'sparse retained.Why
Having the suite in-tree lets any future
ijsonchange, human or agent-authored, be judged on the paths RedisJSON exercises with time and memory together. Earlier versions of it were used to measure #27 and #28, and caught confounds in its own harness (aniter_batchedsetup clone, a benchmark that timed aNone); this revision fixes the ones found in review.Checks
cargo test --lib -- --test-threads=1passes with--no-default-features(134 tests) and--features thread_safe(129);cargo bench --no-runbuilds in both configurations;cargo bench --bench callpaths -- --testruns all 79 benchmarks once in both;--bench memoryand themem_attributionexample run in both; on Linux,--bench corpus -- --testruns its 32 benchmarks over the eight default files.cargo fmt --checkpasses; clippy reports nothing inbenches/orexamples/, and the library's own clippy output is unchanged.src/; the unit tests and fuzz targets are unaffected.🤖 Generated with Claude Code
Note
Low Risk
Benchmark-only and CI automation with no library code changes; the memory gate may fail PRs that increase retained memory even when behavior is correct.
Overview
Adds a full benchmark harness around RedisJSON’s real
ijsonusage: Criterioncallpaths(parse, serialise, lookup, mutation, typed arrays, clone/drop, CBOR, defrag), deterministicmemoryreferee viamockalloc, and optionalcorpusruns over downloaded datasets.Cargo.tomlpicks upcriterionand three[[bench]]targets; bundled fixtures plusfetch-datasets.sh/ pinneddatasets.sha256support larger corpus runs.CI now
cargo bench --no-runin default andthread_safebuilds, and a new memory gate job runs.github/scripts/memory-gate.sh: base-branch tip vs that tip with the PR merged, samememoryharness—zero tolerance on retained/peak growth in the default build, +5% median threshold forthread_safe.memory_gate.pydiffs JSON bench output into the job summary.Docs:
benches/README.md(A/B protocol, agent contract), README pointer,examples/mem_attribution.rs..gitignoreignoresbenches/datasetsand__pycache__. No changes undersrc/.Reviewed by Cursor Bugbot for commit bebaf8d. Bugbot is set up for automated code reviews on this repo. Configure here.