azure_data_cosmos_driver 0.5.0

Core implementation layer for Azure Cosmos DB - provides transport, routing, and protocol handling for cross-language SDK reuse
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

//! Local evaluator for Cosmos DB PATCH operations.
//!
//! This is the "M" of the PATCH handler's Read-Modify-Write loop. After the
//! handler reads the current item it asks [`apply_patch_ops`] to materialize
//! the requested mutations on the in-memory document; the handler then writes
//! the result back via an ETag-guarded Replace.
//!
//! The evaluator is intentionally schema-agnostic — it works against
//! [`serde_json::Value`] and never deserializes into the caller's type.
//!
//! # Semantics
//!
//! Path parsing follows RFC 6901 (JSON Pointer), with the standard escapes
//! `~0 -> ~` and `~1 -> /`. The trailing token `-` in an array context refers
//! to the past-the-end position (used only by [`PatchOperation::Add`] to append).
//!
//! Op semantics follow Cosmos DB's documented PATCH behavior:
//!
//! * [`Add`](PatchOperation::Add) — the parent path must exist. Arrays: numeric index
//!   `<= len`, or `-` to append. Objects: replaces existing keys.
//! * [`Set`](PatchOperation::Set) — like Add but a missing leaf in an object always
//!   succeeds (Add-or-Replace). Cosmos-specific.
//! * [`Replace`](PatchOperation::Replace) — the leaf must already exist.
//! * [`Remove`](PatchOperation::Remove) — the leaf must exist; cannot target root.
//! * [`Increment`](PatchOperation::Increment) — leaf must be a JSON number;
//!   [`CosmosNumber::Int`] refuses to merge with a fractional target.
//! * [`MoveOp`](PatchOperation::MoveOp) — source must exist; source and destination
//!   must be distinct; destination cannot be a descendant of the source.
//!
//! Failures return [`PatchEvalError`], which converts into a
//! [`crate::error::CosmosError`] with HTTP status `400 BadRequest` (via the
//! `From<PatchEvalError>` impl below) before being surfaced to callers.

use crate::models::{CosmosNumber, PatchOperation};
use serde_json::Value;
use std::fmt;

/// Errors produced by [`apply_patch_ops`] when an op cannot be applied.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum PatchEvalError {
    /// The path is not a valid JSON Pointer (e.g., does not start with `/`,
    /// or contains an invalid `~`-escape).
    InvalidPath(String),
    /// A non-final token addressed a non-container (e.g., navigating into a
    /// scalar) or referenced a missing key/index.
    MissingParent(String),
    /// The leaf path the op needed does not exist.
    MissingTarget(String),
    /// An array token was not `-` and not parseable as a non-negative integer.
    InvalidArrayIndex {
        /// The offending token, percent-decoded.
        token: String,
        /// The full path that contained it.
        path: String,
    },
    /// An array index was greater than the array's length.
    ArrayIndexOutOfRange {
        /// Index requested.
        index: usize,
        /// Array length.
        len: usize,
        /// Containing path.
        path: String,
    },
    /// The path resolved to a value of an unexpected JSON type (e.g.,
    /// [`Increment`](PatchOperation::Increment) on a string).
    TypeMismatch {
        /// Human-readable expected description.
        expected: &'static str,
        /// Human-readable actual type.
        actual: &'static str,
        /// Containing path.
        path: String,
    },
    /// Attempted to remove the root document, which is not permitted.
    CannotRemoveRoot,
    /// A `move` op specified identical `from`/`path`, or attempted to move a
    /// subtree under its own descendant.
    InvalidMove(String),
}

impl fmt::Display for PatchEvalError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PatchEvalError::InvalidPath(p) => write!(f, "invalid JSON Pointer: '{p}'"),
            PatchEvalError::MissingParent(p) => write!(f, "missing parent path: '{p}'"),
            PatchEvalError::MissingTarget(p) => write!(f, "missing path: '{p}'"),
            PatchEvalError::InvalidArrayIndex { token, path } => {
                write!(f, "invalid array index '{token}' in path '{path}'")
            }
            PatchEvalError::ArrayIndexOutOfRange { index, len, path } => write!(
                f,
                "array index {index} out of range (len={len}) in path '{path}'"
            ),
            PatchEvalError::TypeMismatch {
                expected,
                actual,
                path,
            } => write!(
                f,
                "type mismatch at '{path}': expected {expected}, got {actual}"
            ),
            PatchEvalError::CannotRemoveRoot => write!(f, "cannot remove root document"),
            PatchEvalError::InvalidMove(msg) => write!(f, "invalid move: {msg}"),
        }
    }
}

