selene-db-core 1.2.0

Foundation types for the selene-db ISO/IEC 39075:2024 GQL property graph engine.
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
use std::{collections::BTreeSet, fmt, sync::Arc};

use serde::{
    Deserialize, Deserializer, Serialize, Serializer,
    de::{DeserializeSeed, Error as DeError, MapAccess, SeqAccess, Visitor},
};
use serde_json::{Map as SerdeJsonMap, Value as SerdeJsonValue};

use crate::{
    CoreError, CoreResult, DbString, db_string::MAX_DB_STRING_BYTES, json_patch::apply_json_patch,
};

/// Selector used by JSON path-existence helpers.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum JsonPathSelector {
    /// Select an object member by key.
    Key(DbString),
    /// Select an array element by signed index.
    ///
    /// Negative indexes count from the end, matching `json_has_path`.
    Index(i64),
    /// Select an array element by unsigned index.
    UnsignedIndex(u64),
}

/// Native JSON payload stored as a first-class [`crate::Value`].
///
/// `JsonValue` validates once at construction and deserialization so every
/// engine layer can assume a finite JSON data-model value whose strings and
/// container cardinalities stay inside the implementation-defined GQL caps.
#[derive(Clone, Debug, PartialEq)]
pub struct JsonValue {
    value: Arc<SerdeJsonValue>,
}

/// Borrowed JSON subvalue selected from a validated [`JsonValue`].
///
/// This keeps scan paths from cloning selected JSON values until the caller
/// knows the value must be materialized into an owned result.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct JsonValueRef<'a> {
    value: &'a SerdeJsonValue,
}

impl<'a> JsonValueRef<'a> {
    /// Borrow the underlying serde-json value.
    #[must_use]
    pub fn as_serde(self) -> &'a SerdeJsonValue {
        self.value
    }

    /// Clone this validated subvalue into an owned [`JsonValue`].
    #[must_use]
    pub fn to_owned_json_value(self) -> JsonValue {
        JsonValue {
            value: Arc::new(self.value.clone()),
        }
    }
}

impl JsonValue {
    /// Build a validated JSON value from an owned serde-json value.
    pub fn new(value: SerdeJsonValue) -> CoreResult<Self> {
        validate_json_value(&value)?;
        Ok(Self {
            value: Arc::new(value),
        })
    }

    /// Parse and validate a JSON value from text.
    ///
    /// # Errors
    ///
    /// Returns [`CoreError::JsonParse`] when `text` is not valid JSON, or the
    /// usual value-limit errors when the parsed value exceeds engine caps.
    pub fn parse_str(text: &str) -> CoreResult<Self> {
        let value = parse_json_text(text).map_err(|err| CoreError::JsonParse {
            message: err.to_string(),
        })?;
        Self::new(value)
    }

    /// Borrow the underlying serde-json value.
    #[must_use]
    pub fn as_serde(&self) -> &SerdeJsonValue {
        &self.value
    }

    /// Clone the shared JSON storage.
    #[must_use]
    pub fn as_arc(&self) -> Arc<SerdeJsonValue> {
        Arc::clone(&self.value)
    }

    /// Return a stable compact JSON rendering with object keys sorted.
    #[must_use]
    pub fn to_canonical_string(&self) -> String {
        let mut output = String::new();
        write_json_canonical(self.as_serde(), &mut output);
        output
    }

