relate-core 1.0.0

Core values, errors, and IDs for Relate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
use super::*;
use std::cmp::Ordering;

use std::sync::Arc;

// CIP-271: the toString() display form, pinned against Neo4j 2026.09.0
// probes (unquoted strings, sorted map keys, recursive rendering).
#[test]
fn to_display_string_matches_neo4j_2026_09() {
    let m = |pairs: &[(&str, Value)]| {
        Value::Map(
            pairs
                .iter()
                .map(|(k, v)| ((*k).to_string(), v.clone()))
                .collect::<BTreeMap<_, _>>()
                .into(),
        )
    };
    let cases: Vec<(Value, &str)> = vec![
        (
            m(&[
                ("a", Value::Int(1)),
                ("b", Value::String("x y".into())),
                ("c", Value::List(vec![Value::Int(1), Value::Int(2)].into())),
                ("d", m(&[("e", Value::Bool(true))])),
            ]),
            "{a: 1, b: x y, c: [1, 2], d: {e: true}}",
        ),
        // Sorted key order regardless of construction order.
        (
            m(&[("z", Value::Int(1)), ("a", Value::Int(2))]),
            "{a: 2, z: 1}",
        ),
        (Value::Map(BTreeMap::new().into()), "{}"),
        (Value::List(vec![].into()), "[]"),
        (
            Value::List(vec![Value::Int(1), Value::Null, Value::String("a".into())].into()),
            "[1, null, a]",
        ),
        (Value::Float(1.0), "1.0"),
        (Value::Float(1.5), "1.5"),
        // A point renders the CRS name and float coordinates (the harness's
        // `toString(point())` and `'hi' + point(...)` pins).
        (
            Value::Point(PointValue::cartesian_2d(1.0, 2.5)),
            "point({x: 1.0, y: 2.5, crs: 'cartesian'})",
        ),
        (
            Value::Point(PointValue::cartesian_3d(0.0, 4.0, 1.5)),
            "point({x: 0.0, y: 4.0, z: 1.5, crs: 'cartesian-3d'})",
        ),
        (
            Value::Point(PointValue::wgs84_2d(-73.9857, 40.7484)),
            "point({x: -73.9857, y: 40.7484, crs: 'wgs-84'})",
        ),
        (Value::Null, "null"),
        (Value::Bool(true), "true"),
        (
            Value::from_node(Node {
                id: 1,
                labels: Arc::new(vec!["X".into()]),
                properties: crate::PropertyMap::share(BTreeMap::new()),
            }),
            "(:X)",
        ),
        (
            Value::from_relationship(Relationship {
                id: 1,
                start: 1,
                end: 2,
                rel_type: "REL".into(),
                properties: crate::PropertyMap::share(BTreeMap::new()),
            }),
            "[:REL]",
        ),
        // A vector renders as its value constructor: the coordinate type is
        // `vector()`'s argument, never a `NOT NULL` type expression
        // (TypeConversion4 [3], StringInterpolation [1.10]).
        (
            Value::Vector {
                coord: VectorCoordKind::Int8,
                values: vec![Value::Int(1), Value::Int(2)].into(),
            },
            "vector([1, 2], 2, INTEGER8)",
        ),
    ];
    for (input, expected) in cases {
        assert_eq!(input.to_display_string(), expected, "input {input:?}");
    }
}

#[test]
fn vector_literal_is_a_value_constructor() {
    let vector = |coord, values: Vec<Value>| Value::Vector {
        coord,
        values: values.into(),
    };
    assert_eq!(
        vector(VectorCoordKind::Int8, vec![Value::Int(1), Value::Int(2)]).to_cypher_literal(),
        "vector([1, 2], 2, INTEGER8)"
    );
    assert_eq!(
        vector(
            VectorCoordKind::Float32,
            vec![Value::Float(1.0), Value::Float(2.5)]
        )
        .to_cypher_literal(),
        "vector([1.0, 2.5], 2, FLOAT32)"
    );
    assert_eq!(
        vector(VectorCoordKind::BFloat16, vec![Value::Float(257.0)]).to_cypher_literal(),
        "vector([257.0], 1, BFLOAT16)"
    );
}

