relate-executor 1.5.0

In-memory graph and Cypher physical executor
Documentation
//! Cross-clause HashJoin and SemiMask SIP tests across `MATCH ... WITH ... MATCH` (`SNW q7`).

use std::collections::BTreeMap;

use relate_core::Value;

use super::{take_hash_join_engagements, with_hash_join_disabled, with_hash_join_forced};
use crate::exec::test_support::{exec_cypher, profiled, same_rows, try_exec_cypher_params};
use crate::graph::Graph;

fn build_snw_q7_graph(persons: usize, interests_per_person: usize) -> Graph {
    let g = Graph::default();
    g.begin_write().unwrap();

    let city = g
        .create_node(
            vec!["City".into()],
            BTreeMap::from([("name".into(), Value::String("Metropolis".into()))]),
        )
        .unwrap();

    let mut interest_nodes = Vec::new();
    for topic in ["graph", "databases", "rust", "distributed"] {
        interest_nodes.push(
            g.create_node(
                vec!["Interest".into()],
                BTreeMap::from([("topic".into(), Value::String(topic.into()))]),
            )
            .unwrap(),
        );
    }

    for p in 0..persons {
        let person = g
            .create_node(
                vec!["Person".into()],
                BTreeMap::from([
                    ("id".into(), Value::Int(p as i64)),
                    ("name".into(), Value::String(format!("person_{p}").into())),
                ]),
            )
            .unwrap();

        g.create_rel(person, city, "LIVES_IN".into(), BTreeMap::new())
            .unwrap();

        for i in 0..interests_per_person {
            let int_node = interest_nodes[i % interest_nodes.len()];
            g.create_rel(person, int_node, "HAS_INTEREST".into(), BTreeMap::new())
                .unwrap();
        }
    }

    g.commit_write();
    g
}

#[test]
fn snw_q7_cross_clause_hash_join_multiplicity_parity() {
    let g = build_snw_q7_graph(150, 4);
    let query = "MATCH (p:Person)-[:LIVES_IN]->(s) WITH p, s \
                 MATCH (p)-[:HAS_INTEREST]->(i:Interest) WHERE i.topic = 'graph' \
                 RETURN count(p) AS c";

    let _ = take_hash_join_engagements();
    let joined = exec_cypher(&g, query);
    assert!(
        take_hash_join_engagements() >= 1,
        "cross-clause hash join engaged"
    );

    let nested = with_hash_join_disabled(|| exec_cypher(&g, query));
    assert!(
        same_rows(&joined, &nested),
        "multiplicity mode matches nested loop"
    );
    assert_eq!(joined.rows, vec![vec![Value::Int(150)]]);
}

#[test]
fn cross_clause_hash_join_rows_mode_when_internal_var_needed() {
    let g = build_snw_q7_graph(140, 2);
    let query = "MATCH (p:Person)-[:LIVES_IN]->(s) WITH p, s \
                 MATCH (p)-[:HAS_INTEREST]->(i:Interest) \
                 RETURN p.id AS pid, i.topic AS topic ORDER BY pid, topic LIMIT 50";

    let _ = take_hash_join_engagements();
    let joined = exec_cypher(&g, query);
    assert!(
        take_hash_join_engagements() >= 1,
        "cross-clause hash join engaged in rows mode"
    );

    let nested = with_hash_join_disabled(|| exec_cypher(&g, query));
    assert!(same_rows(&joined, &nested), "rows mode matches nested loop");
    assert_eq!(joined.rows.len(), 50);
}

#[test]
fn cross_clause_hash_join_rows_mode_when_subsequent_clause_consumes_internal_var() {
    let g = build_snw_q7_graph(140, 2);
    // MATCH has no immediate projection/reduce (the following clause is WITH i),
    // so Multiplicity mode must be declined in favor of Rows mode to preserve `i`.
    let query = "MATCH (p:Person)-[:LIVES_IN]->(s) WITH p, s \
                 MATCH (p)-[:HAS_INTEREST]->(i:Interest) \
                 WITH i \
                 RETURN count(i) AS c";

    let _ = take_hash_join_engagements();
    let joined = exec_cypher(&g, query);
    assert!(
        take_hash_join_engagements() >= 1,
        "cross-clause hash join engaged"
    );

    let nested = with_hash_join_disabled(|| exec_cypher(&g, query));
    assert!(
        same_rows(&joined, &nested),
        "rows mode preserves internal var across WITH"
    );
    assert_eq!(joined.rows, vec![vec![Value::Int(280)]]);
}

#[test]
fn cross_clause_hash_join_with_limit_and_early_halt() {
    let g = build_snw_q7_graph(150, 3);
    let query = "MATCH (p:Person)-[:LIVES_IN]->(s) WITH p, s \
                 MATCH (p)-[:HAS_INTEREST]->(i:Interest) \
                 RETURN p.id AS pid LIMIT 10";

    let _ = take_hash_join_engagements();
    let joined = exec_cypher(&g, query);
    assert!(
        take_hash_join_engagements() >= 1,
        "cross-clause hash join engaged with LIMIT"
    );

    let nested = with_hash_join_disabled(|| exec_cypher(&g, query));
    assert_eq!(joined.rows.len(), 10);
    assert_eq!(joined.rows.len(), nested.rows.len());
}