    /// Return the JSON data-model type name.
    #[must_use]
    pub fn json_type_name(&self) -> &'static str {
        match self.as_serde() {
            SerdeJsonValue::Null => "null",
            SerdeJsonValue::Bool(_) => "boolean",
            SerdeJsonValue::Number(_) => "number",
            SerdeJsonValue::String(_) => "string",
            SerdeJsonValue::Array(_) => "array",
            SerdeJsonValue::Object(_) => "object",
        }
    }

    /// Return true when this JSON value recursively contains `candidate`.
    ///
    /// Objects contain candidates whose keys are present and whose values are
    /// themselves contained. Arrays contain array candidates when each
    /// candidate element is contained by at least one target element. A scalar
    /// or object candidate also matches any containing target array element.
    #[must_use]
    pub fn contains(&self, candidate: &Self) -> bool {
        json_contains_value(self.as_serde(), candidate.as_serde())
    }

    /// Return true when every selector in `path` resolves inside this value.
    ///
    /// Stored-value shape mismatches return false. This makes the helper useful
    /// for heterogeneous graph scans where one malformed document should not
    /// abort the entire candidate search.
    #[must_use]
    pub fn path_exists(&self, path: &[JsonPathSelector]) -> bool {
        select_json_path(self.as_serde(), path).is_some()
    }

    /// Return the JSON subvalue selected by `path`.
    ///
    /// Stored-value shape mismatches return [`None`]. A selected JSON `null`
    /// still returns `Some(JsonValue)`, which lets callers distinguish present
    /// null values from absent paths.
    #[must_use]
    pub fn path_value(&self, path: &[JsonPathSelector]) -> Option<Self> {
        self.path_value_ref(path)
            .map(JsonValueRef::to_owned_json_value)
    }

    /// Borrow the JSON subvalue selected by `path`.
    ///
    /// Stored-value shape mismatches return [`None`]. A selected JSON `null`
    /// still returns `Some(JsonValueRef)`, which lets callers distinguish
    /// present null values from absent paths without cloning the subvalue.
    #[must_use]
    pub fn path_value_ref(&self, path: &[JsonPathSelector]) -> Option<JsonValueRef<'_>> {
        select_json_path(self.as_serde(), path).map(|value| JsonValueRef { value })
    }

    /// Return true when `path` selects a JSON value that contains `candidate`.
    ///
    /// Stored-value shape mismatches return false, matching
    /// [`Self::path_exists`]. Containment follows [`Self::contains`] semantics
    /// on the selected subvalue.
    #[must_use]
    pub fn path_contains(&self, path: &[JsonPathSelector], candidate: &Self) -> bool {
        select_json_path(self.as_serde(), path)
            .is_some_and(|value| json_contains_value(value, candidate.as_serde()))
    }

    /// Return the result of applying an RFC 7396 JSON Merge Patch document.
    ///
    /// The operation is copy-on-write: this value and `patch` are left
    /// unchanged, and the merged result is validated as a fresh [`JsonValue`].
    ///
    /// # Errors
    ///
    /// Returns the usual value-limit errors if the merged result exceeds engine
    /// caps.
    pub fn merge_patch(&self, patch: &Self) -> CoreResult<Self> {
        let mut target = self.as_serde().clone();
        merge_patch_value(&mut target, patch.as_serde());
        Self::new(target)
    }

    /// Return the result of applying an RFC 6902 JSON Patch document.
    ///
    /// The operation is atomic from the caller's perspective: this value and
    /// `patch` are left unchanged, and an invalid patch returns an error
    /// without exposing any intermediate document state.
    ///
    /// # Errors
    ///
    /// Returns [`CoreError::JsonPatch`] when the patch document is malformed or
    /// an operation fails. Returns the usual value-limit errors if the patched
    /// result exceeds engine caps.
    pub fn apply_patch(&self, patch: &Self) -> CoreResult<Self> {
        Self::new(apply_json_patch(self.as_serde(), patch.as_serde())?)
    }
}

fn select_json_path<'a>(
    mut current: &'a SerdeJsonValue,
    path: &[JsonPathSelector],
) -> Option<&'a SerdeJsonValue> {
    for selector in path {
        current = select_json_child(current, selector)?;
    }
    Some(current)
}

fn select_json_child<'a>(
    current: &'a SerdeJsonValue,
    selector: &JsonPathSelector,
) -> Option<&'a SerdeJsonValue> {
    match (current, selector) {
        (SerdeJsonValue::Object(values), JsonPathSelector::Key(key)) => values.get(key.as_str()),
        (SerdeJsonValue::Array(values), JsonPathSelector::Index(index)) => {
            signed_array_index(*index, values.len()).and_then(|index| values.get(index))
        }
        (SerdeJsonValue::Array(values), JsonPathSelector::UnsignedIndex(index)) => {
            usize::try_from(*index)
                .ok()
                .and_then(|index| values.get(index))
        }
        _ => None,
    }
}

