minigraf 1.0.0

Zero-config, single-file, embedded graph database with bi-temporal Datalog queries
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
use serde::{Deserialize, Serialize};
use std::time::{SystemTime, UNIX_EPOCH};
use uuid::Uuid;

// ============================================================================
// Datalog EAV Model (Phase 3+)
// ============================================================================

/// Transaction ID type - milliseconds since UNIX epoch
///
/// We use timestamps as transaction IDs for natural chronological ordering
/// and consistency with bi-temporal valid_time (Phase 4). Millisecond precision
/// is sufficient for Phase 3's single-threaded usage.
pub(crate) type TxId = u64;

/// Get current timestamp as transaction ID (milliseconds since UNIX epoch)
pub(crate) fn tx_id_now() -> TxId {
    #[cfg(all(target_arch = "wasm32", feature = "browser"))]
    {
        // On WASM browser targets, `std::time::SystemTime::now()` panics.
        // Use `js_sys::Date::now()` which returns milliseconds since the Unix
        // epoch as an f64 (same precision as `Date.now()` in JavaScript).
        js_sys::Date::now() as u64
    }
    #[cfg(not(all(target_arch = "wasm32", feature = "browser")))]
    {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("System time before UNIX epoch")
            .as_millis() as u64
    }
}

/// A unique identifier for a graph entity (UUID v4).
///
/// In Datalog syntax, entities are written as keywords (`:alice`, `:person/42`)
/// or as UUID literals (`#uuid "550e8400-e29b-41d4-a716-446655440000"`).
/// `EntityId` values appear in [`Value::Ref`] for cross-entity relationships
/// and are returned in query result rows.
pub type EntityId = Uuid;

/// Attribute name - namespace-qualified keywords like ":person/name" or ":friend"
pub(crate) type Attribute = String;

/// All value types that can be stored in a Minigraf fact.
///
/// Values appear in the third position of EAV triples:
/// `[entity attribute value]`, e.g. `[:alice :person/name "Alice"]`.
///
/// # Datalog literals
///
/// | Variant | Datalog syntax | Example |
/// |---------|---------------|---------|
/// | `String` | double-quoted | `"hello"` |
/// | `Integer` | bare integer | `42`, `-7` |
/// | `Float` | decimal | `3.14`, `-0.5` |
/// | `Boolean` | `true` / `false` | `true` |
/// | `Ref` | keyword entity or UUID | `:alice`, `#uuid "550e8400-..."` |
/// | `Keyword` | colon-prefixed | `:status/active`, `:red` |
/// | `Null` | `nil` | `nil` |
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum Value {
    /// A UTF-8 string. Datalog literal: `"hello"`.
    String(String),
    /// A 64-bit signed integer. Datalog literal: `42` or `-7`.
    Integer(i64),
    /// A 64-bit float. Datalog literal: `3.14` or `-0.5`.
    Float(f64),
    /// A boolean. Datalog literal: `true` or `false`.
    Boolean(bool),
    /// A reference to another entity by its [`EntityId`] (UUID).
    /// Datalog literal: `:alice` (keyword short-form) or `#uuid "..."`.
    Ref(EntityId),
    /// A namespaced keyword used for enumerated values and tags.
    /// Datalog literal: `:status/active`, `:red`.
    Keyword(String),
    /// An absent value. Datalog literal: `nil`.
    Null,
}

impl Eq for Value {}

impl std::hash::Hash for Value {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        std::mem::discriminant(self).hash(state);
        match self {
            Value::String(s) => s.hash(state),
            Value::Integer(i) => i.hash(state),
            Value::Float(f) => {
                if f.is_nan() {
                    0_u8.hash(state);
                } else if f.is_sign_negative() {
                    1_u8.hash(state);
                    (-f).to_bits().hash(state);
                } else {
                    2_u8.hash(state);
                    f.to_bits().hash(state);
                }
            }
            Value::Boolean(b) => b.hash(state),
            Value::Ref(r) => r.hash(state),
            Value::Keyword(k) => k.hash(state),
            Value::Null => {}
        }
    }
}