impl std::error::Error for PatchEvalError {}

impl From<PatchEvalError> for crate::error::CosmosError {
    fn from(err: PatchEvalError) -> Self {
        crate::error::CosmosError::builder()
            .with_status(crate::error::CosmosStatus::new(
                azure_core::http::StatusCode::BadRequest,
            ))
            .with_message(err.to_string())
            .build()
    }
}

/// Applies the ordered list of `ops` to `doc` in place, returning the first
/// failure (if any). Ops up to the failing one have already mutated `doc`.
pub(crate) fn apply_patch_ops(
    doc: &mut Value,
    ops: &[PatchOperation],
) -> Result<(), PatchEvalError> {
    for op in ops {
        apply_one(doc, op)?;
    }
    Ok(())
}

fn apply_one(doc: &mut Value, op: &PatchOperation) -> Result<(), PatchEvalError> {
    match op {
        PatchOperation::Add { path, value } => add_or_set(doc, path, value.clone(), AddOrSet::Add),
        PatchOperation::Set { path, value } => add_or_set(doc, path, value.clone(), AddOrSet::Set),
        PatchOperation::Replace { path, value } => replace(doc, path, value.clone()),
        PatchOperation::Remove { path } => remove(doc, path).map(|_| ()),
        PatchOperation::Increment { path, value } => increment(doc, path, *value),
        PatchOperation::Move { from, path } => move_value(doc, from, path),
    }
}

// ---------------------------------------------------------------------------
// JSON Pointer parsing (RFC 6901)
// ---------------------------------------------------------------------------

fn parse_pointer(path: &str) -> Result<Vec<String>, PatchEvalError> {
    if path.is_empty() {
        return Ok(Vec::new());
    }
    if !path.starts_with('/') {
        return Err(PatchEvalError::InvalidPath(path.to_string()));
    }
    let mut tokens = Vec::new();
    for raw in path[1..].split('/') {
        tokens.push(unescape_token(raw)?);
    }
    Ok(tokens)
}

fn unescape_token(raw: &str) -> Result<String, PatchEvalError> {
    let mut out = String::with_capacity(raw.len());
    let mut chars = raw.chars();
    while let Some(c) = chars.next() {
        if c == '~' {
            match chars.next() {
                Some('0') => out.push('~'),
                Some('1') => out.push('/'),
                _ => return Err(PatchEvalError::InvalidPath(raw.to_string())),
            }
        } else {
            out.push(c);
        }
    }
    Ok(out)
}

fn json_type_name(v: &Value) -> &'static str {
    match v {
        Value::Null => "null",
        Value::Bool(_) => "boolean",
        Value::Number(_) => "number",
        Value::String(_) => "string",
        Value::Array(_) => "array",
        Value::Object(_) => "object",
    }
}

// ---------------------------------------------------------------------------
// Navigation helpers
// ---------------------------------------------------------------------------

/// Walk to the parent of the path, returning a mutable reference plus the
/// final unescaped token. For root paths the caller treats this as "the
/// document itself" or rejects it.
fn navigate_parent_mut<'a, 'b>(
    doc: &'a mut Value,
    tokens: &'b [String],
    path: &str,
) -> Result<(&'a mut Value, &'b str), PatchEvalError> {
    if tokens.is_empty() {
        return Err(PatchEvalError::InvalidPath(path.to_string()));
    }
    let (last, prefix) = tokens.split_last().expect("non-empty");
    let mut cursor = doc;
    for token in prefix {
        cursor = step_into(cursor, token, path)?;
    }
    Ok((cursor, last.as_str()))
}