/// The one float policy at the old vector-only `1e16` boundary: the
/// scalar, literal and display forms agree, and the decimal spelling parses
/// back to the same value (the scientific form is not needed to
/// round-trip).
#[test]
fn float_literal_policy_is_shared_by_scalars_and_vector_coordinates() {
    assert_eq!(float_literal(1.0), "1.0");
    assert_eq!(float_literal(1.5), "1.5");
    assert_eq!(float_literal(1.0e16), "10000000000000000.0");
    assert_eq!(float_literal(9.007199254740992e15), "9007199254740992.0");
    assert_eq!(float_literal(f64::NAN), "NaN");
    assert_eq!(float_literal(f64::INFINITY), "Infinity");
    assert_eq!(float_literal(f64::NEG_INFINITY), "-Infinity");
    for value in [1.0e16, 9.007199254740992e15, 1.7976931348623157e308] {
        assert_eq!(
            float_literal(value).parse::<f64>().expect("round-trips"),
            value
        );
    }
    let vector = Value::Vector {
        coord: VectorCoordKind::Float64,
        values: vec![Value::Float(1.0e16)].into(),
    };
    assert_eq!(
        vector.to_cypher_literal(),
        "vector([10000000000000000.0], 1, FLOAT)"
    );
    assert_eq!(vector.to_display_string(), vector.to_cypher_literal());
}

// CIP-271: labels print alphabetically, and every name position whose
// spelling is not a plain identifier is backticked — the labels/types/keys
// of the spec's worked examples.
#[test]
fn to_display_string_quotes_special_names_and_sorts_labels() {
    let node = |labels: &[&str]| {
        Value::from_node(Node {
            id: 1,
            labels: Arc::new(labels.iter().map(|l| (*l).to_string()).collect()),
            properties: crate::PropertyMap::share(BTreeMap::new()),
        })
    };
    // A node created as (:B:A:`special label`) renders sorted, with only the
    // name that needs escaping quoted.
    assert_eq!(
        node(&["B", "A", "special label"]).to_display_string(),
        "(:A:B:`special label`)"
    );
    assert_eq!(node(&["X"]).to_display_string(), "(:X)");
    let rel = Value::from_relationship(Relationship {
        id: 2,
        start: 1,
        end: 3,
        rel_type: "REL TYPE".into(),
        properties: crate::PropertyMap::share(BTreeMap::new()),
    });
    assert_eq!(rel.to_display_string(), "[:`REL TYPE`]");
    // A map prints sorted, and only the keys outside the plain identifier
    // shape are backticked.
    let map = Value::Map(
        [
            ("first name".to_string(), Value::String("Alice".into())),
            ("123".to_string(), Value::String("digit key".into())),
            ("a.b".to_string(), Value::String("dot".into())),
            ("z".to_string(), Value::Int(1)),
        ]
        .into_iter()
        .collect::<BTreeMap<_, _>>()
        .into(),
    );
    assert_eq!(
        map.to_display_string(),
        "{`123`: digit key, `a.b`: dot, `first name`: Alice, z: 1}"
    );
}

// CIP-271 / TypeConversion4 [6][8][10]: `toString(path)` is the bare
// traversal chain — no enclosing `<…>` and no properties — while the
// round-trippable literal keeps both. Verified against Neo4j 2026.10.1:
// `toString(p)` of (:A {name:'a'})-[:FIRST]->(:B)<-[:SECOND]-(:C) is
// `(:A)-[:FIRST]->(:B)<-[:SECOND]-(:C)`.
#[test]
fn to_display_string_of_a_path_is_the_bare_traversal_chain() {
    let node = |id, label: &str| Node {
        id,
        labels: Arc::new(vec![label.into()]),
        properties: crate::PropertyMap::share(BTreeMap::from([(
            "name".into(),
            Value::String(label.to_ascii_lowercase().into()),
        )])),
    };
    let rel = |id, start, end, ty: &str| Relationship {
        id,
        start,
        end,
        rel_type: ty.into(),
        properties: crate::PropertyMap::share(BTreeMap::from([("w".into(), Value::Int(1))])),
    };
    // The second relationship is traversed backwards.
    let path = Value::from_path(Path {
        nodes: vec![node(1, "A"), node(2, "B"), node(3, "C")],
        rels: vec![rel(10, 1, 2, "FIRST"), rel(11, 3, 2, "SECOND")],
    });
    assert_eq!(
        path.to_display_string(),
        "(:A)-[:FIRST]->(:B)<-[:SECOND]-(:C)"
    );
    assert_eq!(
        path.to_cypher_literal(),
        "<(:A {name: 'a'})-[:FIRST {w: 1}]->(:B {name: 'b'})<-[:SECOND {w: 1}]-(:C {name: 'c'})>"
    );
    // A zero-length path is its single node.
    let single = Value::from_path(Path {
        nodes: vec![node(1, "A")],
        rels: vec![],
    });
    assert_eq!(single.to_display_string(), "(:A)");
    // `toStringList([path])` renders the same bare chain.
    let list = Value::List(vec![path].into());
    assert_eq!(
        list.to_display_string(),
        "[(:A)-[:FIRST]->(:B)<-[:SECOND]-(:C)]"
    );
}

