Skip to main content

relate_core/value/
depth.rs

1//! ADR-0462 value-nesting depth: the fixed cap, the one iterative depth
2//! walk and its two front ends, the typed guard, and the checked
3//! constructors. Extracted from `value/mod.rs` for the file-size rule (the
4//! `ordering.rs`/`json.rs` precedent); the methods stay inherent, so no
5//! caller changes.
6
7use std::collections::{BTreeMap, HashMap};
8use std::sync::Arc;
9
10use super::{Node, PropertyMap, Relationship, Value};
11
12/// The deepest container nesting a [`Value`] may have (ADR-0462,
13/// LABS-606).
14///
15/// Equal to the parser's static nesting limit (ADR-0257) so every
16/// parse-legal literal is accepted, and low enough that the derived
17/// recursive `Drop`, clone, and render walks over an at-cap value stay well
18/// inside every surface's stack. Every dynamic container construction in
19/// the evaluator goes through [`Value::checked_list`]/
20/// [`Value::checked_map`]; a `reduce` accumulator can therefore grow one
21/// level per iteration without ever exceeding this bound — the level-501
22/// construction fails with a typed `ValueDepthExceeded` error instead of
23/// building a value that later overflows a recursive walker.
24///
25/// Fixed constant, no knob: the same house rule as ADR-0257's 4 MiB/500 and
26/// ADR-0395's fixed budget (1 000 000 passes since ADR-0670). Lifting it would require a
27/// payload-newtype `Drop` for `Value` (never `impl Drop for Value`, which
28/// makes the move-out matches E0509), so a recursive drop cannot overflow.
29pub const MAX_VALUE_DEPTH: u32 = 500;
30
31/// What the infallible renderers emit for a container nested past
32/// [`MAX_VALUE_DEPTH`] instead of recursing (ADR-0462). Unreachable behind
33/// the checked constructors: it is the depth safety valve for a caller that
34/// bypassed them, never a documented rendering.
35pub(crate) const DEPTH_LIMIT_MARKER: &str = "<depth limit exceeded>";
36
37/// The one `ValueDepthExceeded` detail payload (ADR-0462), beside
38/// [`MAX_VALUE_DEPTH`]. `what` names the value shape the walker rejected
39/// (`"value"`, `"tagged value"`, `"coll.flatten() input"`). Every raiser —
40/// [`Value::check_depth`], the tagged decoder and encoder, the collection
41/// helpers — spells the message through here so the detail and the limit
42/// cannot drift.
43pub fn value_depth_exceeded(what: &str) -> String {
44    format!(
45        "ValueDepthExceeded: {what} nesting exceeds {MAX_VALUE_DEPTH} levels; \
46         container nesting compounds per level (security limit)."
47    )
48}
49
50/// The next container level below `depth`, or `None` once that level would
51/// exceed [`MAX_VALUE_DEPTH`]. The canonical ADR-0462 guard for walkers that
52/// saturate or throw at the cap (renderers, JSON decoders/encoders, the
53/// model bridge, the logical-bytes walk); re-exported so the HTTP Query API
54/// encoder spells it the same way. `depth` is the number of containers
55/// enclosing the value, so a root is 0.
56pub fn next_depth(depth: u32) -> Option<u32> {
57    let next = child_level(depth);
58    (next <= MAX_VALUE_DEPTH).then_some(next)
59}
60
61/// The most worklist steps one depth walk may take before it conservatively
62/// refuses (ADR-0462, PR #547 round-5). The walk memoizes container payloads
63/// by identity, so a DAG of N distinct payloads costs O(N) steps; this is the
64/// belt-and-braces refusal for a sharing pattern the memo cannot collapse —
65/// the walk gives up as over-cap instead of hanging. Symmetric with the fixed
66/// pass budgets elsewhere (ADR-0395).
67const MAX_DEPTH_WALK_STEPS: u64 = 10_000_000;
68
69/// Identity of one container payload during a depth walk: its `Arc`
70/// allocation address. Distinct live allocations never share an address, and
71/// the walk's root keeps every visited payload alive for the walk's duration,
72/// so a key can never alias a freed allocation. The variant kind is
73/// redundant: the address already identifies the container, and the memo
74/// stores a depth derived from that payload's own contents.
75pub(super) type PayloadKey = usize;
76
77/// The one derivation of a payload's identity from its `Arc` (ADR-0462's
78/// depth memo and ADR-0691's expansion memo both key through it).
79pub(super) fn payload_key<T: ?Sized>(payload: &Arc<T>) -> PayloadKey {
80    Arc::as_ptr(payload) as *const () as usize
81}
82
83/// One container's lazily enumerated children. Every variant is O(1) to
84/// build, so a memo hit drops it without touching the children — the walk
85/// stays O(distinct payloads), never O(expanded edges).
86enum Children<'a> {
87    Values(std::slice::Iter<'a, Value>),
88    MapValues(std::collections::btree_map::Values<'a, String, Value>),
89    PropValues(PropValues<'a>),
90    Path {
91        nodes: std::slice::Iter<'a, Node>,
92        rels: std::slice::Iter<'a, Relationship>,
93        current: Option<PropValues<'a>>,
94    },
95}
96
97/// `PropertyMap` entry values: the depth walk only needs the value half.
98type PropValues<'a> =
99    std::iter::Map<std::slice::Iter<'a, (String, Value)>, fn(&'a (String, Value)) -> &'a Value>;
100
101fn entry_value((_, value): &(String, Value)) -> &Value {
102    value
103}
104
105fn prop_values(props: &PropertyMap) -> PropValues<'_> {
106    props.entries().iter().map(entry_value)
107}
108
109impl<'a> Iterator for Children<'a> {
110    type Item = &'a Value;
111
112    fn next(&mut self) -> Option<Self::Item> {
113        match self {
114            Children::Values(items) => items.next(),
115            Children::MapValues(values) => values.next(),
116            Children::PropValues(values) => values.next(),
117            Children::Path {
118                nodes,
119                rels,
120                current,
121            } => loop {
122                if let Some(values) = current.as_mut() {
123                    if let Some(value) = values.next() {
124                        return Some(value);
125                    }
126                    *current = None;
127                }
128                if let Some(node) = nodes.next() {
129                    *current = Some(prop_values(&node.properties));
130                    continue;
131                }
132                if let Some(rel) = rels.next() {
133                    *current = Some(prop_values(&rel.properties));
134                    continue;
135                }
136                return None;
137            },
138        }
139    }
140}
141
142/// The one owner of the container vocabulary (ADR-0462): a container value's
143/// memo identity and its children together, from one enumeration — so the
144/// memo key, the child count and the child iteration cannot drift apart. The
145/// scalar variants are spelled out on purpose: a future `Value` variant is a
146/// non-exhaustive-match compile error at this one classification site.
147fn container(value: &Value) -> Option<(PayloadKey, Children<'_>)> {
148    match value {
149        Value::List(xs) => Some((payload_key(xs), Children::Values(xs.iter()))),
150        Value::Map(map) => Some((payload_key(map), Children::MapValues(map.values()))),
151        Value::Node(node) => Some((
152            payload_key(node),
153            Children::PropValues(prop_values(&node.properties)),
154        )),
155        Value::Relationship(rel) => Some((
156            payload_key(rel),
157            Children::PropValues(prop_values(&rel.properties)),
158        )),
159        Value::Path(path) => Some((
160            payload_key(path),
161            Children::Path {
162                nodes: path.nodes.iter(),
163                rels: path.rels.iter(),
164                current: None,
165            },
166        )),
167        // A packed Vector (ADR-0706) has no child Values — its
168        // coordinates are one homogeneous numeric slice — so it walks as
169        // a scalar, not a container.
170        Value::Null
171        | Value::Bool(_)
172        | Value::Int(_)
173        | Value::Float(_)
174        | Value::String(_)
175        | Value::Temporal(_)
176        | Value::Point(_)
177        | Value::Uuid(_)
178        | Value::Vector { .. }
179        | Value::Bytes(_) => None,
180    }
181}
182
183/// One frame of the iterative depth walk.
184enum Frame<'a> {
185    /// Visit a value: a scalar completes with depth 0, a container with its
186    /// memoized relative depth, or — on its first visit — schedules its
187    /// children and the matching [`Frame::Exit`].
188    Enter(&'a Value),
189    /// A container's children have each pushed exactly one result on top of
190    /// `results`; fold those results (from `base`) into the container's
191    /// relative depth and memoize it.
192    Exit { key: PayloadKey, base: usize },
193}
194
195/// The one owner of the level arithmetic (ADR-0462): the level one container
196/// deeper than `depth`, saturating at `u32::MAX` — a value that deep is
197/// over the cap in every caller. Every walker and guard routes through here
198/// so the three previous spellings cannot drift.
199fn child_level(depth: u32) -> u32 {
200    depth.saturating_add(1)
201}
202
203/// Whether a walker at `depth` (containers enclosing the value) may descend
204/// into the value's contents — the boolean spelling of [`next_depth`] for
205/// the comparison walkers, whose guards read naturally as a match-arm
206/// condition. [`next_depth`] owns the boundary; this only answers its
207/// `Some`/`None`.
208pub(crate) fn descends(depth: u32) -> bool {
209    next_depth(depth).is_some()
210}
211
212impl Value {
213    /// Whether every container in this value nests at most `limit` levels
214    /// deep (ADR-0462). Iterative over an explicit worklist — never
215    /// recursive — so an over-deep value is rejected without first growing
216    /// the stack to its depth.
217    ///
218    /// A scalar has depth 0; a container's own level is one more than its
219    /// parent's, so `[]` is depth 1 and `[[]]` depth 2. Node, relationship
220    /// and path values count as containers, and their property values nest
221    /// inside them.
222    pub fn depth_within(&self, limit: u32) -> bool {
223        // One iterative walker, two front ends (ADR-0462): the walk is on
224        // capped values, so the exact depth is cheap to compute and there is
225        // no separate early-exit spelling to drift.
226        self.depth() <= limit
227    }
228
229    /// The typed depth guard: `Ok` when this value nests at most
230    /// [`MAX_VALUE_DEPTH`] levels (ADR-0462), else a `ValueDepthExceeded`
231    /// execution error. The `Kind:` prefix is the token the error channel
232    /// classifies (`ErrorKind::ValueDepthExceeded`).
233    pub fn check_depth(&self) -> crate::Result<()> {
234        Self::check_known_depth(self.depth())
235    }
236
237    /// This value's exact container depth (scalar 0, `[]` 1, `[[]]` 2),
238    /// walked iteratively once. For a value whose depth is already known,
239    /// [`Value::checked_list_with_depth`] avoids this walk.
240    ///
241    /// The walk memoizes container payloads by identity: a shared subtree is
242    /// measured once, so the cost is linear in **distinct payloads**, never in
243    /// the expanded node count of a fan-out DAG (a `[acc, acc]` chain would
244    /// otherwise expand exponentially). A walk that exceeds
245    /// [`MAX_DEPTH_WALK_STEPS`] conservatively answers [`u32::MAX`] (over any
246    /// cap), so it can refuse but never hang.
247    pub fn depth(&self) -> u32 {
248        self.depth_capped().unwrap_or(u32::MAX)
249    }
250
251    /// [`Value::depth`] with the ADR-0462 step bound: `None` when the walk
252    /// exceeds [`MAX_DEPTH_WALK_STEPS`], which every caller treats as
253    /// over-cap.
254    fn depth_capped(&self) -> Option<u32> {
255        let mut memo: HashMap<PayloadKey, u32> = HashMap::new();
256        let mut results: Vec<u32> = Vec::new();
257        let mut stack: Vec<Frame<'_>> = vec![Frame::Enter(self)];
258        let mut steps: u64 = 0;
259        while let Some(frame) = stack.pop() {
260            steps += 1;
261            if steps > MAX_DEPTH_WALK_STEPS {
262                return None;
263            }
264            match frame {
265                Frame::Enter(value) => {
266                    let Some((key, children)) = container(value) else {
267                        results.push(0);
268                        continue;
269                    };
270                    if let Some(rel) = memo.get(&key) {
271                        // Memo hit: the lazily built `children` is dropped
272                        // unused, so a shared payload costs O(1).
273                        results.push(*rel);
274                        continue;
275                    }
276                    // Record where this container's children's results begin,
277                    // then push the children on top of the Exit frame.
278                    let base = results.len();
279                    stack.push(Frame::Exit { key, base });
280                    stack.extend(children.map(Frame::Enter));
281                }
282                Frame::Exit { key, base } => {
283                    // Every child of this container pushed exactly one result
284                    // after `base` was recorded; fold them into `1 + max`.
285                    let max = results[base..].iter().copied().max().unwrap_or(0);
286                    results.truncate(base);
287                    let rel = child_level(max);
288                    memo.insert(key, rel);
289                    results.push(rel);
290                }
291            }
292        }
293        results.pop()
294    }
295
296    /// The depth check for a caller that already knows the result's depth —
297    /// the O(1) path behind [`Value::checked_list_with_depth`]. `depth` is
298    /// the candidate value's own container level.
299    fn check_known_depth(depth: u32) -> crate::Result<()> {
300        if depth <= MAX_VALUE_DEPTH {
301            Ok(())
302        } else {
303            Err(crate::Error::execution(value_depth_exceeded("value")))
304        }
305    }
306
307    /// Build a list value, rejecting one that would nest deeper than
308    /// [`MAX_VALUE_DEPTH`] (ADR-0462). The one constructor for a list the
309    /// evaluator builds from dynamic expression results.
310    pub fn checked_list(values: Vec<Value>) -> crate::Result<Value> {
311        let value = Value::List(values.into());
312        value.check_depth()?;
313        Ok(value)
314    }
315
316    /// **Evaluator-internal O(1) seam** (ADR-0462): build a list when the
317    /// caller already knows `child_depth` — the exact maximum container depth
318    /// of `values` — instead of walking the subtree. The result's own level
319    /// is `child_depth + 1`.
320    ///
321    /// Invariant: only the evaluator's depth-tracking loops (the
322    /// `reduce`/`allReduce` wrap fast path) may call this, passing the depth
323    /// they track per iteration. Every other caller must use
324    /// [`Value::checked_list`]. Release builds trust the caller and stay
325    /// O(1); debug builds assert every element is within the claimed depth.
326    #[doc(hidden)]
327    pub fn checked_list_with_depth(values: Vec<Value>, child_depth: u32) -> crate::Result<Value> {
328        debug_assert!(
329            values.iter().all(|v| v.depth_within(child_depth)),
330            "checked_list_with_depth: an element is deeper than the claimed child_depth"
331        );
332        Self::check_known_depth(child_level(child_depth))?;
333        Ok(Value::List(values.into()))
334    }
335
336    /// Build a map value, rejecting one that would nest deeper than
337    /// [`MAX_VALUE_DEPTH`] (ADR-0462). The one constructor for a map the
338    /// evaluator builds from dynamic expression results.
339    pub fn checked_map(values: BTreeMap<String, Value>) -> crate::Result<Value> {
340        let value = Value::Map(values.into());
341        value.check_depth()?;
342        Ok(value)
343    }
344}