fn signed_array_index(index: i64, len: usize) -> Option<usize> {
    if index >= 0 {
        usize::try_from(index).ok().filter(|index| *index < len)
    } else {
        let offset = usize::try_from(index.unsigned_abs()).ok()?;
        (offset <= len).then_some(len - offset)
    }
}

impl TryFrom<SerdeJsonValue> for JsonValue {
    type Error = CoreError;

    fn try_from(value: SerdeJsonValue) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

impl From<JsonValue> for SerdeJsonValue {
    fn from(value: JsonValue) -> Self {
        value.as_serde().clone()
    }
}

impl Serialize for JsonValue {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        if serializer.is_human_readable() {
            self.as_serde().serialize(serializer)
        } else {
            serializer.serialize_str(&self.to_canonical_string())
        }
    }
}

impl<'de> Deserialize<'de> for JsonValue {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = if deserializer.is_human_readable() {
            StrictJsonValueSeed.deserialize(deserializer)?
        } else {
            let value = String::deserialize(deserializer)?;
            parse_json_text(&value).map_err(serde::de::Error::custom)?
        };
        Self::new(value).map_err(serde::de::Error::custom)
    }
}

fn parse_json_text(text: &str) -> Result<SerdeJsonValue, serde_json::Error> {
    let mut deserializer = serde_json::Deserializer::from_str(text);
    let value = StrictJsonValueSeed.deserialize(&mut deserializer)?;
    deserializer.end()?;
    Ok(value)
}

struct StrictJsonValueSeed;

impl<'de> DeserializeSeed<'de> for StrictJsonValueSeed {
    type Value = SerdeJsonValue;

    fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_any(StrictJsonValueVisitor)
    }
}

struct StrictJsonValueVisitor;

impl<'de> Visitor<'de> for StrictJsonValueVisitor {
    type Value = SerdeJsonValue;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("a JSON value with unique object keys")
    }

    fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E> {
        Ok(SerdeJsonValue::Bool(value))
    }

    fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E> {
        Ok(SerdeJsonValue::Number(value.into()))
    }

    fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E> {
        Ok(SerdeJsonValue::Number(value.into()))
    }

    fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
    where
        E: DeError,
    {
        let number = serde_json::Number::from_f64(value)
            .ok_or_else(|| E::custom("JSON number is not finite"))?;
        Ok(SerdeJsonValue::Number(number))
    }

    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> {
        Ok(SerdeJsonValue::String(value.to_owned()))
    }

    fn visit_string<E>(self, value: String) -> Result<Self::Value, E> {
        Ok(SerdeJsonValue::String(value))
    }

    fn visit_none<E>(self) -> Result<Self::Value, E> {
        Ok(SerdeJsonValue::Null)
    }

    fn visit_unit<E>(self) -> Result<Self::Value, E> {
        Ok(SerdeJsonValue::Null)
    }

    fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
    where
        D: Deserializer<'de>,
    {
        StrictJsonValueSeed.deserialize(deserializer)
    }

    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
    where
        A: SeqAccess<'de>,
    {
        let mut values = Vec::with_capacity(seq.size_hint().unwrap_or(0));
        while let Some(value) = seq.next_element_seed(StrictJsonValueSeed)? {
            values.push(value);
        }
        Ok(SerdeJsonValue::Array(values))
    }

    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
    where
        A: MapAccess<'de>,
    {
        let mut seen = BTreeSet::new();
        let mut values = SerdeJsonMap::new();
        while let Some(key) = map.next_key::<String>()? {
            if !seen.insert(key.clone()) {
                return Err(A::Error::custom(format!(
                    "duplicate JSON object key '{key}'"
                )));
            }
            let value = map.next_value_seed(StrictJsonValueSeed)?;
            values.insert(key, value);
        }
        Ok(SerdeJsonValue::Object(values))
    }
}