impl PartialOrd for Value {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

/// Ordering for `Value` variants.
///
/// # NaN Semantics
/// - `NaN` is ordered as **Greater** than all other float values (including positive infinity)
/// - `NaN` equals `NaN` (two NaN values are considered equal)
/// - When comparing a float against a non-float, the float's NaN status determines ordering
///
/// # Cross-Variant Ordering
/// Values of different variants are ordered by discriminant:
/// - String (0) < Integer (1) < Float (2) < Boolean (3) < Ref (4) < Keyword (5) < Null (6)
impl Ord for Value {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // Simple variant ordering using match
        match (self, other) {
            // Same variant - compare inner values
            (Value::String(a), Value::String(b)) => a.cmp(b),
            (Value::Integer(a), Value::Integer(b)) => a.cmp(b),
            (Value::Float(a), Value::Float(b)) => {
                if a.is_nan() && b.is_nan() {
                    std::cmp::Ordering::Equal
                } else if a.is_nan() {
                    std::cmp::Ordering::Greater
                } else if b.is_nan() {
                    std::cmp::Ordering::Less
                } else {
                    a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)
                }
            }
            (Value::Boolean(a), Value::Boolean(b)) => a.cmp(b),
            (Value::Ref(a), Value::Ref(b)) => a.cmp(b),
            (Value::Keyword(a), Value::Keyword(b)) => a.cmp(b),
            (Value::Null, Value::Null) => std::cmp::Ordering::Equal,
            // Different variants — order by a stable integer discriminant so
            // the total order is deterministic and does not depend on stack
            // addresses (the previous implementation used pointer values here,
            // which are non-deterministic and violate Ord's contract).
            _ => {
                fn discriminant(v: &Value) -> u8 {
                    match v {
                        Value::String(_) => 0,
                        Value::Integer(_) => 1,
                        Value::Float(_) => 2,
                        Value::Boolean(_) => 3,
                        Value::Ref(_) => 4,
                        Value::Keyword(_) => 5,
                        Value::Null => 6,
                    }
                }
                discriminant(self).cmp(&discriminant(other))
            }
        }
    }
}

impl Value {
    /// Extract string value if this is a String variant
    pub fn as_string(&self) -> Option<&str> {
        match self {
            Value::String(s) => Some(s),
            _ => None,
        }
    }

    /// Extract integer value if this is an Integer variant
    pub fn as_integer(&self) -> Option<i64> {
        match self {
            Value::Integer(i) => Some(*i),
            _ => None,
        }
    }

    /// Extract float value if this is a Float variant
    pub fn as_float(&self) -> Option<f64> {
        match self {
            Value::Float(f) => Some(*f),
            _ => None,
        }
    }

    /// Extract boolean value if this is a Boolean variant
    pub fn as_boolean(&self) -> Option<bool> {
        match self {
            Value::Boolean(b) => Some(*b),
            _ => None,
        }
    }

    /// Extract entity reference if this is a Ref variant
    pub fn as_ref(&self) -> Option<EntityId> {
        match self {
            Value::Ref(id) => Some(*id),
            _ => None,
        }
    }

    /// Extract keyword if this is a Keyword variant
    pub fn as_keyword(&self) -> Option<&str> {
        match self {
            Value::Keyword(k) => Some(k),
            _ => None,
        }
    }

    /// Check if this value is Null
    pub fn is_null(&self) -> bool {
        matches!(self, Value::Null)
    }
}

/// Sentinel value for open-ended valid time (a fact is valid "forever").
/// Used as the default `valid_to` when no end time is specified.
pub(crate) const VALID_TIME_FOREVER: i64 = i64::MAX;

/// A Datalog fact: (Entity, Attribute, Value) triple with transaction metadata
///
/// This is the core data structure for Phase 3+. Facts are immutable and versioned
/// by transaction ID. Facts are never deleted, only retracted (asserted=false).
///
/// Phase 4 adds bi-temporal fields:
/// - `tx_count`: monotonically incrementing batch counter within a transaction
/// - `valid_from`: when the fact became valid in the real world (millis since epoch)
/// - `valid_to`: when the fact stopped being valid (`VALID_TIME_FOREVER` = open-ended)
///
/// # Examples
/// ```ignore
/// use uuid::Uuid;
/// use crate::graph::types::{Fact, Value};
///
/// // Fact: Alice's name is "Alice"
/// let alice_id = Uuid::new_v4();
/// let fact = Fact::new(
///     alice_id,
///     ":person/name".to_string(),
///     Value::String("Alice".to_string()),
///     1, // transaction ID
/// );
///
/// // Fact: Alice is friends with Bob (reference)
/// let bob_id = Uuid::new_v4();
/// let friendship = Fact::new(
///     alice_id,
///     ":friend".to_string(),
///     Value::Ref(bob_id),
///     2,
/// );
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub(crate) struct Fact {
    /// The entity this fact is about
    pub(crate) entity: EntityId,
    /// The attribute/property name (namespace-qualified, e.g., ":person/name")
    pub(crate) attribute: Attribute,
    /// The value of this attribute
    pub(crate) value: Value,
    /// Transaction ID that asserted or retracted this fact
    pub(crate) tx_id: TxId,
    /// Monotonically incrementing batch counter within a transaction (Phase 4)
    pub(crate) tx_count: u64,
    /// Valid-time start: when the fact became valid in the real world (millis since epoch).
    /// Defaults to `tx_id as i64` (wall-clock time of the transaction).
    pub(crate) valid_from: i64,
    /// Valid-time end: when the fact stopped being valid (millis since epoch).
    /// `VALID_TIME_FOREVER` means the fact is open-ended (still valid).
    pub(crate) valid_to: i64,
    /// True if this fact is asserted, false if retracted.
    /// Retractions are used instead of deletions to maintain history.
    pub(crate) asserted: bool,
}