// ADR-0170: cloning a String, List, Map or Vector shares its payload.
#[test]
fn clone_shares_arc_payloads() {
    let s = Value::String("shared".into());
    let (Value::String(a), Value::String(b)) = (&s, &s.clone()) else {
        panic!("clone changed the variant");
    };
    assert!(Arc::ptr_eq(a, b));

    let list = Value::List(vec![Value::Int(1), Value::String("x".into())].into());
    let (Value::List(a), Value::List(b)) = (&list, &list.clone()) else {
        panic!("clone changed the variant");
    };
    assert!(Arc::ptr_eq(a, b));

    let map = Value::Map(BTreeMap::from([("k".to_string(), Value::Int(1))]).into());
    let (Value::Map(a), Value::Map(b)) = (&map, &map.clone()) else {
        panic!("clone changed the variant");
    };
    assert!(Arc::ptr_eq(a, b));

    let vector = Value::Vector {
        coord: VectorCoordKind::Float32,
        values: vec![Value::Float(1.0), Value::Float(2.0)].into(),
    };
    let (Value::Vector { values: a, .. }, Value::Vector { values: b, .. }) =
        (&vector, &vector.clone())
    else {
        panic!("clone changed the variant");
    };
    assert!(Arc::ptr_eq(a, b));
}

#[test]
fn int_float_eq() {
    assert!(Value::Int(1).eq_non_null(&Value::Float(1.0)));
    assert_eq!(Value::Int(1).cypher_eq(&Value::Null), Value::Null);
}

#[test]
fn int_float_eq_and_compare_are_exact_past_2_pow_53() {
    // 2^53 + 1 is an exact i64 but rounds to 2^53 as an f64; a lossy
    // `(a as f64) == b` cast (the old code) called these EQUAL.
    let big = Value::Int(9_007_199_254_740_993);
    let near = Value::Float(9_007_199_254_740_992.0);
    assert!(!big.eq_non_null(&near));
    assert!(!near.eq_non_null(&big));
    assert_eq!(big.cypher_eq(&near), Value::Bool(false));
    // Ordering agrees: the integer sits strictly above the float.
    assert_eq!(big.compare(&near), Some(Ordering::Greater));
    assert_eq!(near.compare(&big), Some(Ordering::Less));
    // The float DOES equal/compare-equal the integer it exactly denotes.
    let exact = Value::Int(9_007_199_254_740_992);
    assert!(exact.eq_non_null(&near));
    assert_eq!(exact.compare(&near), Some(Ordering::Equal));
    // Small values keep `1 = 1.0`, `0.0 = -0.0`.
    assert!(Value::Int(1).eq_non_null(&Value::Float(1.0)));
    assert!(Value::Int(0).eq_non_null(&Value::Float(-0.0)));
    assert_eq!(
        Value::Int(1).compare(&Value::Float(1.5)),
        Some(Ordering::Less)
    );
    assert_eq!(
        Value::Int(2).compare(&Value::Float(1.5)),
        Some(Ordering::Greater)
    );
    // i64::MAX is not 2^63 (which is out of the exact-integer range).
    assert!(!Value::Int(i64::MAX).eq_non_null(&Value::Float(9_223_372_036_854_775_808.0)));
    assert_eq!(
        Value::Int(i64::MAX).compare(&Value::Float(9_223_372_036_854_775_808.0)),
        Some(Ordering::Less)
    );
}

#[test]
fn vector_eq_is_elementwise_numeric() {
    // Same rule as the List arm and as the equivalence keys: vector
    // elements compare by mathematical value, so an Int element matches
    // the Float it denotes. A derived `av == bv` (the old code) was
    // variant-strict and disagreed with DISTINCT/GROUP BY.
    let int_backed = Value::Vector {
        coord: VectorCoordKind::Float64,
        values: vec![Value::Int(1)].into(),
    };
    let float_backed = Value::Vector {
        coord: VectorCoordKind::Float64,
        values: vec![Value::Float(1.0)].into(),
    };
    assert!(int_backed.eq_non_null(&float_backed));
    assert!(float_backed.eq_non_null(&int_backed));
    // ... including the exact large-magnitude rule elementwise.
    let big_int_backed = Value::Vector {
        coord: VectorCoordKind::Float64,
        values: vec![Value::Int(9_007_199_254_740_993)].into(),
    };
    let near_float_backed = Value::Vector {
        coord: VectorCoordKind::Float64,
        values: vec![Value::Float(9_007_199_254_740_992.0)].into(),
    };
    assert!(!big_int_backed.eq_non_null(&near_float_backed));
    // Different values and different coordinate kinds stay unequal.
    let two = Value::Vector {
        coord: VectorCoordKind::Float64,
        values: vec![Value::Float(2.0)].into(),
    };
    assert!(!int_backed.eq_non_null(&two));
    let other_kind = Value::Vector {
        coord: VectorCoordKind::Int32,
        values: vec![Value::Int(1)].into(),
    };
    assert!(!int_backed.eq_non_null(&other_kind));
}