fn validate_json_value(value: &SerdeJsonValue) -> CoreResult<()> {
    match value {
        SerdeJsonValue::Null | SerdeJsonValue::Bool(_) | SerdeJsonValue::Number(_) => Ok(()),
        SerdeJsonValue::String(value) => {
            validate_json_string_len(value.len())?;
            Ok(())
        }
        SerdeJsonValue::Array(values) => {
            ensure_json_container_len(values.len())?;
            for value in values {
                validate_json_value(value)?;
            }
            Ok(())
        }
        SerdeJsonValue::Object(values) => {
            ensure_json_container_len(values.len())?;
            for (key, value) in values {
                validate_json_string_len(key.len())?;
                validate_json_value(value)?;
            }
            Ok(())
        }
    }
}

fn validate_json_string_len(len: usize) -> CoreResult<()> {
    if len > MAX_DB_STRING_BYTES {
        return Err(CoreError::StringTooLong {
            got: len,
            max: u32::MAX,
        });
    }
    Ok(())
}

fn ensure_json_container_len(len: usize) -> CoreResult<()> {
    if len > u32::MAX as usize {
        return Err(CoreError::ConstructedValueTooLarge {
            got: len,
            max: u32::MAX,
        });
    }
    Ok(())
}

fn json_contains_value(target: &SerdeJsonValue, candidate: &SerdeJsonValue) -> bool {
    match (target, candidate) {
        (SerdeJsonValue::Object(target), SerdeJsonValue::Object(candidate)) => {
            candidate.iter().all(|(key, value)| {
                target
                    .get(key)
                    .is_some_and(|found| json_contains_value(found, value))
            })
        }
        (SerdeJsonValue::Array(target), SerdeJsonValue::Array(candidate)) => candidate
            .iter()
            .all(|value| target.iter().any(|found| json_contains_value(found, value))),
        (SerdeJsonValue::Array(target), candidate) => target
            .iter()
            .any(|found| json_contains_value(found, candidate)),
        _ => target == candidate,
    }
}

fn merge_patch_value(target: &mut SerdeJsonValue, patch: &SerdeJsonValue) {
    let SerdeJsonValue::Object(patch) = patch else {
        *target = patch.clone();
        return;
    };

    if !target.is_object() {
        *target = SerdeJsonValue::Object(SerdeJsonMap::new());
    }
    let target = target
        .as_object_mut()
        .expect("target was normalized to object");

    for (key, value) in patch {
        if value.is_null() {
            target.remove(key);
        } else {
            let entry = target.entry(key.clone()).or_insert(SerdeJsonValue::Null);
            merge_patch_value(entry, value);
        }
    }
}