#[test]
fn cross_clause_hash_join_profile_metrics() {
    let g = build_snw_q7_graph(150, 4);
    let query = "MATCH (p:Person)-[:LIVES_IN]->(s) WITH p, s \
                 MATCH (p)-[:HAS_INTEREST]->(i:Interest) WHERE i.topic = 'rust' \
                 RETURN count(p) AS c";

    let _ = take_hash_join_engagements();
    let records = profiled(&g, query);
    assert!(take_hash_join_engagements() >= 1);

    let hj_rec = records.iter().find(|r| r.hash_join.build_rows > 0);
    assert!(
        hj_rec.is_some(),
        "PROFILE records contain cross-clause hash_join metrics"
    );
    let hj = hj_rec.unwrap().hash_join;
    assert!(hj.build_rows > 0, "build_rows tracked: {}", hj.build_rows);
    assert!(hj.probe_rows > 0, "probe_rows tracked: {}", hj.probe_rows);
}

#[test]
fn cross_clause_hash_join_parameter_equivalence() {
    let g = build_snw_q7_graph(150, 4);
    let query_literal = "MATCH (p:Person)-[:LIVES_IN]->(s) WITH p, s \
                         MATCH (p)-[:HAS_INTEREST]->(i:Interest) WHERE i.topic = 'graph' \
                         RETURN count(p) AS c";
    let query_param = "MATCH (p:Person)-[:LIVES_IN]->(s) WITH p, s \
                       MATCH (p)-[:HAS_INTEREST]->(i:Interest) WHERE i.topic = $topic \
                       RETURN count(p) AS c";

    let mut params = BTreeMap::new();
    params.insert("topic".into(), Value::String("graph".into()));

    let res_lit = exec_cypher(&g, query_literal);
    let res_param = try_exec_cypher_params(&g, query_param, &params).unwrap();
    assert!(same_rows(&res_lit, &res_param));
}

#[test]
fn cross_clause_non_node_variable_declines_without_panic() {
    let g = build_snw_q7_graph(50, 2);
    let query =
        "UNWIND range(1, 30) AS p WITH p MATCH (p:Person)-[:LIVES_IN]->(s) RETURN count(s) AS c";
    let res = exec_cypher(&g, query);
    assert_eq!(res.rows, vec![vec![Value::Int(0)]]);
}

#[test]
fn cross_clause_null_variable_declines_without_panic() {
    let g = build_snw_q7_graph(50, 2);
    let query = "UNWIND [null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null] AS p WITH p MATCH (p:Person)-[:LIVES_IN]->(s) RETURN count(s) AS c";
    let res = exec_cypher(&g, query);
    assert_eq!(res.rows, vec![vec![Value::Int(0)]]);
}

#[test]
fn cross_clause_comma_joined_match_declines_to_walker_with_full_correctness() {
    let g = build_snw_q7_graph(30, 2);
    let query = "MATCH (p:Person)-[:LIVES_IN]->(s) WITH p, s \
                 MATCH (p)-[:LIVES_IN]->(c), (p)-[:HAS_INTEREST]->(i) \
                 RETURN count(p) AS c";
    let res = exec_cypher(&g, query);
    let nested = with_hash_join_disabled(|| exec_cypher(&g, query));
    assert!(same_rows(&res, &nested));
    assert_eq!(res.rows, vec![vec![Value::Int(60)]]);
}

#[test]
fn cross_clause_where_referencing_outer_variable_declines_to_walker() {
    let g = build_snw_q7_graph(30, 2);
    let query = "MATCH (p:Person)-[:LIVES_IN]->(s) WITH p, s \
                 MATCH (p)-[:HAS_INTEREST]->(i:Interest) \
                 WHERE i.topic = s.name \
                 RETURN count(p) AS c";
    let res = exec_cypher(&g, query);
    let nested = with_hash_join_disabled(|| exec_cypher(&g, query));
    assert!(same_rows(&res, &nested));
    assert_eq!(res.rows, vec![vec![Value::Int(0)]]);
}

fn build_snw_q7_benchmark_graph(
    persons: usize,
    bound_persons: usize,
    num_interests: usize,
) -> Graph {
    let g = Graph::default();
    g.begin_write().unwrap();

    let target_city = g
        .create_node(
            vec!["City".into()],
            BTreeMap::from([("name".into(), Value::String("Berlin".into()))]),
        )
        .unwrap();

    let other_city = g
        .create_node(
            vec!["City".into()],
            BTreeMap::from([("name".into(), Value::String("Munich".into()))]),
        )
        .unwrap();

    let mut interest_nodes = Vec::new();
    for i in 0..num_interests {
        interest_nodes.push(
            g.create_node(
                vec!["Interest".into()],
                BTreeMap::from([(
                    "interest".into(),
                    Value::String(format!("topic_{i}").into()),
                )]),
            )
            .unwrap(),
        );
    }

    for p in 0..persons {
        let person = g
            .create_node(
                vec!["Person".into()],
                BTreeMap::from([
                    ("id".into(), Value::Int(p as i64)),
                    ("name".into(), Value::String(format!("person_{p}").into())),
                ]),
            )
            .unwrap();

        let city = if p < bound_persons {
            target_city
        } else {
            other_city
        };
        g.create_rel(person, city, "LIVES_IN".into(), BTreeMap::new())
            .unwrap();

        let int_node = interest_nodes[p % num_interests];
        g.create_rel(person, int_node, "HAS_INTEREST".into(), BTreeMap::new())
            .unwrap();
    }

    g.commit_write();
    g
}

