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