fn write_json_canonical(value: &SerdeJsonValue, output: &mut String) {
    match value {
        SerdeJsonValue::Null => output.push_str("null"),
        SerdeJsonValue::Bool(value) => output.push_str(if *value { "true" } else { "false" }),
        SerdeJsonValue::Number(value) => output.push_str(&value.to_string()),
        SerdeJsonValue::String(value) => {
            output.push_str(&serde_json::to_string(value).expect("JSON string rendering succeeds"));
        }
        SerdeJsonValue::Array(values) => {
            output.push('[');
            for (index, value) in values.iter().enumerate() {
                if index > 0 {
                    output.push(',');
                }
                write_json_canonical(value, output);
            }
            output.push(']');
        }
        SerdeJsonValue::Object(values) => {
            output.push('{');
            let mut entries = values.iter().collect::<Vec<_>>();
            entries.sort_unstable_by(|lhs, rhs| lhs.0.cmp(rhs.0));
            for (index, (key, value)) in entries.into_iter().enumerate() {
                if index > 0 {
                    output.push(',');
                }
                output.push_str(&serde_json::to_string(key).expect("JSON key rendering succeeds"));
                output.push(':');
                write_json_canonical(value, output);
            }
            output.push('}');
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{JsonPathSelector, JsonValue};
    use crate::db_string;

    #[test]
    fn human_readable_serde_preserves_json_shape() {
        let value = JsonValue::new(serde_json::json!({"b": [2, true], "a": null})).unwrap();
        let encoded = serde_json::to_value(&value).expect("JSON value serializes");
        assert_eq!(encoded, serde_json::json!({"a": null, "b": [2, true]}));
        let decoded: JsonValue = serde_json::from_value(encoded).expect("JSON value deserializes");
        assert_eq!(decoded, value);
    }

    #[test]
    fn parse_str_rejects_duplicate_object_keys() {
        let err = JsonValue::parse_str(r#"{"a":1,"nested":{"b":1,"b":2}}"#)
            .expect_err("duplicate JSON object key rejected");

        assert_eq!(err.gqlstatus(), "22018");
        assert!(err.to_string().contains("duplicate JSON object key 'b'"));
    }

    #[test]
    fn human_readable_serde_rejects_duplicate_object_keys() {
        let err = serde_json::from_str::<JsonValue>(r#"{"a":1,"a":2}"#)
            .expect_err("duplicate JSON object key rejected");

        assert!(err.to_string().contains("duplicate JSON object key 'a'"));
    }

    #[test]
    fn contains_matches_nested_subset_and_array_membership() {
        let target = JsonValue::new(serde_json::json!({
            "memory": {"kind": "episodic", "score": 7},
            "tags": ["agent", "graph", {"scope": "current"}]
        }))
        .unwrap();

        assert!(target.contains(
            &JsonValue::new(serde_json::json!({"memory": {"kind": "episodic"}})).unwrap()
        ));
        assert!(target.contains(&JsonValue::new(serde_json::json!({"tags": "graph"})).unwrap()));
        assert!(target.contains(
            &JsonValue::new(serde_json::json!({"tags": [{"scope": "current"}, "agent"]})).unwrap()
        ));
        assert!(!target.contains(
            &JsonValue::new(serde_json::json!({"memory": {"kind": "semantic"}})).unwrap()
        ));
    }

    #[test]
    fn path_exists_matches_object_keys_and_array_indexes() {
        let target = JsonValue::new(serde_json::json!({
            "memory": {"facts": [{"title": "old"}, {"title": "current"}]}
        }))
        .unwrap();
        let path = [
            JsonPathSelector::Key(db_string("memory").unwrap()),
            JsonPathSelector::Key(db_string("facts").unwrap()),
            JsonPathSelector::Index(1),
            JsonPathSelector::Key(db_string("title").unwrap()),
        ];

        assert!(target.path_exists(&path));
        assert!(target.path_exists(&[
            JsonPathSelector::Key(db_string("memory").unwrap()),
            JsonPathSelector::Key(db_string("facts").unwrap()),
            JsonPathSelector::Index(-1),
            JsonPathSelector::Key(db_string("title").unwrap()),
        ]));
        assert!(!target.path_exists(&[
            JsonPathSelector::Key(db_string("memory").unwrap()),
            JsonPathSelector::Key(db_string("facts").unwrap()),
            JsonPathSelector::UnsignedIndex(9),
        ]));
    }

    #[test]
    fn path_value_returns_selected_json_subvalue() {
        let target = JsonValue::new(serde_json::json!({
            "memory": {
                "facts": [{"title": "old"}, {"title": "current"}],
                "score": null
            }
        }))
        .unwrap();

        let selected = target
            .path_value(&[
                JsonPathSelector::Key(db_string("memory").unwrap()),
                JsonPathSelector::Key(db_string("facts").unwrap()),
                JsonPathSelector::Index(-1),
                JsonPathSelector::Key(db_string("title").unwrap()),
            ])
            .expect("path selects a value");
        assert_eq!(selected.as_serde(), &serde_json::json!("current"));

        let null_value = target
            .path_value(&[
                JsonPathSelector::Key(db_string("memory").unwrap()),
                JsonPathSelector::Key(db_string("score").unwrap()),
            ])
            .expect("JSON null is present");
        assert_eq!(null_value.as_serde(), &serde_json::Value::Null);

        assert!(
            target
                .path_value(&[
                    JsonPathSelector::Key(db_string("memory").unwrap()),
                    JsonPathSelector::Key(db_string("missing").unwrap()),
                ])
                .is_none()
        );
    }

    #[test]
    fn path_value_ref_borrows_selected_json_subvalue() {
        let target = JsonValue::new(serde_json::json!({
            "memory": {"facts": [{"title": "old"}, {"title": "current"}]}
        }))
        .unwrap();
        let path = [
            JsonPathSelector::Key(db_string("memory").unwrap()),
            JsonPathSelector::Key(db_string("facts").unwrap()),
            JsonPathSelector::Index(-1),
            JsonPathSelector::Key(db_string("title").unwrap()),
        ];

        let selected = target.path_value_ref(&path).expect("path selects a value");

        assert_eq!(selected.as_serde(), &serde_json::json!("current"));
        assert_eq!(
            selected.to_owned_json_value().as_serde(),
            &serde_json::json!("current")
        );
    }

    #[test]
    fn path_contains_applies_containment_to_selected_subvalue() {
        let target = JsonValue::new(serde_json::json!({
            "memory": {
                "facts": [
                    {"title": "old", "tags": ["archive"]},
                    {"title": "current", "tags": ["agent", {"scope": "fresh"}]}
                ]
            }
        }))
        .unwrap();
        let path = [
            JsonPathSelector::Key(db_string("memory").unwrap()),
            JsonPathSelector::Key(db_string("facts").unwrap()),
            JsonPathSelector::Index(-1),
        ];

        assert!(target.path_contains(
            &path,
            &JsonValue::new(serde_json::json!({"tags": [{"scope": "fresh"}]})).unwrap()
        ));
        assert!(!target.path_contains(
            &path,
            &JsonValue::new(serde_json::json!({"tags": "archive"})).unwrap()
        ));
        assert!(!target.path_contains(
            &[JsonPathSelector::Key(db_string("missing").unwrap())],
            &JsonValue::new(serde_json::json!(null)).unwrap()
        ));
    }

    #[test]
    fn merge_patch_matches_rfc7396_core_cases() {
        for (target, patch, expected) in [
            (r#"{"a":"b"}"#, r#"{"a":"c"}"#, r#"{"a":"c"}"#),
            (r#"{"a":"b"}"#, r#"{"b":"c"}"#, r#"{"a":"b","b":"c"}"#),
            (r#"{"a":"b"}"#, r#"{"a":null}"#, r#"{}"#),
            (r#"{"a":"b","b":"c"}"#, r#"{"a":null}"#, r#"{"b":"c"}"#),
            (r#"{"a":["b"]}"#, r#"{"a":"c"}"#, r#"{"a":"c"}"#),
            (r#"{"a":"c"}"#, r#"{"a":["b"]}"#, r#"{"a":["b"]}"#),
            (
                r#"{"a":{"b":"c"}}"#,
                r#"{"a":{"b":"d","c":null}}"#,
                r#"{"a":{"b":"d"}}"#,
            ),
            (r#"{"a":[{"b":"c"}]}"#, r#"{"a":[1]}"#, r#"{"a":[1]}"#),
            (r#"["a","b"]"#, r#"["c","d"]"#, r#"["c","d"]"#),
            (r#"{"a":"b"}"#, r#"["c"]"#, r#"["c"]"#),
            (r#"{"a":"foo"}"#, r#"null"#, r#"null"#),
            (r#"{"a":"foo"}"#, r#""bar""#, r#""bar""#),
            (r#"{"e":null}"#, r#"{"a":1}"#, r#"{"a":1,"e":null}"#),
        ] {
            let target = JsonValue::parse_str(target).expect("target JSON parses");
            let patch = JsonValue::parse_str(patch).expect("patch JSON parses");
            let expected = JsonValue::parse_str(expected).expect("expected JSON parses");

            assert_eq!(
                target.merge_patch(&patch).expect("merge patch succeeds"),
                expected
            );
        }
    }
}