Skip to content

MOD-17687 Support Auto-Create missing paths - #1640

Merged
AvivDavid23 merged 35 commits into
masterfrom
MOD-17687-auto-create-paths
Sep 29, 2026
Merged

AvivDavid23 merged 35 commits into
masterfrom
MOD-17687-auto-create-paths

Conversation

@AvivDavid23

@AvivDavid23 AvivDavid23 commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Adds opt-in creation of missing object paths (json-auto-create-deep-paths yes, disabled by default).

  • Supported: JSON.SET, JSON.MSET, JSON.MERGE.
  • Also supported: JSON.ARRAPPEND, JSON.ARRINSERT (index 0 only),
    JSON.STRAPPEND, JSON.NUMINCRBY.
  • Prepares missing subtrees before attachment using shared logic.
  • Enforces depth limits; tests cover overlapping paths, failures, and replication.
  • Example when enabled: JSON.SET k $.a.b 5 on {} produces {"a":{"b":5}}.

Performance results

  • CI comparisons showed no broad slowdown with auto-creation disabled, although results were noisy(for both sides).
  • With auto-creation enabled, the new benchmarks measured ~106k SET requests/s and ~63k MSET requests/s (two writes per request); master has no equivalent operation.

Why I kept path-based attachment

  • I kept validation and preparation of missing subtrees before document modification, followed by resolving their
    parent paths again to attach them.
  • I tested a scoped-reference prototype: negligible gains for simple paths, ~4.1% improvement for deep shared
    paths, and ~1–2% slowdowns for shallow fan-out. It still required attachment-time traversal.
  • I found these gains insufficient to justify the added API and lifetime complexity. Keeping references from
    discovery would introduce invalidation constraints across backends; path-based attachment keeps the preparation boundary and works consistently with current implementors.

Note

High Risk
Changes JSON mutation semantics, replication/AOF behavior when the flag differs across nodes, and adds complex multi-target write planning with partial-attachment edge cases.

Overview
Adds json-auto-create-deep-paths (load-time, default off) so JSON write commands can materialize missing object keys along a path instead of failing or returning nil. Documented in module.conf; registered as an immutable module bool in lib.rs. Array indexes are still never invented.

Command behavior when enabled: JSON.SET / JSON.MERGE / JSON.MSET use a new auto_create pipeline—resolve prefix matches once, walk trailing object keys, build detached subtrees, then dict_add attach before applying updates or seeds. Missing keys on absent documents can be built via root_key_chain / nest_in_objects. JSON.NUMINCRBY, JSON.STRAPPEND, JSON.ARRAPPEND, and JSON.ARRINSERT (index 0 only) seed new leaves (0, "", []) through the same preparation path; MULTBY/POWBY and non-zero ARRINSERT keep prior semantics.

json_path support: Query is Clone with pop_last_object_key (single-key suffixes only). Path evaluation gains visit_once_with_paths / visit_with_paths_on_root using ControlFlow so traversal can stop early without collecting all matches—used heavily during path resolution.

Supporting changes: Manager gains clone_value / create_object; shared number_op_result in number.rs. Coverage workflow pins Redis via .install/get-redis-ref.sh; make coverage no longer ignores test failures. New benchmarks exercise deep-path SET/MSET with auto-create on.

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

@codecov

codecov Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.36752% with 34 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.06%. Comparing base (2c01c80) to head (66348d3).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
redis_json/src/auto_create.rs 96.73% 16 Missing ⚠️
json_path/src/json_path.rs 88.97% 14 Missing ⚠️
redis_json/src/commands.rs 98.31% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1640      +/-   ##
==========================================
+ Coverage   85.84%   88.06%   +2.21%     
==========================================
  Files          15       17       +2     
  Lines        5278     5957     +679     
==========================================
+ Hits         4531     5246     +715     
+ Misses        747      711      -36     

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

Stale Bugbot comment from a previous run.

Comment thread redis_json/src/key_value.rs Resolved

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

Stale Bugbot comment from a previous run.

Comment thread redis_json/src/auto_create.rs Resolved
Comment thread redis_json/src/commands.rs Resolved

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

Stale Bugbot comment from a previous run.

Comment thread redis_json/src/commands.rs Resolved
AvivDavid23 and others added 2 commits September 23, 2026 15:58
…ting and missing targets together, then prepare detached subtrees before attachment.
@AvivDavid23