fn step_into<'a>(
    node: &'a mut Value,
    token: &str,
    full_path: &str,
) -> Result<&'a mut Value, PatchEvalError> {
    match node {
        Value::Object(map) => map
            .get_mut(token)
            .ok_or_else(|| PatchEvalError::MissingParent(full_path.to_string())),
        Value::Array(arr) => {
            let idx = parse_array_index(token, full_path, arr.len(), false)?;
            arr.get_mut(idx)
                .ok_or_else(|| PatchEvalError::MissingParent(full_path.to_string()))
        }
        _ => Err(PatchEvalError::MissingParent(full_path.to_string())),
    }
}

fn parse_array_index(
    token: &str,
    full_path: &str,
    len: usize,
    allow_append: bool,
) -> Result<usize, PatchEvalError> {
    if token == "-" {
        if allow_append {
            return Ok(len);
        }
        return Err(PatchEvalError::InvalidArrayIndex {
            token: token.to_string(),
            path: full_path.to_string(),
        });
    }
    let idx: usize = token
        .parse()
        .map_err(|_| PatchEvalError::InvalidArrayIndex {
            token: token.to_string(),
            path: full_path.to_string(),
        })?;
    // when `allow_append=false` (Set / Replace on a numeric index), the
    // array must contain that index. `len.saturating_sub(1)` is `0` for an
    // empty array, which would let `idx=0` slip through and cause the caller's
    // `arr[idx] = v` to panic with "index out of bounds". Reject empty arrays
    // up front so the typed `ArrayIndexOutOfRange` surfaces instead of a
    // panic.
    if !allow_append && len == 0 {
        return Err(PatchEvalError::ArrayIndexOutOfRange {
            index: idx,
            len,
            path: full_path.to_string(),
        });
    }
    let upper = if allow_append {
        len
    } else {
        len.saturating_sub(1)
    };
    if idx > upper {
        return Err(PatchEvalError::ArrayIndexOutOfRange {
            index: idx,
            len,
            path: full_path.to_string(),
        });
    }
    Ok(idx)
}

// ---------------------------------------------------------------------------
// Op evaluators
// ---------------------------------------------------------------------------

#[derive(Copy, Clone)]
enum AddOrSet {
    Add,
    Set,
}

fn add_or_set(
    doc: &mut Value,
    path: &str,
    new_value: Value,
    mode: AddOrSet,
) -> Result<(), PatchEvalError> {
    let tokens = parse_pointer(path)?;
    if tokens.is_empty() {
        // Replacing the entire document is allowed by Set; Add at root is also
        // accepted (treated as a Replace of root).
        *doc = new_value;
        return Ok(());
    }
    let (parent, last) = navigate_parent_mut(doc, &tokens, path)?;
    match parent {
        Value::Object(map) => {
            match mode {
                AddOrSet::Add | AddOrSet::Set => {
                    map.insert(last.to_string(), new_value);
                }
            }
            Ok(())
        }
        Value::Array(arr) => {
            // Set on a numeric array index replaces the element (no shift).
            // Add inserts at the index, shifting the tail right. The trailing
            // '-' token always appends, regardless of mode. This matches the
            // .NET / Java SDK's "Set is similar to Add… in an array, Set
            // replaces an existing element value" semantics.
            if matches!(mode, AddOrSet::Set) && last != "-" {
                let idx = parse_array_index(last, path, arr.len(), false)?;
                arr[idx] = new_value;
                return Ok(());
            }
            let idx = parse_array_index(last, path, arr.len(), true)?;
            if idx == arr.len() {
                arr.push(new_value);
            } else {
                arr.insert(idx, new_value);
            }
            Ok(())
        }
        other => Err(PatchEvalError::TypeMismatch {
            expected: "object or array",
            actual: json_type_name(other),
            path: path.to_string(),
        }),
    }
}

