Skip to main content

relate_core/value/
json.rs

1//! JSON encode/decode for [`Value`]: the tagged `{"t":..., "v":...}` form
2//! (WAL/checkpoint bytes) and the plain FFI form, plus the `Tagged*Ref` serde
3//! impls behind the canonical tagged encoder.
4
5use super::*;
6
7impl Value {
8    /// The tagged `{"t":..., "v":...}` JSON form. Built from the canonical
9    /// [`serde::Serialize`] impl (via [`TaggedRef`]), so the tree here and the
10    /// direct WAL/checkpoint bytes cannot diverge. Graph entities are not
11    /// persistence properties: the encoder rejects them (see [`TaggedRef`]),
12    /// and that internal error maps to `Null` here.
13    pub fn to_json_tagged(&self) -> serde_json::Value {
14        serde_json::to_value(self).unwrap_or(serde_json::Value::Null)
15    }
16
17    pub fn from_json_tagged(v: &serde_json::Value) -> crate::Result<Value> {
18        Self::from_json_tagged_at(v, 0)
19    }
20
21    /// [`Value::from_json_tagged`] with the ADR-0462 `depth` (the number of
22    /// tagged containers enclosing `v`): an untrusted persistence input
23    /// nested past [`MAX_VALUE_DEPTH`] is rejected with a typed storage
24    /// error instead of driving the recursive decoder off the stack.
25    fn from_json_tagged_at(v: &serde_json::Value, depth: u32) -> crate::Result<Value> {
26        fn malformed(expected: &str) -> crate::Error {
27            crate::Error::storage(format!("malformed tagged value: expected {expected}"))
28        }
29        fn too_deep() -> crate::Error {
30            crate::Error::storage(value_depth_exceeded("tagged value"))
31        }
32        let obj = v
33            .as_object()
34            .ok_or_else(|| crate::Error::storage("property JSON must be an object"))?;
35        let t = obj
36            .get("t")
37            .and_then(|x| x.as_str())
38            .ok_or_else(|| crate::Error::storage("missing type tag"))?;
39        Ok(match t {
40            "null" => Value::Null,
41            "bool" => Value::Bool(
42                obj.get("v")
43                    .and_then(|x| x.as_bool())
44                    .ok_or_else(|| malformed("\"bool\" with a boolean \"v\""))?,
45            ),
46            "int" => Value::Int(
47                obj.get("v")
48                    .and_then(|x| x.as_i64())
49                    .ok_or_else(|| malformed("\"int\" with an integer \"v\""))?,
50            ),
51            "float" => Value::Float(match obj.get("v") {
52                Some(serde_json::Value::String(s)) if s == "NaN" => f64::NAN,
53                Some(serde_json::Value::String(s)) if s == "Infinity" => f64::INFINITY,
54                Some(serde_json::Value::String(s)) if s == "-Infinity" => f64::NEG_INFINITY,
55                other => other
56                    .and_then(|x| x.as_f64())
57                    .ok_or_else(|| malformed("\"float\" with a number \"v\""))?,
58            }),
59            "string" => Value::String(
60                obj.get("v")
61                    .and_then(|x| x.as_str())
62                    .ok_or_else(|| malformed("\"string\" with a string \"v\""))?
63                    .into(),
64            ),
65            "uuid" => {
66                let s = obj
67                    .get("v")
68                    .and_then(|x| x.as_str())
69                    .ok_or_else(|| malformed("\"uuid\" with a string \"v\""))?;
70                Value::Uuid(
71                    uuid_parse(s)
72                        .ok_or_else(|| malformed("\"uuid\" with a canonical hyphenated \"v\""))?,
73                )
74            }
75            "list" => {
76                let Some(next) = next_depth(depth) else {
77                    return Err(too_deep());
78                };
79                let arr = obj
80                    .get("v")
81                    .and_then(|x| x.as_array())
82                    .ok_or_else(|| malformed("\"list\" with an array \"v\""))?;
83                Value::List(
84                    arr.iter()
85                        .map(|x| Value::from_json_tagged_at(x, next))
86                        .collect::<crate::Result<Vec<_>>>()?
87                        .into(),
88                )
89            }
90            "map" => {
91                let Some(next) = next_depth(depth) else {
92                    return Err(too_deep());
93                };
94                let mut map = BTreeMap::new();
95                let o = obj
96                    .get("v")
97                    .and_then(|x| x.as_object())
98                    .ok_or_else(|| malformed("\"map\" with an object \"v\""))?;
99                for (k, val) in o {
100                    map.insert(k.clone(), Value::from_json_tagged_at(val, next)?);
101                }
102                Value::Map(map.into())
103            }
104            "date" | "time" | "localtime" | "datetime" | "localdatetime" | "duration" => {
105                let s = obj
106                    .get("v")
107                    .and_then(|x| x.as_str())
108                    .ok_or_else(|| crate::Error::storage("missing temporal value"))?;
109                Value::Temporal(crate::temporal::parse_iso(t, s)?)
110            }
111            "point" => {
112                let p = obj
113                    .get("v")
114                    .and_then(|x| x.as_object())
115                    .ok_or_else(|| malformed("\"point\" with an object \"v\""))?;
116                Value::Point(PointValue {
117                    srid: p
118                        .get("srid")
119                        .and_then(|x| x.as_i64())
120                        .and_then(|x| i32::try_from(x).ok())
121                        .ok_or_else(|| malformed("\"point\" with an integer \"srid\""))?,
122                    x: p.get("x")
123                        .and_then(|x| x.as_f64())
124                        .ok_or_else(|| malformed("\"point\" with a number \"x\""))?,
125                    y: p.get("y")
126                        .and_then(|x| x.as_f64())
127                        .ok_or_else(|| malformed("\"point\" with a number \"y\""))?,
128                    z: p.get("z").and_then(|x| x.as_f64()),
129                })
130            }
131            "vector" => {
132                let Some(next) = next_depth(depth) else {
133                    return Err(too_deep());
134                };
135                let coord = obj
136                    .get("coord")
137                    .and_then(|x| x.as_str())
138                    .and_then(VectorCoordKind::from_canonical_name)
139                    .ok_or_else(|| crate::Error::storage("invalid vector coordinate type"))?;
140                let xs = obj
141                    .get("v")
142                    .and_then(|x| x.as_array())
143                    .ok_or_else(|| malformed("\"vector\" with an array \"v\""))?;
144                // Each entry decodes through the same scalar tagged decode
145                // the `Vec<Value>` walk used, then lands packed per family
146                // (ADR-0706) behind the checked constructor.
147                let values = xs
148                    .iter()
149                    .map(|x| Value::from_json_tagged_at(x, next))
150                    .collect::<crate::Result<Vec<_>>>()?;
151                let coords = pack_decoded_values(coord, &values).map_err(crate::Error::storage)?;
152                Value::vector(coord, coords)
153            }
154            other => return Err(crate::Error::storage(format!("unknown type tag {other:?}"))),
155        })
156    }
157
158    /// Best-effort Python/JSON-ish value for FFI clients.
159    pub fn to_json_plain(&self) -> serde_json::Value {
160        self.to_json_plain_at(0)
161    }
162
163    /// [`Value::to_json_plain`] with the ADR-0462 `depth` guard: a container
164    /// past [`MAX_VALUE_DEPTH`] encodes as JSON `null` instead of recursing.
165    /// Unreachable behind the checked constructors.
166    fn to_json_plain_at(&self, depth: u32) -> serde_json::Value {
167        use serde_json::json;
168        match self {
169            Value::Null => serde_json::Value::Null,
170            Value::Bool(b) => json!(b),
171            Value::Int(i) => json!(i),
172            Value::Float(f) => json!(f),
173            Value::String(s) => json!(&**s),
174            Value::Uuid(u) => json!(uuid_hyphenated(*u)),
175            // The byte values 0-255, the `value_to_cypher` shape (ADR-0327).
176            Value::Bytes(b) => json!(&**b),
177            Value::List(xs) => {
178                let Some(next) = next_depth(depth) else {
179                    return serde_json::Value::Null;
180                };
181                json!(xs
182                    .iter()
183                    .map(|v| v.to_json_plain_at(next))
184                    .collect::<Vec<_>>())
185            }
186            Value::Map(m) => {
187                let Some(next) = next_depth(depth) else {
188                    return serde_json::Value::Null;
189                };
190                map_to_json_plain(m.iter(), next)
191            }
192            Value::Node(n) => node_json(n, depth),
193            Value::Relationship(r) => rel_json(r, depth),
194            Value::Path(p) => {
195                if next_depth(depth).is_none() {
196                    return serde_json::Value::Null;
197                }
198                // A path's embedded entities are not an extra container
199                // level (ADR-0462 depth accounting); they share the path's.
200                json!({
201                    "_type": "path",
202                    "nodes": p.nodes.iter().map(|n| node_json(n, depth)).collect::<Vec<_>>(),
203                    "relationships": p.rels.iter().map(|r| rel_json(r, depth)).collect::<Vec<_>>(),
204                })
205            }
206            Value::Temporal(t) => json!({
207                "_type": t.kind_name(),
208                "value": t.iso_string(),
209            }),
210            Value::Point(p) => json!({
211                "_type": "point", "srid": p.srid, "x": p.x, "y": p.y, "z": p.z
212            }),
213            Value::Vector { coord, coords } => {
214                // No depth: the packed coordinates are scalars, nothing
215                // recurses.
216                json!({
217                    "_type": "vector",
218                    "coordinateType": coord.canonical_name(),
219                    // The per-`Value` scalars these replaced encoded as
220                    // plain JSON numbers; the packed read (ADR-0706) is
221                    // the same encoding.
222                    "values": coords.iter().map(|c| match c {
223                        Coord::I(n) => json!(n),
224                        Coord::F(f) => json!(f),
225                    }).collect::<Vec<_>>()
226                })
227            }
228        }
229    }
230
231    pub fn from_json_plain(v: &serde_json::Value) -> Value {
232        match v {
233            serde_json::Value::Null => Value::Null,
234            serde_json::Value::Bool(b) => Value::Bool(*b),
235            serde_json::Value::Number(n) => {
236                if let Some(i) = n.as_i64() {
237                    Value::Int(i)
238                } else if let Some(f) = n.as_f64() {
239                    Value::Float(f)
240                } else {
241                    Value::Null
242                }
243            }
244            serde_json::Value::String(s) => Value::String(s.as_str().into()),
245            serde_json::Value::Array(a) => Value::List(
246                a.iter()
247                    .map(Value::from_json_plain)
248                    .collect::<Vec<_>>()
249                    .into(),
250            ),
251            serde_json::Value::Object(o) => {
252                // Probe the `_type` tag exactly once: the handled set
253                // ("node", "point", "vector") and the fall-through to a
254                // plain map are explicit in one place.
255                match o.get("_type").and_then(|t| t.as_str()) {
256                    Some("node") => {
257                        return Value::Node(Arc::new(Node {
258                            id: o.get("id").and_then(|x| x.as_i64()).unwrap_or(0),
259                            labels: Arc::new(
260                                o.get("labels")
261                                    .and_then(|x| x.as_array())
262                                    .map(|a| {
263                                        a.iter()
264                                            .filter_map(|x| x.as_str().map(|s| s.to_string()))
265                                            .collect::<Vec<_>>()
266                                    })
267                                    .unwrap_or_default(),
268                            ),
269                            properties: match o.get("properties") {
270                                Some(p) => match Value::from_json_plain(p) {
271                                    Value::Map(m) => PropertyMap::share(Arc::unwrap_or_clone(m)),
272                                    _ => PropertyMap::share(PropertyMap::new()),
273                                },
274                                None => PropertyMap::share(PropertyMap::new()),
275                            },
276                        }));
277                    }
278                    Some("point") => {
279                        return Value::Point(PointValue {
280                            srid: o
281                                .get("srid")
282                                .and_then(|x| x.as_i64())
283                                .and_then(|x| i32::try_from(x).ok())
284                                .unwrap_or(7203),
285                            x: o.get("x").and_then(|x| x.as_f64()).unwrap_or(0.0),
286                            y: o.get("y").and_then(|x| x.as_f64()).unwrap_or(0.0),
287                            z: o.get("z").and_then(|x| x.as_f64()),
288                        });
289                    }
290                    Some("vector") => {
291                        if let Some(coord) = o
292                            .get("coordinateType")
293                            .and_then(|x| x.as_str())
294                            .and_then(VectorCoordKind::from_canonical_name)
295                        {
296                            // A missing or non-array `values` is not a
297                            // vector — fall through to the plain-map path
298                            // (an explicit `[]` stays the legitimate
299                            // empty vector).
300                            let Some(values) = o.get("values").and_then(|x| x.as_array()) else {
301                                return Value::Map(
302                                    o.iter()
303                                        .map(|(k, v)| (k.clone(), Value::from_json_plain(v)))
304                                        .collect::<BTreeMap<_, _>>()
305                                        .into(),
306                                );
307                            };
308                            let values: Vec<Value> =
309                                values.iter().map(Value::from_json_plain).collect();
310                            // Best-effort decoder: a shape the packed
311                            // invariant rejects (ADR-0706) falls back to
312                            // this decoder's own unrecognized-tag path —
313                            // the plain map — instead of a panic or a
314                            // malformed Vector.
315                            if let Ok(coords) = pack_decoded_values(coord, &values) {
316                                return Value::vector(coord, coords);
317                            }
318                        }
319                    }
320                    _ => {}
321                }
322                let mut m = BTreeMap::new();
323                for (k, val) in o {
324                    m.insert(k.clone(), Value::from_json_plain(val));
325                }
326                Value::Map(m.into())
327            }
328        }
329    }
330
331    /// Decode JSON whose objects are always maps. A `_type` of `node`,
332    /// `point`, or `vector` stays a string property. This is the decoder for
333    /// untrusted property documents. [`from_json_plain`] is the inverse of
334    /// [`to_json_plain`] and still recognizes those tags.
335    pub fn from_json_scalars(v: &serde_json::Value) -> Value {
336        match v {
337            serde_json::Value::Null => Value::Null,
338            serde_json::Value::Bool(b) => Value::Bool(*b),
339            serde_json::Value::Number(n) => {
340                if let Some(i) = n.as_i64() {
341                    Value::Int(i)
342                } else if let Some(f) = n.as_f64() {
343                    Value::Float(f)
344                } else {
345                    Value::Null
346                }
347            }
348            serde_json::Value::String(s) => Value::String(s.as_str().into()),
349            serde_json::Value::Array(a) => Value::List(
350                a.iter()
351                    .map(Value::from_json_scalars)
352                    .collect::<Vec<_>>()
353                    .into(),
354            ),
355            serde_json::Value::Object(o) => {
356                let mut m = BTreeMap::new();
357                for (k, val) in o {
358                    m.insert(k.clone(), Value::from_json_scalars(val));
359                }
360                Value::Map(m.into())
361            }
362        }
363    }
364}
365
366/// Borrowing encoder of the tagged string `{"t":"string","v":...}`.
367/// Construct it with [`tagged_str`]. [`Value`]'s tagged encoder writes the
368/// same two entries.
369pub struct TaggedStr<'a>(&'a str);
370
371fn write_tagged_str<M: serde::ser::SerializeMap>(m: &mut M, s: &str) -> Result<(), M::Error> {
372    m.serialize_entry("t", "string")?;
373    m.serialize_entry("v", s)?;
374    Ok(())
375}
376
377impl serde::Serialize for TaggedStr<'_> {
378    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
379        use serde::ser::SerializeMap;
380        let mut m = serializer.serialize_map(Some(2))?;
381        write_tagged_str(&mut m, self.0)?;
382        m.end()
383    }
384}
385
386/// The tagged string [`TaggedRef`] writes for [`Value::String`].
387pub fn tagged_str(s: &str) -> TaggedStr<'_> {
388    TaggedStr(s)
389}
390
391/// Serializes a [`Value`] as the tagged `{"t":..., ...}` JSON that both the
392/// WAL and the Parquet checkpoint codec record — directly, without building an
393/// intermediate `serde_json::Value` tree. This is the single canonical tagged
394/// encoder; [`Value::to_json_tagged`] produces its `serde_json::Value` from it,
395/// so the two cannot drift.
396///
397/// Graph entities ([`Value::Node`], [`Value::Relationship`],
398/// [`Value::Path`]) are not persistence properties: encoding one is a
399/// serialization error, mirroring the v2 persistence codec's "graph entity
400/// is not a persistence property" rejection. Byte arrays are the second
401/// not-a-persistence-property rejection class (ADR-0327: statement-scoped,
402/// and the executor's property check rejects them with a typed `TypeError`
403/// before persistence), with their own "byte array is not a persistence
404/// property" error.
405struct TaggedRef<'a>(&'a Value);
406
407impl serde::Serialize for TaggedRef<'_> {
408    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
409        use serde::ser::SerializeMap;
410        // The arms write two entries except the vector arm's three
411        // ("coord"/"t"/"v"), so no fixed arity is declared.
412        let mut m = serializer.serialize_map(None)?;
413        match self.0 {
414            Value::Null => m.serialize_entry("t", "null")?,
415            Value::Bool(b) => {
416                m.serialize_entry("t", "bool")?;
417                m.serialize_entry("v", b)?;
418            }
419            Value::Int(i) => write_tagged_number(&mut m, Coord::I(*i))?,
420            Value::Float(f) => write_tagged_number(&mut m, Coord::F(*f))?,
421            Value::String(s) => write_tagged_str(&mut m, s)?,
422            Value::Uuid(u) => {
423                m.serialize_entry("t", "uuid")?;
424                m.serialize_entry("v", &uuid_hyphenated(*u))?;
425            }
426            Value::List(xs) => {
427                m.serialize_entry("t", "list")?;
428                m.serialize_entry("v", &TaggedListRef(xs))?;
429            }
430            Value::Map(map) => {
431                m.serialize_entry("t", "map")?;
432                m.serialize_entry("v", &TaggedMapRef(map))?;
433            }
434            // Invariant: this encoder records graph *property* values only,
435            // and a property is never a graph entity -- `sanitize_props`
436            // (relate-executor) rejects Node/Relationship/Path before
437            // persistence, and the documented v2 persistence codec
438            // (relate-model `serde_value`) errors with "graph entity is
439            // not a persistence property". Fail loudly instead of silently
440            // writing the entity as a null tag.
441            Value::Node(_) | Value::Relationship(_) | Value::Path(_) => {
442                return Err(serde::ser::Error::custom(
443                    "graph entity is not a persistence property",
444                ));
445            }
446            // Invariant, as for graph entities: a byte array is
447            // statement-scoped (ADR-0327) and the executor's property check
448            // rejects it with a typed TypeError before persistence. The
449            // tagged codec has no byte-array tag; fail loudly instead.
450            Value::Bytes(_) => {
451                return Err(serde::ser::Error::custom(
452                    "byte array is not a persistence property",
453                ));
454            }
455            Value::Temporal(t) => {
456                m.serialize_entry("t", t.kind_name())?;
457                m.serialize_entry("v", &t.iso_string())?;
458            }
459            Value::Point(p) => {
460                m.serialize_entry("t", "point")?;
461                m.serialize_entry("v", &TaggedPointRef(p))?;
462            }
463            Value::Vector { coord, coords } => {
464                // serde_json's Map is a BTreeMap: keys serialize sorted, so
465                // "coord" precedes "t". Match the historical bytes.
466                m.serialize_entry("coord", coord.canonical_name())?;
467                m.serialize_entry("t", "vector")?;
468                m.serialize_entry("v", &TaggedCoordsRef(coords))?;
469            }
470        }
471        m.end()
472    }
473}
474
475struct TaggedListRef<'a>(&'a [Value]);
476impl serde::Serialize for TaggedListRef<'_> {
477    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
478        use serde::ser::SerializeSeq;
479        let mut seq = s.serialize_seq(Some(self.0.len()))?;
480        for v in self.0 {
481            seq.serialize_element(&TaggedRef(v))?;
482        }
483        seq.end()
484    }
485}
486
487/// A packed vector's coordinates as the tagged sequence the
488/// `Vec<Value>` form serialized (ADR-0706): each coordinate is the same
489/// `{"t": "int"/"float", "v": …}` entry `TaggedRef` emitted for the
490/// scalar it replaces (coordinates are finite by construction, so the
491/// NaN/Infinity spellings are unreachable).
492struct TaggedCoordsRef<'a>(&'a VectorCoords);
493impl serde::Serialize for TaggedCoordsRef<'_> {
494    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
495        use serde::ser::SerializeSeq;
496        let coords = self.0;
497        let mut seq = s.serialize_seq(Some(coords.len()))?;
498        for c in coords.iter() {
499            seq.serialize_element(&TaggedCoordRef(&c))?;
500        }
501        seq.end()
502    }
503}
504
505struct TaggedCoordRef<'a>(&'a Coord);
506impl serde::Serialize for TaggedCoordRef<'_> {
507    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
508        use serde::ser::SerializeMap;
509        let mut m = serializer.serialize_map(Some(2))?;
510        write_tagged_number(&mut m, *self.0)?;
511        m.end()
512    }
513}
514
515struct TaggedMapRef<'a>(&'a BTreeMap<String, Value>);
516impl serde::Serialize for TaggedMapRef<'_> {
517    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
518        use serde::ser::SerializeMap;
519        let mut m = s.serialize_map(Some(self.0.len()))?;
520        for (k, v) in self.0 {
521            m.serialize_entry(k, &TaggedRef(v))?;
522        }
523        m.end()
524    }
525}
526
527struct TaggedPointRef<'a>(&'a PointValue);
528impl serde::Serialize for TaggedPointRef<'_> {
529    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
530        use serde::ser::SerializeMap;
531        let p = self.0;
532        let mut m = s.serialize_map(Some(4))?;
533        m.serialize_entry("srid", &p.srid)?;
534        m.serialize_entry("x", &p.x)?;
535        m.serialize_entry("y", &p.y)?;
536        m.serialize_entry("z", &p.z)?;
537        m.end()
538    }
539}
540
541impl serde::Serialize for Value {
542    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
543        // ADR-0462: one bounded pre-walk at the public entry keeps the
544        // recursive `TaggedRef` encoder inside the depth cap. Unreachable
545        // behind the checked constructors — a graph property cannot nest
546        // past the cap without a typed error at construction.
547        if !self.depth_within(MAX_VALUE_DEPTH) {
548            return Err(serde::ser::Error::custom(value_depth_exceeded("value")));
549        }
550        TaggedRef(self).serialize(serializer)
551    }
552}
553
554impl<'de> serde::Deserialize<'de> for Value {
555    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
556        let json = serde_json::Value::deserialize(deserializer)?;
557        Value::from_json_tagged(&json).map_err(serde::de::Error::custom)
558    }
559}
560
561/// The tagged number vocabulary (`{"t": "int"/"float", "v": …}`) — one
562/// spelling for `TaggedRef`'s scalar arms and the packed-coordinate
563/// encoder (ADR-0706), including the non-finite float spellings.
564fn write_tagged_number<M: serde::ser::SerializeMap>(m: &mut M, c: Coord) -> Result<(), M::Error> {
565    match c {
566        Coord::I(n) => {
567            m.serialize_entry("t", "int")?;
568            m.serialize_entry("v", &n)?;
569        }
570        Coord::F(f) => {
571            m.serialize_entry("t", "float")?;
572            if f.is_nan() {
573                m.serialize_entry("v", "NaN")?;
574            } else if f == f64::INFINITY {
575                m.serialize_entry("v", "Infinity")?;
576            } else if f == f64::NEG_INFINITY {
577                m.serialize_entry("v", "-Infinity")?;
578            } else {
579                m.serialize_entry("v", &f)?;
580            }
581        }
582    }
583    Ok(())
584}
585
586fn map_to_json_plain<'a>(
587    m: impl IntoIterator<Item = (&'a String, &'a Value)>,
588    depth: u32,
589) -> serde_json::Value {
590    let mut o = serde_json::Map::new();
591    for (k, v) in m {
592        o.insert(k.clone(), v.to_json_plain_at(depth));
593    }
594    serde_json::Value::Object(o)
595}
596
597/// Plain-JSON form of a node, shared by the [`Value::Node`] arm and the
598/// [`Value::Path`] arm of [`Value::to_json_plain`], which renders each path
599/// element directly instead of cloning it into a [`Value`] and re-entering
600/// the dispatcher one arm down.
601fn node_json(n: &Node, depth: u32) -> serde_json::Value {
602    // `depth` is the node's ancestor-container count; the property values sit
603    // one container deeper. The guard matches the sibling container arms and
604    // returns the null form (ADR-0462).
605    let Some(next) = next_depth(depth) else {
606        return serde_json::Value::Null;
607    };
608    serde_json::json!({
609        "_type": "node",
610        "id": n.id,
611        "labels": n.labels,
612        "properties": map_to_json_plain(n.properties.iter(), next),
613    })
614}
615
616/// Plain-JSON form of a relationship (see [`node_json`]).
617fn rel_json(r: &Relationship, depth: u32) -> serde_json::Value {
618    let Some(next) = next_depth(depth) else {
619        return serde_json::Value::Null;
620    };
621    serde_json::json!({
622        "_type": "relationship",
623        "id": r.id,
624        "start": r.start,
625        "end": r.end,
626        "type": r.rel_type,
627        "properties": map_to_json_plain(r.properties.iter(), next),
628    })
629}
630
631/// Decode-side packing (ADR-0706): scalars a tagged/plain JSON decode
632/// produced, validated per `coord` kind and packed into the family
633/// buffer. The storage path fails closed on a crafted document (the
634/// `Vec<Value>` decode this replaces accepted inconsistent coordinates
635/// and let the encoder reject them later); the lenient
636/// `from_json_plain` path treats an `Err` as an unrecognized shape.
637pub fn pack_decoded_values(
638    coord: VectorCoordKind,
639    values: &[Value],
640) -> Result<VectorCoords, String> {
641    // The decode-side classification (fail-closed with this codec's own
642    // error detail), landing in the ONE family-selection policy
643    // (ADR-0706's `VectorCoords::from_coords`) — the family mapping, the
644    // empty vector and the one-family rule have their single spelling
645    // there.
646    let reject = |what: &str| format!("vector {what}");
647    let mut tokens = Vec::with_capacity(values.len());
648    if coord.is_integer() {
649        for v in values {
650            let Value::Int(n) = v else {
651                return Err(reject("coordinate is not an integer"));
652            };
653            if !coord.holds_int(*n) {
654                return Err(reject("coordinate out of kind range"));
655            }
656            tokens.push(Coord::I(*n));
657        }
658    } else {
659        for v in values {
660            match v {
661                Value::Int(n) => tokens.push(Coord::I(*n)),
662                Value::Float(f) if f.is_finite() && coord.is_exact(*f) => {
663                    tokens.push(Coord::F(*f));
664                }
665                Value::Float(_) => {
666                    return Err(reject("coordinate is not finite or loses precision"));
667                }
668                _ => return Err(reject("coordinate is not a number")),
669            }
670        }
671    }
672    VectorCoords::from_coords(coord, tokens.into_iter())
673        .ok_or_else(|| reject("coordinates mix integer and float forms"))
674}