Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-gql/tests/gql.rs

//! Each construct against a plain reference on a small graph: fixed edges, labels, WHERE,
//! RETURN with and without DISTINCT, LIMIT, and quantified edges planned as graph walks.

use std::collections::{BTreeMap, BTreeSet, VecDeque};

use kleene_gql::{Catalog, GqlError, Params, Table, lower, lower_with, parse, query, query_with};
use kleene_plan::{Datum, Engine, Facts, Source, Stratum, Type, Way};
use kleene_sparse::{CpuBackend, CpuDevice};

const FUNC: [u64; 7] = [0, 1, 2, 3, 4, 5, 6];
const ENTRY: [u64; 2] = [0, 1];
const LIB: [u64; 3] = [7, 8, 9];
const FILE: [u64; 2] = [10, 11];
const CALLS: [(u64, u64); 11] = [
    (0, 1),
    (1, 2),
    (2, 0),
    (2, 3),
    (3, 7),
    (4, 5),
    (5, 6),
    (6, 4),
    (1, 8),
    (8, 9),
    (9, 9),
];
const IN: [(u64, u64); 5] = [(0, 10), (1, 10), (2, 11), (3, 11), (7, 11)];
const FUNC_SIZE: [(u64, u64); 7] = [(0, 5), (1, 20), (2, 15), (3, 40), (4, 1), (5, 60), (6, 7)];
const LIB_SIZE: [(u64, u64); 3] = [(7, 100), (8, 3), (9, 9)];
/// Some functions only: the others have no depth (a comparison of it is unknown).
const FUNC_DEPTH: [(u64, u64); 4] = [(0, 1), (1, 2), (2, 2), (4, 9)];

fn ones(xs: &[u64]) -> Source {
    Source::Facts(Facts::from_rows(1, xs.iter().map(|&x| [x])).unwrap())
}

fn twos(xs: &[(u64, u64)]) -> Source {
    Source::Facts(Facts::from_rows(2, xs.iter().map(|&(a, b)| [a, b])).unwrap())
}

fn catalog() -> Catalog {
    let mut c = Catalog::new();
    c.label("Func", ones(&FUNC))
        .label("Entry", ones(&ENTRY))
        .label("Lib", ones(&LIB))
        .label("File", ones(&FILE))
        .edge("CALLS", twos(&CALLS))
        .edge("IN", twos(&IN))
        .property("Func", "size", twos(&FUNC_SIZE))
        .property("Lib", "size", twos(&LIB_SIZE))
        .property("Func", "depth", twos(&FUNC_DEPTH))
        .edge_property(
            "CALLS",
            "weight",
            Source::Facts(
                Facts::from_rows(3, CALLS.iter().map(|&(a, b)| [a, b, weight(a, b)])).unwrap(),
            ),
        );
    c
}

/// The weight of call `a -> b`.
fn weight(a: u64, b: u64) -> u64 {
    (a * 3 + b) % 7
}

fn engine() -> Engine<CpuBackend> {
    Engine::new(CpuDevice::new(2))
}

async fn run(text: &str) -> Table {
    query(&engine(), &catalog(), text)
        .await
        .unwrap_or_else(|e| panic!("{text}: {e}"))
}

fn sorted(mut rows: Vec<Vec<u64>>) -> Vec<Vec<u64>> {
    rows.sort_unstable();
    rows
}

fn size(x: u64) -> Option<u64> {
    let in_func = FUNC.contains(&x);
    let table: &[(u64, u64)] = if in_func { &FUNC_SIZE } else { &LIB_SIZE };
    table.iter().find(|p| p.0 == x).map(|p| p.1)
}

/// Nodes reached from `seeds` along `edges` (seeds included).
fn walk(edges: &[(u64, u64)], seeds: &[u64]) -> BTreeSet<u64> {
    let mut seen: BTreeSet<u64> = seeds.iter().copied().collect();
    let mut q: VecDeque<u64> = seeds.iter().copied().collect();
    while let Some(v) = q.pop_front() {
        for &(a, b) in edges {
            if a == v && seen.insert(b) {
                q.push_back(b);
            }
        }
    }
    seen
}

/// Nodes reached from `s` by one edge or more.
fn walk1(s: u64) -> BTreeSet<u64> {
    let next: Vec<u64> = CALLS.iter().filter(|e| e.0 == s).map(|e| e.1).collect();
    walk(&CALLS, &next)
}

fn reversed(edges: &[(u64, u64)]) -> Vec<(u64, u64)> {
    edges.iter().map(|&(a, b)| (b, a)).collect()
}

fn path_strata(text: &str) -> Vec<Stratum> {
    let l = lower(&parse(text).unwrap(), &catalog()).unwrap();
    let strata = l.strata().unwrap();
    strata
        .into_iter()
        .filter(|s| s.relations().iter().any(|r| l.paths.contains(r)))
        .collect()
}

#[tokio::test]
async fn fixed_edges_and_labels() {
    let t = run("MATCH (a:Func)-[:CALLS]->(b:Func) RETURN a, b").await;
    assert_eq!(t.columns, ["a", "b"]);
    let want: Vec<Vec<u64>> = CALLS
        .iter()
        .filter(|(a, b)| FUNC.contains(a) && FUNC.contains(b))
        .map(|&(a, b)| vec![a, b])
        .collect();
    assert_eq!(t.rows, sorted(want));

    // Against the edges: the callers of the entries' callees... reversed.
    let t = run("MATCH (a)<-[:CALLS]-(e:Entry) RETURN DISTINCT a").await;
    let want: BTreeSet<u64> = CALLS
        .iter()
        .filter(|(e, _)| ENTRY.contains(e))
        .map(|e| e.1)
        .collect();
    assert_eq!(t.rows, want.iter().map(|&x| vec![x]).collect::<Vec<_>>());

    // Two edges in a row, anonymous middle.
    let t = run("MATCH (e:Entry)-[:CALLS]->()-[:CALLS]->(c) RETURN DISTINCT c").await;
    let mut want = BTreeSet::new();
    for &(e, m) in &CALLS {
        for &(m2, c) in &CALLS {
            if ENTRY.contains(&e) && m == m2 {
                want.insert(c);
            }
        }
    }
    assert_eq!(t.rows, want.iter().map(|&x| vec![x]).collect::<Vec<_>>());

    // Two labels, another edge label, two patterns sharing a node.
    let t = run("MATCH (x:Lib)-[:IN]->(f:File), (g:Func)-[:CALLS]->(x) RETURN f, x, g").await;
    let mut want = Vec::new();
    for &(x, f) in &IN {
        for &(g, x2) in &CALLS {
            if LIB.contains(&x) && FILE.contains(&f) && x2 == x && FUNC.contains(&g) {
                want.push(vec![f, x, g]);
            }
        }
    }
    assert_eq!(t.rows, sorted(want));
}

#[tokio::test]
async fn where_comparisons() {
    let t = run("MATCH (a:Func)-[:CALLS]->(b:Func) \
         WHERE a.size < b.size AND b.size >= 15 AND a <> 2 \
         RETURN a, b.size AS s")
    .await;
    assert_eq!(t.columns, ["a", "s"]);
    let want: Vec<Vec<u64>> = CALLS
        .iter()
        .filter(|(a, b)| FUNC.contains(a) && FUNC.contains(b))
        .filter(|&&(a, b)| size(a) < size(b) && size(b) >= Some(15) && a != 2)
        .map(|&(a, b)| vec![a, size(b).unwrap()])
        .collect();
    assert!(!want.is_empty());
    assert_eq!(t.rows, sorted(want));

    // Ids compared with constants, both sides; a property of a second label.
    let t = run("MATCH (a)-[:CALLS]->(b:Lib) WHERE 3 <= a AND b.size > 5 RETURN a, b").await;
    let want: Vec<Vec<u64>> = CALLS
        .iter()
        .filter(|&&(a, b)| LIB.contains(&b) && 3 <= a && size(b) > Some(5))
        .map(|&(a, b)| vec![a, b])
        .collect();
    assert_eq!(t.rows, sorted(want));
}

#[tokio::test]
async fn distinct_bag_and_limit() {
    // Without DISTINCT: one row per match (a caller once per callee).
    let t = run("MATCH (a:Func)-[:CALLS]->(b) RETURN a").await;
    let want: Vec<Vec<u64>> = CALLS
        .iter()
        .filter(|(a, _)| FUNC.contains(a))
        .map(|&(a, _)| vec![a])
        .collect();
    assert_eq!(t.rows, sorted(want.clone()));
    let t = run("MATCH (a:Func)-[:CALLS]->(b) RETURN DISTINCT a").await;
    let set: BTreeSet<Vec<u64>> = want.iter().cloned().collect();
    assert_eq!(t.rows, set.iter().cloned().collect::<Vec<_>>());
    assert!(t.rows.len() < want.len());
    // LIMIT: the first rows in order, the same on every run.
    let t = run("MATCH (a:Func)-[:CALLS]->(b) RETURN a LIMIT 3").await;
    assert_eq!(t.rows, sorted(want.clone())[..3].to_vec());
    let t = run("MATCH (a:Func)-[:CALLS]->(b) RETURN DISTINCT a LIMIT 2").await;
    assert_eq!(t.rows, set.iter().take(2).cloned().collect::<Vec<_>>());
    let t = run("MATCH (a:Func)-[:CALLS]->(b) RETURN DISTINCT a LIMIT 0").await;
    assert!(t.rows.is_empty());
}

#[tokio::test]
async fn quantified_edges_as_reach() {
    // From the entries, along the edges, zero or more (GQL *): a BFS from the seeds.
    let q = "MATCH (e:Entry)-[:CALLS]->*(b) RETURN DISTINCT b";
    let t = run(q).await;
    let want = walk(&CALLS, &ENTRY);
    assert_eq!(t.rows, want.iter().map(|&x| vec![x]).collect::<Vec<_>>());
    let s = path_strata(q);
    assert!(
        matches!(
            s[..],
            [Stratum::Reach {
                way: Way::Forward,
                ..
            }]
        ),
        "{s:?}"
    );

    // One or more, in GQL and in Cypher form, seeds by a property.
    let mut from3 = BTreeSet::new();
    for x in walk1(3) {
        if LIB.contains(&x) {
            from3.insert(vec![x]);
        }
    }
    for q in [
        "MATCH (a:Func)-[:CALLS]->+(b:Lib) WHERE a.size = 40 RETURN DISTINCT b",
        "MATCH (a:Func)-[:CALLS*]->(b:Lib) WHERE a.size = 40 RETURN DISTINCT b",
        "MATCH (a:Func)-[:CALLS]->{1,}(b:Lib) WHERE a.size = 40 RETURN DISTINCT b",
    ] {
        let t = run(q).await;
        assert_eq!(t.rows, from3.iter().cloned().collect::<Vec<_>>(), "{q}");
        assert!(matches!(path_strata(q)[..], [Stratum::Reach { .. }]), "{q}");
    }

    // Seeds by a condition on the id alone, one or more.
    let q = "MATCH (a)-[:CALLS]->+(b) WHERE a = 3 RETURN DISTINCT b";
    let t = run(q).await;
    assert_eq!(
        t.rows,
        walk1(3).iter().map(|&x| vec![x]).collect::<Vec<_>>()
    );
    assert!(matches!(path_strata(q)[..], [Stratum::Reach { .. }]), "{q}");

    // Back from the far end: who reaches the library of size 9 (itself included).
    let q = "MATCH (a)-[:CALLS]->*(b:Lib) WHERE b.size = 9 RETURN DISTINCT a";
    let t = run(q).await;
    let want = walk(&reversed(&CALLS), &[9]);
    assert_eq!(t.rows, want.iter().map(|&x| vec![x]).collect::<Vec<_>>());
    let s = path_strata(q);
    assert!(
        matches!(
            s[..],
            [Stratum::Reach {
                way: Way::Backward,
                ..
            }]
        ),
        "{s:?}"
    );
    // The same written against the edge.
    let t = run("MATCH (b:Lib)<-[:CALLS]-*(a) WHERE b.size = 9 RETURN DISTINCT a").await;
    assert_eq!(t.rows, want.iter().map(|&x| vec![x]).collect::<Vec<_>>());
}

