cqlite-core 0.15.0

Core engine for CQLite — read Apache Cassandra 5.0 SSTables locally without a cluster
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
//! Value comparison and arithmetic helpers for the SELECT executor.
//!
//! Pure functions over [`Value`] shared by predicate evaluation, sorting,
//! aggregation, and constant folding. They were previously inline in
//! `select_executor.rs`; centralising them keeps one copy of the comparison and
//! arithmetic semantics across every execution path.

use super::super::select_ast::{ArithmeticOperator, ComparisonOperator};
use crate::{types::Value, Error, Result};

/// Compare two `Value`s for equality, including limited cross-type numeric
/// coercion (int↔bigint, int↔float, bigint↔float).
///
/// `Value` implements `PartialEq` natively but only matches identical variants;
/// we additionally treat the small set of cross-numeric cases that show up in
/// CQL predicates.
pub(super) fn values_equal(a: &Value, b: &Value) -> bool {
    if a == b {
        return true;
    }
    // Integer-vs-integer must compare as the widest native integer (`i128`),
    // NEVER via `as_f64` (issue #2231): two distinct `i64` above 2^53 collapse
    // to the same `f64` mantissa, so an f64 fallback would report them equal and
    // — because a fully-translated Trino conjunct is removed from the plan — leak
    // rows Trino would drop. Every CQL integral type fits losslessly in `i128`.
    if let (Some(x), Some(y)) = (as_integral_i128(a), as_integral_i128(b)) {
        return x == y;
    }
    // Otherwise coerce only when both operands are numeric — a genuine float on
    // at least one side. Non-numeric pairs (e.g. Text vs Integer) must not
    // spuriously compare equal via `as_f64`.
    if same_numeric_family(a, b) {
        if let (Some(x), Some(y)) = (a.as_f64(), b.as_f64()) {
            return x == y;
        }
    }
    false
}

/// The exact integer value of an integral CQL numeric `Value`, or `None` for
/// float/non-numeric variants. Widened to `i128` so every integral type
/// (`tinyint`..`bigint`, `counter`) is represented losslessly, enabling exact
/// integer equality/comparison without an `f64` round-trip (issue #2231).
pub(super) fn as_integral_i128(v: &Value) -> Option<i128> {
    match v {
        Value::Integer(i) => Some(*i as i128),
        Value::BigInt(i) => Some(*i as i128),
        Value::Counter(i) => Some(*i as i128),
        Value::TinyInt(i) => Some(*i as i128),
        Value::SmallInt(i) => Some(*i as i128),
        _ => None,
    }
}

/// True when `v` is an IEEE floating-point value that is NaN (CQL `float`/
/// `double`). Predicate (WHERE) evaluation uses this to implement SQL
/// three-valued logic: any relational comparison (`<`, `<=`, `>`, `>=`) with a
/// NaN operand is UNKNOWN, so the row is dropped (issue #2231). Only the `float`
/// variants can be NaN — integral types never are, so this is principled, not a
/// bit-pattern heuristic.
pub(in crate::query) fn is_nan_value(v: &Value) -> bool {
    match v {
        Value::Float(x) => x.is_nan(),
        Value::Float32(x) => x.is_nan(),
        _ => false,
    }
}

/// True when both `Value`s are numeric variants eligible for cross-type coercion.
pub(super) fn same_numeric_family(a: &Value, b: &Value) -> bool {
    a.as_f64().is_some() && b.as_f64().is_some()
}

/// Compare two `Value`s for ordering, returning `Ordering::Equal` for
/// incomparable variants. Used by sorting/aggregation paths that historically
/// swallowed comparison errors via `unwrap_or(0)`.
pub(super) fn compare_values_ordering(a: &Value, b: &Value) -> std::cmp::Ordering {
    try_compare_values(a, b).unwrap_or(std::cmp::Ordering::Equal)
}