#[test]
fn snw_q7_benchmark_scale_parity_and_db_hits() {
    let g = build_snw_q7_benchmark_graph(2000, 200, 20);
    let query = "MATCH (p:Person)-[:LIVES_IN]->(s:City {name: 'Berlin'}) WITH p, s \
                 MATCH (p)-[:HAS_INTEREST]->(i:Interest) WHERE tolower(i.interest) = tolower($interest) \
                 RETURN count(p) AS c, s.name AS city";

    let mut params = BTreeMap::new();
    params.insert("interest".into(), Value::String("TOPIC_0".into()));

    let _ = take_hash_join_engagements();
    let records = crate::exec::test_support::profiled_params(&g, query, &params);
    assert!(
        take_hash_join_engagements() >= 1,
        "cross-clause hash join must engage for SNW q7"
    );

    let total_db_hits: u64 = records.iter().map(|r| r.reads.total()).sum();

    let nested_res =
        with_hash_join_disabled(|| try_exec_cypher_params(&g, query, &params).unwrap());
    let joined_res = try_exec_cypher_params(&g, query, &params).unwrap();

    assert!(
        same_rows(&joined_res, &nested_res),
        "exact parity with nested loop"
    );
    assert_eq!(
        joined_res.rows,
        vec![vec![Value::Int(10), Value::String("Berlin".into())]]
    );

    // The second MATCH clause with hash-join reversed to i:Interest only scans 20 Interest nodes
    // and expands incoming edges for the 1 matching interest, instead of scanning all 2,000 Person nodes.
    // Total db_hits is dramatically smaller than scanning all 2,000 Person nodes.
    assert!(
        total_db_hits < 600,
        "total db_hits ({total_db_hits}) must be dramatically smaller than scanning all 2,000 Person nodes"
    );
}

#[test]
fn cross_clause_multi_shared_var_does_not_misapply_primary_semi_mask() {
    let g = build_snw_q7_benchmark_graph(400, 100, 10);
    // Both `p` (Person) and `i` (Interest) are carried across WITH and shared by the second MATCH.
    // Their NodeIds are disjoint: if `p`'s SemiMask were mistakenly installed under `i`,
    // the second MATCH would falsely reject every `i` node and return 0 rows.
    let query = "MATCH (p:Person)-[:HAS_INTEREST]->(i:Interest) WITH p, i \
                 MATCH (p)-[:HAS_INTEREST]->(i) RETURN p.name, i.interest";

    let _ = take_hash_join_engagements();
    let joined_res = with_hash_join_forced(|| exec_cypher(&g, query));
    assert!(
        take_hash_join_engagements() >= 1,
        "forced cross-clause hash join must engage for two shared variables"
    );
    let nested_res = with_hash_join_disabled(|| exec_cypher(&g, query));

    assert_eq!(joined_res.rows.len(), 400);
    assert!(
        same_rows(&joined_res, &nested_res),
        "multi-shared-var cross-clause join must match nested loop"
    );
}

#[test]
fn cross_clause_named_path_preserves_element_order() {
    let g = build_snw_q7_benchmark_graph(400, 100, 10);
    // `i:Interest` is much smaller than `p:Person`, so an unnamed pattern would reverse.
    // A named path `path = (p)-[:HAS_INTEREST]->(i)` must preserve `[p, i]` node order.
    let query = "MATCH (p:Person)-[:LIVES_IN]->(:City {name: 'Berlin'}) WITH p \
                 MATCH path = (p)-[:HAS_INTEREST]->(i:Interest {interest: 'topic_0'}) \
                 RETURN [n IN nodes(path) | labels(n)[0]] AS order";

    let _ = take_hash_join_engagements();
    let joined_res = with_hash_join_forced(|| exec_cypher(&g, query));
    assert!(
        take_hash_join_engagements() >= 1,
        "forced cross-clause hash join must engage for named path"
    );
    let nested_res = with_hash_join_disabled(|| exec_cypher(&g, query));

    assert!(!joined_res.rows.is_empty());
    assert!(
        same_rows(&joined_res, &nested_res),
        "named path element order must match nested loop"
    );
    for row in &joined_res.rows {
        assert_eq!(
            row[0],
            Value::List(
                vec![
                    Value::String("Person".into()),
                    Value::String("Interest".into()),
                ]
                .into(),
            )
        );
    }
}