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

nordisk/kleene

crates/kleene-plan/src/resolve.rs

//! A typed plan made ready for one run: its typed inputs coded (strings through the run's
//! dictionary), its string constants made dictionary ids, and the null checks that the
//! semantics of comparisons and joins ask for added as conditions.

use std::collections::HashMap;

use arrow_array::{Array, ArrayRef};

use crate::compute::{Compute, Expr, Func};
use crate::facts::{Column, ColumnBuilder, Facts};
use crate::rules::{Agg, Cmp, Cond, Plan, ReduceOp, RelId, Rule, Term, TextOp, Var};
use crate::typed::{Dict, Type, build_dict, coded};
use crate::{PlanError, Result};

/// Whether a run of `p` must be resolved: a typed relation, a string constant, a null
/// test or a text test anywhere.
pub(crate) fn needs_resolving(p: &Plan) -> bool {
    p.has_types()
        || !p.strings().is_empty()
        || p.rules().iter().any(|r| {
            r.conds
                .iter()
                .any(|c| matches!(c, Cond::IsNull { .. } | Cond::Text { .. }))
        })
}

/// The run's dictionary over the string columns of `pending` (typed inputs as chunks per
/// column) and the plan's string constants; every pending relation coded into `inputs`.
pub(crate) fn load_typed(
    par: &crate::cols::Par,
    p: &Plan,
    inputs: &mut HashMap<RelId, Facts>,
    pending: Vec<(RelId, Vec<Vec<ArrayRef>>)>,
) -> Result<Dict> {
    let pending = pending
        .into_iter()
        .map(|(rel, cols)| Ok((rel, without_unsigned_nulls(p, rel, cols)?)))
        .collect::<Result<Vec<_>>>()?;
    let mut strs: Vec<&ArrayRef> = Vec::new();
    for (rel, cols) in &pending {
        for (i, chunks) in cols.iter().enumerate() {
            if p.col_type(*rel, i) == Type::Str {
                strs.extend(chunks.iter());
            }
        }
    }
    let (dict, mut coded_strs) = if strs.is_empty() && p.strings().is_empty() {
        (Dict::default(), Vec::new())
    } else {
        build_dict(par, &strs, p.strings())?
    };
    coded_strs.reverse();
    for (rel, cols) in pending {
        let mut out = Vec::with_capacity(cols.len());
        for (i, chunks) in cols.into_iter().enumerate() {
            let ty = p.col_type(rel, i);
            let parts: Vec<Column> = if ty == Type::Str {
                chunks
                    .iter()
                    .map(|_| coded_strs.pop().expect("one coded column per chunk"))
                    .collect()
            } else {
                chunks
                    .iter()
                    .map(|a| coded(par, ty, a))
                    .collect::<Result<Vec<Column>>>()?
            };
            out.push(join(parts));
        }
        let f = Facts::from_columns(out).map_err(|_| {
            PlanError::Input(format!(
                "columns of different lengths for `{}`",
                p.relation_info(rel).name
            ))
        })?;
        inputs.insert(rel, f);
    }
    Ok(dict)
}

/// The column chunks `cols` of typed relation `rel` with every row that holds a null in a
/// `u64` column left out (an unsigned value has no null: the row has no value); the chunks
/// as they are when no `u64` column has one. The columns' chunks are of one length each.
fn without_unsigned_nulls(
    p: &Plan,
    rel: RelId,
    cols: Vec<Vec<ArrayRef>>,
) -> Result<Vec<Vec<ArrayRef>>> {
    let unsigned: Vec<usize> = (0..cols.len())
        .filter(|&i| p.col_type(rel, i) == Type::U64)
        .collect();
    let nulls = unsigned
        .iter()
        .any(|&i| cols[i].iter().any(|c| c.null_count() > 0));
    if !nulls {
        return Ok(cols);
    }
    let chunks = cols[unsigned[0]].len();
    if cols.iter().any(|c| c.len() != chunks) {
        return Err(PlanError::Input(format!(
            "columns of `{}` in different chunks",
            p.relation_info(rel).name
        )));
    }
    let mut out: Vec<Vec<ArrayRef>> = vec![Vec::with_capacity(chunks); cols.len()];
    for k in 0..chunks {
        let n = cols[unsigned[0]][k].len();
        if cols.iter().any(|c| c[k].len() != n) {
            return Err(PlanError::Input(format!(
                "columns of different lengths for `{}`",
                p.relation_info(rel).name
            )));
        }
        let keep: arrow_array::BooleanArray = (0..n)
            .map(|r| Some(unsigned.iter().all(|&i| cols[i][k].is_valid(r))))
            .collect();
        for (i, c) in cols.iter().enumerate() {
            out[i].push(datafusion::arrow::compute::filter(c[k].as_ref(), &keep)?);
        }
    }
    Ok(out)
}