impl Fact {
    /// Create a new asserted fact with default valid time (valid_from=tx_id, valid_to=FOREVER).
    pub(crate) fn new(entity: EntityId, attribute: Attribute, value: Value, tx_id: TxId) -> Self {
        Fact {
            entity,
            attribute,
            value,
            tx_id,
            tx_count: 0,
            valid_from: tx_id as i64,
            valid_to: VALID_TIME_FOREVER,
            asserted: true,
        }
    }

    /// Create an asserted fact with explicit valid time and tx_count.
    pub(crate) fn with_valid_time(
        entity: EntityId,
        attribute: Attribute,
        value: Value,
        tx_id: TxId,
        tx_count: u64,
        valid_from: i64,
        valid_to: i64,
    ) -> Self {
        Fact {
            entity,
            attribute,
            value,
            tx_id,
            tx_count,
            valid_from,
            valid_to,
            asserted: true,
        }
    }

    /// Create a retraction with default valid time.
    pub(crate) fn retract(
        entity: EntityId,
        attribute: Attribute,
        value: Value,
        tx_id: TxId,
    ) -> Self {
        Fact {
            entity,
            attribute,
            value,
            tx_id,
            tx_count: 0,
            valid_from: tx_id as i64,
            valid_to: VALID_TIME_FOREVER,
            asserted: false,
        }
    }

    /// Check if this is an assertion (not a retraction)
    pub(crate) fn is_asserted(&self) -> bool {
        self.asserted
    }
}

#[cfg(test)]
impl Fact {
    /// Create a fact with explicit asserted flag and default valid time.
    /// Used only in tests.
    #[allow(dead_code)]
    pub(crate) fn with_asserted(
        entity: EntityId,
        attribute: Attribute,
        value: Value,
        tx_id: TxId,
        asserted: bool,
    ) -> Self {
        Fact {
            entity,
            attribute,
            value,
            tx_id,
            tx_count: 0,
            valid_from: tx_id as i64,
            valid_to: VALID_TIME_FOREVER,
            asserted,
        }
    }

    /// Check if this is a retraction. Used only in tests.
    pub(crate) fn is_retracted(&self) -> bool {
        !self.asserted
    }
}

/// Options for controlling valid time on a transact/retract call.
///
/// When `valid_from` is `None`, defaults to the transaction timestamp.
/// When `valid_to` is `None`, defaults to `VALID_TIME_FOREVER` (open-ended).
#[derive(Debug, Clone, Default)]
pub(crate) struct TransactOptions {
    /// Override the valid-time start (millis since epoch). `None` = use tx timestamp.
    pub(crate) valid_from: Option<i64>,
    /// Override the valid-time end (millis since epoch). `None` = open-ended (FOREVER).
    pub(crate) valid_to: Option<i64>,
}