#[tokio::test]
async fn quantified_edges_as_closure() {
    // Both ends returned: pairs, a closure from the labelled start.
    let q = "MATCH (a:Func)-[:CALLS]->+(b) RETURN a, b";
    let t = run(q).await;
    let mut want = Vec::new();
    for a in FUNC {
        for b in walk1(a) {
            want.push(vec![a, b]);
        }
    }
    assert_eq!(t.rows, sorted(want));
    assert!(matches!(path_strata(q)[..], [Stratum::Closure { .. }]));

    // Zero or more from any node to a labelled end: the closure's base is the end.
    let q = "MATCH (a)-[:CALLS]->*(b:Lib) RETURN a, b";
    let t = run(q).await;
    let back = reversed(&CALLS);
    let mut want = Vec::new();
    for b in LIB {
        for a in walk(&back, &[b]) {
            want.push(vec![a, b]);
        }
    }
    assert_eq!(t.rows, sorted(want));
    assert!(matches!(path_strata(q)[..], [Stratum::Closure { .. }]));

    // Without DISTINCT the start counts: one row per (entry, reached) pair.
    let q = "MATCH (e:Entry)-[:CALLS]->*(b) RETURN b";
    let t = run(q).await;
    let mut want = Vec::new();
    for e in ENTRY {
        for b in walk(&CALLS, &[e]) {
            want.push(vec![b]);
        }
    }
    assert_eq!(t.rows, sorted(want));
    assert!(matches!(path_strata(q)[..], [Stratum::Closure { .. }]));

    // A cycle back to the same node.
    let t = run("MATCH (a:Func)-[:CALLS]->+(a) RETURN a").await;
    let want: Vec<Vec<u64>> = FUNC
        .iter()
        .filter(|&&a| walk1(a).contains(&a))
        .map(|&a| vec![a])
        .collect();
    assert_eq!(t.rows, want);
}

#[tokio::test]
async fn refusals() {
    let cat = catalog();
    let refused = |text: &str| lower(&parse(text).unwrap(), &cat).unwrap_err();
    assert!(matches!(
        refused("MATCH (a:Nope) RETURN a"),
        GqlError::Semantic(_)
    ));
    assert!(matches!(
        refused("MATCH (a)-[:NOPE]->(b) RETURN a"),
        GqlError::Semantic(_)
    ));
    assert!(matches!(
        refused("MATCH (a:Func) WHERE z = 1 RETURN a"),
        GqlError::Semantic(_)
    ));
    assert!(matches!(
        refused("MATCH (a:Func) WHERE a.colour = 1 RETURN a"),
        GqlError::Semantic(_)
    ));
    // `RETURN e` is the whole edge (tests/entities.rs); an edge in a comparison is not a value.
    assert!(matches!(
        refused("MATCH (a:Func)-[e:CALLS]->(b) WHERE e = 1 RETURN a"),
        GqlError::Unsupported(_)
    ));
    assert!(matches!(
        // (in WHERE it is a predicate over each edge; returned, a value per edge)
        refused("MATCH (a:Func)-[e:CALLS]->+(b) RETURN e.weight"),
        GqlError::Unsupported(_)
    ));
    assert!(matches!(
        refused("MATCH (a:Func)-[e:IN]->(b) WHERE e.weight = 1 RETURN a"),
        GqlError::Semantic(_)
    ));
    assert!(matches!(
        refused("MATCH (a:Func)-[e:CALLS]->(b), (b)-[e:CALLS]->(c) RETURN a"),
        GqlError::Semantic(_)
    ));
    assert!(matches!(
        refused("MATCH (a)-[:CALLS]->{0,3}(b) WHERE a = 3 RETURN DISTINCT b"),
        GqlError::Unsupported(_)
    ));
    assert!(matches!(
        refused("MATCH (a)-[:CALLS]->*(b) RETURN a, b"),
        GqlError::Unsupported(_)
    ));
    // Length 0 from a node with no label: no node set to start from.
    assert!(matches!(
        refused("MATCH (a)-[:CALLS]->*(b) WHERE a = 3 RETURN DISTINCT b"),
        GqlError::Unsupported(_)
    ));
    // `(b)` with no label and no edge is any node of any label (tests/entities.rs).
    // Every rule the lowering makes is in the plan, printed in its rule notation.
    let l = lower(
        &parse("MATCH (e:Entry)-[:CALLS]->*(b) RETURN DISTINCT b").unwrap(),
        &cat,
    )
    .unwrap();
    let rules: BTreeMap<usize, String> = (0..l.plan.rules().len())
        .map(|i| (i, format!("{:?}", l.plan.rules()[i].head.rel)))
        .collect();
    assert_eq!(rules.len(), 3, "two path rules and the match rule");
}

#[tokio::test]
async fn parameters_and_the_table_text() {
    let mut params = Params::new();
    params.insert("s".into(), 3.into());
    params.insert("min".into(), 15.into());
    let text = "MATCH (a:Func)-[:CALLS]->+(b) WHERE a = $s RETURN DISTINCT b";
    let t = query_with(&engine(), &catalog(), text, &params)
        .await
        .unwrap();
    assert_eq!(
        t.rows,
        walk1(3).iter().map(|&x| vec![x]).collect::<Vec<_>>()
    );
    assert_eq!(
        t,
        run("MATCH (a:Func)-[:CALLS]->+(b) WHERE a = 3 RETURN DISTINCT b").await
    );
    // A parameter on either side of a comparison, with a property.
    let text = "MATCH (a:Func) WHERE $min <= a.size RETURN id(a) AS a, a.size AS s";
    let t = query_with(&engine(), &catalog(), text, &params)
        .await
        .unwrap();
    let want: Vec<Vec<u64>> = FUNC_SIZE
        .iter()
        .filter(|p| p.1 >= 15)
        .map(|&(a, s)| vec![a, s])
        .collect();
    assert_eq!(t.rows, want);
    // The text form: header, rule, right-aligned values, the count.
    assert_eq!(
        t.to_string(),
        " a | s\n---+----\n 1 | 20\n 2 | 15\n 3 | 40\n 5 | 60\n(4 rows)\n"
    );
    let one = Table {
        columns: vec!["a.size".into()],
        rows: vec![vec![7]],
        list_columns: vec![],
        lists: vec![],
        float_columns: vec![],
        nulls: vec![],
        entities: vec![],
    };
    assert_eq!(one.to_string(), " a.size\n--------\n      7\n(1 row)\n");
    // A parameter with no value is refused.
    let q = parse("MATCH (a:Func) WHERE a = $nope RETURN a").unwrap();
    assert!(matches!(
        lower_with(&q, &catalog(), &params),
        Err(GqlError::Semantic(m)) if m.contains("$nope")
    ));
    assert!(matches!(lower(&q, &catalog()), Err(GqlError::Semantic(_))));
}

/// The ends of walks from `s` of a length in `min..=max` (WALK mode: level by level,
/// nothing visited; no `max`: 40 levels, past every cycle here).
fn walks(edges: &[(u64, u64)], s: &[u64], min: u64, max: Option<u64>) -> BTreeSet<u64> {
    let mut level: BTreeSet<u64> = s.iter().copied().collect();
    let mut out = BTreeSet::new();
    for depth in 0..=max.unwrap_or(40) {
        if depth >= min {
            out.extend(level.iter().copied());
        }
        level = edges
            .iter()
            .filter(|e| level.contains(&e.0))
            .map(|e| e.1)
            .collect();
    }
    out
}

#[tokio::test]
async fn bounded_path_lengths_as_walks() {
    let ranges: [(&str, u64, Option<u64>); 9] = [
        ("{2}", 2, Some(2)),
        ("{1,3}", 1, Some(3)),
        ("{,2}", 0, Some(2)),
        ("{3,}", 3, None),
        ("{10}", 10, Some(10)),
        ("{0,0}", 0, Some(0)),
        ("{2,5}", 2, Some(5)),
        ("{1}", 1, Some(1)),
        ("{4,1000}", 4, Some(1000)),
    ];
    for (q, min, max) in ranges {
        // Ends from the entries: a walk of the ends.
        let text = format!("MATCH (e:Entry)-[:CALLS]->{q}(b) RETURN DISTINCT b");
        let t = run(&text).await;
        let want = walks(&CALLS, &ENTRY, min, max);
        assert_eq!(
            t.rows,
            want.iter().map(|&x| vec![x]).collect::<Vec<_>>(),
            "{text}"
        );
        if q != "{1}" {
            assert!(
                matches!(path_strata(&text)[..], [Stratum::Walk { .. }]),
                "{text}"
            );
        }
        // Back from the far end: who reaches the library of size 9 so.
        let text = format!("MATCH (a)-[:CALLS]->{q}(b:Lib) WHERE b.size = 9 RETURN DISTINCT a");
        if min > 0 {
            let t = run(&text).await;
            let want = walks(&reversed(&CALLS), &[9], min, max);
            assert_eq!(
                t.rows,
                want.iter().map(|&x| vec![x]).collect::<Vec<_>>(),
                "{text}"
            );
        }
        // Pairs: every (start, end) of a labelled start, each once (DISTINCT).
        let text = format!("MATCH (a:Func)-[:CALLS]->{q}(b) RETURN DISTINCT a, b");
        let t = run(&text).await;
        let mut want = Vec::new();
        for a in FUNC {
            for b in walks(&CALLS, &[a], min, max) {
                want.push(vec![a, b]);
            }
        }
        assert_eq!(t.rows, sorted(want), "{text}");
    }
    // The Cypher forms ask the same: `*2..3` and `{2,3}`, `*10` and `{10}`.
    for (cypher, gql) in [
        ("-[:CALLS*2..3]->", "-[:CALLS]->{2,3}"),
        ("-[:CALLS*10]->", "-[:CALLS]->{10}"),
        ("<-[:CALLS*1..2]-", "<-[:CALLS]-{1,2}"),
    ] {
        let a = run(&format!("MATCH (e:Entry){cypher}(b) RETURN e, b")).await;
        let b = run(&format!("MATCH (e:Entry){gql}(b) RETURN e, b")).await;
        assert_eq!(a, b, "{cypher}");
        assert!(!a.rows.is_empty(), "{cypher}");
    }
    // No label at either end, one or more edges: the walk starts at every edge's source.
    let t = run("MATCH (a)-[:CALLS]->{2}(b) RETURN a, b").await;
    let mut want = Vec::new();
    let sources: BTreeSet<u64> = CALLS.iter().map(|e| e.0).collect();
    for &a in &sources {
        for b in walks(&CALLS, &[a], 2, Some(2)) {
            want.push(vec![a, b]);
        }
    }
    assert_eq!(t.rows, sorted(want));
    // The start by its id alone, the k-hop question: within 3 edges of 3, 3 left out.
    let t = run("MATCH (a)-[:CALLS]->{1,3}(b) WHERE a = 3 AND b <> 3 RETURN DISTINCT b").await;
    let mut want = walks(&CALLS, &[3], 1, Some(3));
    want.remove(&3);
    assert_eq!(t.rows, want.iter().map(|&x| vec![x]).collect::<Vec<_>>());
    // The cycle 0 -> 1 -> 2 -> 0: back at the start after exactly 3 and 6 edges, not 4.
    let back = |q: &'static str| async move { run(q).await.rows };
    assert_eq!(
        back("MATCH (a:Entry)-[:CALLS]->{3}(a) RETURN a").await,
        vec![vec![0], vec![1]]
    );
    assert_eq!(
        back("MATCH (a:Entry)-[:CALLS]->{6}(a) RETURN a").await,
        vec![vec![0], vec![1]]
    );
    assert!(
        back("MATCH (a:Entry)-[:CALLS]->{4}(a) RETURN a")
            .await
            .is_empty()
    );
}