/// Column chunks as one column (one chunk: itself, shared).
fn join(mut parts: Vec<Column>) -> Column {
    if parts.len() == 1 {
        return parts.pop().expect("one part");
    }
    let mut b = ColumnBuilder::with_capacity(parts.iter().map(Column::len).sum());
    for c in &parts {
        for x in c.iter() {
            b.push(x);
        }
    }
    b.finish()
}

/// `p` as one run with dictionary `dict` reads it: each string constant (in a str column
/// of an atom, or compared with a str variable) the string's id; a null test of a u64
/// variable decided (it is never null); and for every nullable variable that a rule joins
/// (it occurs twice among the positive atoms) or compares, an `IS NOT NULL` condition, so a
/// join or a comparison with null is not true and filters its row (and so for the keys of
/// a min or max, the counted variables of a count and a fold's values: their nulls are
/// skipped).
pub(crate) fn resolve(p: &Plan, dict: &Dict) -> Result<Plan> {
    let mut q = p.clone();
    // a string constant's id: those of the plan's strings are all in the dictionary
    let id = |k: u64| -> Result<u64> {
        let s = p
            .strings()
            .get(k as usize)
            .ok_or_else(|| PlanError::Program(format!("string constant {k} is not in the plan")))?;
        Ok(dict
            .id(s)
            .expect("the plan's strings are in the run's dictionary") as u64)
    };
    // the string constants of computed values (in a string place of a call)
    for rule in q.rules_mut().iter_mut() {
        for c in rule.computes.iter_mut() {
            let mut bad = None;
            c.expr.string_consts_mut(&mut |t| {
                if let Term::Const(k) = t {
                    match id(*k) {
                        Ok(i) => *k = i,
                        Err(e) => bad = Some(e),
                    }
                }
            });
            if let Some(e) = bad {
                return Err(e);
            }
        }
    }
    // only a plan that makes strings has values whose ids do not follow the byte order
    if p.makes_strings() {
        by_bytes(&mut q, p, &id)?;
    }
    // a list of strings: the members' ids, sorted, once per run
    for l in q.lists.iter_mut().filter(|l| l.ty == Type::Str) {
        l.run = l.members.iter().map(|&k| id(k)).collect::<Result<_>>()?;
        l.run.sort_unstable();
        l.run.dedup();
    }
    let types: Vec<Vec<(Var, Type)>> = (0..p.rules().len())
        .map(|r| p.var_types(crate::rules::RuleId(r as u32)).to_vec())
        .collect();
    let mut sets: Vec<Vec<u64>> = Vec::new();
    for (r, rule) in q.rules_mut().iter_mut().enumerate() {
        let ty = |v: Var| {
            types[r]
                .iter()
                .find(|x| x.0 == v)
                .map_or(Type::U64, |x| x.1)
        };
        let fix_atom = |a: &mut crate::rules::Atom| -> Result<()> {
            for (j, t) in a.terms.iter_mut().enumerate() {
                if let Term::Const(k) = t
                    && p.col_type(a.rel, j) == Type::Str
                {
                    *k = id(*k)?;
                }
            }
            Ok(())
        };
        fix_atom(&mut rule.head)?;
        for a in rule.body.iter_mut().chain(rule.negated.iter_mut()) {
            fix_atom(a)?;
        }
        let mut checked: Vec<Var> = Vec::new();
        for c in rule.conds.iter_mut() {
            let cty = c
                .terms()
                .iter()
                .find_map(|t| match t {
                    Term::Var(v) => Some(ty(*v)),
                    Term::Const(_) => None,
                })
                .unwrap_or(Type::U64);
            let fix = |t: &mut Term| -> Result<()> {
                if let Term::Const(k) = t
                    && cty == Type::Str
                {
                    *k = id(*k)?;
                }
                Ok(())
            };
            match c {
                Cond::Cmp { left, right, .. } => {
                    fix(left)?;
                    fix(right)?;
                }
                Cond::Within { x, lo, hi } => {
                    fix(x)?;
                    fix(lo)?;
                    fix(hi)?;
                }
                // the members are coded above
                Cond::OneOf { x, .. } => fix(x)?,
                Cond::Text { x, op, pat } => {
                    let Term::Const(k) = *pat else {
                        return Err(PlanError::Program(
                            "the pattern of a text test is a string constant".into(),
                        ));
                    };
                    let pat_s = p.strings().get(k as usize).ok_or_else(|| {
                        PlanError::Program(format!("string constant {k} is not in the plan"))
                    })?;
                    if *op == TextOp::StartsWith {
                        // the strings with a prefix are one range of the sorted ids
                        let (lo, hi) = dict.prefix_range(pat_s);
                        *c = Cond::Within {
                            x: *x,
                            lo: Term::Const(lo as u64),
                            hi: Term::Const(hi as u64),
                        };
                    } else {
                        // once over the dictionary, not per row
                        let mut bits = vec![0u64; dict.len().div_ceil(64)];
                        for (i, s) in dict.iter().enumerate() {
                            if op.holds(s, pat_s) {
                                bits[i / 64] |= 1 << (i % 64);
                            }
                        }
                        *pat = Term::Const(sets.len() as u64);
                        sets.push(bits);
                    }
                }
                Cond::IsNull { x, null } => {
                    if let Term::Var(v) = *x
                        && !ty(v).nullable()
                    {
                        // a u64 value is never null: decided here
                        *c = constant(!*null);
                    }
                    continue;
                }
            }
            for v in c.vars() {
                if ty(v).nullable() && !checked.contains(&v) {
                    checked.push(v);
                }
            }
        }
        // min / max / rank keys and counted tuples skip their nulls
        let skipped: Vec<Var> = match rule.agg.as_ref().map(|a| &a.agg) {
            Some(Agg::Min { key } | Agg::Max { key } | Agg::Rank { key, .. }) => key.clone(),
            Some(Agg::Count { of, .. } | Agg::SetNumber { of, .. }) => of.clone(),
            // each reduction skips its own nulls
            Some(Agg::Many { .. }) => Vec::new(),
            _ => rule
                .fold
                .iter()
                .filter(|f| f.op != crate::rules::FoldOp::Count)
                .map(|f| f.of)
                .collect(),
        };
        for v in joined(p, rule).into_iter().chain(skipped) {
            if ty(v).nullable() && !checked.contains(&v) {
                checked.push(v);
            }
        }
        for v in checked {
            rule.conds.push(Cond::IsNull {
                x: Term::Var(v),
                null: false,
            });
        }
    }
    q.text_sets = sets;
    Ok(q)
}