fn replace(doc: &mut Value, path: &str, new_value: Value) -> Result<(), PatchEvalError> {
    let tokens = parse_pointer(path)?;
    if tokens.is_empty() {
        *doc = new_value;
        return Ok(());
    }
    let (parent, last) = navigate_parent_mut(doc, &tokens, path)?;
    match parent {
        Value::Object(map) => {
            if !map.contains_key(last) {
                return Err(PatchEvalError::MissingTarget(path.to_string()));
            }
            map.insert(last.to_string(), new_value);
            Ok(())
        }
        Value::Array(arr) => {
            let idx = parse_array_index(last, path, arr.len(), false)?;
            arr[idx] = new_value;
            Ok(())
        }
        other => Err(PatchEvalError::TypeMismatch {
            expected: "object or array",
            actual: json_type_name(other),
            path: path.to_string(),
        }),
    }
}

fn remove(doc: &mut Value, path: &str) -> Result<Value, PatchEvalError> {
    let tokens = parse_pointer(path)?;
    if tokens.is_empty() {
        return Err(PatchEvalError::CannotRemoveRoot);
    }
    let (parent, last) = navigate_parent_mut(doc, &tokens, path)?;
    match parent {
        Value::Object(map) => map
            .remove(last)
            .ok_or_else(|| PatchEvalError::MissingTarget(path.to_string())),
        Value::Array(arr) => {
            let idx = parse_array_index(last, path, arr.len(), false)?;
            if arr.is_empty() {
                return Err(PatchEvalError::MissingTarget(path.to_string()));
            }
            Ok(arr.remove(idx))
        }
        other => Err(PatchEvalError::TypeMismatch {
            expected: "object or array",
            actual: json_type_name(other),
            path: path.to_string(),
        }),
    }
}

fn increment(doc: &mut Value, path: &str, delta: CosmosNumber) -> Result<(), PatchEvalError> {
    let tokens = parse_pointer(path)?;
    if tokens.is_empty() {
        return Err(PatchEvalError::MissingTarget(path.to_string()));
    }
    let (parent, last) = navigate_parent_mut(doc, &tokens, path)?;
    let leaf = match parent {
        Value::Object(map) => map
            .get_mut(last)
            .ok_or_else(|| PatchEvalError::MissingTarget(path.to_string()))?,
        Value::Array(arr) => {
            let idx = parse_array_index(last, path, arr.len(), false)?;
            arr.get_mut(idx)
                .ok_or_else(|| PatchEvalError::MissingTarget(path.to_string()))?
        }
        other => {
            return Err(PatchEvalError::TypeMismatch {
                expected: "object or array",
                actual: json_type_name(other),
                path: path.to_string(),
            });
        }
    };

    let num = match leaf {
        Value::Number(n) => n.clone(),
        other => {
            return Err(PatchEvalError::TypeMismatch {
                expected: "number",
                actual: json_type_name(other),
                path: path.to_string(),
            });
        }
    };

    let new_value = match (delta, num.as_i64(), num.as_f64()) {
        // Integer delta on integer target — preserve integer fidelity.
        (CosmosNumber::Int(d), Some(target), _) => {
            let sum = target
                .checked_add(d)
                .ok_or_else(|| PatchEvalError::TypeMismatch {
                    expected: "i64 (within range)",
                    actual: "i64 (overflow)",
                    path: path.to_string(),
                })?;
            Value::Number(sum.into())
        }
        // Integer delta on floating target — fail rather than demote.
        (CosmosNumber::Int(_), None, Some(_)) => {
            return Err(PatchEvalError::TypeMismatch {
                expected: "integer number",
                actual: "fractional number",
                path: path.to_string(),
            });
        }
        // Float delta on integer target — promote to f64.
        //
        // Integers outside ±2^53 are not exactly representable in f64, so the
        // `as` cast on the next line would silently round (e.g.
        // `9_007_199_254_740_993i64 as f64 == 9_007_199_254_740_992.0`).
        // Round-tripping that back to JSON would durably mutate the value,
        // including in the `Float(0.0)` no-op case. Reject up front rather
        // than silently demote precision — the integer-delta arm above is
        // available for callers that need exact arithmetic on large
        // integers.
        (CosmosNumber::Float(d), Some(target), _) => {
            const F64_INT_LIMIT: u64 = 1u64 << 53;
            if target.unsigned_abs() > F64_INT_LIMIT {
                return Err(PatchEvalError::TypeMismatch {
                    expected: "integer target within ±2^53 for fractional Increment",
                    actual: "integer outside ±2^53",
                    path: path.to_string(),
                });
            }
            let sum = (target as f64) + d;
            match serde_json::Number::from_f64(sum) {
                Some(n) => Value::Number(n),
                None => {
                    return Err(PatchEvalError::TypeMismatch {
                        expected: "finite number",
                        actual: "non-finite",
                        path: path.to_string(),
                    });
                }
            }
        }
        // Float delta on floating target.
        (CosmosNumber::Float(d), None, Some(target)) => {
            let sum = target + d;
            match serde_json::Number::from_f64(sum) {
                Some(n) => Value::Number(n),
                None => {
                    return Err(PatchEvalError::TypeMismatch {
                        expected: "finite number",
                        actual: "non-finite",
                        path: path.to_string(),
                    });
                }
            }
        }
        _ => {
            return Err(PatchEvalError::TypeMismatch {
                expected: "number",
                actual: "non-numeric",
                path: path.to_string(),
            });
        }
    };

    *leaf = new_value;
    Ok(())
}