fn depth(x: u64) -> Option<u64> {
    FUNC_DEPTH.iter().find(|p| p.0 == x).map(|p| p.1)
}

/// Three-valued logic for the reference: `None` is unknown.
fn and(a: Option<bool>, b: Option<bool>) -> Option<bool> {
    match (a, b) {
        (Some(false), _) | (_, Some(false)) => Some(false),
        (Some(true), Some(true)) => Some(true),
        _ => None,
    }
}

fn or(a: Option<bool>, b: Option<bool>) -> Option<bool> {
    match (a, b) {
        (Some(true), _) | (_, Some(true)) => Some(true),
        (Some(false), Some(false)) => Some(false),
        _ => None,
    }
}

fn not(a: Option<bool>) -> Option<bool> {
    a.map(|x| !x)
}

fn cmp(a: Option<u64>, f: fn(&u64, &u64) -> bool, b: u64) -> Option<bool> {
    a.map(|x| f(&x, &b))
}

#[tokio::test]
async fn where_or_not_in_xor_with_unknowns() {
    type Pred = fn(u64, u64) -> Option<bool>;
    let cases: Vec<(&str, Pred)> = vec![
        ("a.size < 10 OR b.size > 30", |a, b| {
            or(cmp(size(a), u64::lt, 10), cmp(size(b), u64::gt, 30))
        }),
        ("NOT (a.depth = 2)", |a, _| not(cmp(depth(a), u64::eq, 2))),
        ("a.depth = 1 OR a.size = 15", |a, _| {
            or(cmp(depth(a), u64::eq, 1), cmp(size(a), u64::eq, 15))
        }),
        ("a IN (0, 2, 4) AND NOT b IN [1, 5]", |a, b| {
            Some([0, 2, 4].contains(&a) && ![1, 5].contains(&b))
        }),
        ("(a.depth > 1 XOR b.depth > 1) AND a <> b", |a, b| {
            let (x, y) = (cmp(depth(a), u64::gt, 1), cmp(depth(b), u64::gt, 1));
            and(x.zip(y).map(|(x, y)| x != y), Some(a != b))
        }),
        ("NOT (a.depth = 9 OR b.depth = 9)", |a, b| {
            not(or(cmp(depth(a), u64::eq, 9), cmp(depth(b), u64::eq, 9)))
        }),
        ("a.size IN ()", |_, _| Some(false)),
        ("1 = 1 OR a.depth = 3", |_, _| Some(true)),
        ("1 = 2 AND a.depth = 3", |_, _| Some(false)),
        ("NOT NOT a.depth >= 2 AND b.depth IN ($two, 9)", |a, b| {
            and(
                cmp(depth(a), u64::ge, 2),
                or(cmp(depth(b), u64::eq, 2), cmp(depth(b), u64::eq, 9)),
            )
        }),
        (
            "a.depth = 2 OR NOT (b.size < 20 AND (a = 0 OR a.depth > 5))",
            |a, b| {
                or(
                    cmp(depth(a), u64::eq, 2),
                    not(and(
                        cmp(size(b), u64::lt, 20),
                        or(Some(a == 0), cmp(depth(a), u64::gt, 5)),
                    )),
                )
            },
        ),
        ("a.size > 4 XOR a.size > 10 XOR a.size > 30", |a, _| {
            let s = size(a)?;
            Some((s > 4) ^ (s > 10) ^ (s > 30))
        }),
    ];
    let mut params = Params::new();
    params.insert("two".into(), 2.into());
    for (cond, pred) in cases {
        let text = format!("MATCH (a:Func)-[:CALLS]->(b:Func) WHERE {cond} RETURN a, b");
        let t = query_with(&engine(), &catalog(), &text, &params)
            .await
            .unwrap_or_else(|e| panic!("{text}: {e}"));
        let want: Vec<Vec<u64>> = CALLS
            .iter()
            .filter(|(a, b)| FUNC.contains(a) && FUNC.contains(b))
            .filter(|&&(a, b)| pred(a, b) == Some(true))
            .map(|&(a, b)| vec![a, b])
            .collect();
        assert_eq!(t.rows, sorted(want), "{cond}");
    }

    // A filter on the start of a walk with a label: the walk's seeds (a reach, not a closure).
    let q = "MATCH (a:Func)-[:CALLS]->+(b) WHERE a.depth = 9 OR a.size = 40 RETURN DISTINCT b";
    let t = run(q).await;
    let mut want = BTreeSet::new();
    for a in [3, 4] {
        want.extend(walk1(a));
    }
    assert_eq!(t.rows, want.iter().map(|&x| vec![x]).collect::<Vec<_>>());
    assert!(matches!(path_strata(q)[..], [Stratum::Reach { .. }]), "{q}");
    // On a node with no label: over the match's bindings.
    let t = run("MATCH (a)-[:CALLS]->+(b) WHERE a = 1 OR a IN [4] RETURN DISTINCT b").await;
    let mut want = walk1(1);
    want.extend(walk1(4));
    assert_eq!(t.rows, want.iter().map(|&x| vec![x]).collect::<Vec<_>>());
    // A filter over three nodes, one of them a walk's end, with a bounded length.
    let t = run(
        "MATCH (e:Entry)-[:CALLS]->{1,2}(m), (m)-[:IN]->(f:File) WHERE NOT (f = 10 AND e = 0) OR m = 3 RETURN e, m, f",
    )
    .await;
    let mut want = Vec::new();
    for e in ENTRY {
        for m in walks(&CALLS, &[e], 1, Some(2)) {
            for &(m2, f) in &IN {
                if m2 == m && FILE.contains(&f) && (!(f == 10 && e == 0) || m == 3) {
                    want.push(vec![e, m, f]);
                }
            }
        }
    }
    assert_eq!(t.rows, sorted(want));
}

/// Twenty `OR`s joined by `AND`: as one disjunctive form 2^20 rules; here a few per part.
#[tokio::test]
async fn long_conditions_stay_linear() {
    let parts: Vec<String> = (0..20)
        .map(|k| format!("(a = {k} OR b.size > {k})"))
        .collect();
    let text = format!(
        "MATCH (a:Func)-[:CALLS]->(b:Func) WHERE NOT ({}) RETURN a, b",
        parts.join(" AND ")
    );
    let l = lower(&parse(&text).unwrap(), &catalog()).unwrap();
    assert!(
        l.plan.rules().len() < 4 * 20 + 10,
        "{} rules",
        l.plan.rules().len()
    );
    let t = l.run(&engine()).await.unwrap();
    let want: Vec<Vec<u64>> = CALLS
        .iter()
        .filter(|(a, b)| FUNC.contains(a) && FUNC.contains(b))
        .filter(|&&(a, b)| !(0..20).all(|k| a == k || size(b).unwrap() > k))
        .map(|&(a, b)| vec![a, b])
        .collect();
    assert!(!want.is_empty());
    assert_eq!(t.rows, sorted(want));
}

#[tokio::test]
async fn order_by_offset_and_limit() {
    // Every (a, b) of a call between functions with b's size, in many orders.
    let base: Vec<(u64, u64, u64)> = CALLS
        .iter()
        .filter(|(a, b)| FUNC.contains(a) && FUNC.contains(b))
        .map(|&(a, b)| (a, b, size(b).unwrap()))
        .collect();
    let q = "MATCH (a:Func)-[:CALLS]->(b:Func) RETURN a, b, b.size AS s";
    // By s falling, ties by the whole row rising.
    let t = run(&format!("{q} ORDER BY s DESC")).await;
    let mut want: Vec<Vec<u64>> = base.iter().map(|&(a, b, s)| vec![a, b, s]).collect();
    want.sort_by(|x, y| y[2].cmp(&x[2]).then(x.cmp(y)));
    assert_eq!(t.rows, want);
    // By a property not returned, then b falling; OFFSET and LIMIT on the ordered rows.
    let t =
        run("MATCH (a:Func)-[:CALLS]->(b:Func) RETURN b ORDER BY a.size, b DESC SKIP 1 LIMIT 3")
            .await;
    let mut all: Vec<(u64, u64, u64)> = base
        .iter()
        .map(|&(a, b, _)| (size(a).unwrap(), b, a))
        .collect();
    all.sort_by(|x, y| x.0.cmp(&y.0).then(y.1.cmp(&x.1)).then(x.1.cmp(&y.1)));
    let want: Vec<Vec<u64>> = all.iter().skip(1).take(3).map(|x| vec![x.1]).collect();
    assert_eq!(t.rows, want);
    // By the written form of a returned property, ascending said out loud; OFFSET past the end.
    let t = run(&format!("{q} ORDER BY b.size ASC, a OFFSET 2")).await;
    let mut want: Vec<Vec<u64>> = base.iter().map(|&(a, b, s)| vec![a, b, s]).collect();
    want.sort_by(|x, y| x[2].cmp(&y[2]).then(x[0].cmp(&y[0])).then(x.cmp(y)));
    assert_eq!(t.rows, want[2..].to_vec());
    assert!(run(&format!("{q} OFFSET 100")).await.rows.is_empty());
    // DISTINCT and ORDER BY a returned value: the distinct callers, the busiest first is not
    // a GQL ordering (no aggregates yet), so by id falling.
    let t = run("MATCH (a:Func)-[:CALLS]->(b) RETURN DISTINCT a ORDER BY a DESC LIMIT 2").await;
    let mut want: Vec<u64> = CALLS
        .iter()
        .filter(|e| FUNC.contains(&e.0))
        .map(|e| e.0)
        .collect();
    want.sort_unstable_by(|x, y| y.cmp(x));
    want.dedup();
    assert_eq!(
        t.rows,
        want[..2].iter().map(|&x| vec![x]).collect::<Vec<_>>()
    );
    // Over a walk: the reached libraries by size falling.
    let t =
        run("MATCH (e:Entry)-[:CALLS]->+(x:Lib) RETURN DISTINCT x, x.size AS s ORDER BY s DESC")
            .await;
    let mut want: Vec<Vec<u64>> = walk(&CALLS, &ENTRY)
        .into_iter()
        .filter(|x| LIB.contains(x))
        .map(|x| vec![x, size(x).unwrap()])
        .collect();
    want.sort_by(|x, y| y[1].cmp(&x[1]));
    assert_eq!(t.rows, want);
    // Under DISTINCT a key must be returned.
    let cat = catalog();
    let q = parse("MATCH (a:Func)-[:CALLS]->(b) RETURN DISTINCT a ORDER BY b").unwrap();
    assert!(matches!(lower(&q, &cat), Err(GqlError::Semantic(_))));
    let q = parse("MATCH (a:Func) RETURN a ORDER BY z").unwrap();
    assert!(matches!(lower(&q, &cat), Err(GqlError::Semantic(_))));
}