/// A condition that always holds (`true`) or never.
fn constant(holds: bool) -> Cond {
    Cond::Cmp {
        left: Term::Const(0),
        op: if holds { Cmp::Eq } else { Cmp::Ne },
        right: Term::Const(0),
    }
}

/// The variables that occur twice or more among `rule`'s positive atoms that are not of
/// external relations (an external is handed its keys, nulls too, and answers them).
fn joined(p: &Plan, rule: &Rule) -> Vec<Var> {
    let mut seen: Vec<(Var, usize)> = Vec::new();
    let facts = rule
        .body
        .iter()
        .filter(|a| p.relation_info(a.rel).kind != crate::rules::RelKind::External);
    for v in facts.flat_map(|a| a.vars()) {
        match seen.iter_mut().find(|x| x.0 == v) {
            Some(x) => x.1 += 1,
            None => seen.push((v, 1)),
        }
    }
    seen.into_iter().filter(|x| x.1 > 1).map(|x| x.0).collect()
}

/// The variables of each rule of `p` that may hold a string a rule made (whose id does not
/// follow the byte order): the variable of a `concat` or `substr`, and every variable an
/// atom binds from a column such a variable reaches through a head (to a fixed point).
pub(crate) fn made_vars(p: &Plan) -> Vec<Vec<Var>> {
    let mut cols: Vec<(RelId, usize)> = Vec::new();
    loop {
        let made: Vec<Vec<Var>> = p
            .rules()
            .iter()
            .map(|rule| {
                let mut vs: Vec<Var> = rule
                    .computes
                    .iter()
                    .filter(|c| c.expr.is_string())
                    .map(|c| c.out)
                    .collect();
                for a in &rule.body {
                    for (j, t) in a.terms.iter().enumerate() {
                        if let Term::Var(v) = *t
                            && cols.contains(&(a.rel, j))
                            && !vs.contains(&v)
                        {
                            vs.push(v);
                        }
                    }
                }
                vs
            })
            .collect();
        let mut grew = false;
        for (rule, vs) in p.rules().iter().zip(&made) {
            for (j, t) in rule.head.terms.iter().enumerate() {
                if let Term::Var(v) = *t
                    && vs.contains(&v)
                    && !cols.contains(&(rule.head.rel, j))
                {
                    cols.push((rule.head.rel, j));
                    grew = true;
                }
            }
        }
        if !grew {
            return made;
        }
    }
}