fn move_value(doc: &mut Value, from: &str, to: &str) -> Result<(), PatchEvalError> {
    if from == to {
        return Ok(());
    }

    // descendant check at the JSON-Pointer token level, not byte level.
    // The previous byte-prefix check happens to be correct for canonical
    // encodings (escapes only encode '/' and '~'), but it's brittle: e.g.
    // `from = "/a"` would erroneously look like a prefix of `to = "/ab/c"`
    // without the trailing-'/' guard. Comparing parsed token slices makes
    // the invariant explicit and robust to any future encoding changes.
    let from_tokens = parse_pointer(from)?;
    let to_tokens = parse_pointer(to)?;
    if to_tokens.len() > from_tokens.len() && to_tokens[..from_tokens.len()] == from_tokens[..] {
        return Err(PatchEvalError::InvalidMove(format!(
            "destination '{to}' is a descendant of source '{from}'"
        )));
    }

    // atomic move via clone-stage-commit. The previous implementation
    // performed `remove` directly on `doc`, then `add_or_set`. If the
    // second step failed (e.g. the destination's parent didn't exist), the
    // original document was already mutated and the caller observed a
    // partial state — violating the "fail leaves doc unchanged" invariant.
    // Stage both steps on a clone, then commit on success.
    let mut staged = doc.clone();
    let value = remove(&mut staged, from)?;
    add_or_set(&mut staged, to, value, AddOrSet::Add)?;
    *doc = staged;
    Ok(())
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn apply(doc: Value, ops: &[PatchOperation]) -> Result<Value, PatchEvalError> {
        let mut d = doc;
        apply_patch_ops(&mut d, ops)?;
        Ok(d)
    }

    #[test]
    fn add_into_object_inserts_key() {
        let doc = json!({"a": 1});
        let out = apply(doc, &[PatchOperation::add("/b", json!(2))]).unwrap();
        assert_eq!(out, json!({"a": 1, "b": 2}));
    }

    #[test]
    fn add_with_dash_appends_to_array() {
        let doc = json!({"xs": [1, 2]});
        let out = apply(doc, &[PatchOperation::add("/xs/-", json!(3))]).unwrap();
        assert_eq!(out, json!({"xs": [1, 2, 3]}));
    }

    #[test]
    fn add_at_array_index_inserts() {
        let doc = json!({"xs": [1, 3]});
        let out = apply(doc, &[PatchOperation::add("/xs/1", json!(2))]).unwrap();
        assert_eq!(out, json!({"xs": [1, 2, 3]}));
    }

    #[test]
    fn add_with_missing_parent_fails() {
        let doc = json!({});
        let err = apply(doc, &[PatchOperation::add("/a/b", json!(1))]).unwrap_err();
        assert!(matches!(err, PatchEvalError::MissingParent(_)), "{err}");
    }

    #[test]
    fn set_creates_missing_leaf_in_object() {
        let doc = json!({"a": 1});
        let out = apply(doc, &[PatchOperation::set("/b", json!(2))]).unwrap();
        assert_eq!(out, json!({"a": 1, "b": 2}));
    }

    #[test]
    fn replace_missing_leaf_fails() {
        let doc = json!({"a": 1});
        let err = apply(doc, &[PatchOperation::replace("/b", json!(2))]).unwrap_err();
        assert!(matches!(err, PatchEvalError::MissingTarget(_)), "{err}");
    }

    #[test]
    fn replace_allows_type_change() {
        // RFC 6902 permits replace to change a value's type.
        let doc = json!({"a": 1});
        let out = apply(doc, &[PatchOperation::replace("/a", json!("hi"))]).unwrap();
        assert_eq!(out, json!({"a": "hi"}));
    }

    #[test]
    fn remove_strips_leaf() {
        let doc = json!({"a": 1, "b": 2});
        let out = apply(doc, &[PatchOperation::remove("/a")]).unwrap();
        assert_eq!(out, json!({"b": 2}));
    }

    #[test]
    fn remove_root_fails() {
        let doc = json!({"a": 1});
        let err = apply(doc, &[PatchOperation::remove("")]).unwrap_err();
        assert!(matches!(err, PatchEvalError::CannotRemoveRoot));
    }

    #[test]
    fn remove_missing_fails() {
        let doc = json!({"a": 1});
        let err = apply(doc, &[PatchOperation::remove("/missing")]).unwrap_err();
        assert!(matches!(err, PatchEvalError::MissingTarget(_)), "{err}");
    }

    #[test]
    fn increment_int_preserves_fidelity() {
        let doc = json!({"n": 9_000_000_000_000_000i64});
        let out = apply(doc, &[PatchOperation::increment("/n", 1i64)]).unwrap();
        let n = out["n"].as_i64().unwrap();
        assert_eq!(n, 9_000_000_000_000_001);
    }

    #[test]
    fn increment_int_on_float_fails() {
        let doc = json!({"n": 1.5});
        let err = apply(doc, &[PatchOperation::increment("/n", 1i64)]).unwrap_err();
        assert!(matches!(err, PatchEvalError::TypeMismatch { .. }), "{err}");
    }

    #[test]
    fn increment_float_on_int_promotes_to_float() {
        let doc = json!({"n": 2});
        let out = apply(doc, &[PatchOperation::increment("/n", 0.5f64)]).unwrap();
        assert!((out["n"].as_f64().unwrap() - 2.5).abs() < f64::EPSILON);
    }

    #[test]
    fn increment_float_on_huge_int_rejects() {
        // Integers outside ±2^53 are not exactly representable in f64, so
        // promoting them via `(target as f64)` silently rounds. Without the
        // range guard, `Increment(/n, 0.0)` against a stored value of
        // `9_007_199_254_740_993i64` would silently mutate it to
        // `9_007_199_254_740_992.0` — durably losing the value when written
        // back as JSON. Pin the fast-fail behavior.
        let doc = json!({ "n": 9_007_199_254_740_993i64 });
        let err = apply(doc, &[PatchOperation::increment("/n", 0.0f64)]).unwrap_err();
        assert!(
            matches!(err, PatchEvalError::TypeMismatch { .. }),
            "Float-delta Increment on i64 outside ±2^53 must reject; got {err}"
        );

        // Negative side of the limit too.
        let doc = json!({ "n": -9_007_199_254_740_993i64 });
        let err = apply(doc, &[PatchOperation::increment("/n", 0.0f64)]).unwrap_err();
        assert!(
            matches!(err, PatchEvalError::TypeMismatch { .. }),
            "Float-delta Increment on negative i64 outside ±2^53 must reject; got {err}"
        );

        // Right at the limit (±2^53) is still representable and must succeed.
        let doc = json!({ "n": 9_007_199_254_740_992i64 });
        let out = apply(doc, &[PatchOperation::increment("/n", 0.0f64)]).unwrap();
        assert_eq!(out["n"].as_f64().unwrap(), 9_007_199_254_740_992.0);
    }

    #[test]
    fn increment_on_non_number_fails() {
        let doc = json!({"n": "five"});
        let err = apply(doc, &[PatchOperation::increment("/n", 1i64)]).unwrap_err();
        assert!(matches!(err, PatchEvalError::TypeMismatch { .. }), "{err}");
    }

    #[test]
    fn move_renames_field() {
        let doc = json!({"a": 1});
        let out = apply(doc, &[PatchOperation::move_value("/a", "/b")]).unwrap();
        assert_eq!(out, json!({"b": 1}));
    }

    #[test]
    fn move_to_same_path_is_noop() {
        let doc = json!({"a": 1});
        let out = apply(doc, &[PatchOperation::move_value("/a", "/a")]).unwrap();
        assert_eq!(out, json!({"a": 1}));
    }

    #[test]
    fn move_into_own_descendant_fails() {
        let doc = json!({"a": {"x": 1}});
        let err = apply(doc, &[PatchOperation::move_value("/a", "/a/inner")]).unwrap_err();
        assert!(matches!(err, PatchEvalError::InvalidMove(_)), "{err}");
    }

    #[test]
    fn move_into_escaped_descendant_fails() {
        // a token containing an escaped '/' must still count as a single
        // pointer segment when computing the descendant relationship. The
        // unescaped key is `a/b`, so `/a~1b/c` is a true descendant of
        // `/a~1b` even though the byte-prefix check is also correct in this
        // specific case.
        let doc = json!({"a/b": {"x": 1}});
        let err = apply(doc, &[PatchOperation::move_value("/a~1b", "/a~1b/c")]).unwrap_err();
        assert!(matches!(err, PatchEvalError::InvalidMove(_)), "{err}");
    }

    #[test]
    fn move_to_sibling_with_shared_prefix_succeeds() {
        // `/a` is NOT a descendant of `/ab` (byte-prefix would say yes
        // without a `/` guard; token-level compare says no). The move must
        // proceed.
        let doc = json!({"a": 1, "ab": {"x": 2}});
        let out = apply(doc, &[PatchOperation::move_value("/a", "/ab/y")]).unwrap();
        assert_eq!(out, json!({"ab": {"x": 2, "y": 1}}));
    }

    #[test]
    fn move_failure_leaves_doc_unchanged() {
        // when the destination is invalid (parent missing), the source
        // must not be removed. The pre-fix implementation would have left
        // the doc as `{"b": {}}` (source removed before add_or_set failed).
        let doc = json!({"a": 1, "b": {}});
        let original = doc.clone();
        let mut d = doc;
        let err = apply_patch_ops(
            &mut d,
            &[PatchOperation::move_value("/a", "/missing/parent/x")],
        )
        .unwrap_err();
        assert!(matches!(err, PatchEvalError::MissingParent(_)), "{err}");
        assert_eq!(
            d, original,
            "move_value must be atomic: a failed move must leave the document unchanged"
        );
    }

    #[test]
    fn set_at_array_index_replaces_in_place() {
        // Set on a numeric array index replaces the existing element
        // (no shift). Cosmos backend semantics: "set is similar to add… in
        // an array, Set replaces an existing element value".
        let doc = json!({"xs": [1, 2, 3]});
        let out = apply(doc, &[PatchOperation::set("/xs/1", json!(9))]).unwrap();
        assert_eq!(out, json!({"xs": [1, 9, 3]}));
    }

    #[test]
    fn set_with_dash_appends_to_array() {
        // Set with the trailing '-' token still appends, matching Add.
        let doc = json!({"xs": [1, 2]});
        let out = apply(doc, &[PatchOperation::set("/xs/-", json!(3))]).unwrap();
        assert_eq!(out, json!({"xs": [1, 2, 3]}));
    }

    #[test]
    fn set_at_array_index_out_of_range_fails() {
        // Set on an out-of-range numeric index must fail rather than
        // silently insert (the Add codepath uses allow_append=true; Set
        // does not).
        let doc = json!({"xs": [1, 2]});
        let err = apply(doc, &[PatchOperation::set("/xs/5", json!(9))]).unwrap_err();
        assert!(
            matches!(err, PatchEvalError::ArrayIndexOutOfRange { .. }),
            "{err}"
        );
    }

    #[test]
    fn pointer_escapes() {
        // ~1 -> '/', ~0 -> '~'
        let doc = json!({"a/b": 1, "tilde~": "x"});
        let out = apply(doc.clone(), &[PatchOperation::replace("/a~1b", json!(2))]).unwrap();
        assert_eq!(out["a/b"], json!(2));
        let out2 = apply(doc, &[PatchOperation::replace("/tilde~0", json!("y"))]).unwrap();
        assert_eq!(out2["tilde~"], json!("y"));
    }

    #[test]
    fn invalid_pointer_fails() {
        let doc = json!({});
        let err = apply(doc, &[PatchOperation::add("invalid", json!(1))]).unwrap_err();
        assert!(matches!(err, PatchEvalError::InvalidPath(_)), "{err}");
    }

    #[test]
    fn array_index_out_of_range_fails() {
        let doc = json!({"xs": [1]});
        let err = apply(doc, &[PatchOperation::add("/xs/5", json!(2))]).unwrap_err();
        assert!(
            matches!(err, PatchEvalError::ArrayIndexOutOfRange { .. }),
            "{err}"
        );
    }

    #[test]
    fn ops_apply_in_order() {
        // Increment is transitive, so three Increments alone would pass even
        // if ops were reordered. Use Increment -> Move -> Increment so the
        // assertion is only satisfied when ops execute in the listed order.
        // Sequence: start at {a: 0}.
        // 1. `Increment /a 1`   -> {a: 1}
        // 2. `Move /a /b`       -> {b: 1}        (a is now absent)
        // 3. `Increment /b 1`   -> {b: 2}
        // If any pair is reordered, step 3 either errors (path missing) or
        // observes a different intermediate state.
        let doc = json!({"a": 0});
        let out = apply(
            doc,
            &[
                PatchOperation::increment("/a", 1i64),
                PatchOperation::move_value("/a", "/b"),
                PatchOperation::increment("/b", 1i64),
            ],
        )
        .unwrap();
        assert_eq!(out["b"], json!(2));
        assert!(
            out.get("a").is_none(),
            "after Move /a /b, /a must be absent; got {out}"
        );
    }

    #[test]
    fn set_on_empty_array_index_zero_errors_not_panics() {
        // `Set('/xs/0', v)` against `{xs: []}` would previously slip
        // through `parse_array_index` (because `len.saturating_sub(1) = 0`
        // when `len == 0`) and panic at `arr[0] = v`. The empty-array guard
        // must convert this into a typed `ArrayIndexOutOfRange`.
        let doc = json!({"xs": []});
        let err = apply(doc, &[PatchOperation::set("/xs/0", json!("v"))]).unwrap_err();
        assert!(
            matches!(
                err,
                PatchEvalError::ArrayIndexOutOfRange {
                    index: 0,
                    len: 0,
                    ..
                }
            ),
            "{err}"
        );
    }

    #[test]
    fn replace_on_empty_array_index_zero_errors_not_panics() {
        // same shape as the Set case but on the pre-existing Replace
        // branch (`arr[idx] = v` at the bottom of `replace`).
        let doc = json!({"xs": []});
        let err = apply(doc, &[PatchOperation::replace("/xs/0", json!("v"))]).unwrap_err();
        assert!(
            matches!(
                err,
                PatchEvalError::ArrayIndexOutOfRange {
                    index: 0,
                    len: 0,
                    ..
                }
            ),
            "{err}"
        );
    }

    #[test]
    fn add_on_empty_array_index_zero_succeeds() {
        // F14 regression guard: the empty-array fix only applies when
        // `allow_append=false`. `Add('/xs/0', v)` on `{xs: []}` is an insert
        // at index 0 on an empty array (equivalent to push), which RFC 6902
        // permits and which `allow_append=true` correctly handles.
        let doc = json!({"xs": []});
        let out = apply(doc, &[PatchOperation::add("/xs/0", json!("v"))]).unwrap();
        assert_eq!(out, json!({"xs": ["v"]}));
    }

    #[test]
    fn add_on_empty_array_with_dash_succeeds() {
        // F14 regression guard: `-` (append) on an empty array still works.
        let doc = json!({"xs": []});
        let out = apply(doc, &[PatchOperation::add("/xs/-", json!("v"))]).unwrap();
        assert_eq!(out, json!({"xs": ["v"]}));
    }
}