#[tokio::test]
async fn either_way_no_label_alternatives_and_edge_properties() {
    let both: Vec<(u64, u64)> = CALLS.iter().flat_map(|&(a, b)| [(a, b), (b, a)]).collect();
    // Either way: each call from an entry, or to one.
    let t = run("MATCH (a:Entry)-[:CALLS]-(b) RETURN a, b").await;
    let set: BTreeSet<Vec<u64>> = both
        .iter()
        .filter(|e| ENTRY.contains(&e.0))
        .map(|&(a, b)| vec![a, b])
        .collect();
    assert_eq!(t.rows, set.iter().cloned().collect::<Vec<_>>());
    assert_eq!(t, run("MATCH (a:Entry)<-[:CALLS]->(b) RETURN a, b").await);
    // Either way, quantified: a reach over the edges both ways.
    let q = "MATCH (e:Entry)-[:CALLS]-*(b) RETURN DISTINCT b";
    let t = run(q).await;
    assert_eq!(
        t.rows,
        walk(&both, &ENTRY)
            .iter()
            .map(|&x| vec![x])
            .collect::<Vec<_>>()
    );
    assert!(matches!(path_strata(q)[..], [Stratum::Reach { .. }]), "{q}");
    let t = run("MATCH (e:Entry)-[:CALLS]-{2}(b) RETURN DISTINCT b").await;
    assert_eq!(
        t.rows,
        walks(&both, &ENTRY, 2, Some(2))
            .iter()
            .map(|&x| vec![x])
            .collect::<Vec<_>>()
    );
    // No label: any edge label; with no brackets too.
    let any: Vec<(u64, u64)> = CALLS.iter().chain(&IN).copied().collect();
    let t = run("MATCH (a:Lib)-[]->(b) RETURN a, b").await;
    let want: Vec<Vec<u64>> = any
        .iter()
        .filter(|e| LIB.contains(&e.0))
        .map(|&(a, b)| vec![a, b])
        .collect();
    assert_eq!(t.rows, sorted(want.clone()));
    assert_eq!(t, run("MATCH (a:Lib)-->(b) RETURN a, b").await);
    assert_eq!(t, run("MATCH (a:Lib)->(b) RETURN a, b").await);
    let t = run("MATCH (f:File)<-(a) RETURN DISTINCT a").await;
    let set: BTreeSet<u64> = IN.iter().map(|e| e.0).collect();
    assert_eq!(t.rows, set.iter().map(|&x| vec![x]).collect::<Vec<_>>());
    let t = run("MATCH (e:Entry)-[e2]->+(x) RETURN DISTINCT x").await;
    let mut from: BTreeSet<u64> = BTreeSet::new();
    for e in ENTRY {
        let next: Vec<u64> = any.iter().filter(|x| x.0 == e).map(|x| x.1).collect();
        from.extend(walk(&any, &next));
    }
    assert_eq!(t.rows, from.iter().map(|&x| vec![x]).collect::<Vec<_>>());
    // Label alternatives on nodes and edges.
    let t = run("MATCH (x:Lib|File)<-[:CALLS|IN]-(a:Entry|Lib) RETURN a, x").await;
    let want: Vec<Vec<u64>> = any
        .iter()
        .filter(|e| {
            (LIB.contains(&e.1) || FILE.contains(&e.1))
                && (ENTRY.contains(&e.0) || LIB.contains(&e.0))
        })
        .map(|&(a, x)| vec![a, x])
        .collect();
    assert!(!want.is_empty());
    assert_eq!(t.rows, sorted(want));
    // A property of either label of an alternative.
    let t = run("MATCH (x IS Func|Lib) WHERE x.size > 30 RETURN x, x.size").await;
    let want: Vec<Vec<u64>> = FUNC
        .iter()
        .chain(&LIB)
        .filter_map(|&x| size(x).filter(|&s| s > 30).map(|s| vec![x, s]))
        .collect();
    assert_eq!(t.rows, sorted(want));
    // Edge properties in WHERE, RETURN and ORDER BY.
    let t = run("MATCH (a:Func)-[c:CALLS]->(b) WHERE c.weight > 3 RETURN a, b, c.weight AS w ORDER BY w DESC").await;
    let mut want: Vec<Vec<u64>> = CALLS
        .iter()
        .filter(|&&(a, b)| FUNC.contains(&a) && weight(a, b) > 3)
        .map(|&(a, b)| vec![a, b, weight(a, b)])
        .collect();
    want.sort_by(|x, y| y[2].cmp(&x[2]).then(x.cmp(y)));
    assert_eq!(t.rows, want);
    // Either way, the property of the edge as stored; with no label, of the labels that
    // have it (IN edges have no weight: unknown, so left out).
    let t = run("MATCH (a:Entry)-[c:CALLS]-(b) RETURN a, b, c.weight").await;
    let set: BTreeSet<Vec<u64>> = CALLS
        .iter()
        .flat_map(|&(x, y)| [(x, y, weight(x, y)), (y, x, weight(x, y))])
        .filter(|e| ENTRY.contains(&e.0))
        .map(|(a, b, w)| vec![a, b, w])
        .collect();
    assert_eq!(t.rows, set.iter().cloned().collect::<Vec<_>>());
    let t = run("MATCH (a:Lib)-[c]->(b) WHERE c.weight >= 0 RETURN a, b").await;
    let want: Vec<Vec<u64>> = CALLS
        .iter()
        .filter(|e| LIB.contains(&e.0))
        .map(|&(a, b)| vec![a, b])
        .collect();
    assert_eq!(t.rows, sorted(want));
}

#[tokio::test]
async fn aggregates_grouped_by_the_other_items() {
    let calls: Vec<(u64, u64)> = CALLS
        .iter()
        .filter(|(a, b)| FUNC.contains(a) && FUNC.contains(b))
        .copied()
        .collect();
    // Per caller: its calls, its distinct callees' sizes, the least and greatest callee size.
    let t = run(
        "MATCH (a:Func)-[:CALLS]->(b:Func) RETURN a, count(*) AS n, count(b) AS m, \
         count(DISTINCT b.size) AS d, min(b.size) AS lo, max(b.size) AS hi ORDER BY n DESC, a",
    )
    .await;
    assert_eq!(t.columns, ["a", "n", "m", "d", "lo", "hi"]);
    let mut want: Vec<Vec<u64>> = Vec::new();
    for a in FUNC {
        let bs: Vec<u64> = calls.iter().filter(|e| e.0 == a).map(|e| e.1).collect();
        if bs.is_empty() {
            continue;
        }
        let sizes: BTreeSet<u64> = bs.iter().map(|&b| size(b).unwrap()).collect();
        let n = bs.len() as u64;
        want.push(vec![
            a,
            n,
            n,
            sizes.len() as u64,
            *sizes.first().unwrap(),
            *sizes.last().unwrap(),
        ]);
    }
    want.sort_by(|x, y| y[1].cmp(&x[1]).then(x[0].cmp(&y[0])));
    assert_eq!(t.rows, want);
    // No groups: one row; count(*) counts matches, count(DISTINCT) values.
    let t =
        run("MATCH (a:Func)-[:CALLS]->(b) RETURN count(*), count(DISTINCT b), max(a.size)").await;
    let n = CALLS.iter().filter(|e| FUNC.contains(&e.0)).count() as u64;
    let d = CALLS
        .iter()
        .filter(|e| FUNC.contains(&e.0))
        .map(|e| e.1)
        .collect::<BTreeSet<_>>()
        .len() as u64;
    let hi = FUNC
        .iter()
        .filter(|&&a| CALLS.iter().any(|e| e.0 == a))
        .map(|&a| size(a).unwrap())
        .max()
        .unwrap();
    assert_eq!(t.rows, vec![vec![n, d, hi]]);
    // Nothing matches: counts are 0.
    let t = run("MATCH (a:Func) WHERE a.size > 1000 RETURN count(*) AS n, count(DISTINCT a)").await;
    assert_eq!(t.rows, vec![vec![0, 0]]);
    // The k-hop count: distinct ends of walks of 1 to 3 edges from 3, 3 left out.
    let t =
        run("MATCH (a)-[:CALLS]->{1,3}(b) WHERE a = 3 AND b <> 3 RETURN count(DISTINCT b) AS c")
            .await;
    let mut ends = walks(&CALLS, &[3], 1, Some(3));
    ends.remove(&3);
    assert_eq!(t.rows, vec![vec![ends.len() as u64]]);
    // Grouped by a property and an edge property; groups of a walk's start.
    let t = run("MATCH (e:Entry)-[:CALLS]->+(b) RETURN e, count(DISTINCT b) AS c").await;
    let want: Vec<Vec<u64>> = ENTRY
        .iter()
        .map(|&e| vec![e, walk1(e).len() as u64])
        .collect();
    assert_eq!(t.rows, want);
    let t =
        run("MATCH (a:Func)-[c:CALLS]->(b) RETURN c.weight AS w, count(*) AS n, min(a) ORDER BY w")
            .await;
    let mut by: BTreeMap<u64, (u64, u64)> = BTreeMap::new();
    for &(a, b) in CALLS.iter().filter(|e| FUNC.contains(&e.0)) {
        let e = by.entry(weight(a, b)).or_insert((0, u64::MAX));
        e.0 += 1;
        e.1 = e.1.min(a);
    }
    let want: Vec<Vec<u64>> = by.iter().map(|(&w, &(n, m))| vec![w, n, m]).collect();
    assert_eq!(t.rows, want);
    // Refused: ORDER BY a column not returned.
    let cat = catalog();
    let q = parse("MATCH (a:Func)-[:CALLS]->(b) RETURN a, count(*) ORDER BY b").unwrap();
    assert!(matches!(lower(&q, &cat), Err(GqlError::Semantic(_))));
}

/// Every shortest walk from `s` along `edges` with at least `min` (0 or 1) edges, per end,
/// as vertex lists sorted: all walks grown a level at a time, a level's walks kept only
/// to ends not reached before.
fn all_shortest(edges: &[(u64, u64)], s: u64, min: u64) -> BTreeMap<u64, Vec<Vec<u64>>> {
    let mut best: BTreeMap<u64, Vec<Vec<u64>>> = BTreeMap::new();
    let mut level = vec![vec![s]];
    let mut depth = 0;
    while !level.is_empty() {
        let mut next_level = Vec::new();
        for w in level {
            let t = *w.last().unwrap();
            if depth >= min {
                match best.get_mut(&t) {
                    Some(v) if v[0].len() < w.len() => continue,
                    Some(v) => v.push(w.clone()),
                    None => {
                        best.insert(t, vec![w.clone()]);
                    }
                }
            }
            for e in edges.iter().filter(|e| e.0 == t) {
                let mut x = w.clone();
                x.push(e.1);
                next_level.push(x);
            }
        }
        level = next_level;
        depth += 1;
        if depth > 40 {
            break;
        }
    }
    for v in best.values_mut() {
        v.sort();
        v.dedup();
    }
    best
}

/// The path through the lowest vertex at each step back from the end.
fn any_shortest(paths: &[Vec<u64>]) -> Vec<u64> {
    let mut r: Vec<Vec<u64>> = paths
        .iter()
        .map(|p| p.iter().rev().copied().collect())
        .collect();
    r.sort();
    r[0].iter().rev().copied().collect()
}

/// A 3 x 3 grid, edges right and down: C(4, 2) = 6 shortest paths corner to corner.
fn grid() -> (Catalog, Vec<(u64, u64)>) {
    let mut e = Vec::new();
    for r in 0..3u64 {
        for c in 0..3u64 {
            let v = r * 3 + c;
            if c < 2 {
                e.push((v, v + 1));
            }
            if r < 2 {
                e.push((v, v + 3));
            }
        }
    }
    let mut c = Catalog::new();
    c.label("V", ones(&(0..9).collect::<Vec<_>>()))
        .edge("R", twos(&e));
    (c, e)
}

/// Each row's list in column `c`.
fn lists(t: &Table, c: usize) -> Vec<Vec<u64>> {
    (0..t.rows.len())
        .map(|r| t.list(r, c).unwrap().to_vec())
        .collect()
}

