8000 fix(executor): order strings lexicographically in comparison predicates by rnewman · Pull Request #312 · project-minigraf/minigraf · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## Unreleased

### Bug fixes

- **String comparison in predicates**: `[(< ?a ?b)]`, `>`, `<=` and `>=` now order two strings lexicographically instead of failing. Previously every ordering predicate routed through `to_float_pair`, which errors on non-numeric operands, so a string comparison silently matched no rows — and because both directions returned nothing, a range filter dropped the entire relation rather than partitioning it. This most often bit ISO-8601 timestamps stored as strings. The predicate path now agrees with `value_lt` / `value_cmp`, which `min`, `max` and `:order-by` already use. Mixed-type comparison (string vs number) remains an error, and NaN comparisons remain false.

## v1.2.1 — 2026-06-28

Drop-in replacement for v1.2.0. No file-format changes, no public API changes.
Expand Down
116 changes: 107 additions & 9 deletions src/query/datalog/executor.rs
10BC8
Original file line number Diff line number Diff line change
Expand Up @@ -2178,16 +2178,30 @@ fn eval_binop(op: &BinOp, l: Value, r: Value) -> Result<Value, ()> {
}

match op {
// Numeric comparisons — require both numeric; int/float promotion via to_float_pair.
// Ordering comparisons. Strings order lexicographically, matching value_lt /
// value_cmp — which min/max and :order-by already use — so the same two strings
// order the same way whether compared by a predicate or by an aggregate.
// Numbers order numerically with int/float promotion via to_float_pair.
// Mixed types (string vs number) remain a type error.
BinOp::Lt | BinOp::Gt | BinOp::Lte | BinOp::Gte => {
let (lf, rf) = to_float_pair(&l, &r)?;
Ok(Value::Boolean(match op {
BinOp::Lt => lf < rf,
BinOp::Gt => lf > rf,
BinOp::Lte => lf <= rf,
BinOp::Gte => lf >= rf,
#[allow(clippy::unreachable)]
_ => unreachable!(),
let ordering = match (&l, &r) {
(Value::String(a), Value::String(b)) => Some(a.cmp(b)),
// None when either operand is NaN: every ordering against NaN is false.
_ => {
let (lf, rf) = to_float_pair(&l, &r)?;
lf.partial_cmp(&rf)
}
};
Ok(Value::Boolean(match ordering {
None => false,
Some(ord) => match op {
BinOp::Lt => ord.is_lt(),
BinOp::Gt => ord.is_gt(),
BinOp::Lte => ord.is_le(),
BinOp::Gte => ord.is_ge(),
#[allow(clippy::unreachable)]
_ => unreachable!(),
},
}))
}

Expand Down Expand Up @@ -4098,6 +4112,90 @@ mod expr_eval_tests {
assert_eq!(eval_expr(&e, &HashMap::new(), None), Err(()));
}

/// Evaluate `a <op> b` for two string literals.
fn eval_str_cmp(op: BinOp, a: &str, b: &str) -> Result<Value, ()> {
eval_expr(
&Expr::BinOp(
op,
Box::new(Expr::Lit(Value::String(a.to_string()))),
Box::new(Expr::Lit(Value::String(b.to_string()))),
),
&HashMap::new(),
None,
)
}

#[test]
fn test_eval_string_comparison_is_lexicographic() {
assert_eq!(
eval_str_cmp(BinOp::Lt, "apple", "banana"),
Ok(Value::Boolean(true))
);
assert_eq!(
eval_str_cmp(BinOp::Lt, "banana", "apple"),
Ok(Value::Boolean(false))
);
assert_eq!(
eval_str_cmp(BinOp::Gt, "banana", "apple"),
Ok(Value::Boolean(true))
);
}

#[test]
fn test_eval_string_comparison_equal_operands() {
// Strict comparisons are false and non-strict are true for equal strings.
assert_eq!(
eval_str_cmp(BinOp::Lt, "same", "same"),
Ok(Value::Boolean(false))
);
assert_eq!(
eval_str_cmp(BinOp::Gt, "same", "same"),
Ok(Value::Boolean(false))
);
assert_eq!(
eval_str_cmp(BinOp::Lte, "same", "same"),
Ok(Value::Boolean(true))
);
assert_eq!(
eval_str_cmp(BinOp::Gte, "same", "same"),
Ok(Value::Boolean(true))
);
}

#[test]
fn test_eval_string_comparison_totality() {
// Regression: both directions returned no match, so a range filter silently
// dropped every row instead of partitioning them. Exactly one must hold.
let lt = eval_str_cmp(BinOp::Lt, "2025-05-06", "2026-01-01");
let gte = eval_str_cmp(BinOp::Gte, "2025-05-06", "2026-01-01");
assert_eq!(lt, Ok(Value::Boolean(true)), "earlier date sorts first");
assert_eq!(gte, Ok(Value::Boolean(false)), "and not the other way");
}

#[test]
fn test_eval_nan_comparison_is_false() {
// Unchanged by the string arm: every ordering against NaN stays false.
let e = Expr::BinOp(
BinOp::Lt,
Box::new(Expr::Lit(Value::Float(f64::NAN))),
Box::new(Expr::Lit(Value::Float(1.0))),
);
assert_eq!(
eval_expr(&e, &HashMap::new(), None),
Ok(Value::Boolean(false))
);

let e = Expr::BinOp(
BinOp::Gte,
Box::new(Expr::Lit(Value::Float(f64::NAN))),
Box::new(Expr::Lit(Value::Float(1.0))),
);
assert_eq!(
eval_expr(&e, &HashMap::new(), None),
Ok(Value::Boolean(false))
);
}

#[test]
fn test_eval_string_q_true() {
let e = Expr::UnaryOp(
Expand Down
67 changes: 67 additions & 0 deletions tests/predicate_expr_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -382,3 +382,70 @@ fn test_arithmetic_binding_into_sum_aggregate() {
totals.sort_unstable();
assert_eq!(totals, vec![20, 30]);
}

// ── String comparison filters ─────────────────────────────────────────────────

#[test]
fn test_string_comparison_filters_lexicographically() {
let db = open();
db.execute(r#"(transact [[:a :name "alice"] [:b :name "bob"] [:c :name "carol"]])"#)
.expect("transact");
let r = db
.execute(r#"(query [:find ?e :where [?e :name ?n] [(< ?n "c")]])"#)
.expect("query");
assert_eq!(count(r), 2, "alice and bob sort before \"c\"");
}

#[test]
fn test_string_range_partitions_all_rows() {
// Regression: ordering predicates on strings matched nothing, so both halves of a
// range came back empty rather than summing to the whole relation.
let db = open();
db.execute(
r#"(transact [[:e1 :at "2025-05-06T19:30:00-07:00"]
[:e2 :at "2026-06-11T19:30:00-07:00"]])"#,
)
.expect("transact");

let before = db
.execute(r#"(query [:find ?d :where [?e :at ?d] [(< ?d "2026-01-01")]])"#)
.expect("query");
let after = db
.execute(r#"(query [:find ?d :where [?e :at ?d] [(>= ?d "2026-01-01")]])"#)
.expect("query");

assert_eq!(count(before), 1, "one event before the boundary");
assert_eq!(count(after), 1, "one event on or after it");
}

#[test]
fn test_string_comparison_agrees_with_min_aggregate() {
// The predicate path and the aggregate path must order strings the same way.
let db = open();
db.execute(r#"(transact [[:a :name "alice"] [:b :name "bob"]])"#)
.expect("transact");

let rs = rows(
db.execute(r#"(query [:find (min ?n) :where [?e :name ?n]])"#)
.expect("query"),
);
assert_eq!(rs.len(), 1);
assert_eq!(rs[0][0], MgValue::String("alice".to_string()));

let r = db
.execute(r#"(query [:find ?n :where [?e :name ?n] [(<= ?n "alice")]])"#)
.expect("query");
assert_eq!(count(r), 1, "the minimum is <= itself and nothing else is");
}

#[test]
fn test_string_vs_number_comparison_is_still_an_error() {
// Mixed-type ordering remains unsupported — the row is filtered, not coerced.
let db = open();
db.execute(r#"(transact [[:a :name "alice"]])"#)
.expect("transact");
let r = db
.execute(r#"(query [:find ?n :where [?e :name ?n] [(< ?n 100)]])"#)
.expect("query");
assert_eq!(count(r), 0, "string vs integer yields no rows");
}
Loading
0