#[test]
fn logical_bytes_string_header() {
    assert_eq!(Value::String("abc".into()).logical_bytes(), 19);
    assert_eq!(Value::Int(1).logical_bytes(), 8);
}

fn logical_bytes_cases() -> Vec<(Value, u64)> {
    let node = Node {
        id: 1,
        labels: Arc::new(vec!["L".into()]),
        properties: crate::PropertyMap::share(BTreeMap::from([(
            "name".into(),
            Value::String("x".into()),
        )])),
    };
    let rel = Relationship {
        id: 2,
        start: 1,
        end: 1,
        rel_type: "R".into(),
        properties: crate::PropertyMap::share(BTreeMap::from([("w".into(), Value::Float(0.5))])),
    };
    vec![
        (Value::Null, 1),
        (Value::Bool(true), 1),
        (Value::Int(1), 8),
        (Value::Float(1.0), 8),
        (Value::String("abc".into()), 19),
        (
            Value::List(vec![Value::Int(1), Value::String("ab".into())].into()),
            16 + 8 + 18,
        ),
        (
            Value::Map(BTreeMap::from([("k".into(), Value::Int(1))]).into()),
            16 + 17 + 8,
        ),
        (Value::from_node(node.clone()), 17 + 20 + 17),
        (Value::from_relationship(rel.clone()), 17 + 17 + 8),
        (
            Value::from_path(Path {
                nodes: vec![node.clone(), node],
                rels: vec![rel],
            }),
            54 + 54 + 42,
        ),
        (Value::Uuid(7), 16),
        (
            Value::Vector {
                coord: VectorCoordKind::Float64,
                values: vec![Value::Float(1.0), Value::Float(2.0)].into(),
            },
            16 + 16,
        ),
    ]
}

#[test]
fn logical_bytes_formula_is_pinned_per_variant() {
    for (value, expected) in logical_bytes_cases() {
        assert_eq!(value.logical_bytes(), expected, "{value:?}");
    }
}

// The budgeted walk shares the formula: it reports exceeded exactly when
// the summed `logical_bytes()` is over the limit (ADR-0341).
#[test]
fn logical_bytes_within_agrees_with_logical_bytes() {
    let cases = logical_bytes_cases();
    for (value, bytes) in &cases {
        assert_eq!(
            logical_bytes_within([value], *bytes),
            Some(*bytes),
            "{value:?}"
        );
        assert_eq!(logical_bytes_within([value], bytes - 1), None, "{value:?}");
    }
    let total: u64 = cases.iter().map(|(_, bytes)| bytes).sum();
    assert_eq!(
        logical_bytes_within(cases.iter().map(|(v, _)| v), total),
        Some(total)
    );
    assert_eq!(
        logical_bytes_within(cases.iter().map(|(v, _)| v), total - 1),
        None
    );
    assert_eq!(logical_bytes_within([], 0), Some(0));
}

// ADR-0311: the within-budget walk returns the exact sum while it fits and
// `None` once the total passes the limit.
#[test]
fn logical_bytes_within_returns_the_sum_under_the_limit() {
    let cases = logical_bytes_cases();
    let total: u64 = cases.iter().map(|(_, bytes)| bytes).sum();
    let values = || cases.iter().map(|(v, _)| v);
    assert_eq!(logical_bytes_within(values(), total), Some(total));
    assert_eq!(logical_bytes_within(values(), total - 1), None);
    assert_eq!(logical_bytes_within([], 0), Some(0));
}

// 40 rounds of self-sharing give 2^40 logical leaves in 41 allocations;
// an unbounded sum would take hours, the budgeted walk stops after about
// a mebibyte of leaves.
#[test]
fn logical_bytes_within_stops_once_over_budget() {
    let mut x = Value::Int(1);
    for _ in 0..40 {
        x = Value::List(vec![x.clone(), x].into());
    }
    let started = std::time::Instant::now();
    assert_eq!(logical_bytes_within([&x], 1 << 20), None);
    assert!(
        started.elapsed() < std::time::Duration::from_secs(1),
        "budgeted walk took {:?}",
        started.elapsed()
    );
}

#[test]
fn list_map_three_valued_eq() {
    assert_eq!(
        Value::List(vec![Value::Null].into()).cypher_eq(&Value::List(vec![Value::Int(1)].into())),
        Value::Null
    );
    assert_eq!(
        Value::List(vec![Value::Int(1)].into()).cypher_eq(&Value::List(vec![Value::Int(2)].into())),
        Value::Bool(false)
    );
    let mut a = BTreeMap::new();
    a.insert("k".into(), Value::Null);
    assert_eq!(
        Value::Map(a.clone().into()).cypher_eq(&Value::Map(a.into())),
        Value::Null
    );
}