#[tokio::test]
async fn path_variables_and_shortest_paths() {
    // ANY SHORTEST from the entries: one path per reached end, its length and nodes.
    let q = "MATCH p = ANY SHORTEST (a:Entry)-[:CALLS]->+(b) RETURN a, b, length(p) AS n, nodes(p) AS path";
    let t = run(q).await;
    assert_eq!(t.columns, ["a", "b", "n", "path"]);
    assert_eq!(t.list_columns, [3]);
    let mut want: Vec<(Vec<u64>, Vec<u64>)> = Vec::new();
    for a in ENTRY {
        for (b, paths) in all_shortest(&CALLS, a, 1) {
            let p = any_shortest(&paths);
            want.push((vec![a, b, p.len() as u64 - 1], p));
        }
    }
    want.sort();
    let got: Vec<(Vec<u64>, Vec<u64>)> = t
        .rows
        .iter()
        .zip(lists(&t, 3))
        .map(|(r, l)| (r[..3].to_vec(), l))
        .collect();
    assert_eq!(got, want);
    // 0 back to itself through the cycle 0 -> 1 -> 2 -> 0.
    assert!(want.iter().any(|w| w.1 == [0, 1, 2, 0]));
    let strata = path_strata(q);
    assert!(
        matches!(
            strata[..],
            [Stratum::Walk {
                shortest: Some(kleene_plan::Shortest::Any),
                ..
            }]
        ),
        "{strata:?}"
    );
    // The Cypher spellings, ANY, and RETURN p as the nodes.
    for q2 in [
        "MATCH p = shortestPath((a:Entry)-[:CALLS*]->(b)) RETURN a, b, length(p) AS n, p AS path",
        "MATCH p = ANY (a:Entry)-[:CALLS]->+(b) RETURN a, b, length(p) AS n, p AS path",
        "MATCH p = ANY SHORTEST WALK PATH (a:Entry)-[:CALLS]->+(b) RETURN a, b, length(p) AS n, nodes(p) AS path",
    ] {
        let t2 = run(q2).await;
        assert_eq!(
            t2.rows.iter().map(|r| r[..3].to_vec()).collect::<Vec<_>>(),
            want.iter().map(|w| w.0.clone()).collect::<Vec<_>>(),
            "{q2}"
        );
        assert_eq!(lists(&t2, 3), lists(&t, 3), "{q2}");
    }
    // Length 0 too: `*` from a node with a label.
    let t = run("MATCH p = ANY SHORTEST (a:Entry)-[:CALLS]->*(b) WHERE a = b RETURN a, length(p)")
        .await;
    assert_eq!(t.rows, vec![vec![0, 0], vec![1, 0]]);
    // Against the edges, from a node with no label: the path starts at x.
    let t =
        run("MATCH p = ANY SHORTEST (x:Lib)<-[:CALLS]-+(a:Entry) RETURN x, a, length(p), nodes(p)")
            .await;
    let back = reversed(&CALLS);
    let mut want: Vec<Vec<u64>> = Vec::new();
    let mut want_lists = Vec::new();
    for x in LIB {
        for (a, paths) in all_shortest(&back, x, 1) {
            if ENTRY.contains(&a) {
                let p = any_shortest(&paths);
                want.push(vec![x, a, p.len() as u64 - 1]);
                want_lists.push(p);
            }
        }
    }
    assert_eq!(
        t.rows.iter().map(|r| r[..3].to_vec()).collect::<Vec<_>>(),
        want
    );
    assert_eq!(lists(&t, 3), want_lists);
    // ALL SHORTEST on a grid: six corner-to-corner paths, a row each.
    let (g, e) = grid();
    let eng = engine();
    let t = query(
        &eng,
        &g,
        "MATCH p = ALL SHORTEST (a:V)-[:R]->*(b) WHERE a = 0 AND b = 8 RETURN length(p), nodes(p)",
    )
    .await
    .unwrap();
    let all = all_shortest(&e, 0, 0);
    assert_eq!(all[&8].len(), 6);
    assert_eq!(lists(&t, 1), all[&8]);
    assert!(t.rows.iter().all(|r| r[0] == 4));
    let t = query(&eng, &g, "MATCH p = allShortestPaths((a:V)-[:R*0..]->(b)) WHERE a = 0 RETURN b, count(*) AS n ORDER BY b")
        .await
        .unwrap();
    let want: Vec<Vec<u64>> = all
        .iter()
        .map(|(&b, ps)| vec![b, ps.len() as u64])
        .collect();
    assert_eq!(t.rows, want);
    // ANY SHORTEST on the grid: the path through the lowest vertices going back.
    let t = query(
        &eng,
        &g,
        "MATCH p = ANY SHORTEST (a:V)-[:R]->+(b:V) WHERE a = 0 AND b = 8 RETURN p",
    )
    .await
    .unwrap();
    assert_eq!(lists(&t, 0), vec![any_shortest(&all[&8])]);
    assert_eq!(
        t.to_string(),
        " p\n-----------------\n [0, 1, 2, 5, 8]\n(1 row)\n"
    );
    // Bounded: no path of at most 3 edges from 0 to 8.
    let t = query(
        &eng,
        &g,
        "MATCH p = ANY SHORTEST (a:V)-[:R]->{1,3}(b) WHERE a = 0 AND b = 8 RETURN p",
    )
    .await
    .unwrap();
    assert!(t.rows.is_empty());
    // A fixed path: its nodes in pattern order, its length the number of edges.
    let t = run(
        "MATCH p = (a:Entry)-[:CALLS]->(b)<-[:CALLS]-(c) RETURN p, length(p) AS n, a ORDER BY a",
    )
    .await;
    let mut want: Vec<Vec<u64>> = Vec::new();
    for &(a, b) in CALLS.iter().filter(|e| ENTRY.contains(&e.0)) {
        for &(c, _) in CALLS.iter().filter(|e| e.1 == b) {
            want.push(vec![a, b, c]);
        }
    }
    want.sort();
    let mut got = lists(&t, 0);
    got.sort();
    assert_eq!(got, want);
    assert!(t.rows.iter().all(|r| r[1] == 2));
    // ORDER BY a length by its name, falling.
    let t = run("MATCH p = ANY SHORTEST (a:Entry)-[:CALLS]->+(b) WHERE a = 0 RETURN b, length(p) AS n ORDER BY n DESC, b").await;
    let mut want: Vec<Vec<u64>> = all_shortest(&CALLS, 0, 1)
        .iter()
        .map(|(&b, ps)| vec![b, ps[0].len() as u64 - 1])
        .collect();
    want.sort_by(|x, y| y[1].cmp(&x[1]).then(x[0].cmp(&y[0])));
    assert_eq!(t.rows, want);
    // Refused.
    let cat = catalog();
    for (q, semantic) in [
        ("MATCH p = (a:Func)-[:CALLS]->+(b) RETURN p", false),
        (
            "MATCH p = ANY SHORTEST (a:Func)-[:CALLS]->{2,4}(b) RETURN p",
            false,
        ),
        (
            "MATCH p = ANY SHORTEST (a:Func)-[:CALLS]->+(b)-[:IN]->(f) RETURN p",
            false,
        ),
        (
            "MATCH p = ANY SHORTEST (a:Func)-[:CALLS]->+(b) RETURN nodes(p), count(*)",
            false,
        ),
        (
            "MATCH p = ANY SHORTEST (a:Func)-[:CALLS]->+(b) RETURN nodes(p) AS l ORDER BY l",
            false,
        ),
        (
            "MATCH p = ANY SHORTEST (a:Func)-[:CALLS]->+(b) WHERE p = 1 RETURN a",
            false,
        ),
        ("MATCH p = (a:Func)-[:CALLS]->(b) RETURN length(q)", true),
        ("MATCH a = (a:Func)-[:CALLS]->(b) RETURN a", true),
    ] {
        let e = lower(&parse(q).unwrap(), &cat).err();
        match e {
            Some(GqlError::Semantic(_)) if semantic => {}
            Some(GqlError::Unsupported(_)) if !semantic => {}
            other => panic!("{q}: {other:?}"),
        }
    }
}

/// CALLS as a matrix over its vertices `0..10`, and its transpose.
fn calls_csr() -> (kleene_sparse::Csr<u8>, kleene_sparse::Csr<u8>) {
    let (s, d): (Vec<u32>, Vec<u32>) = CALLS.iter().map(|&(a, b)| (a as u32, b as u32)).unzip();
    let a = kleene_sparse::Csr::from_edges(10, 10, &s, &d, None, kleene_sparse::BoolOrAnd).unwrap();
    let t = a.transpose();
    (a, t)
}

