Skip to main content

relate_core/value/
ordering.rs

1//! `Value` equality and ordering: Cypher's three-valued `cypher_eq`, the
2//! strict `eq_non_null`, the three-valued `compare` and the total
3//! `order_by_cmp` (ADR-0462 depth guards threaded through every container
4//! arm). Extracted from `value/mod.rs` for the file-size rule, following
5//! the `json.rs`/`props.rs` precedent; the methods stay inherent, so no
6//! caller changes.
7
8use std::cmp::Ordering;
9
10use super::*;
11
12/// Three-valued AND over element-wise `cypher_eq` results: any false pair
13/// yields false; otherwise any null pair yields null. Shared by the List
14/// and Map arms of [`Value::cypher_eq`]; `depth` is threaded through so the
15/// ADR-0462 guard reaches the recursive element comparison.
16fn cypher_eq_pairs<'a>(pairs: impl Iterator<Item = (&'a Value, &'a Value)>, depth: u32) -> Value {
17    let mut saw_null = false;
18    for (x, y) in pairs {
19        match x.cypher_eq_at(y, depth) {
20            Value::Bool(false) => return Value::Bool(false),
21            Value::Null => saw_null = true,
22            _ => {}
23        }
24    }
25    if saw_null {
26        Value::Null
27    } else {
28        Value::Bool(true)
29    }
30}
31
32/// The first elementwise comparison that is not `equal`, or `tie` when every
33/// zipped pair ties. Both iterators are zipped, so only the first `min(len)`
34/// pairs are compared; `tie` is where a caller states its length rule. A
35/// `None` result from `cmp` is terminal: a null operand decides the whole
36/// comparison as null. The one spelling of the hand-rolled
37/// first-non-equal loops ([`compare_maps`], [`Value::compare`]'s list arm,
38/// [`Value::order_by_cmp`]'s list/vector arms).
39fn lexicographic<A, B, C>(
40    a: impl Iterator<Item = A>,
41    b: impl Iterator<Item = B>,
42    equal: C,
43    tie: C,
44    mut cmp: impl FnMut(A, B) -> C,
45) -> C
46where
47    C: PartialEq,
48{
49    for (x, y) in a.zip(b) {
50        let result = cmp(x, y);
51        if result != equal {
52            return result;
53        }
54    }
55    tie
56}
57
58/// Elementwise [`Value::eq_non_null`] over two same-length sequences — the
59/// one list/vector element comparison in [`Value::eq_non_null`]. `depth` is
60/// the container level of the elements; the ADR-0462 guard caps the walk.
61fn elementwise_eq(a: &[Value], b: &[Value], depth: u32) -> bool {
62    a.len() == b.len()
63        && a.iter()
64            .zip(b.iter())
65            .all(|(x, y)| x.eq_non_null_at(y, depth))
66}
67
68/// The size-then-keys prefix both map comparators share: size first, then
69/// the sorted key lists element by element. Both operands are `BTreeMap`s,
70/// so iteration is already key order and equal lengths plus equal key lists
71/// mean the same key set — only the values are left to the caller, and the
72/// three-valued [`compare_maps`] and the total [`order_maps`] differ in
73/// exactly that comparison.
74fn map_size_then_keys(
75    a: &std::collections::BTreeMap<String, Value>,
76    b: &std::collections::BTreeMap<String, Value>,
77) -> Ordering {
78    a.len().cmp(&b.len()).then_with(|| {
79        lexicographic(
80            a.keys(),
81            b.keys(),
82            Ordering::Equal,
83            Ordering::Equal,
84            |ka: &String, kb: &String| ka.cmp(kb),
85        )
86    })
87}
88
89/// The map half of [`Value::compare`]: the shared size-then-keys prefix,
90/// then the values under those keys, three-valued.
91fn compare_maps(
92    a: &std::collections::BTreeMap<String, Value>,
93    b: &std::collections::BTreeMap<String, Value>,
94    depth: u32,
95) -> Option<Ordering> {
96    let by_shape = map_size_then_keys(a, b);
97    if by_shape != Ordering::Equal {
98        return Some(by_shape);
99    }
100    lexicographic(
101        a.values(),
102        b.values(),
103        Some(Ordering::Equal),
104        Some(Ordering::Equal),
105        |x, y| x.compare_at(y, depth),
106    )
107}
108
109/// A point's total order: SRID (the CRS) first, then x, y and z, so every
110/// distinct point orders. `f64::total_cmp` keeps a NaN coordinate ordered
111/// instead of collapsing the pair; an absent z sorts before a present one
112/// (a decoder can produce a 2D point carrying a 3D SRID, `point()` cannot).
113fn point_order(a: &PointValue, b: &PointValue) -> Ordering {
114    a.srid
115        .cmp(&b.srid)
116        .then_with(|| a.x.total_cmp(&b.x))
117        .then_with(|| a.y.total_cmp(&b.y))
118        .then_with(|| match (a.z, b.z) {
119            (None, None) => Ordering::Equal,
120            (None, Some(_)) => Ordering::Less,
121            (Some(_), None) => Ordering::Greater,
122            (Some(x), Some(y)) => x.total_cmp(&y),
123        })
124}
125
126/// The map arm of the total order: the shared size-then-keys prefix, then
127/// the values under those keys — the shape [`compare_maps`] states, but
128/// every step recursive through the total order, so a null, a cross-type
129/// pair, a point or a NaN under a key orders instead of deciding equality.
130/// `depth` is the values' container level (the caller's + 1).
131fn order_maps(
132    a: &std::collections::BTreeMap<String, Value>,
133    b: &std::collections::BTreeMap<String, Value>,
134    depth: u32,
135) -> Ordering {
136    map_size_then_keys(a, b).then_with(|| {
137        lexicographic(
138            a.values(),
139            b.values(),
140            Ordering::Equal,
141            Ordering::Equal,
142            |x, y| x.order_by_cmp_at(y, depth),
143        )
144    })
145}
146
147/// A path's total order (Neo4j's `PathValue.compareTo`): length, then the
148/// node sequence, then the relationship sequence — both by entity id, the
149/// same key a lone node or relationship orders by.
150fn path_order(a: &Path, b: &Path) -> Ordering {
151    a.nodes
152        .len()
153        .cmp(&b.nodes.len())
154        .then_with(|| {
155            a.nodes
156                .iter()
157                .map(|n| n.id)
158                .cmp(b.nodes.iter().map(|n| n.id))
159        })
160        .then_with(|| a.rels.iter().map(|r| r.id).cmp(b.rels.iter().map(|r| r.id)))
161}
162
163impl Value {
164    /// Cypher equality: numbers compare across int/float; null = x is null.
165    /// Lists and maps are three-valued: any `false` pair yields false; otherwise
166    /// any `null` pair yields null.
167    pub fn cypher_eq(&self, other: &Value) -> Value {
168        self.cypher_eq_at(other, 0)
169    }
170
171    /// [`Value::cypher_eq`] with the ADR-0462 depth guard threaded through
172    /// the container arms: a comparison past [`MAX_VALUE_DEPTH`] levels
173    /// answers `false` instead of recursing, consistent with the sibling
174    /// comparison walkers. Unreachable behind the checked constructors.
175    fn cypher_eq_at(&self, other: &Value, depth: u32) -> Value {
176        if self.is_null() || other.is_null() {
177            return Value::Null;
178        }
179        match (self, other) {
180            (Value::List(a), Value::List(b)) if descends(depth) => {
181                if a.len() != b.len() {
182                    return Value::Bool(false);
183                }
184                cypher_eq_pairs(a.iter().zip(b.iter()), depth + 1)
185            }
186            (Value::Map(a), Value::Map(b)) if descends(depth) => {
187                if a.len() != b.len() || a.keys().any(|k| !b.contains_key(k)) {
188                    return Value::Bool(false);
189                }
190                cypher_eq_pairs(
191                    a.iter().map(|(k, v)| (v, b.get(k).expect("key checked"))),
192                    depth + 1,
193                )
194            }
195            // Over-depth containers saturate instead of recursing.
196            (Value::List(_), Value::List(_)) | (Value::Map(_), Value::Map(_)) => Value::Bool(false),
197            // Everything else — including a Vector pair at over-cap depth —
198            // inherits the accumulated budget rather than restarting at 0.
199            _ => Value::Bool(self.eq_non_null_at(other, depth)),
200        }
201    }
202
203    pub fn eq_non_null(&self, other: &Value) -> bool {
204        self.eq_non_null_at(other, 0)
205    }
206
207    /// [`Value::eq_non_null`] with the ADR-0462 depth guard threaded through
208    /// the container arms: a comparison past [`MAX_VALUE_DEPTH`] levels
209    /// answers `false` instead of recursing. Unreachable behind the checked
210    /// constructors — the arms that descend only run at a legal depth.
211    fn eq_non_null_at(&self, other: &Value, depth: u32) -> bool {
212        match (self, other) {
213            (Value::Bool(a), Value::Bool(b)) => a == b,
214            (Value::Int(a), Value::Int(b)) => a == b,
215            (Value::Float(a), Value::Float(b)) => a == b,
216            // Exact Int-vs-Float equality: a plain `(a as f64) == b` cast
217            // rounds away low bits for `|a| > 2^53`, so `9007199254740993`
218            // spuriously equaled `9007199254740992.0` here while the exact
219            // equivalence keys (DISTINCT/GROUP BY/property index) did not --
220            // an index's presence could change a MATCH/MERGE answer.
221            (Value::Int(a), Value::Float(b)) => relate_model::canonical_key::eq_i64_f64(*a, *b),
222            (Value::Float(a), Value::Int(b)) => relate_model::canonical_key::eq_i64_f64(*b, *a),
223            (Value::String(a), Value::String(b)) => a == b,
224            (Value::Bytes(a), Value::Bytes(b)) => a == b,
225            (Value::Uuid(a), Value::Uuid(b)) => a == b,
226            (Value::List(a), Value::List(b)) if descends(depth) => elementwise_eq(a, b, depth + 1),
227            (Value::Map(a), Value::Map(b)) if descends(depth) => {
228                a.len() == b.len()
229                    && a.iter()
230                        .all(|(k, v)| b.get(k).is_some_and(|o| v.eq_non_null_at(o, depth + 1)))
231            }
232            (Value::Node(a), Value::Node(b)) => a.id == b.id,
233            (Value::Relationship(a), Value::Relationship(b)) => a.id == b.id,
234            (Value::Path(a), Value::Path(b)) => a == b,
235            // The spec's temporal equality is offset/zone-sensitive and is
236            // *not* `compare() == Equal`: a DST fall-back overlap is equal
237            // (`Temporal::equals`) yet ordered.
238            (Value::Temporal(a), Value::Temporal(b)) => a.equals(b),
239            (Value::Point(a), Value::Point(b)) => a == b,
240            (
241                Value::Vector {
242                    coord: ac,
243                    values: av,
244                },
245                Value::Vector {
246                    coord: bc,
247                    values: bv,
248                },
249            ) if descends(depth) => {
250                // Elementwise-exact, like the List arm: a derived `av == bv`
251                // is variant-strict (`Int(1)` vs `Float(1.0)` differs), which
252                // disagreed with the equivalence keys' numeric normalization
253                // of vector elements.
254                ac == bc && elementwise_eq(av, bv, depth + 1)
255            }
256            _ => false,
257        }
258    }
259
260    /// Cypher's three-valued ordering over one type-pair (`None` = null: the
261    /// pair is incomparable, or a `null` operand reached here). Orderable:
262    /// numbers, strings, bytes, booleans, lists, maps, and the temporal kinds
263    /// except durations. Not orderable despite having `=`: UUIDs, points,
264    /// durations, and any cross-type pair — the `<=`/`>=` arms of the
265    /// comparison operators still hold for equal operands (`cmp_bool`).
266    pub fn compare(&self, other: &Value) -> Option<Ordering> {
267        self.compare_at(other, 0)
268    }
269
270    /// [`Value::compare`] with the ADR-0462 depth guard threaded through the
271    /// container arms: a comparison past [`MAX_VALUE_DEPTH`] levels answers
272    /// `None` (incomparable) instead of recursing.
273    fn compare_at(&self, other: &Value, depth: u32) -> Option<Ordering> {
274        if self.is_null() || other.is_null() {
275            return None;
276        }
277        match (self, other) {
278            (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
279            (Value::Float(a), Value::Float(b)) => a.partial_cmp(b),
280            // Exact Int-vs-Float ordering, consistent with the equality above
281            // (both route through `relate_model::canonical_key`), so `<`/
282            // `ORDER BY` and `=` never disagree past `2^53`.
283            (Value::Int(a), Value::Float(b)) => relate_model::canonical_key::cmp_i64_f64(*a, *b),
284            (Value::Float(a), Value::Int(b)) => {
285                relate_model::canonical_key::cmp_i64_f64(*b, *a).map(Ordering::reverse)
286            }
287            (Value::String(a), Value::String(b)) => Some(a.cmp(b)),
288            // Byte-wise, like the List arm: element by element, then length.
289            (Value::Bytes(a), Value::Bytes(b)) => Some(a.cmp(b)),
290            (Value::Bool(a), Value::Bool(b)) => Some(a.cmp(b)),
291            // CIP-246: UUIDs are NOT ordered by the comparison operators --
292            // only equality is defined, so a distinct pair is incomparable
293            // (NULL for `<`/`>`), while an equal pair still yields `Equal`
294            // and so `>=`/`<=` are true (`UUID(x) >= UUID(x)` is true). The
295            // numeric order lives in `order_by_cmp` (UUID ranks between
296            // BOOLEAN and TEMPORAL), so ORDER BY / min / max still sort.
297            (Value::Uuid(a), Value::Uuid(b)) => (*a == *b).then_some(Ordering::Equal),
298            (Value::Temporal(a), Value::Temporal(b)) => a.compare(b),
299            (Value::List(a), Value::List(b)) if descends(depth) => lexicographic(
300                a.iter(),
301                b.iter(),
302                Some(Ordering::Equal),
303                Some(a.len().cmp(&b.len())),
304                |x, y| x.compare_at(y, depth + 1),
305            ),
306            // Maps have a total order: size, then the sorted keys, then the
307            // values under them. A null value makes the comparison null
308            // while a differing key decides the order on its own, which is
309            // why `{k1: 42} < {k2: null}` is true but `{k: 42} < {k: null}`
310            // is null.
311            (Value::Map(a), Value::Map(b)) if descends(depth) => compare_maps(a, b, depth + 1),
312            // Everything left has no ordering arm: UUIDs and points (only `=`
313            // is defined for them — `ORDER BY` still ranks them, see
314            // `order_by_cmp`), paths, entities, and every cross-type pair.
315            _ => None,
316        }
317    }
318
319    /// Total order for ORDER BY / min / max. Comparison operators still use
320    /// `compare`, which is three-valued and incomparable across types.
321    ///
322    /// Every value kind has an arm, so the relation is a total order:
323    /// antisymmetric, transitive, and `Equal` only for two values of one
324    /// kind. The kind rank decides cross-kind pairs; the same-kind arms
325    /// decide the rest. A new kind with a rank of its own needs its arm
326    /// here — the last arm's `Equal` is the wrong answer for it.
327    pub fn order_by_cmp(&self, other: &Value) -> Ordering {
328        self.order_by_cmp_at(other, 0)
329    }
330
331    /// [`Value::order_by_cmp`] with the ADR-0462 depth guard threaded
332    /// through the container arms: past [`MAX_VALUE_DEPTH`] levels the walk
333    /// answers `Equal` instead of recursing. Unreachable behind the checked
334    /// constructors.
335    fn order_by_cmp_at(&self, other: &Value, depth: u32) -> Ordering {
336        let ra = self.order_type_rank();
337        let rb = other.order_type_rank();
338        if ra != rb {
339            return ra.cmp(&rb);
340        }
341        match (self, other) {
342            (Value::Null, Value::Null) => Ordering::Equal,
343            // Not orderable by `compare` (no comparison operators), but
344            // ORDER BY / min / max still rank them.
345            (Value::Uuid(a), Value::Uuid(b)) => a.cmp(b),
346            (Value::Temporal(a), Value::Temporal(b)) => a.total_cmp(b),
347            (Value::Point(a), Value::Point(b)) => point_order(a, b),
348            (Value::Node(a), Value::Node(b)) => a.id.cmp(&b.id),
349            (Value::Relationship(a), Value::Relationship(b)) => a.id.cmp(&b.id),
350            (Value::Path(a), Value::Path(b)) => path_order(a, b),
351            (Value::Map(a), Value::Map(b)) if descends(depth) => order_maps(a, b, depth + 1),
352            (Value::List(a), Value::List(b)) if descends(depth) => lexicographic(
353                a.iter(),
354                b.iter(),
355                Ordering::Equal,
356                a.len().cmp(&b.len()),
357                |x, y| x.order_by_cmp_at(y, depth + 1),
358            ),
359            (
360                Value::Vector {
361                    coord: ac,
362                    values: av,
363                },
364                Value::Vector {
365                    coord: bc,
366                    values: bv,
367                },
368            ) if descends(depth) => {
369                let type_order = ac
370                    .order_rank()
371                    .cmp(&bc.order_rank())
372                    .then_with(|| av.len().cmp(&bv.len()));
373                if type_order != Ordering::Equal {
374                    return type_order;
375                }
376                lexicographic(
377                    av.iter(),
378                    bv.iter(),
379                    Ordering::Equal,
380                    Ordering::Equal,
381                    |x, y| x.order_by_cmp_at(y, depth + 1),
382                )
383            }
384            // The same-rank scalars (numbers across int/float, strings,
385            // booleans, bytes), and the over-depth containers saturating as
386            // ADR-0462 states. A scalar pair's three-valued comparison is
387            // already total here.
388            _ => self.compare_at(other, depth).unwrap_or(Ordering::Equal),
389        }
390    }
391
392    /// OpenCypher ORDER BY type order (ascending):
393    /// MAP < NODE < RELATIONSHIP < LIST < BYTES < PATH < VECTOR < POINT <
394    /// TEMPORAL < STRING < BOOLEAN < UUID < NUMBER < NaN < NULL. A temporal
395    /// sorts after the containers/points and before STRING (CIP-222's
396    /// Neo4j-verified mixed-type max/min/sort: `date('2024-06-01')` is the
397    /// minimum and `true` the maximum of `[date, true, 'hi']`; UUID sits
398    /// between BOOLEAN and NUMBER per the CIP-246 amendment; BYTES, a
399    /// sequence value in Neo4j, directly after LIST, ADR-0327).
400    ///
401    /// The temporal kinds are ordered among themselves — ZONED DATETIME <
402    /// LOCAL DATETIME < DATE < ZONED TIME < LOCAL TIME < DURATION — because
403    /// `Temporal::total_cmp` answers `Equal` across unlike kinds and this
404    /// rank is what keeps them distinct (live Neo4j 2026.10.1: `coll.sort`
405    /// and `ORDER BY` agree on that sequence, independent of the values).
406    /// [`TemporalKind`] is declared in exactly that order, so its
407    /// discriminant is the rank's offset from TEMPORAL's base rank.
408    fn order_type_rank(&self) -> u8 {
409        match self {
410            Value::Map(_) => 0,
411            Value::Node(_) => 1,
412            Value::Relationship(_) => 2,
413            Value::List(_) => 3,
414            Value::Bytes(_) => 4,
415            Value::Path(_) => 5,
416            Value::Vector { .. } => 6,
417            Value::Point(_) => 7,
418            Value::Temporal(t) => 8 + t.kind() as u8,
419            Value::String(_) => 14,
420            Value::Bool(_) => 15,
421            // CIP-246: UUID orders between BOOLEAN and NUMBER (live
422            // Neo4j 2026.09: true < uuid < 1).
423            Value::Uuid(_) => 16,
424            Value::Int(_) => 17,
425            Value::Float(f) if f.is_nan() => 19,
426            Value::Float(_) => 17,
427            Value::Null => 20,
428        }
429    }
430}
431
432#[cfg(test)]
433#[path = "ordering_tests.rs"]
434mod total_order_tests;