#[test]
fn tagged_roundtrip() {
    let v = Value::List(vec![Value::Int(1), Value::String("a".into())].into());
    let j = v.to_json_tagged();
    assert_eq!(Value::from_json_tagged(&j).unwrap(), v);

    let point = Value::Point(PointValue::cartesian_3d(1.0, 2.0, 3.0));
    assert_eq!(
        Value::from_json_tagged(&point.to_json_tagged()).unwrap(),
        point
    );
    let vector = Value::Vector {
        coord: VectorCoordKind::Int32,
        values: vec![Value::Int(1), Value::Int(2)].into(),
    };
    assert_eq!(
        Value::from_json_tagged(&vector.to_json_tagged()).unwrap(),
        vector
    );
}

#[test]
fn order_by_type_rank() {
    assert_eq!(
        Value::List(vec![Value::Int(1), Value::Int(2)].into()).order_by_cmp(&Value::Int(1)),
        Ordering::Less
    );
    assert_eq!(
        Value::String("a".into()).order_by_cmp(&Value::Int(1)),
        Ordering::Less
    );
    assert_eq!(
        Value::List(vec![Value::Null, Value::Int(1)].into())
            .order_by_cmp(&Value::List(vec![Value::Null, Value::Int(2)].into())),
        Ordering::Less
    );
}

/// ORDER BY / coll.sort order the temporal kinds among themselves, in the
/// live Neo4j 2026.10.1 sequence ZONED DATETIME < LOCAL DATETIME < DATE <
/// ZONED TIME < LOCAL TIME < DURATION (value-independent; `coll.sort` and
/// `ORDER BY` agree).
#[test]
fn order_by_temporal_kind_ranks() {
    use crate::temporal::Temporal;
    use chrono::{NaiveDate, NaiveDateTime, NaiveTime};

    let date = NaiveDate::from_ymd_opt(2023, 5, 24).unwrap();
    let time = NaiveTime::from_hms_opt(2, 2, 2).unwrap();
    let ordered = [
        Value::Temporal(Temporal::DateTime {
            utc: NaiveDateTime::new(date, time),
            offset: 0,
            zone: None,
        }),
        Value::Temporal(Temporal::LocalDateTime(NaiveDateTime::new(date, time))),
        Value::Temporal(Temporal::Date(date)),
        Value::Temporal(Temporal::Time { time, offset: 0 }),
        Value::Temporal(Temporal::LocalTime(time)),
        Value::Temporal(Temporal::Duration {
            months: 0,
            days: 0,
            nanos: 3 * 3_600 * 1_000_000_000,
        }),
    ];
    for pair in ordered.windows(2) {
        assert_eq!(
            pair[0].order_by_cmp(&pair[1]),
            Ordering::Less,
            "{} < {}",
            pair[0],
            pair[1]
        );
        assert_eq!(pair[1].order_by_cmp(&pair[0]), Ordering::Greater);
    }
    // The whole block still sits between POINT and STRING.
    let point = Value::Point(PointValue::cartesian_2d(0.5, 0.5));
    assert_eq!(point.order_by_cmp(&ordered[0]), Ordering::Less);
    assert_eq!(
        ordered[ordered.len() - 1].order_by_cmp(&Value::String("a".into())),
        Ordering::Less
    );
}

#[test]
fn uuid_compare_and_order() {
    // CIP-246: comparison operators do NOT order UUIDs -- only equality is
    // defined, so a distinct pair is incomparable (NULL), while an equal
    // pair is `Equal` (so `>=`/`<=` hold). ORDER BY / min / max DO order
    // them by numeric value.
    let a = Value::Uuid(0x0000_0000_0000_0000_0000_0000_0000_000a);
    let b = Value::Uuid(0x0000_0000_0000_0000_0000_0000_0000_000b);
    assert_eq!(a.compare(&b), None);
    assert_eq!(b.compare(&a), None);
    assert_eq!(a.compare(&a), Some(Ordering::Equal));
    assert!(a.eq_non_null(&a));
    // A list of incomparable UUIDs is incomparable too.
    assert_eq!(
        Value::List(vec![a.clone()].into()).compare(&Value::List(vec![b.clone()].into())),
        None
    );
    // ORDER BY uses order_by_cmp, which must not fall back to Equal.
    assert_eq!(a.order_by_cmp(&b), Ordering::Less);
    assert_eq!(b.order_by_cmp(&a), Ordering::Greater);
    // Rank: BOOLEAN < UUID < NUMBER (CIP-246's `true < uuid < 1`).
    assert_eq!(Value::Bool(true).order_by_cmp(&a), Ordering::Less);
    assert_eq!(
        a.order_by_cmp(&Value::Int(1)),
        Ordering::Less,
        "UUID ranks below every number"
    );
    // min()/max() are `.min_by`/`.max_by` over order_by_cmp (see
    // execute aggregate); sorting is the equivalent core-level check.
    let mut xs = vec![b.clone(), a.clone()];
    xs.sort_by(Value::order_by_cmp);
    assert_eq!(xs, vec![a.clone(), b.clone()]);
    assert_eq!(xs.iter().min_by(|x, y| x.order_by_cmp(y)).unwrap(), &a);
    assert_eq!(xs.iter().max_by(|x, y| x.order_by_cmp(y)).unwrap(), &b);
}