#[tokio::test]
async fn call_procedures_on_graph_kernels() {
    let n = 10u64;
    // Weak components by a plain union-find; each named by its least vertex.
    let mut root: Vec<u64> = (0..n).collect();
    fn find(r: &mut [u64], x: u64) -> u64 {
        let mut x = x;
        while r[x as usize] != x {
            x = r[x as usize];
        }
        x
    }
    for &(a, b) in &CALLS {
        let (x, y) = (find(&mut root, a), find(&mut root, b));
        root[x.max(y) as usize] = x.min(y);
    }
    let weak: Vec<Vec<u64>> = (0..n).map(|v| vec![v, find(&mut root, v)]).collect();
    let t = run("CALL wcc(CALLS) YIELD node, component RETURN node, component").await;
    assert_eq!(t.rows, weak);
    // A CALL alone returns every column; the GDS and quoted spellings.
    for q in [
        "CALL wcc(CALLS)",
        "CALL gds.wcc.stream('CALLS')",
        "CALL algo.weaklyConnectedComponents(CALLS);",
    ] {
        let t = run(q).await;
        assert_eq!(t.columns, ["node", "component"], "{q}");
        assert_eq!(t.rows, weak, "{q}");
    }
    // Joined with a MATCH on the yielded node, grouped.
    let t =
        run("CALL wcc(CALLS) YIELD node, component AS c MATCH (node:Func) RETURN c, count(*) AS n")
            .await;
    let mut by: BTreeMap<u64, u64> = BTreeMap::new();
    for v in FUNC {
        *by.entry(weak[v as usize][1]).or_default() += 1;
    }
    assert_eq!(
        t.rows,
        by.iter().map(|(&c, &k)| vec![c, k]).collect::<Vec<_>>()
    );
    let t = run("CALL wcc(CALLS) YIELD node, component MATCH (node)-[:IN]->(f:File) RETURN DISTINCT component, f").await;
    let set: BTreeSet<Vec<u64>> = IN
        .iter()
        .map(|&(a, f)| vec![weak[a as usize][1], f])
        .collect();
    assert_eq!(t.rows, set.into_iter().collect::<Vec<_>>());
    // Strong components: a vertex with another as its name lies on a cycle with it.
    let t = run("CALL scc(CALLS) YIELD node AS v, component AS c WHERE c <> v RETURN v, c").await;
    let mut want = Vec::new();
    for v in 0..n {
        let c = (0..n)
            .find(|&u| walk(&CALLS, &[v]).contains(&u) && walk(&CALLS, &[u]).contains(&v))
            .unwrap();
        if c != v {
            want.push(vec![v, c]);
        }
    }
    assert_eq!(want, vec![vec![1, 0], vec![2, 0], vec![5, 4], vec![6, 4]]);
    assert_eq!(t.rows, want);
    // Shortest paths: weighted by an edge property (Bellman-Ford), and unit (BFS levels).
    let bellman = |s: u64, weighted: bool| -> Vec<Vec<u64>> {
        let mut d = vec![u64::MAX; n as usize];
        d[s as usize] = 0;
        for _ in 0..n {
            for &(a, b) in &CALLS {
                let c = if weighted { weight(a, b) } else { 1 };
                if d[a as usize] != u64::MAX && d[a as usize] + c < d[b as usize] {
                    d[b as usize] = d[a as usize] + c;
                }
            }
        }
        (0..n)
            .filter(|&v| d[v as usize] != u64::MAX)
            .map(|v| vec![v, d[v as usize]])
            .collect()
    };
    let t = run("CALL sssp(CALLS, 0, weight) YIELD node, distance RETURN node, distance").await;
    assert_eq!(t.rows, bellman(0, true));
    for s in [0u64, 1, 4] {
        let mut ps = Params::new();
        ps.insert("s".into(), s.into());
        let t = query_with(
            &engine(),
            &catalog(),
            "CALL bfs(CALLS, $s) YIELD node, distance AS d RETURN node, d",
            &ps,
        )
        .await
        .unwrap();
        assert_eq!(t.rows, bellman(s, false), "bfs {s}");
    }
    // Triangles: 0-1-2 and 4-5-6, the edges taken both ways, self-loops left out.
    let mut und: BTreeSet<(u64, u64)> = BTreeSet::new();
    for &(a, b) in CALLS.iter().filter(|e| e.0 != e.1) {
        und.insert((a.min(b), a.max(b)));
    }
    let mut tri = 0;
    for &(a, b) in &und {
        for c in b + 1..n {
            if und.contains(&(a, c)) && und.contains(&(b, c)) {
                tri += 1;
            }
        }
    }
    let t = run("CALL triangleCount(CALLS) YIELD count RETURN count").await;
    assert_eq!(t.rows, vec![vec![tri]]);
    assert_eq!(tri, 2);
    // PageRank and betweenness: the kernels' scores, as floats, ordered by score.
    let (a, at) = calls_csr();
    let cpu = CpuDevice::new(2);
    let pr =
        kleene_graph::pagerank(&a, &at, &kleene_graph::PageRankOptions::default(), &cpu).unwrap();
    let t = run("CALL pagerank(CALLS) YIELD node, score RETURN node, score ORDER BY score DESC, node LIMIT 3").await;
    assert_eq!(t.float_columns, [1]);
    let mut want: Vec<(u64, f64)> = pr
        .scores
        .iter()
        .enumerate()
        .map(|(v, &x)| (v as u64, x as f64))
        .collect();
    want.sort_by(|x, y| y.1.total_cmp(&x.1).then(x.0.cmp(&y.0)));
    want.truncate(3);
    let got: Vec<(u64, f64)> = (0..t.rows.len())
        .map(|r| (t.rows[r][0], t.float(r, 1).unwrap()))
        .collect();
    assert_eq!(got, want);
    // (the node whole, as a node of a MATCH is)
    let line = t.to_string().lines().nth(2).unwrap().to_string();
    let node = t.entity(0, 0).expect("a whole node").to_string();
    assert!(node.starts_with(&format!("({}:", want[0].0)), "{node}");
    assert_eq!(line.trim(), format!("{node} | {:.6}", want[0].1));
    let bc = kleene_graph::betweenness(&a, &at, &(0..10).collect::<Vec<u32>>(), &cpu).unwrap();
    let t =
        run("CALL betweenness(CALLS) YIELD node, score MATCH (node:Lib) RETURN node, score").await;
    let got: Vec<(u64, f64)> = (0..t.rows.len())
        .map(|r| (t.rows[r][0], t.float(r, 1).unwrap()))
        .collect();
    let want: Vec<(u64, f64)> = LIB.iter().map(|&v| (v, bc[v as usize])).collect();
    assert_eq!(got, want);
    // A score compared with a float literal (coded as the score's type).
    let t = run("CALL pagerank(CALLS) YIELD node, score WHERE score > 0.1 RETURN node").await;
    let want: Vec<Vec<u64>> = (0..10u64)
        .filter(|&v| pr.scores[v as usize] as f64 > 0.1)
        .map(|v| vec![v])
        .collect();
    assert!(!want.is_empty() && want.len() < 10);
    assert_eq!(t.rows, want);
    // max of a float stays a float.
    let t = run("CALL betweenness(CALLS) YIELD node, score RETURN max(score) AS top").await;
    assert_eq!(t.float(0, 0), bc.iter().copied().reduce(f64::max));
    // Refused.
    let cat = catalog();
    for (q, semantic) in [
        ("CALL louvain(CALLS)", true),
        ("CALL pagerank()", true),
        ("CALL pagerank(CALLS, 3)", true),
        ("CALL sssp(CALLS)", true),
        ("CALL bfs(CALLS, 0, weight)", true),
        ("CALL sssp(CALLS, 0, nope)", true),
        ("CALL pagerank(NOPE)", true),
        ("CALL pagerank(CALLS) YIELD rank", true),
        (
            "CALL pagerank(CALLS) YIELD score, score AS s, node AS score",
            true,
        ),
        (
            "CALL pagerank(CALLS) YIELD node, score MATCH (score) RETURN node",
            true,
        ),
    ] {
        match lower(&parse(q).unwrap(), &cat).err() {
            Some(GqlError::Semantic(_)) if semantic => {}
            Some(GqlError::Unsupported(_)) if !semantic => {}
            other => panic!("{q}: {other:?}"),
        }
    }
}

#[tokio::test]
async fn sum_and_avg_grouped() {
    // Per caller: the sum over its calls of the callee's size (a callee twice counts
    // twice), over its distinct callee sizes, and the mean (a float).
    let t = run(
        "MATCH (a:Func)-[:CALLS]->(b:Func) RETURN a, sum(b.size) AS s, sum(DISTINCT b.size) AS d, avg(b.size) AS m",
    )
    .await;
    assert_eq!(t.float_columns, [3]);
    let mut want: Vec<(Vec<u64>, f64)> = Vec::new();
    for a in FUNC {
        let bs: Vec<u64> = CALLS
            .iter()
            .filter(|e| e.0 == a && FUNC.contains(&e.1))
            .map(|e| size(e.1).unwrap())
            .collect();
        if bs.is_empty() {
            continue;
        }
        let d: BTreeSet<u64> = bs.iter().copied().collect();
        let s: u64 = bs.iter().sum();
        want.push((vec![a, s, d.iter().sum()], s as f64 / bs.len() as f64));
    }
    let got: Vec<(Vec<u64>, f64)> = (0..t.rows.len())
        .map(|r| (t.rows[r][..3].to_vec(), t.float(r, 3).unwrap()))
        .collect();
    assert_eq!(got, want);
    // No groups: one row; the mean of every Func size.
    let t = run("MATCH (a:Func) RETURN sum(a.size), avg(a.size)").await;
    let total: u64 = FUNC_SIZE.iter().map(|p| p.1).sum();
    assert_eq!(t.rows[0][0], total);
    assert_eq!(t.float(0, 1), Some(total as f64 / FUNC_SIZE.len() as f64));
    // A sum of floats: the PageRank scores of the functions.
    let (a, at) = calls_csr();
    let pr = kleene_graph::pagerank(
        &a,
        &at,
        &kleene_graph::PageRankOptions::default(),
        &CpuDevice::new(2),
    )
    .unwrap();
    let t = run("CALL pagerank(CALLS) YIELD node, score MATCH (node:Func) RETURN sum(score) AS s")
        .await;
    let want: f64 = FUNC.iter().map(|&v| pr.scores[v as usize] as f64).sum();
    assert!((t.float(0, 0).unwrap() - want).abs() < 1e-9, "{t}");
    // Ordered by a sum.
    let t = run(
        "MATCH (a:Func)-[:CALLS]->(b:Func) RETURN a, sum(b.size) AS s ORDER BY s DESC, a LIMIT 2",
    )
    .await;
    let mut by: Vec<(u64, u64)> = want_sums();
    by.sort_by(|x, y| y.1.cmp(&x.1).then(x.0.cmp(&y.0)));
    assert_eq!(
        t.rows,
        by.iter()
            .take(2)
            .map(|&(a, s)| vec![a, s])
            .collect::<Vec<_>>()
    );
}

/// Per Func caller with a Func callee: the sum of the callees' sizes.
fn want_sums() -> Vec<(u64, u64)> {
    FUNC.iter()
        .filter_map(|&a| {
            let bs: Vec<u64> = CALLS
                .iter()
                .filter(|e| e.0 == a && FUNC.contains(&e.1))
                .map(|e| size(e.1).unwrap())
                .collect();
            (!bs.is_empty()).then(|| (a, bs.iter().sum()))
        })
        .collect()
}

/// Rows with `None` for each null cell.
fn with_nulls(t: &Table) -> Vec<Vec<Option<u64>>> {
    (0..t.rows.len())
        .map(|r| {
            (0..t.columns.len())
                .map(|c| (!t.is_null(r, c)).then_some(t.rows[r][c]))
                .collect()
        })
        .collect()
}

/// Each Func `a` with the ends `f` of its edges in `edges` that pass `keep`, or one row
/// with no `f`: OPTIONAL MATCH by a plain loop.
fn left_join(edges: &[(u64, u64)], keep: &dyn Fn(u64, u64) -> bool) -> Vec<Vec<Option<u64>>> {
    let mut out = Vec::new();
    for a in FUNC {
        let fs: BTreeSet<u64> = edges
            .iter()
            .filter(|e| e.0 == a && keep(a, e.1))
            .map(|e| e.1)
            .collect();
        if fs.is_empty() {
            out.push(vec![Some(a), None]);
        }
        out.extend(fs.iter().map(|&f| vec![Some(a), Some(f)]));
    }
    out.sort();
    out
}

/// Sorted as `ORDER BY` sorts them: nulls last.
fn nulls_last(mut rows: Vec<Vec<Option<u64>>>) -> Vec<Vec<Option<u64>>> {
    rows.sort_by(|x, y| {
        x.iter()
            .zip(y)
            .map(|(a, b)| match (a, b) {
                (None, None) => std::cmp::Ordering::Equal,
                (None, Some(_)) => std::cmp::Ordering::Greater,
                (Some(_), None) => std::cmp::Ordering::Less,
                (Some(a), Some(b)) => a.cmp(b),
            })
            .find(|o| o.is_ne())
            .unwrap_or(std::cmp::Ordering::Equal)
    });
    rows
}