/// In `q` (the plan `p` being resolved), each ordered comparison, range or text test of a
/// variable that may hold a made string ([`made_vars`]) becomes a computed value over the
/// strings' bytes ([`Func::Cmp`], [`Func::Text`]) and a test of it; a least or greatest by
/// such a variable is refused. `id` gives a string constant's id.
fn by_bytes(q: &mut Plan, p: &Plan, id: &dyn Fn(u64) -> Result<u64>) -> Result<()> {
    let made = made_vars(p);
    for (r, vs) in made.iter().enumerate() {
        if vs.is_empty() {
            continue;
        }
        let rid = crate::rules::RuleId(r as u32);
        let rule = &p.rules()[r];
        let is_made = |t: Term| matches!(t, Term::Var(v) if vs.contains(&v));
        let refused = |v: &Var| {
            PlanError::Program(format!(
                "a least or greatest by {}, a string a rule made, is not covered: {}",
                p.var_name(*v),
                p.show_rule(rid)
            ))
        };
        match rule.agg.as_ref().map(|a| &a.agg) {
            Some(Agg::Min { key } | Agg::Max { key }) => {
                if let Some(v) = key.iter().find(|v| vs.contains(v)) {
                    return Err(refused(v));
                }
            }
            Some(Agg::Many { reduces, .. }) => {
                if let Some(v) = reduces
                    .iter()
                    .filter(|x| matches!(x.op, ReduceOp::Min | ReduceOp::Max))
                    .flat_map(|x| x.of.iter())
                    .find(|v| vs.contains(v))
                {
                    return Err(refused(v));
                }
            }
            _ => {}
        }
        // a string constant beside a made variable: its id
        let fix = |t: Term| -> Result<Expr> {
            Ok(Expr::Term(match t {
                Term::Const(k) => Term::Const(id(k)?),
                v => v,
            }))
        };
        let mut conds = Vec::with_capacity(rule.conds.len());
        let mut added: Vec<Compute> = Vec::new();
        let new_var = |q: &mut Plan, name: String, e: Expr, added: &mut Vec<Compute>| {
            let v = q.var(&name);
            q.set_var_type(rid, v, Type::U64);
            let mut c = Compute::new(v, e);
            c.of_test = true;
            added.push(c);
            Term::Var(v)
        };
        for c in &rule.conds {
            let cmp_of = |a: Term, b: Term| -> Result<Expr> {
                Ok(Expr::call(Func::Cmp, [fix(a)?, fix(b)?]))
            };
            let show = |t: Term| match t {
                Term::Var(v) => p.var_name(v).to_string(),
                Term::Const(k) => p.show_const(k, Type::Str),
            };
            match *c {
                Cond::Cmp { left, op, right }
                    if !matches!(op, Cmp::Eq | Cmp::Ne) && (is_made(left) || is_made(right)) =>
                {
                    let b = new_var(
                        q,
                        format!("cmp({}, {})", show(left), show(right)),
                        cmp_of(left, right)?,
                        &mut added,
                    );
                    // cmp gives 0 below, 1 equal, 2 above
                    conds.push(Cond::Cmp {
                        left: b,
                        op,
                        right: Term::Const(1),
                    });
                }
                Cond::Within { x, lo, hi } if [x, lo, hi].into_iter().any(is_made) => {
                    let a = new_var(
                        q,
                        format!("cmp({}, {})", show(lo), show(x)),
                        cmp_of(lo, x)?,
                        &mut added,
                    );
                    let b = new_var(
                        q,
                        format!("cmp({}, {})", show(x), show(hi)),
                        cmp_of(x, hi)?,
                        &mut added,
                    );
                    conds.push(Cond::Cmp {
                        left: a,
                        op: Cmp::Le,
                        right: Term::Const(1),
                    });
                    conds.push(Cond::Cmp {
                        left: b,
                        op: Cmp::Lt,
                        right: Term::Const(1),
                    });
                }
                Cond::Text { x, op, pat } if is_made(x) => {
                    let e = Expr::call(Func::Text(op), [fix(x)?, fix(pat)?]);
                    let b = new_var(
                        q,
                        format!("{}({}, {})", Func::Text(op).name(), show(x), show(pat)),
                        e,
                        &mut added,
                    );
                    conds.push(Cond::Cmp {
                        left: b,
                        op: Cmp::Eq,
                        right: Term::Const(1),
                    });
                }
                _ => conds.push(*c),
            }
        }
        let qr = &mut q.rules_mut()[r];
        qr.conds = conds;
        qr.computes.extend(added);
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::compute::{Compute, Expr, Func};
    use crate::rules::{Atom, Literal};

    /// `pair(X, Y)` of two strings into `r(X, Y)` where `X < Y`, with a number computed
    /// beside; `make`: also `Z = concat(X, Y)` and `Z < Y`.
    fn plan_of(make: bool) -> Plan {
        let mut p = Plan::new();
        let pair = p.input_typed("pair", &[Type::Str, Type::Str, Type::U64]);
        let r = p.derived_typed("r", &[Type::Str, Type::Str, Type::U64]);
        let (x, y, n, m, z) = (p.var("X"), p.var("Y"), p.var("N"), p.var("M"), p.var("Z"));
        let mut body = vec![
            Literal::Pos(Atom {
                rel: pair,
                terms: vec![x.into(), y.into(), n.into()],
            }),
            Literal::Cond(Cond::Cmp {
                left: x.into(),
                op: Cmp::Lt,
                right: y.into(),
            }),
            Literal::Compute(Compute::new(m, Expr::from(n) + 1u64)),
        ];
        if make {
            body.push(Literal::Compute(Compute::new(z, Expr::concat([x, y]))));
            body.push(Literal::Cond(Cond::Cmp {
                left: z.into(),
                op: Cmp::Lt,
                right: y.into(),
            }));
        }
        let head = Atom {
            rel: r,
            terms: vec![x.into(), y.into(), m.into()],
        };
        p.rule(head, body).unwrap();
        p
    }

    fn calls_cmp(q: &Plan) -> bool {
        q.rules()[0]
            .computes
            .iter()
            .any(|c| matches!(&c.expr, Expr::Call(Func::Cmp, _)))
    }

    #[test]
    fn a_plan_that_makes_no_string_keeps_the_old_path() {
        let p = plan_of(false);
        assert!(!p.makes_strings());
        assert!(made_vars(&p).iter().all(Vec::is_empty));
        let q = resolve(&p, &Dict::default()).unwrap();
        // the string comparison stays a comparison of ids; no compute added
        assert_eq!(q.rules()[0].computes, p.rules()[0].computes);
        assert!(!calls_cmp(&q));
        assert!(q.rules()[0].conds.contains(&p.rules()[0].conds[0]));
    }

    #[test]
    fn a_plan_that_makes_strings_compares_made_ones_by_bytes() {
        let p = plan_of(true);
        assert!(p.makes_strings());
        assert_eq!(made_vars(&p)[0].len(), 1);
        let q = resolve(&p, &Dict::default()).unwrap();
        assert!(calls_cmp(&q));
        // X < Y (no made value) stays as it is
        assert!(q.rules()[0].conds.contains(&p.rules()[0].conds[0]));
    }
}