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) | Value::Vector { values: xs, .. } => {
150            Some((payload_key(xs), Children::Values(xs.iter())))
151        }
152        Value::Map(map) => Some((payload_key(map), Children::MapValues(map.values()))),
153        Value::Node(node) => Some((
154            payload_key(node),
155            Children::PropValues(prop_values(&node.properties)),
156        )),
157        Value::Relationship(rel) => Some((
158            payload_key(rel),
159            Children::PropValues(prop_values(&rel.properties)),
160        )),
161        Value::Path(path) => Some((
162            payload_key(path),
163            Children::Path {
164                nodes: path.nodes.iter(),
165                rels: path.rels.iter(),
166                current: None,
167            },
168        )),
169        Value::Null
170        | Value::Bool(_)
171        | Value::Int(_)
172        | Value::Float(_)
173        | Value::String(_)
174        | Value::Temporal(_)
175        | Value::Point(_)
176        | Value::Uuid(_)
177        | Value::Bytes(_) => None,
178    }
179}
180
181/// One frame of the iterative depth walk.
182enum Frame<'a> {
183    /// Visit a value: a scalar completes with depth 0, a container with its
184    /// memoized relative depth, or — on its first visit — schedules its
185    /// children and the matching [`Frame::Exit`].
186    Enter(&'a Value),
187    /// A container's children have each pushed exactly one result on top of
188    /// `results`; fold those results (from `base`) into the container's
189    /// relative depth and memoize it.
190    Exit { key: PayloadKey, base: usize },
191}
192
193/// The one owner of the level arithmetic (ADR-0462): the level one container
194/// deeper than `depth`, saturating at `u32::MAX` — a value that deep is
195/// over the cap in every caller. Every walker and guard routes through here
196/// so the three previous spellings cannot drift.
197fn child_level(depth: u32) -> u32 {
198    depth.saturating_add(1)
199}
200
201/// Whether a walker at `depth` (containers enclosing the value) may descend
202/// into the value's contents — the boolean spelling of [`next_depth`] for
203/// the comparison walkers, whose guards read naturally as a match-arm
204/// condition. [`next_depth`] owns the boundary; this only answers its
205/// `Some`/`None`.
206pub(crate) fn descends(depth: u32) -> bool {
207    next_depth(depth).is_some()
208}
209
210impl Value {
211    /// Whether every container in this value nests at most `limit` levels
212    /// deep (ADR-0462). Iterative over an explicit worklist — never
213    /// recursive — so an over-deep value is rejected without first growing
214    /// the stack to its depth.
215    ///
216    /// A scalar has depth 0; a container's own level is one more than its
217    /// parent's, so `[]` is depth 1 and `[[]]` depth 2. Node, relationship
218    /// and path values count as containers, and their property values nest
219    /// inside them.
220    pub fn depth_within(&self, limit: u32) -> bool {
221        // One iterative walker, two front ends (ADR-0462): the walk is on
222        // capped values, so the exact depth is cheap to compute and there is
223        // no separate early-exit spelling to drift.
224        self.depth() <= limit
225    }
226
227    /// The typed depth guard: `Ok` when this value nests at most
228    /// [`MAX_VALUE_DEPTH`] levels (ADR-0462), else a `ValueDepthExceeded`
229    /// execution error. The `Kind:` prefix is the token the error channel
230    /// classifies (`ErrorKind::ValueDepthExceeded`).
231    pub fn check_depth(&self) -> crate::Result<()> {
232        Self::check_known_depth(self.depth())
233    }
234
235    /// This value's exact container depth (scalar 0, `[]` 1, `[[]]` 2),
236    /// walked iteratively once. For a value whose depth is already known,
237    /// [`Value::checked_list_with_depth`] avoids this walk.
238    ///
239    /// The walk memoizes container payloads by identity: a shared subtree is
240    /// measured once, so the cost is linear in **distinct payloads**, never in
241    /// the expanded node count of a fan-out DAG (a `[acc, acc]` chain would
242    /// otherwise expand exponentially). A walk that exceeds
243    /// [`MAX_DEPTH_WALK_STEPS`] conservatively answers [`u32::MAX`] (over any
244    /// cap), so it can refuse but never hang.
245    pub fn depth(&self) -> u32 {
246        self.depth_capped().unwrap_or(u32::MAX)
247    }
248
249    /// [`Value::depth`] with the ADR-0462 step bound: `None` when the walk
250    /// exceeds [`MAX_DEPTH_WALK_STEPS`], which every caller treats as
251    /// over-cap.
252    fn depth_capped(&self) -> Option<u32> {
253        let mut memo: HashMap<PayloadKey, u32> = HashMap::new();
254        let mut results: Vec<u32> = Vec::new();
255        let mut stack: Vec<Frame<'_>> = vec![Frame::Enter(self)];
256        let mut steps: u64 = 0;
257        while let Some(frame) = stack.pop() {
258            steps += 1;
259            if steps > MAX_DEPTH_WALK_STEPS {
260                return None;
261            }
262            match frame {
263                Frame::Enter(value) => {
264                    let Some((key, children)) = container(value) else {
265                        results.push(0);
266                        continue;
267                    };
268                    if let Some(rel) = memo.get(&key) {
269                        // Memo hit: the lazily built `children` is dropped
270                        // unused, so a shared payload costs O(1).
271                        results.push(*rel);
272                        continue;
273                    }
274                    // Record where this container's children's results begin,
275                    // then push the children on top of the Exit frame.
276                    let base = results.len();
277                    stack.push(Frame::Exit { key, base });
278                    stack.extend(children.map(Frame::Enter));
279                }
280                Frame::Exit { key, base } => {
281                    // Every child of this container pushed exactly one result
282                    // after `base` was recorded; fold them into `1 + max`.
283                    let max = results[base..].iter().copied().max().unwrap_or(0);
284                    results.truncate(base);
285                    let rel = child_level(max);
286                    memo.insert(key, rel);
287                    results.push(rel);
288                }
289            }
290        }
291        results.pop()
292    }
293
294    /// The depth check for a caller that already knows the result's depth —
295    /// the O(1) path behind [`Value::checked_list_with_depth`]. `depth` is
296    /// the candidate value's own container level.
297    fn check_known_depth(depth: u32) -> crate::Result<()> {
298        if depth <= MAX_VALUE_DEPTH {
299            Ok(())
300        } else {
301            Err(crate::Error::execution(value_depth_exceeded("value")))
302        }
303    }
304
305    /// Build a list value, rejecting one that would nest deeper than
306    /// [`MAX_VALUE_DEPTH`] (ADR-0462). The one constructor for a list the
307    /// evaluator builds from dynamic expression results.
308    pub fn checked_list(values: Vec<Value>) -> crate::Result<Value> {
309        let value = Value::List(values.into());
310        value.check_depth()?;
311        Ok(value)
312    }
313
314    /// **Evaluator-internal O(1) seam** (ADR-0462): build a list when the
315    /// caller already knows `child_depth` — the exact maximum container depth
316    /// of `values` — instead of walking the subtree. The result's own level
317    /// is `child_depth + 1`.
318    ///
319    /// Invariant: only the evaluator's depth-tracking loops (the
320    /// `reduce`/`allReduce` wrap fast path) may call this, passing the depth
321    /// they track per iteration. Every other caller must use
322    /// [`Value::checked_list`]. Release builds trust the caller and stay
323    /// O(1); debug builds assert every element is within the claimed depth.
324    #[doc(hidden)]
325    pub fn checked_list_with_depth(values: Vec<Value>, child_depth: u32) -> crate::Result<Value> {
326        debug_assert!(
327            values.iter().all(|v| v.depth_within(child_depth)),
328            "checked_list_with_depth: an element is deeper than the claimed child_depth"
329        );
330        Self::check_known_depth(child_level(child_depth))?;
331        Ok(Value::List(values.into()))
332    }
333
334    /// Build a map value, rejecting one that would nest deeper than
335    /// [`MAX_VALUE_DEPTH`] (ADR-0462). The one constructor for a map the
336    /// evaluator builds from dynamic expression results.
337    pub fn checked_map(values: BTreeMap<String, Value>) -> crate::Result<Value> {
338        let value = Value::Map(values.into());
339        value.check_depth()?;
340        Ok(value)
341    }
342}