impl TransactOptions {
    pub(crate) fn new(valid_from: Option<i64>, valid_to: Option<i64>) -> Self {
        TransactOptions {
            valid_from,
            valid_to,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Create a TxId from a SystemTime. Test-only helper.
    fn tx_id_from_system_time(time: std::time::SystemTime) -> TxId {
        time.duration_since(std::time::UNIX_EPOCH)
            .expect("System time before UNIX epoch")
            .as_millis() as u64
    }

    #[test]
    fn test_tx_id_timestamp() {
        // Test tx_id_now() returns monotonically increasing values
        let tx1 = tx_id_now();
        std::thread::sleep(std::time::Duration::from_millis(5));
        let tx2 = tx_id_now();

        // tx2 should be after tx1 (monotonicity is what matters)
        assert!(
            tx2 > tx1,
            "Transaction IDs should be chronologically ordered"
        );

        // Test that tx_id_from_system_time produces valid tx_id
        use std::time::SystemTime;
        let now = SystemTime::now();
        let tx_id = tx_id_from_system_time(now);
        // tx_id should be positive (valid timestamp)
        assert!(
            tx_id > 0,
            "tx_id_from_system_time should produce positive value"
        );
    }

    #[test]
    fn test_tx_id_ordering() {
        // TxIds created sequentially should be ordered (monotonicity is what matters, not exact timing)
        let mut tx_ids = vec![];
        for _ in 0..5 {
            tx_ids.push(tx_id_now());
            std::thread::sleep(std::time::Duration::from_millis(1));
        }

        // Verify chronological order
        for i in 1..tx_ids.len() {
            assert!(
                tx_ids[i] > tx_ids[i - 1],
                "TxIds should be strictly increasing"
            );
        }
    }

    #[test]
    fn test_value_creation_and_accessors() {
        // String value
        let string_val = Value::String("Alice".to_string());
        assert_eq!(string_val.as_string(), Some("Alice"));
        assert_eq!(string_val.as_integer(), None);
        assert!(!string_val.is_null());

        // Integer value
        let int_val = Value::Integer(42);
        assert_eq!(int_val.as_integer(), Some(42));
        assert_eq!(int_val.as_string(), None);

        // Float value
        let float_val = Value::Float(4.5);
        assert_eq!(float_val.as_float(), Some(4.5));

        // Boolean value
        let bool_val = Value::Boolean(true);
        assert_eq!(bool_val.as_boolean(), Some(true));

        // Reference value
        let ref_id = Uuid::new_v4();
        let ref_val = Value::Ref(ref_id);
        assert_eq!(ref_val.as_ref(), Some(ref_id));
        assert_eq!(ref_val.as_string(), None);

        // Keyword value
        let keyword_val = Value::Keyword(":person".to_string());
        assert_eq!(keyword_val.as_keyword(), Some(":person"));

        // Null value
        let null_val = Value::Null;
        assert!(null_val.is_null());
        assert_eq!(null_val.as_string(), None);
    }

    #[test]
    fn test_fact_creation() {
        let entity = Uuid::new_v4();
        let fact = Fact::new(
            entity,
            ":person/name".to_string(),
            Value::String("Alice".to_string()),
            1,
        );

        assert_eq!(fact.entity, entity);
        assert_eq!(fact.attribute, ":person/name");
        assert_eq!(fact.value, Value::String("Alice".to_string()));
        assert_eq!(fact.tx_id, 1);
        assert!(fact.is_asserted());
        assert!(!fact.is_retracted());
    }

    #[test]
    fn test_fact_retraction() {
        let entity = Uuid::new_v4();
        let fact = Fact::retract(
            entity,
            ":person/name".to_string(),
            Value::String("Alice".to_string()),
            2,
        );

        assert_eq!(fact.entity, entity);
        assert_eq!(fact.attribute, ":person/name");
        assert_eq!(fact.tx_id, 2);
        assert!(!fact.is_asserted());
        assert!(fact.is_retracted());
    }

    #[test]
    fn test_fact_with_ref_value() {
        let alice = Uuid::new_v4();
        let bob = Uuid::new_v4();

        // Fact: Alice is friends with Bob
        let friendship = Fact::new(alice, ":friend".to_string(), Value::Ref(bob), 1);

        assert_eq!(friendship.entity, alice);
        assert_eq!(friendship.attribute, ":friend");
        assert_eq!(friendship.value.as_ref(), Some(bob));
        assert!(friendship.is_asserted());
    }

    #[test]
    fn test_fact_equality() {
        let entity = Uuid::new_v4();

        let fact1 = Fact::new(
            entity,
            ":person/name".to_string(),
            Value::String("Alice".to_string()),
            1,
        );

        let fact2 = Fact::new(
            entity,
            ":person/name".to_string(),
            Value::String("Alice".to_string()),
            1,
        );

        assert_eq!(fact1, fact2);

        // Different transaction ID = different fact
        let fact3 = Fact::new(
            entity,
            ":person/name".to_string(),
            Value::String("Alice".to_string()),
            2,
        );

        assert_ne!(fact1, fact3);

        // Different tx_count = different fact
        let fact4 = Fact::with_valid_time(
            entity,
            ":person/name".to_string(),
            Value::String("Alice".to_string()),
            1,
            99, // tx_count differs from fact1 (which has tx_count=0)
            1,
            VALID_TIME_FOREVER,
        );

        assert_ne!(fact1, fact4);

        // Different valid_from = different fact
        let fact5 = Fact::with_valid_time(
            entity,
            ":person/name".to_string(),
            Value::String("Alice".to_string()),
            1,
            0,
            9999, // valid_from differs from fact1 (which has valid_from=tx_id=1)
            VALID_TIME_FOREVER,
        );

        assert_ne!(fact1, fact5);

        // Different valid_to = different fact
        let fact6 = Fact::with_valid_time(
            entity,
            ":person/name".to_string(),
            Value::String("Alice".to_string()),
            1,
            0,
            1,
            12345, // valid_to differs from fact1 (which has valid_to=VALID_TIME_FOREVER)
        );

        assert_ne!(fact1, fact6);
    }

    #[test]
    fn test_value_types() {
        let values = vec![
            Value::String("test".to_string()),
            Value::Integer(42),
            Value::Float(4.5),
            Value::Boolean(true),
            Value::Ref(Uuid::new_v4()),
            Value::Keyword(":status/active".to_string()),
            Value::Null,
        ];

        // All values should serialize/deserialize correctly
        for value in values {
            let serialized = serde_json::to_string(&value).unwrap();
            let deserialized: Value = serde_json::from_str(&serialized).unwrap();
            assert_eq!(value, deserialized);
        }
    }

    #[test]
    fn test_fact_has_valid_time_fields() {
        let entity = Uuid::new_v4();
        let fact = Fact::new(
            entity,
            ":person/name".to_string(),
            Value::String("Alice".to_string()),
            1000,
        );
        // Defaults: valid_from = tx_id as i64, valid_to = FOREVER, tx_count = 0
        assert_eq!(fact.valid_from, 1000_i64);
        assert_eq!(fact.valid_to, VALID_TIME_FOREVER);
        assert_eq!(fact.tx_count, 0);
    }

    #[test]
    fn test_fact_with_explicit_valid_time() {
        let entity = Uuid::new_v4();
        let fact = Fact::with_valid_time(
            entity,
            ":employment/status".to_string(),
            Value::Keyword(":active".to_string()),
            1000,
            1,
            1672531200000_i64, // 2023-01-01
            1685577600000_i64, // 2023-06-01
        );
        assert_eq!(fact.valid_from, 1672531200000_i64);
        assert_eq!(fact.valid_to, 1685577600000_i64);
        assert_eq!(fact.tx_count, 1);
    }

    #[test]
    fn test_valid_time_forever_constant() {
        assert_eq!(VALID_TIME_FOREVER, i64::MAX);
    }

    #[test]
    fn test_transact_options_defaults() {
        let opts = TransactOptions::default();
        assert!(opts.valid_from.is_none());
        assert!(opts.valid_to.is_none());
    }

    // Helper used by the cross-variant Ord tests: moves values into a fresh
    // stack frame so the two parameters are always at distinct, consistent
    // addresses independent of the call site.
    fn cmp_values(a: Value, b: Value) -> std::cmp::Ordering {
        a.cmp(&b)
    }

    #[test]
    fn value_ord_cross_variant_is_antisymmetric() {
        // The pointer-address bug causes both cmp_values(A, B) and
        // cmp_values(B, A) to return the same ordering (whichever parameter
        // slot has the lower address "wins" in both calls), violating the
        // antisymmetry requirement for Ord: cmp(a,b) must equal reverse(cmp(b,a)).
        let pairs: &[(Value, Value)] = &[
            (Value::String("hello".into()), Value::Integer(42)),
            (Value::Integer(1), Value::Float(1.0)),
            (Value::Boolean(true), Value::Null),
            (Value::Keyword(":k".into()), Value::String("x".into())),
        ];
        for (a, b) in pairs {
            let forward = cmp_values(a.clone(), b.clone());
            let backward = cmp_values(b.clone(), a.clone());
            assert_eq!(
                forward,
                backward.reverse(),
                "Value::Ord cross-variant comparison must be antisymmetric"
            );
            assert_ne!(
                forward,
                std::cmp::Ordering::Equal,
                "Values of different types must not compare as Equal"
            );
        }
    }

    #[test]
    fn value_ord_cross_variant_is_stable() {
        // Ordering between two fixed variant types must be stable: it should
        // not depend on what the inner value is, only on which variant it is.
        // With the pointer-address bug every allocation is at a different
        // address, so this constraint can be violated non-deterministically.
        let string_lt_integer = cmp_values(Value::String("a".into()), Value::Integer(0));
        for s in ["", "z", "hello world"] {
            for i in [i64::MIN, 0, i64::MAX] {
                let result = cmp_values(Value::String(s.into()), Value::Integer(i));
                assert_eq!(
                    result, string_lt_integer,
                    "Cross-variant ordering must depend only on the variant, not the inner value"
                );
            }
        }
    }
}