Copy link
Copy Markdown
Contributor Author

I think we should consider the recursive version, where we validate the path while traversing forward, reach the last element, create it, and link everything back into the existing path as the recursion unwinds. I believe this would allow us to remove all the planning functions and make the code less complex. As mentioned, a single traversal could handle creation, planning, and validation together. Aviv, could you look into this approach?

good idea, check now

@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 2 potential issues.

There are 4 total unresolved issues (including 2 from previous reviews).

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 3ea575e. Configure here.

Comment thread redis_json/src/commands.rs Resolved
Comment thread redis_json/src/commands.rs Resolved
Comment thread json_path/src/json_path.rs Outdated
struct PathCalculatorData<'i, S: SelectValue, UPT: UserPathTracker> {
struct PathCalculatorData<'v, 'i, S: SelectValue, UPT: UserPathTracker> {
results: Vec<CalculationResult<'i, S, UPT>>,
visitor: Option<&'v mut dyn FnMut(CalculationResult<'i, S, UPT>)>,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can the callback signature changed to return result ? currently we can not stop traversing ,
I think once we see an error we should stop

Comment thread redis_json/src/ivalue_manager.rs Outdated
}

fn create_object(&self, fields: Vec<(String, IValue)>) -> RedisResult<IValue> {
let mut object = IObject::new();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can we initialize the object with the known capacity to avoid reallocations for big nested objects?

Comment thread redis_json/src/commands.rs Outdated
// creation list can mean that every target already exists.
let nx_has_existing_targets =
op == SetOptions::NotExists && auto_create_enabled() && {
let targets = calc_once(query.clone(), doc);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

should we return a ref flag from prepare_set that tells us wether we founf existing target or not ? and avoid this work ?

Comment thread redis_json/src/commands.rs Outdated
redis_key.notify_keyspace_event(ctx, "json.set")?;
manager.apply_changes(ctx);
REDIS_OK
let new_doc = if path == JSON_ROOT_PATH {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

it seems like this path and merge has shared logic , should we use some helper function ?

Comment thread redis_json/src/commands.rs Outdated
if query.is_projection() {
return Err(err_projection_readonly());
}
if calc_once(query.clone(), doc).is_empty() && !can_create(query.clone(), doc)? {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

can we avoid double travrsal ?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I combined the existing-target and creation checks into one traversal; MSET still re-plans during the write

Comment thread redis_json/src/key_value.rs Outdated
query: Query,
option: SetOptions,
) -> RedisResult<Vec<UpdateInfo>> {
if option == SetOptions::NotExists {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could we reject projections before the NX early return? The caller catches this later, but checking here keeps validation consistent.

Comment thread redis_json/src/number.rs

/// Arithmetic shared by OSS writes and creation preflight on every backend.
/// Integer operations must fit i64; floating-point results must be finite.
pub(crate) fn number_op_result<V: SelectValue, F1, F2>(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can you add unit tests for this helper, covering integer overflow/underflow, mixed integer and float inputs, non-finite results, and large integers that fall back to f64?

// keep their replies. MSET handles the depth error explicitly as nil.
// No target with this suffix can fit. Reject before exposing a
// target or allocating the remaining creation sites.
if value_type.is_none() && suffix_len >= MAX_DEPTH {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can we include the parent depth in this check before copying the missing suffix into every target?
I think that a key with 127 nested obj already exceed it

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

kept the parent-depth check after pruning because SET may replace an ancestor and discard those over-depth creation targets; rejecting them earlier would fail a valid write.

Comment thread redis_json/src/auto_create.rs Outdated
let mut resolution = Ok(());
// Evaluate the prefix on the original document. Re-evaluating a filter
// after seeding can lose matches or select unrelated new targets.
visit_once_with_paths(query, root, |matched| {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Maybe we should stop evaluating once resolve match return an error ?

Comment thread redis_json/src/auto_create.rs Outdated
}
let suffix = object_suffix(&mut query);
let mut creatable = false;
visit_once_with_paths(query, root, |matched| {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

We only need one creatable target here. Once we find it, can we stop the traversal? The || skips the suffix check, but we still go through all the remaining matches.

@AvivDavid23
AvivDavid23 merged commit 6e28c8c into master Sep 29, 2026
16 checks passed
@AvivDavid23
AvivDavid23 deleted the MOD-17687-auto-create-paths branch September 29, 2026 06:31
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.

2 participants