/// Compare two `Value`s for ordering, returning an error when the operand
/// types are not comparable. Preferred in WHERE-clause evaluation so users see
/// a real diagnostic rather than a silent equality.
///
/// Cross-type numerics are coerced via `f64` first; same-variant comparisons
/// fall back to `Value::partial_cmp`. We deliberately avoid `partial_cmp` for
/// non-matching variants because it stringifies and would produce surprising
/// orderings (e.g. `Text("9")` < `Text("10")` lexicographically).
pub(super) fn try_compare_values(a: &Value, b: &Value) -> Result<std::cmp::Ordering> {
    if same_numeric_family(a, b) {
        if let (Some(x), Some(y)) = (a.as_f64(), b.as_f64()) {
            // Cassandra/Java `Double.compare` total order: NaN last, -0.0 < +0.0
            // (issues #1870, #2010). Never `partial_cmp().unwrap_or(Equal)`,
            // which collapses NaN and signed zeros to Equal.
            return Ok(crate::float_cmp::cassandra_double_cmp(x, y));
        }
    }
    if std::mem::discriminant(a) == std::mem::discriminant(b) {
        return a.partial_cmp(b).ok_or_else(|| {
            Error::query_execution("Cannot compare incompatible types".to_string())
        });
    }
    // Data-safety (issue #1694): log the operand TYPES, never their values.
    tracing::debug!(
        "Cannot compare values of incompatible types: {:?} vs {:?}",
        a.data_type(),
        b.data_type()
    );
    Err(Error::query_execution(
        "Cannot compare incompatible types".to_string(),
    ))
}

/// Relational comparison for PREDICATE (WHERE) evaluation, with SQL
/// three-valued logic for IEEE NaN AND exact-integer ordering above the f64
/// precision boundary.
///
/// Returns `Ok(None)` — SQL UNKNOWN, so the caller DROPS the row — when either
/// operand is a NaN float. Cassandra's total order (`cassandra_double_cmp`, used
/// by `try_compare_values`/`compare_values_ordering`) sorts NaN as the GREATEST
/// value, which would make `d > 1.5` TRUE for `d = NaN` and leak rows Trino
/// would drop once the conjunct is pushed down and removed from the plan (issue
/// #2231).
///
/// When both operands are integral (mirroring `values_equal`'s own structure),
/// compares them as exact `i128` BEFORE any f64 fallback: two distinct `i64`
/// above 2^53 collapse to the same f64 mantissa, so `bigcol > 9007199254740992`
/// against a row where `bigcol = 9007199254740993` would otherwise compare
/// `Equal` via `cassandra_double_cmp` and wrongly evaluate `is_gt()` to `false`
/// — the same leak-once-pushed-down mechanism as the `=` divergence.
///
/// This function is for filter/`WHERE` evaluation ONLY — do NOT use it for
/// ORDER BY / MIN / MAX / clustering-key ordering, which must keep the
/// NaN-greatest total order and existing f64-based numeric ordering
/// (`try_compare_values`/`compare_values_ordering`, unchanged).
pub(super) fn try_compare_values_predicate(
    a: &Value,
    b: &Value,
) -> Result<Option<std::cmp::Ordering>> {
    if is_nan_value(a) || is_nan_value(b) {
        return Ok(None);
    }
    if let (Some(x), Some(y)) = (as_integral_i128(a), as_integral_i128(b)) {
        return Ok(Some(x.cmp(&y)));
    }
    try_compare_values(a, b).map(Some)
}

/// `compare_values_ordering` counterpart for predicate evaluation: routes
/// through [`try_compare_values_predicate`] so it shares BOTH predicate-only
/// fixes (issue #2231) — NaN → `None` (SQL UNKNOWN → drop the row) and exact
/// `i128` integer ordering above the f64 precision boundary — then swallows any
/// remaining comparison error to `Ordering::Equal`, matching
/// `compare_values_ordering`'s error-tolerant behaviour for non-NaN,
/// non-integral pairs. Used by the SSTable leaf-predicate evaluator's
/// inequalities so neither a NaN nor a large `bigint` pair is mishandled.
pub(super) fn compare_values_ordering_predicate(
    a: &Value,
    b: &Value,
) -> Option<std::cmp::Ordering> {
    match try_compare_values_predicate(a, b) {
        Ok(ordering) => ordering,
        Err(_) => Some(std::cmp::Ordering::Equal),
    }
}