#[test]
fn uuid_parse_is_strict_and_case_insensitive() {
    // Canonical lowercase parses, and round-trips through the renderer.
    let id = "f066ecfc-5151-4121-8a36-b35e00d72918";
    let u = uuid_parse(id).unwrap();
    assert_eq!(uuid_hyphenated(u), id);
    // Uppercase hex is accepted and equals the lowercase parse.
    assert_eq!(uuid_parse(&id.to_ascii_uppercase()), Some(u));

    // Strictness: exactly 8-4-4-4-12 hex groups, four hyphens, nothing
    // before or after -- any deviation is rejected.
    for bad in [
        "",
        "f066ecfc-5151-4121-8a36-b35e00d7291", // too short (last group)
        "f066ecfc-5151-4121-8a36-b35e00d729188", // too long (last group)
        "f066ecfc5151-4121-8a36-b35e00d72918", // missing first hyphen
        "f066ecfc-51514121-8a36-b35e00d72918", // hyphen in wrong place
        "f066ecfc-5151-4121-8a36-b35e00d7291g", // non-hex digit
        "f066ecfc-5151-4121-8a36-b35e00d72918-", // trailing hyphen
        " f066ecfc-5151-4121-8a36-b35e00d72918", // leading space
    ] {
        assert_eq!(uuid_parse(bad), None, "uuid_parse accepted {bad:?}");
    }
}

#[test]
fn cypher_literal_string() {
    assert_eq!(
        Value::String("o'reilly".into()).to_cypher_literal(),
        "'o\\'reilly'"
    );
}

#[test]
fn from_json_tagged_rejects_malformed_payloads() {
    use serde_json::json;
    // Tag without a matching `v` payload must not silently default.
    assert!(Value::from_json_tagged(&json!({"t": "bool"})).is_err());
    assert!(Value::from_json_tagged(&json!({"t": "int"})).is_err());
    assert!(Value::from_json_tagged(&json!({"t": "int", "v": "nope"})).is_err());
    assert!(Value::from_json_tagged(&json!({"t": "float"})).is_err());
    assert!(Value::from_json_tagged(&json!({"t": "float", "v": "1.5"})).is_err());
    assert!(Value::from_json_tagged(&json!({"t": "string"})).is_err());
    assert!(Value::from_json_tagged(&json!({"t": "list"})).is_err());
    assert!(Value::from_json_tagged(&json!({"t": "list", "v": {}})).is_err());
    assert!(Value::from_json_tagged(&json!({"t": "map"})).is_err());
    assert!(Value::from_json_tagged(&json!({"t": "map", "v": []})).is_err());
    assert!(Value::from_json_tagged(&json!({"t": "point"})).is_err());
    assert!(Value::from_json_tagged(&json!({"t": "point", "v": {"srid": 4326}})).is_err());
    assert!(Value::from_json_tagged(&json!({"t": "vector", "coord": "float32"})).is_err());
    assert!(Value::from_json_tagged(&json!({"t": "vector", "v": []})).is_err());
    assert!(Value::from_json_tagged(&json!({"t": "date"})).is_err());
    assert!(Value::from_json_tagged(&json!({"t": "date", "v": 7})).is_err());
    // Unknown tags are errors, not Null.
    assert!(Value::from_json_tagged(&json!({"t": "bogus", "v": 1})).is_err());
    assert!(Value::from_json_tagged(&json!({"v": 1})).is_err());
    assert!(Value::from_json_tagged(&json!(7)).is_err());
    // Well-formed payloads still decode.
    assert_eq!(
        Value::from_json_tagged(&json!({"t": "int", "v": 7})).unwrap(),
        Value::Int(7)
    );
    assert!(matches!(
        Value::from_json_tagged(&json!({"t": "float", "v": "NaN"})).unwrap(),
        Value::Float(f) if f.is_nan()
    ));
    assert_eq!(
        Value::from_json_tagged(&json!({"t": "list", "v": []})).unwrap(),
        Value::List(vec![].into())
    );
    assert_eq!(
        Value::from_json_tagged(&json!({"t": "map", "v": {}})).unwrap(),
        Value::Map(Default::default())
    );
    assert!(matches!(
        Value::from_json_tagged(&json!({"t": "point", "v": {"srid": 4326, "x": 1.0, "y": 2.0}}))
            .unwrap(),
        Value::Point(_)
    ));
}