#[tokio::test]
async fn optional_match() {
    let sorted = |t: &Table| {
        let mut r = with_nulls(t);
        r.sort();
        r
    };
    // Every Func, with its file or null.
    let t = run("MATCH (a:Func) OPTIONAL MATCH (a)-[:IN]->(f:File) RETURN a, f").await;
    assert_eq!(sorted(&t), left_join(&IN, &|_, _| true));
    assert!(t.is_null(t.rows.len() - 1, 1) && !t.is_null(0, 1));
    assert!(t.to_string().contains("null"), "{t}");
    // The OPTIONAL MATCH's WHERE on its own node.
    let t =
        run("MATCH (a:Func) OPTIONAL MATCH (a)-[:CALLS]->(b:Func) WHERE b.size > 10 RETURN a, b")
            .await;
    let callee = |_, b| FUNC.contains(&b) && size(b).unwrap() > 10;
    assert_eq!(sorted(&t), left_join(&CALLS, &callee));
    // ... and on the node before it: the node stays, unextended.
    let t = run("MATCH (a:Func) OPTIONAL MATCH (a)-[:IN]->(f) WHERE a.size > 10 RETURN a, f").await;
    assert_eq!(sorted(&t), left_join(&IN, &|a, _| size(a).unwrap() > 10));
    // A node's property of the OPTIONAL MATCH, null with it.
    let t = run("MATCH (a:Lib) OPTIONAL MATCH (b:Func)-[:CALLS]->(a) RETURN a, b, b.size").await;
    let mut want: Vec<Vec<Option<u64>>> = Vec::new();
    for a in LIB {
        let bs: Vec<u64> = CALLS
            .iter()
            .filter(|e| e.1 == a && FUNC.contains(&e.0))
            .map(|e| e.0)
            .collect();
        if bs.is_empty() {
            want.push(vec![Some(a), None, None]);
        }
        want.extend(bs.iter().map(|&b| vec![Some(a), Some(b), size(b)]));
    }
    want.sort();
    assert_eq!(sorted(&t), want);
    // ORDER BY: nulls last rising, first falling.
    let t = run("MATCH (a:Func) OPTIONAL MATCH (a)-[:IN]->(f) RETURN a, f ORDER BY f, a").await;
    let w = left_join(&IN, &|_, _| true);
    let mut by_f: Vec<Vec<Option<u64>>> = w.iter().map(|r| vec![r[1], r[0]]).collect();
    by_f = nulls_last(by_f);
    let by_f: Vec<Vec<Option<u64>>> = by_f.iter().map(|r| vec![r[1], r[0]]).collect();
    assert_eq!(with_nulls(&t), by_f);
    let t =
        run("MATCH (a:Func) OPTIONAL MATCH (a)-[:IN]->(f) RETURN a, f ORDER BY f DESC, a").await;
    assert_eq!(with_nulls(&t)[0][1], None);
    assert_eq!(with_nulls(&t).last().unwrap()[1], Some(10));
    // DISTINCT keeps one null.
    let t = run("MATCH (a:Func) OPTIONAL MATCH (a)-[:IN]->(f) RETURN DISTINCT f ORDER BY f").await;
    assert_eq!(
        with_nulls(&t),
        vec![vec![Some(10)], vec![Some(11)], vec![None]]
    );
    // count(f) counts found rows (0 for none), count(*) every row.
    let t = run(
        "MATCH (a:Func) OPTIONAL MATCH (a)-[:IN]->(f) RETURN a, count(f) AS n, count(*) AS rows",
    )
    .await;
    let want: Vec<Vec<u64>> = FUNC
        .iter()
        .map(|&a| {
            let n = IN.iter().filter(|e| e.0 == a).count() as u64;
            vec![a, n, n.max(1)]
        })
        .collect();
    assert_eq!(t.rows, want);
    assert!(t.nulls.is_empty());
    let t = run(
        "MATCH (a:Func) OPTIONAL MATCH (a)-[:IN]->(f) RETURN count(f), count(DISTINCT f), count(*)",
    )
    .await;
    let found = IN.iter().filter(|e| FUNC.contains(&e.0)).count() as u64;
    let none = FUNC
        .iter()
        .filter(|&&a| !IN.iter().any(|e| e.0 == a))
        .count() as u64;
    assert_eq!(t.rows, vec![vec![found, 2, found + none]]);
    // Typed rows: null as Datum::Null.
    let q = lower(
        &parse("MATCH (a:Func) OPTIONAL MATCH (a)-[:IN]->(f) RETURN a, f").unwrap(),
        &catalog(),
    )
    .unwrap();
    let typed = q.run_typed(&engine()).await.unwrap();
    assert_eq!(typed.rows.last().unwrap()[1], kleene_plan::Datum::Null);
    // Refused.
    let cat = catalog();
    for q in [
        "MATCH (a:Func) OPTIONAL MATCH (a)-[:IN]->(f) RETURN f, count(*)",
        "MATCH (a:Func) OPTIONAL MATCH (a)-[:CALLS]->(b:Func) WHERE a.size = 1 OR b.size = 2 RETURN a",
        "MATCH (a:Func) OPTIONAL MATCH p = (a)-[:IN]->(f) RETURN nodes(p)",
    ] {
        assert!(
            matches!(
                lower(&parse(q).unwrap(), &cat),
                Err(GqlError::Unsupported(_))
            ),
            "{q}"
        );
    }
}

/// The ends of `a`'s edges in `edges` whose end is in `to`, or one `None`: one OPTIONAL
/// MATCH step by a plain loop.
fn ends_or_none(edges: &[(u64, u64)], a: Option<u64>, to: &[u64]) -> Vec<Option<u64>> {
    let ends: BTreeSet<u64> = edges
        .iter()
        .filter(|e| Some(e.0) == a && to.contains(&e.1))
        .map(|e| e.1)
        .collect();
    if ends.is_empty() {
        vec![None]
    } else {
        ends.into_iter().map(Some).collect()
    }
}

/// Several OPTIONAL MATCH clauses, each extending the rows so far (a part it cannot match
/// null, a later clause on a null node not matching), and min / max / sum / avg of
/// OPTIONAL MATCH values with nulls skipped (null for a group with none), by plain loops.
#[tokio::test]
async fn several_optional_matches_and_null_skipping_aggregates() {
    let sorted = |t: &Table| {
        let mut r = with_nulls(t);
        r.sort();
        r
    };
    // Two clauses on the first MATCH's node.
    let t = run(
        "MATCH (a:Func) OPTIONAL MATCH (a)-[:IN]->(f:File) OPTIONAL MATCH (a)-[:CALLS]->(b:Lib) \
         RETURN a, f, b",
    )
    .await;
    let mut want = Vec::new();
    for a in FUNC {
        for f in ends_or_none(&IN, Some(a), &FILE) {
            for b in ends_or_none(&CALLS, Some(a), &LIB) {
                want.push(vec![Some(a), f, b]);
            }
        }
    }
    want.sort();
    assert_eq!(sorted(&t), want);
    // A chain: the second clause on the first's node, which may be null.
    let t = run(
        "MATCH (a:Func) OPTIONAL MATCH (a)-[:CALLS]->(b:Lib) OPTIONAL MATCH (b)-[:IN]->(f:File) \
         RETURN a, b, f",
    )
    .await;
    let mut want = Vec::new();
    for a in FUNC {
        for b in ends_or_none(&CALLS, Some(a), &LIB) {
            let fs = match b {
                Some(_) => ends_or_none(&IN, b, &FILE),
                None => vec![None],
            };
            for f in fs {
                want.push(vec![Some(a), b, f]);
            }
        }
    }
    want.sort();
    assert_eq!(sorted(&t), want);
    assert!(want.contains(&vec![Some(3), Some(7), Some(11)]));
    assert!(want.contains(&vec![Some(1), Some(8), None]));
    // A WHERE on the second clause's own node, and a property of it.
    let t = run("MATCH (a:Func) OPTIONAL MATCH (a)-[:IN]->(f:File) \
         OPTIONAL MATCH (a)-[:CALLS]->(c:Func) WHERE c.size > 10 RETURN a, f, c, c.size")
    .await;
    let mut want = Vec::new();
    for a in FUNC {
        let big: Vec<u64> = FUNC
            .iter()
            .copied()
            .filter(|&c| size(c).unwrap() > 10)
            .collect();
        for f in ends_or_none(&IN, Some(a), &FILE) {
            for c in ends_or_none(&CALLS, Some(a), &big) {
                want.push(vec![Some(a), f, c, c.and_then(size)]);
            }
        }
    }
    want.sort();
    assert_eq!(sorted(&t), want);
    // Typed rows: each clause's nulls as Datum::Null.
    let q = lower(
        &parse(
            "MATCH (a:Func) WHERE a = 6 OPTIONAL MATCH (a)-[:IN]->(f) \
             OPTIONAL MATCH (a)-[:CALLS]->(b:Lib) RETURN a, f, b",
        )
        .unwrap(),
        &catalog(),
    )
    .unwrap();
    let typed = q.run_typed(&engine()).await.unwrap();
    assert_eq!(
        typed.rows,
        vec![vec![
            kleene_plan::Datum::U64(6),
            kleene_plan::Datum::Null,
            kleene_plan::Datum::Null
        ]]
    );

    // min / max / sum / avg of an OPTIONAL MATCH value: nulls skipped, null for none.
    let t = run("MATCH (a:Func) OPTIONAL MATCH (a)-[:CALLS]->(b:Func) \
         RETURN a, min(b.size), max(b.size), sum(b.size), count(b), avg(b.size)")
    .await;
    let mut want = Vec::new();
    let mut avgs = Vec::new();
    for a in FUNC {
        let sizes: Vec<u64> = ends_or_none(&CALLS, Some(a), &FUNC)
            .into_iter()
            .flatten()
            .map(|b| size(b).unwrap())
            .collect();
        let n = sizes.len() as u64;
        let (min, max) = (sizes.iter().min().copied(), sizes.iter().max().copied());
        let sum = (n > 0).then(|| sizes.iter().sum::<u64>());
        want.push(vec![Some(a), min, max, sum, Some(n)]);
        avgs.push(sum.map(|s| s as f64 / n as f64));
    }
    let got: Vec<Vec<Option<u64>>> = with_nulls(&t)
        .into_iter()
        .map(|r| r[..5].to_vec())
        .collect();
    assert_eq!(got, want);
    let got_avg: Vec<Option<f64>> = (0..t.rows.len())
        .map(|r| (!t.is_null(r, 5)).then(|| t.float(r, 5).unwrap()))
        .collect();
    assert_eq!(got_avg, avgs);
    assert!(
        want.iter().any(|r| r[1].is_none()),
        "a Func with no Func callee"
    );
    // With no groups, over two clauses, and a group whose values are all null.
    let t = run(
        "MATCH (a:Func) OPTIONAL MATCH (a)-[:IN]->(f) OPTIONAL MATCH (a)-[:CALLS]->(b:Lib) \
         RETURN min(b.size), max(b.size), sum(b.size), count(f)",
    )
    .await;
    let lib_sizes: Vec<u64> = CALLS
        .iter()
        .filter(|e| FUNC.contains(&e.0) && LIB.contains(&e.1))
        .map(|e| size(e.1).unwrap())
        .collect();
    let mut count_f = 0;
    for a in FUNC {
        let fs = ends_or_none(&IN, Some(a), &FILE);
        let bs = ends_or_none(&CALLS, Some(a), &LIB).len() as u64;
        count_f += fs.iter().flatten().count() as u64 * bs;
    }
    assert_eq!(
        with_nulls(&t),
        vec![vec![
            lib_sizes.iter().min().copied(),
            lib_sizes.iter().max().copied(),
            Some(lib_sizes.iter().sum()),
            Some(count_f),
        ]]
    );
    let t = run(
        "MATCH (a:Func) WHERE a = 4 OPTIONAL MATCH (a)-[:CALLS]->(b:Lib) \
         RETURN a, max(b.size) AS m, sum(b.size) AS s ORDER BY m",
    )
    .await;
    assert_eq!(with_nulls(&t), vec![vec![Some(4), None, None]]);

    // Still refused: a MATCH after an OPTIONAL MATCH (by the parser), a group key of one.
    assert!(
        parse(
            "MATCH (a) OPTIONAL MATCH (a)-[:T]->(b) OPTIONAL MATCH (b)-[:T]->(c) MATCH (d) RETURN a"
        )
        .is_err()
    );
    let q = "MATCH (a:Func) OPTIONAL MATCH (a)-[:IN]->(f) OPTIONAL MATCH (a)-[:CALLS]->(b) \
             RETURN b, count(*)";
    assert!(matches!(
        lower(&parse(q).unwrap(), &catalog()),
        Err(GqlError::Unsupported(_))
    ));
}