/// Evaluate a scalar `ComparisonOperator` (`=`, `!=`, `<`, `<=`, `>`, `>=`)
/// over two already-evaluated operands with SQL PREDICATE semantics (issue
/// #2231). Shared by the expression-pushdown WHERE evaluator so equality uses
/// exact integer comparison (`values_equal`, no `f64` collapse above 2^53) and
/// the four inequalities treat a NaN operand as UNKNOWN → `false` (row dropped),
/// never NaN-greatest. Non-scalar operators (`IN`, `LIKE`, `IS [NOT] NULL`, …)
/// have their own branches and are rejected here.
pub(super) fn eval_scalar_comparison(
    op: &ComparisonOperator,
    left: &Value,
    right: &Value,
) -> Result<bool> {
    use ComparisonOperator::*;
    Ok(match op {
        Equal => values_equal(left, right),
        NotEqual => !values_equal(left, right),
        LessThan => try_compare_values_predicate(left, right)?.is_some_and(|o| o.is_lt()),
        LessThanOrEqual => try_compare_values_predicate(left, right)?.is_some_and(|o| o.is_le()),
        GreaterThan => try_compare_values_predicate(left, right)?.is_some_and(|o| o.is_gt()),
        GreaterThanOrEqual => try_compare_values_predicate(left, right)?.is_some_and(|o| o.is_ge()),
        other => {
            return Err(Error::query_execution(format!(
                "operator {:?} is not a scalar comparison",
                other
            )))
        }
    })
}

/// Apply an `ArithmeticOperator` to two same-typed numeric `Value`s.
///
/// Behaviour matches the previous inline implementations: same-type only
/// (no implicit coercion), and division/modulo by zero are reported as
/// query-execution errors. Float division-by-zero (matching the original
/// runtime path) yields IEEE inf/NaN rather than an error.
pub(super) fn eval_arithmetic(op: &ArithmeticOperator, left: Value, right: Value) -> Result<Value> {
    use ArithmeticOperator::*;
    macro_rules! int_op {
        ($a:expr, $b:expr, $ctor:expr) => {
            match op {
                Add => Ok($ctor($a + $b)),
                Subtract => Ok($ctor($a - $b)),
                Multiply => Ok($ctor($a * $b)),
                Divide => {
                    if $b == 0 {
                        Err(Error::query_execution("Division by zero".to_string()))
                    } else {
                        Ok($ctor($a / $b))
                    }
                }
                Modulo => {
                    if $b == 0 {
                        Err(Error::query_execution("Modulo by zero".to_string()))
                    } else {
                        Ok($ctor($a % $b))
                    }
                }
            }
        };
    }
    match (left, right) {
        (Value::Integer(a), Value::Integer(b)) => int_op!(a, b, Value::Integer),
        (Value::BigInt(a), Value::BigInt(b)) => int_op!(a, b, Value::BigInt),
        (Value::Float(a), Value::Float(b)) => match op {
            Add => Ok(Value::Float(a + b)),
            Subtract => Ok(Value::Float(a - b)),
            Multiply => Ok(Value::Float(a * b)),
            Divide => Ok(Value::Float(a / b)),
            Modulo => Ok(Value::Float(a % b)),
        },
        _ => Err(Error::query_execution(
            "Incompatible types for arithmetic".to_string(),
        )),
    }
}