#[test]
fn from_json_scalars_keeps_type_tags_as_map_keys() {
    use serde_json::json;
    let wire = json!({"_type": "node", "id": 5, "nested": {"_type": "point", "x": 1}});
    let Value::Map(m) = Value::from_json_scalars(&wire) else {
        panic!("scalars decoder returned a non-map");
    };
    assert_eq!(m.get("_type"), Some(&Value::String("node".into())));
    assert_eq!(m.get("id"), Some(&Value::Int(5)));
    let Value::Map(nested) = m.get("nested").unwrap() else {
        panic!("nested object was not a map");
    };
    assert_eq!(nested.get("_type"), Some(&Value::String("point".into())));
    assert!(matches!(
        Value::from_json_plain(&json!({"_type": "node", "id": 5})),
        Value::Node(_)
    ));
}

// The tagged WAL/checkpoint encoder rejects graph entities instead of
// silently writing a null tag; `to_json_tagged` maps that internal
// error to Null.
#[test]
fn tagged_encoder_rejects_graph_entities() {
    let node = Value::from_node(Node {
        id: 1,
        labels: Arc::new(vec!["L".into()]),
        properties: crate::PropertyMap::share(BTreeMap::new()),
    });
    let rel = Value::from_relationship(Relationship {
        id: 2,
        start: 1,
        end: 1,
        rel_type: "R".into(),
        properties: crate::PropertyMap::share(BTreeMap::new()),
    });
    let path = Value::from_path(Path {
        nodes: vec![],
        rels: vec![],
    });
    for v in [&node, &rel, &path] {
        let err = serde_json::to_value(v).expect_err("entity must not encode");
        assert_eq!(
            err.to_string(),
            "graph entity is not a persistence property"
        );
        assert_eq!(v.to_json_tagged(), serde_json::Value::Null);
    }
    // Nested inside a property container, the error propagates.
    let nested = Value::List(vec![node].into());
    assert!(serde_json::to_value(&nested).is_err());
}

// The Path arm renders each element through the node/relationship
// helpers directly; the output shape is unchanged.
#[test]
fn to_json_plain_path_renders_elements_directly() {
    let node = Node {
        id: 1,
        labels: Arc::new(vec!["L".into()]),
        properties: crate::PropertyMap::share(BTreeMap::from([(
            "name".into(),
            Value::String("x".into()),
        )])),
    };
    let rel = Relationship {
        id: 2,
        start: 1,
        end: 1,
        rel_type: "R".into(),
        properties: crate::PropertyMap::share(BTreeMap::new()),
    };
    let path = Value::from_path(Path {
        nodes: vec![node],
        rels: vec![rel],
    });
    assert_eq!(
        path.to_json_plain(),
        serde_json::json!({
            "_type": "path",
            "nodes": [
                {"_type": "node", "id": 1, "labels": ["L"], "properties": {"name": "x"}}
            ],
            "relationships": [
                {"_type": "relationship", "id": 2, "start": 1, "end": 1, "type": "R",
                 "properties": {}}
            ],
        })
    );
}

// The single `_type` probe: unknown tags and a "vector" with an
// invalid coordinate type fall through to a plain map.
#[test]
fn from_json_plain_falls_through_to_map() {
    use serde_json::json;
    let Value::Map(m) = Value::from_json_plain(&json!({"_type": "bogus", "id": 1})) else {
        panic!("unknown _type did not fall through to a map");
    };
    assert_eq!(m.get("id"), Some(&Value::Int(1)));
    assert_eq!(m.get("_type"), Some(&Value::String("bogus".into())));
    let Value::Map(m) =
        Value::from_json_plain(&json!({"_type": "vector", "coordinateType": "bogus"}))
    else {
        panic!("invalid vector did not fall through to a map");
    };
    assert_eq!(m.get("_type"), Some(&Value::String("vector".into())));
}