#[tokio::test]
async fn union_and_union_all() {
    let t = run("MATCH (a:Func) WHERE a.size > 30 RETURN a AS x UNION MATCH (a:Lib) RETURN a AS x")
        .await;
    let mut want: Vec<u64> = FUNC_SIZE.iter().filter(|p| p.1 > 30).map(|p| p.0).collect();
    want.extend(LIB);
    assert_eq!(t.rows, want.iter().map(|&x| vec![x]).collect::<Vec<_>>());
    // ALL: each part's rows in turn, repeats kept; UNION: the distinct ones.
    let files = |all: &str| {
        format!(
            "MATCH (a:Func)-[:IN]->(f) RETURN f, a.size AS s UNION{all} \
             MATCH (a:Lib)-[:IN]->(f) RETURN f, a.size AS s UNION{all} \
             MATCH (a:Func)-[:IN]->(f) RETURN f, a.size AS s"
        )
    };
    let t = run(&files(" ALL")).await;
    let func: Vec<Vec<u64>> = {
        let mut v: Vec<Vec<u64>> = IN
            .iter()
            .filter(|e| FUNC.contains(&e.0))
            .map(|e| vec![e.1, size(e.0).unwrap()])
            .collect();
        v.sort();
        v
    };
    let lib: Vec<Vec<u64>> = IN
        .iter()
        .filter(|e| LIB.contains(&e.0))
        .map(|e| vec![e.1, size(e.0).unwrap()])
        .collect();
    assert_eq!(t.rows, [func.clone(), lib.clone(), func.clone()].concat());
    let t = run(&files("")).await;
    let set: BTreeSet<Vec<u64>> = func.iter().chain(&lib).cloned().collect();
    assert_eq!(t.rows, set.into_iter().collect::<Vec<_>>());
    // A null and a 0 stay apart; the explain text lists every part.
    let t = run(
        "MATCH (a:Func) OPTIONAL MATCH (a)-[:IN]->(f:File) RETURN f UNION MATCH (a:Func) WHERE a = 0 RETURN a AS f",
    )
    .await;
    assert_eq!(
        with_nulls(&t),
        vec![vec![Some(0)], vec![Some(10)], vec![Some(11)], vec![None]]
    );
    let q = parse("MATCH (a:Func) RETURN a UNION ALL MATCH (a:Lib) RETURN a").unwrap();
    let ex = lower(&q, &catalog()).unwrap().explain().unwrap();
    assert!(
        ex.contains("UNION ALL part 2:") && ex.contains("(a): label scan Lib"),
        "{ex}"
    );
    // Refused.
    let cat = catalog();
    let q = parse("MATCH (a:Func) RETURN a UNION MATCH (b:Lib) RETURN b").unwrap();
    assert!(
        matches!(lower(&q, &cat), Err(GqlError::Semantic(m)) if m.contains("different columns"))
    );
    for q in [
        "MATCH (a:Func) RETURN a ORDER BY a UNION MATCH (a:Lib) RETURN a",
        "MATCH (a:Func) RETURN a UNION MATCH (a:Lib) RETURN a LIMIT 1",
    ] {
        assert!(
            matches!(
                lower(&parse(q).unwrap(), &cat),
                Err(GqlError::Unsupported(_))
            ),
            "{q}"
        );
    }
}

/// Kruskal over `CALLS` taken both ways (self-loops left out): the edge count and total.
fn kruskal(weighted: bool) -> (usize, u64) {
    let mut es: Vec<(u64, u64, u64)> = CALLS
        .iter()
        .filter(|e| e.0 != e.1)
        .map(|&(a, b)| (if weighted { weight(a, b) } else { 1 }, a, b))
        .collect();
    es.sort_unstable();
    let mut p: Vec<u64> = (0..12).collect();
    fn find(p: &[u64], mut x: u64) -> u64 {
        while p[x as usize] != x {
            x = p[x as usize];
        }
        x
    }
    let (mut k, mut t) = (0, 0);
    for (w, a, b) in es {
        let (x, y) = (find(&p, a), find(&p, b));
        if x != y {
            p[x as usize] = y;
            k += 1;
            t += w;
        }
    }
    (k, t)
}

#[tokio::test]
async fn call_spanning_forest() {
    let t =
        run("CALL msf(CALLS, weight) YIELD source, target, weight RETURN source, target, weight")
            .await;
    let (k, total) = kruskal(true);
    assert_eq!(t.rows.len(), k);
    for r in &t.rows {
        assert!(CALLS.contains(&(r[0], r[1])), "{r:?} is a call");
        assert_eq!(r[2], weight(r[0], r[1]));
    }
    assert_eq!(t.rows.iter().map(|r| r[2]).sum::<u64>(), total);
    // the total as a sum (over every yielded edge: a match is a binding of the yielded
    // values, so yielding the weight alone would sum each weight once), other spellings
    for q in [
        "CALL msf(CALLS, weight) YIELD source, target, weight RETURN sum(weight) AS total",
        "CALL gds.spanningForest.stream(CALLS, weight) YIELD source, target, weight AS w RETURN sum(w) AS total",
        "CALL minimumSpanningTree('CALLS', weight) YIELD source AS a, target AS b, weight RETURN sum(weight) AS total",
    ] {
        assert_eq!(run(q).await.rows, vec![vec![total]], "{q}");
    }
    // unit weights: one edge fewer than the nodes of each component (0..=3, 7, 8, 9 and
    // 4, 5, 6: ten nodes, two trees)
    let t = run("CALL msf(CALLS)").await;
    assert_eq!(t.columns, ["source", "target", "weight"]);
    assert_eq!(t.rows.len(), kruskal(false).0);
    assert_eq!(t.rows.len(), 8);
    let cat = catalog();
    for q in [
        "CALL msf(CALLS, 3)",
        "CALL msf(CALLS, nope)",
        "CALL msf(CALLS, weight, weight)",
        "CALL msf(CALLS) YIELD node",
    ] {
        assert!(
            matches!(lower(&parse(q).unwrap(), &cat), Err(GqlError::Semantic(_))),
            "{q}"
        );
    }
}

/// Ford-Fulkerson by breadth-first paths over `CALLS` with capacities `cap`.
fn calls_flow(s: usize, t: usize, cap: impl Fn(u64, u64) -> u64) -> u64 {
    const M: usize = 12;
    let mut r = [[0u64; M]; M];
    for &(a, b) in CALLS.iter().filter(|e| e.0 != e.1) {
        r[a as usize][b as usize] += cap(a, b);
    }
    let mut value = 0;
    loop {
        let mut prev = [usize::MAX; M];
        prev[s] = s;
        let mut q = VecDeque::from([s]);
        while let Some(u) = q.pop_front() {
            for v in 0..M {
                if prev[v] == usize::MAX && r[u][v] > 0 {
                    prev[v] = u;
                    q.push_back(v);
                }
            }
        }
        if prev[t] == usize::MAX {
            return value;
        }
        let (mut push, mut v) = (u64::MAX, t);
        while v != s {
            push = push.min(r[prev[v]][v]);
            v = prev[v];
        }
        let mut v = t;
        while v != s {
            r[prev[v]][v] -= push;
            r[v][prev[v]] += push;
            v = prev[v];
        }
        value += push;
    }
}

#[tokio::test]
async fn call_max_flow() {
    for (s, t) in [(0u64, 9u64), (0, 3), (1, 7), (4, 6), (3, 0)] {
        let q = format!("CALL maxflow(CALLS, {s}, {t}, weight) YIELD flow RETURN flow");
        let want = calls_flow(s as usize, t as usize, weight);
        assert_eq!(run(&q).await.rows, vec![vec![want]], "{q}");
        let q = format!("CALL gds.maxFlow.stream('CALLS', {s}, {t})");
        let t2 = run(&q).await;
        assert_eq!(t2.columns, ["flow"]);
        assert_eq!(
            t2.rows,
            vec![vec![calls_flow(s as usize, t as usize, |_, _| 1)]],
            "{q}"
        );
    }
    let cat = catalog();
    for q in [
        "CALL maxflow(CALLS, 0)",
        "CALL maxflow(CALLS, 0, 3, nope)",
        "CALL maxflow(CALLS, 0, 3, 4)",
        "CALL maxflow(CALLS, 0, 3, weight, weight)",
        "CALL maxflow(CALLS, 0, 3) YIELD node",
    ] {
        assert!(
            matches!(lower(&parse(q).unwrap(), &cat), Err(GqlError::Semantic(_))),
            "{q}"
        );
    }
}

/// `CALLS` with typed edge properties: `fw` float (the weight plus a half), `sw` signed.
fn typed_catalog() -> Catalog {
    use std::sync::Arc;

    use arrow_array::{Float64Array, Int64Array, UInt64Array};
    let ends = |i: usize| -> arrow_array::ArrayRef {
        Arc::new(UInt64Array::from_iter_values(
            CALLS.iter().map(|e| if i == 0 { e.0 } else { e.1 }),
        ))
    };
    let mut c = catalog();
    c.typed_edge_property(
        "CALLS",
        "fw",
        Source::Columns(vec![
            ends(0),
            ends(1),
            Arc::new(Float64Array::from_iter_values(
                CALLS.iter().map(|&(a, b)| weight(a, b) as f64 + 0.5),
            )),
        ]),
        Type::F64,
    )
    .typed_edge_property(
        "CALLS",
        "sw",
        Source::Columns(vec![
            ends(0),
            ends(1),
            Arc::new(Int64Array::from_iter_values(
                CALLS.iter().map(|&(a, b)| weight(a, b) as i64 - 3),
            )),
        ]),
        Type::I64,
    );
    c
}

#[tokio::test]
async fn typed_weights_and_capacities() {
    let cat = typed_catalog();
    let q = "CALL msf(CALLS, fw) YIELD source, target, weight RETURN source, target, weight";
    let t = lower(&parse(q).unwrap(), &cat)
        .unwrap()
        .run_typed(&engine())
        .await
        .unwrap();
    let (k, total) = kruskal(true);
    assert_eq!(t.rows.len(), k);
    let mut sum = 0.0;
    for r in &t.rows {
        let (Datum::U64(a), Datum::U64(b), Datum::F64(w)) = (&r[0], &r[1], &r[2]) else {
            panic!("{r:?}: two vertices and a float weight");
        };
        assert_eq!(*w, weight(*a, *b) as f64 + 0.5);
        sum += w;
    }
    assert_eq!(sum, total as f64 + 0.5 * k as f64);
    // float capacities: a float flow, the flow over the weights plus a half each
    let q = "CALL maxflow(CALLS, 0, 3, fw) YIELD flow RETURN flow";
    let t = lower(&parse(q).unwrap(), &cat)
        .unwrap()
        .run_typed(&engine())
        .await
        .unwrap();
    let want = calls_flow_f64(0, 3, |a, b| weight(a, b) as f64 + 0.5);
    match &t.rows[..] {
        [r] => match r[0] {
            Datum::F64(x) => assert!((x - want).abs() < 1e-9, "{x} for {want}"),
            ref d => panic!("{d:?}: a float flow"),
        },
        rows => panic!("{rows:?}: one row"),
    }
    // signed weights: a forest of signed weights, the same total less 3 an edge
    let q = "CALL msf(CALLS, sw) YIELD source, target, weight RETURN source, target, weight";
    let t = lower(&parse(q).unwrap(), &cat)
        .unwrap()
        .run_typed(&engine())
        .await
        .unwrap();
    assert_eq!(t.rows.len(), k);
    let mut sum = 0i64;
    for r in &t.rows {
        let (Datum::U64(a), Datum::U64(b), Datum::I64(w)) = (&r[0], &r[1], &r[2]) else {
            panic!("{r:?}: two vertices and a signed weight");
        };
        assert_eq!(*w, weight(*a, *b) as i64 - 3);
        sum += w;
    }
    assert_eq!(sum, total as i64 - 3 * k as i64);
    // signed capacities are refused by the plan, as a source that is the target
    for q in ["CALL maxflow(CALLS, 0, 3, sw)", "CALL maxflow(CALLS, 3, 3)"] {
        assert!(lower(&parse(q).unwrap(), &cat).is_err(), "{q}");
    }
}

/// Ford-Fulkerson by breadth-first paths over `CALLS` with float capacities `cap`.
fn calls_flow_f64(s: usize, t: usize, cap: impl Fn(u64, u64) -> f64) -> f64 {
    const M: usize = 12;
    let mut r = [[0f64; M]; M];
    for &(a, b) in CALLS.iter().filter(|e| e.0 != e.1) {
        r[a as usize][b as usize] += cap(a, b);
    }
    let mut value = 0.0;
    loop {
        let mut prev = [usize::MAX; M];
        prev[s] = s;
        let mut q = VecDeque::from([s]);
        while let Some(u) = q.pop_front() {
            for v in 0..M {
                if prev[v] == usize::MAX && r[u][v] > 1e-12 {
                    prev[v] = u;
                    q.push_back(v);
                }
            }
        }
        if prev[t] == usize::MAX {
            return value;
        }
        let (mut push, mut v) = (f64::INFINITY, t);
        while v != s {
            push = push.min(r[prev[v]][v]);
            v = prev[v];
        }
        let mut v = t;
        while v != s {
            r[prev[v]][v] -= push;
            r[v][prev[v]] += push;
            v = prev[v];
        }
        value += push;
    }
}