/// Constant-folding arithmetic. Same operand-type rules as `eval_arithmetic`,
/// plus BigInt support and per-operator error wording matching the legacy
/// implementation (e.g. `"Cannot add incompatible types"` and
/// `"Modulo only supported for integers"`).
pub(super) fn const_arithmetic(
    op: &ArithmeticOperator,
    left: Value,
    right: Value,
) -> Result<Value> {
    use ArithmeticOperator::*;

    // Modulo's error wording is special: any non-integer combination must
    // report `"Modulo only supported for integers"` regardless of which side
    // is offending.
    if matches!(op, Modulo) {
        return match (left, right) {
            (Value::Integer(a), Value::Integer(b)) => {
                eval_arithmetic(op, Value::Integer(a), Value::Integer(b))
            }
            (Value::BigInt(a), Value::BigInt(b)) => {
                eval_arithmetic(op, Value::BigInt(a), Value::BigInt(b))
            }
            _ => Err(Error::query_execution(
                "Modulo only supported for integers".to_string(),
            )),
        };
    }

    let verb = match op {
        Add => "add",
        Subtract => "subtract",
        Multiply => "multiply",
        Divide => "divide",
        Modulo => unreachable!("handled above"),
    };

    match (left, right) {
        (Value::Integer(a), Value::Integer(b)) => {
            eval_arithmetic(op, Value::Integer(a), Value::Integer(b))
        }
        (Value::BigInt(a), Value::BigInt(b)) => {
            eval_arithmetic(op, Value::BigInt(a), Value::BigInt(b))
        }
        (Value::Float(a), Value::Float(b)) => {
            // Constant Float Divide rejects 0.0 (legacy behaviour); runtime
            // Float divide does not. Modulo on Float is rejected above.
            if matches!(op, Divide) && b == 0.0 {
                return Err(Error::query_execution("Division by zero".to_string()));
            }
            eval_arithmetic(op, Value::Float(a), Value::Float(b))
        }
        _ => Err(Error::query_execution(format!(
            "Cannot {} incompatible types",
            verb
        ))),
    }
}

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

    #[test]
    fn test_value_comparison() {
        use std::cmp::Ordering;
        assert_eq!(
            try_compare_values(&Value::Integer(5), &Value::Integer(3)).unwrap(),
            Ordering::Greater
        );
        assert_eq!(
            try_compare_values(&Value::Integer(3), &Value::Integer(5)).unwrap(),
            Ordering::Less
        );
        assert_eq!(
            try_compare_values(&Value::Integer(5), &Value::Integer(5)).unwrap(),
            Ordering::Equal
        );
    }

    /// Issue #2231, divergence 2: `values_equal` distinguishes two DISTINCT
    /// `i64` values straddling the 2^53 f64-precision boundary. An `as_f64`
    /// fallback would round both to the same mantissa and report them equal,
    /// leaking rows once a `bigcol = ...` conjunct is pushed down and removed
    /// from the Trino plan.
    #[test]
    fn values_equal_distinguishes_large_i64_across_f64_boundary() {
        let two53 = 1_i64 << 53; // 9_007_199_254_740_992
        let plus1 = two53 + 1; // 9_007_199_254_740_993 (not representable as f64)
                               // Sanity: the two integers DO collapse to the same f64.
        assert_eq!(
            two53 as f64, plus1 as f64,
            "precondition: f64 collapses them"
        );

        // The exact-integer comparison must keep them distinct.
        assert!(
            !values_equal(&Value::BigInt(two53), &Value::BigInt(plus1)),
            "2^53 != 2^53 + 1 as bigint"
        );
        assert!(
            values_equal(&Value::BigInt(plus1), &Value::BigInt(plus1)),
            "identical large bigints are equal"
        );
        // Repro operand: bigcol = 9_007_199_254_740_993 must NOT match 992.
        assert!(!values_equal(
            &Value::BigInt(9_007_199_254_740_992),
            &Value::BigInt(9_007_199_254_740_993),
        ));

        // Cross-integral-type equality still holds (int == bigint numerically).
        assert!(values_equal(&Value::Integer(7), &Value::BigInt(7)));
        assert!(values_equal(&Value::TinyInt(7), &Value::SmallInt(7)));
        assert!(!values_equal(&Value::Integer(7), &Value::BigInt(8)));
        // Integer-vs-float equality still coerces (genuine float on one side).
        assert!(values_equal(&Value::BigInt(2), &Value::Float(2.0)));
        assert!(!values_equal(&Value::BigInt(2), &Value::Float(2.5)));
    }

    /// Issue #2231 follow-up (roborev blocker): `try_compare_values_predicate` /
    /// `compare_values_ordering_predicate` must ALSO compare large integers
    /// exactly — not just `values_equal`. Without the `as_integral_i128`
    /// short-circuit, `bigcol > 9007199254740992` against a row where
    /// `bigcol = 9007199254740993` would coerce both to the same f64 mantissa,
    /// compare `Equal`, and wrongly evaluate `is_gt()` to `false` (row dropped).
    #[test]
    fn predicate_ordering_distinguishes_large_i64_across_f64_boundary() {
        use std::cmp::Ordering;
        let two53 = 1_i64 << 53; // 9_007_199_254_740_992
        let plus1 = two53 + 1; // 9_007_199_254_740_993

        // ...993 > ...992 must hold exactly (f64 would report Equal).
        assert_eq!(
            try_compare_values_predicate(&Value::BigInt(plus1), &Value::BigInt(two53)).unwrap(),
            Some(Ordering::Greater),
            "9007199254740993 > 9007199254740992 must hold exactly"
        );
        assert_eq!(
            compare_values_ordering_predicate(&Value::BigInt(plus1), &Value::BigInt(two53)),
            Some(Ordering::Greater)
        );
        // The symmetric direction: ...992 is NOT greater than ...993.
        assert_eq!(
            try_compare_values_predicate(&Value::BigInt(two53), &Value::BigInt(plus1)).unwrap(),
            Some(Ordering::Less)
        );
        // Equal large integers still compare Equal.
        assert_eq!(
            try_compare_values_predicate(&Value::BigInt(plus1), &Value::BigInt(plus1)).unwrap(),
            Some(Ordering::Equal)
        );
    }

    /// Issue #2231, divergence 1: under PREDICATE (WHERE) semantics a NaN
    /// operand makes every relational comparison UNKNOWN, so the row is dropped.
    /// Historically only `Lt`/`Lte`/`Eq` dropped NaN while `Gt`/`Gte` leaked it
    /// (NaN sorts greatest under `cassandra_double_cmp`); all four inequalities
    /// must now drop it, and `Eq` continues to.
    #[test]
    fn nan_predicate_comparison_is_unknown_for_all_relations() {
        let nan = Value::Float(f64::NAN);
        let bound = Value::Float(1.5);

        // `d > 1.5` / `d >= 1.5` with d = NaN: previously TRUE (leak), now dropped.
        let cmp = try_compare_values_predicate(&nan, &bound).unwrap();
        assert!(cmp.is_none(), "NaN vs 1.5 is UNKNOWN (Gt/Gte)");
        assert!(
            !cmp.is_some_and(|o| o.is_gt()),
            "d > 1.5 with NaN is dropped"
        );
        assert!(
            !cmp.is_some_and(|o| o.is_ge()),
            "d >= 1.5 with NaN is dropped"
        );
        // Lt/Lte were already consistent (dropped) — confirm they stay dropped.
        assert!(
            !cmp.is_some_and(|o| o.is_lt()),
            "d < 1.5 with NaN is dropped"
        );
        assert!(
            !cmp.is_some_and(|o| o.is_le()),
            "d <= 1.5 with NaN is dropped"
        );
        // NaN on the right-hand side is symmetric.
        assert!(try_compare_values_predicate(&bound, &nan)
            .unwrap()
            .is_none());
        // Two NaNs are also UNKNOWN under predicate comparison.
        assert!(try_compare_values_predicate(&nan, &nan).unwrap().is_none());
        // Float32 (CQL `float`) NaN behaves identically.
        assert!(
            try_compare_values_predicate(&Value::Float32(f32::NAN), &Value::Float32(1.5))
                .unwrap()
                .is_none()
        );

        // Eq already dropped NaN (no NaN-aware equality) — confirm unchanged.
        assert!(!values_equal(&nan, &bound), "NaN = 1.5 is false");
        assert!(!values_equal(&nan, &nan), "NaN = NaN is false (SQL)");

        // Non-NaN floats keep normal ordering under predicate comparison.
        let ok = try_compare_values_predicate(&Value::Float(2.0), &bound).unwrap();
        assert!(ok.is_some_and(|o| o.is_gt()), "2.0 > 1.5 holds");
    }

    /// Issue #2231: the NaN-drop is scoped to PREDICATE comparison only — the
    /// total-order comparator (`compare_values_ordering`, used by ORDER BY /
    /// MIN / MAX / clustering) must STILL sort NaN as the greatest value.
    #[test]
    fn nan_ordering_total_order_unchanged_by_predicate_fix() {
        use std::cmp::Ordering;
        assert_eq!(
            compare_values_ordering(&Value::Float(f64::NAN), &Value::Float(1.5)),
            Ordering::Greater,
            "sort order still puts NaN last (unchanged)"
        );
        // The predicate variant agrees for non-NaN but diverges (None) on NaN.
        assert_eq!(
            compare_values_ordering_predicate(&Value::Float(2.0), &Value::Float(1.5)),
            Some(Ordering::Greater)
        );
        assert!(
            compare_values_ordering_predicate(&Value::Float(f64::NAN), &Value::Float(1.5))
                .is_none()
        );
    }

    /// `eval_scalar_comparison` dispatches each of the 6 scalar operators to the
    /// right predicate-semantics comparator (issue #2231's `mod.rs` expression
    /// path calls this directly, so its per-operator wiring deserves its own
    /// direct test rather than only transitive coverage).
    #[test]
    fn eval_scalar_comparison_dispatches_all_six_operators() {
        use ComparisonOperator::*;
        let five = Value::Integer(5);
        let three = Value::Integer(3);

        assert!(!eval_scalar_comparison(&Equal, &five, &three).unwrap());
        assert!(eval_scalar_comparison(&Equal, &five, &five).unwrap());
        assert!(eval_scalar_comparison(&NotEqual, &five, &three).unwrap());
        assert!(!eval_scalar_comparison(&NotEqual, &five, &five).unwrap());
        assert!(eval_scalar_comparison(&GreaterThan, &five, &three).unwrap());
        assert!(!eval_scalar_comparison(&GreaterThan, &three, &five).unwrap());
        assert!(eval_scalar_comparison(&GreaterThanOrEqual, &five, &five).unwrap());
        assert!(!eval_scalar_comparison(&GreaterThanOrEqual, &three, &five).unwrap());
        assert!(eval_scalar_comparison(&LessThan, &three, &five).unwrap());
        assert!(!eval_scalar_comparison(&LessThan, &five, &three).unwrap());
        assert!(eval_scalar_comparison(&LessThanOrEqual, &five, &five).unwrap());
        assert!(!eval_scalar_comparison(&LessThanOrEqual, &five, &three).unwrap());

        // A non-scalar operator is rejected rather than silently mishandled.
        assert!(eval_scalar_comparison(&In, &five, &three).is_err());
    }

    /// The query ordering comparator (used by ORDER BY / MIN / MAX) must match
    /// Cassandra/Java `Double.compare`: NaN last, -0.0 < +0.0 (issues #1870/#2010).
    #[test]
    fn compare_values_ordering_double_matches_cassandra() {
        use std::cmp::Ordering;
        let f = Value::Float; // f64 → CQL `double`
        assert_eq!(
            compare_values_ordering(&f(f64::NAN), &f(f64::INFINITY)),
            Ordering::Greater,
            "NaN sorts after +Infinity"
        );
        assert_eq!(
            compare_values_ordering(&f(f64::NAN), &f(f64::NAN)),
            Ordering::Equal,
            "two NaNs compare equal"
        );
        assert_eq!(
            compare_values_ordering(&f(-0.0), &f(0.0)),
            Ordering::Less,
            "-0.0 < +0.0"
        );
        assert_eq!(compare_values_ordering(&f(1.0), &f(2.0)), Ordering::Less);
    }

    /// Sorting `Value::Float` keys yields the Cassandra oracle order
    /// `[-Inf, -0.0, +0.0, 1.0, +Inf, NaN, NaN]`.
    #[test]
    fn order_by_double_sort_matches_oracle() {
        let mut v = vec![
            Value::Float(1.0),
            Value::Float(f64::NAN),
            Value::Float(-0.0),
            Value::Float(0.0),
            Value::Float(f64::NEG_INFINITY),
            Value::Float(f64::INFINITY),
            Value::Float(f64::NAN),
        ];
        v.sort_by(compare_values_ordering);
        let f = |i: usize| match v[i] {
            Value::Float(x) => x,
            _ => unreachable!(),
        };
        assert_eq!(f(0), f64::NEG_INFINITY);
        assert!(f(1) == 0.0 && f(1).is_sign_negative(), "index 1 = -0.0");
        assert!(f(2) == 0.0 && f(2).is_sign_positive(), "index 2 = +0.0");
        assert_eq!(f(3), 1.0);
        assert_eq!(f(4), f64::INFINITY);
        assert!(f(5).is_nan() && f(6).is_nan(), "NaNs sort last");
    }

    /// `Value::Float32` (CQL `float`) shares the same ordering semantics.
    #[test]
    fn order_by_float32_sort_matches_oracle() {
        let mut v = [
            Value::Float32(f32::NAN),
            Value::Float32(0.0),
            Value::Float32(-0.0),
            Value::Float32(f32::INFINITY),
        ];
        v.sort_by(compare_values_ordering);
        let f = |i: usize| match v[i] {
            Value::Float32(x) => x,
            _ => unreachable!(),
        };
        assert!(f(0) == 0.0 && f(0).is_sign_negative(), "index 0 = -0.0");
        assert!(f(1) == 0.0 && f(1).is_sign_positive(), "index 1 = +0.0");
        assert_eq!(f(2), f32::INFINITY);
        assert!(f(3).is_nan(), "NaN sorts last");
    }

    /// MIN/MAX (aggregation uses `compare_values_ordering`): MIN over signed
    /// zeros selects -0.0; NaN never wins MIN but is the MAX.
    #[test]
    fn min_max_double_matches_cassandra() {
        let data = [
            Value::Float(f64::NAN),
            Value::Float(3.0),
            Value::Float(-0.0),
            Value::Float(0.0),
            Value::Float(-2.0),
        ];
        let min = data
            .iter()
            .min_by(|a, b| compare_values_ordering(a, b))
            .unwrap();
        assert!(matches!(min, Value::Float(x) if *x == -2.0), "MIN = -2.0");

        let max = data
            .iter()
            .max_by(|a, b| compare_values_ordering(a, b))
            .unwrap();
        assert!(
            matches!(max, Value::Float(x) if x.is_nan()),
            "MAX = NaN (sorts last)"
        );

        // MIN over just the signed zeros picks -0.0.
        let zeros = [Value::Float(0.0), Value::Float(-0.0)];
        let zmin = zeros
            .iter()
            .min_by(|a, b| compare_values_ordering(a, b))
            .unwrap();
        assert!(
            matches!(zmin, Value::Float(x) if *x == 0.0 && x.is_sign_negative()),
            "MIN of {{-0.0, +0.0}} = -0.0"
        );
    }
}