// ADR-0327: the statement-scoped byte array. Byte-wise equality and
// ordering, its own ORDER BY rank right after LIST, the String logical-size
// formula, BINARY as the column type, and the LIST<INTEGER> crossing
// shared by the literal, plain-JSON and `value_to_cypher` renderings.
#[test]
fn bytes_value_semantics() {
    let bytes = |b: &[u8]| Value::Bytes(b.into());
    let ints = |b: &[i64]| Value::List(b.iter().map(|&x| Value::Int(x)).collect::<Vec<_>>().into());

    assert_eq!(
        bytes(&[0, 1, 255]).cypher_eq(&bytes(&[0, 1, 255])),
        Value::Bool(true)
    );
    assert_eq!(
        bytes(&[0, 1]).cypher_eq(&bytes(&[0, 2])),
        Value::Bool(false)
    );
    assert_eq!(bytes(&[0, 1]).cypher_eq(&ints(&[0, 1])), Value::Bool(false));
    assert_eq!(bytes(&[1]).cypher_eq(&Value::Null), Value::Null);

    assert_eq!(
        bytes(&[1, 2]).compare(&bytes(&[1, 3])),
        Some(Ordering::Less)
    );
    assert_eq!(
        bytes(&[1, 2]).compare(&bytes(&[1])),
        Some(Ordering::Greater)
    );
    assert_eq!(bytes(&[1]).compare(&ints(&[1])), None);
    // LIST < BYTES < PATH-ranked values < STRING.
    assert_eq!(ints(&[9]).order_by_cmp(&bytes(&[0])), Ordering::Less);
    assert_eq!(
        bytes(&[255]).order_by_cmp(&Value::String("a".into())),
        Ordering::Less
    );

    assert_eq!(bytes(&[1, 2, 3]).logical_bytes(), 16 + 3);
    assert_eq!(crate::column_type_name(&bytes(&[1])), "BINARY");
    assert_eq!(bytes(&[0, 1, 255]).to_cypher_literal(), "[0, 1, 255]");
    assert_eq!(bytes(&[]).to_display_string(), "[]");
    assert_eq!(
        bytes(&[0, 255]).to_json_plain(),
        serde_json::json!([0, 255])
    );
    assert_eq!(
        crate::value_to_cypher(&bytes(&[0, 255])),
        relate_model::CypherValue::List(vec![
            relate_model::CypherValue::Int(0),
            relate_model::CypherValue::Int(255),
        ])
    );
}

// ADR-0327: the tagged WAL/checkpoint encoder has no byte-array tag; it
// rejects a byte array, also nested, instead of writing a null tag.
#[test]
fn tagged_encoder_rejects_byte_arrays() {
    let value = Value::Bytes(vec![1].into());
    let err = serde_json::to_value(&value).expect_err("bytes must not encode");
    assert_eq!(err.to_string(), "byte array is not a persistence property");
    assert!(serde_json::to_value(Value::List(vec![value].into())).is_err());
}

// Maps have a total order (size, then sorted keys, then values), so the
// comparison operators answer instead of every map pair being incomparable
// (TCK TernaryComparisonAcceptance).
#[test]
fn maps_compare_by_size_then_sorted_keys_then_values() {
    let m = |pairs: &[(&str, Value)]| {
        Value::Map(
            pairs
                .iter()
                .map(|(k, v)| ((*k).to_string(), v.clone()))
                .collect::<BTreeMap<_, _>>()
                .into(),
        )
    };
    assert_eq!(
        m(&[("k", Value::Int(42))]).compare(&m(&[("k", Value::Int(43))])),
        Some(Ordering::Less)
    );
    assert_eq!(
        m(&[("k", Value::Int(42))]).compare(&m(&[("k", Value::Int(42))])),
        Some(Ordering::Equal)
    );
    // A differing key decides the order without inspecting values.
    assert_eq!(
        m(&[("k1", Value::Int(42))]).compare(&m(&[("k2", Value::Null)])),
        Some(Ordering::Less)
    );
    // A null value under a shared key makes the comparison null.
    assert_eq!(
        m(&[("k", Value::Int(42))]).compare(&m(&[("k", Value::Null)])),
        None
    );
    // Size first: one entry orders before two, whatever the keys.
    assert_eq!(
        m(&[("z", Value::Int(9))]).compare(&m(&[("a", Value::Int(1)), ("b", Value::Int(2))])),
        Some(Ordering::Less)
    );
    // Across types a map stays incomparable.
    assert_eq!(m(&[("k", Value::Int(1))]).compare(&Value::Int(1)), None);
}

/// C7: the point accessor answers the same typed `no such component`
/// rejection as the temporal accessor (never a silently null read), and both
/// coordinate spellings of one axis read the same coordinate — the shared
/// axis vocabulary beside `PointValue`.
#[test]
fn point_component_reads_axis_aliases_and_rejects_unknown_keys() {
    let p = PointValue::wgs84_3d(-73.9857, 40.7484, 8.0);
    assert_eq!(point_component(&p, "x").unwrap(), Value::Float(-73.9857));
    assert_eq!(
        point_component(&p, "longitude").unwrap(),
        Value::Float(-73.9857)
    );
    assert_eq!(point_component(&p, "y").unwrap(), Value::Float(40.7484));
    assert_eq!(
        point_component(&p, "latitude").unwrap(),
        Value::Float(40.7484)
    );
    assert_eq!(point_component(&p, "z").unwrap(), Value::Float(8.0));
    assert_eq!(point_component(&p, "height").unwrap(), Value::Float(8.0));
    assert_eq!(
        point_component(&p, "crs").unwrap(),
        Value::String("wgs-84-3d".into())
    );
    assert_eq!(point_component(&p, "srid").unwrap(), Value::Int(4979));
    // 22G03: an unknown component is an invalid-argument rejection.
    assert_eq!(
        point_component(&p, "foo").unwrap_err(),
        Error::argument_error("no such component 'foo' on a point value")
    );
}