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/eval/sets.rs

//! Set numbers ([`Agg::SetNumber`] into a table of sets, [`Plan::sets`]): the groups of a
//! numbering rule's bindings, each group's distinct elements its set; the sets new at a
//! moment (a stratum of set numbers once, a numbered part of rounds each time it is
//! computed) put in rising order of their sorted members and numbered on from the count
//! so far; the head facts and the table's rows given. Nothing here reads a hash order: the
//! groups and sets are kept in sorted maps, a hash map only looks numbers up.

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

use super::*;
use crate::plan::numbers_into;

/// A table of sets as a run fills it.
pub(super) struct Tab {
    name: String,
    limit: u64,
    width: usize,
    /// Each numbered set (its sorted element tuples, one after the other) and its number.
    index: HashMap<Vec<Value>, Value>,
    /// The rows `(n, element..)`, in the order of their numbers.
    pub(super) rows: RowSet,
    /// Per number, the numbered fact that first gave it (its relation and tuple) and the
    /// round of rounds it came in (0: none).
    pub(super) first: Vec<(RelId, Vec<Value>, u32)>,
}

impl Tab {
    pub(super) fn new(p: &Plan, rel: RelId) -> Self {
        let info = p.relation_info(rel);
        Tab {
            name: info.name.clone(),
            limit: p.set_limit(rel).expect("a table of sets"),
            width: info.arity - 1,
            index: HashMap::new(),
            rows: RowSet::new(info.arity),
            first: Vec::new(),
        }
    }
}

/// One key's distinct elements and (explained) its distinct bindings.
type Members = (BTreeSet<Vec<Value>>, BTreeSet<Vec<Value>>);

/// What a numbering rule has gathered from its bindings: per key its distinct elements and
/// (explained) its distinct bindings, and the length of each part of rounds it read when
/// it last ran (a kept numbered head computes from the rows gained since).
#[derive(Default)]
pub(super) struct Gathered {
    keys: BTreeMap<Vec<Value>, Members>,
    read: Option<HashMap<RelId, usize>>,
}

/// One group of a numbering rule: its key's values, its set (the sorted element tuples,
/// one after the other) and its member bindings (in [`Rule::vars`] order; explained only).
pub(super) struct Group {
    key: Vec<Value>,
    set: Vec<Value>,
    members: Vec<Vec<Value>>,
    size: usize,
}

impl Gathered {
    /// Take in the bindings `t` of `rule`; returns the keys they touched.
    fn take(&mut self, par: &Par, rule: &Rule, mut t: Table, explain: bool) -> Vec<Vec<Value>> {
        let Some(Aggregate {
            group,
            agg: Agg::SetNumber { of, .. },
        }) = &rule.agg
        else {
            unreachable!("a numbering rule")
        };
        t.resolve(par);
        let col = |v: &Var| t.col_of(*v).expect("an aggregate variable is bound");
        let keyc: Vec<usize> = group.iter().map(col).collect();
        let ofc: Vec<usize> = of.iter().map(col).collect();
        let allc: Vec<usize> = if explain {
            rule.vars().iter().map(col).collect()
        } else {
            Vec::new()
        };
        let mut touched: BTreeSet<Vec<Value>> = BTreeSet::new();
        for i in 0..t.len {
            let key: Vec<Value> = keyc.iter().map(|&c| t.cols[c][i]).collect();
            let elem: Vec<Value> = ofc.iter().map(|&c| t.cols[c][i]).collect();
            let entry = self.keys.entry(key.clone()).or_default();
            entry.0.insert(elem);
            if explain {
                entry.1.insert(allc.iter().map(|&c| t.cols[c][i]).collect());
            }
            touched.insert(key);
        }
        touched.into_iter().collect()
    }

    /// The groups of `keys`, whole.
    fn groups(&self, keys: &[Vec<Value>]) -> Vec<Group> {
        keys.iter()
            .map(|k| {
                let (elems, bindings) = &self.keys[k];
                Group {
                    key: k.clone(),
                    set: elems.iter().flatten().copied().collect(),
                    members: bindings.iter().cloned().collect(),
                    size: elems.len(),
                }
            })
            .collect()
    }
}

impl<B: GraphBackend> Engine<B> {
    /// The groups of numbering rule `r` to number now. `gathered`: a kept numbered head's
    /// store, whose groups are computed again only where a binding reads a row of a part
    /// of `parts` gained since it last ran (each such group whole: the bindings before it
    /// are in the store); `None`: every group from all its bindings.
    pub(super) fn set_groups(
        &self,
        p: &Plan,
        st: &mut State,
        r: RuleId,
        parts: &[(RelId, Part)],
        gathered: Option<&mut Gathered>,
        ix: &mut Indexes,
    ) -> Result<Vec<Group>> {
        let rule = p.rule_at(r);
        let none: HashMap<RelId, RowSet> = HashMap::new();
        let explain = self.explain;
        let lens = |st: &State| -> HashMap<RelId, usize> {
            rule.body
                .iter()
                .filter(|a| parts.iter().any(|q| q.0 == a.rel))
                .map(|a| (a.rel, st.derived.get(&a.rel).map_or(0, Facts::len)))
                .collect()
        };
        let Some(g) = gathered else {
            let ins = self.inputs_for(p, st, rule, None, &none)?;
            let t = self.bindings(p, st, r, &ins, None, ix)?;
            let mut all = Gathered::default();
            let keys = all.take(&self.par, rule, t, explain);
            return Ok(all.groups(&keys));
        };
        // the parts' lengths as read now (rows this numbering adds come after)
        let now = lens(st);
        let keys = match g.read.take() {
            None => {
                let ins = self.inputs_for(p, st, rule, None, &none)?;
                let t = self.bindings(p, st, r, &ins, None, ix)?;
                g.take(&self.par, rule, t, explain)
            }
            Some(was) => {
                let mut touched: BTreeSet<Vec<Value>> = BTreeSet::new();
                for (pos, a) in rule.body.iter().enumerate() {
                    let Some(&old) = was.get(&a.rel) else {
                        continue;
                    };
                    if now[&a.rel] <= old {
                        continue;
                    }
                    let d = rows_from(&st.derived[&a.rel], old);
                    let ins = self.inputs_gained(p, st, rule, (pos, &d), &none)?;
                    let t = self.bindings(p, st, r, &ins, Some(pos), ix)?;
                    touched.extend(g.take(&self.par, rule, t, explain));
                }
                touched.into_iter().collect()
            }
        };
        g.read = Some(now);
        Ok(g.groups(&keys))
    }

    /// One moment of numbering: the sets of `batch` (each numbering rule's groups) that
    /// `tabs` lacks put in rising order of their members and numbered on from each table's
    /// count (stopping at its limit), the table rows added, then each group's head fact
    /// into `total` (with its members into `prov`). Each new set's first fact is the least
    /// of the facts of this moment that have it. Returns the table rows added.
    #[allow(clippy::too_many_arguments)]
    pub(super) fn give_numbers(
        &self,
        p: &Plan,
        tabs: &mut HashMap<RelId, Tab>,
        batch: Vec<(RuleId, Vec<Group>)>,
        total: &mut HashMap<RelId, RowSet>,
        prov: &mut HashMap<RelId, ProvBuilder>,
        round: u32,
    ) -> Result<usize> {
        let mut new: BTreeMap<RelId, BTreeSet<&[Value]>> = BTreeMap::new();
        for (r, groups) in &batch {
            let table = numbers_into(p.rule_at(*r)).expect("a numbering rule");
            let tab = &tabs[&table];
            for g in groups {
                if !tab.index.contains_key(&g.set) {
                    new.entry(table).or_default().insert(&g.set);
                }
            }
        }
        let mut added = 0;
        let mut was: HashMap<RelId, usize> = HashMap::new();
        for (table, sets) in new {
            let tab = tabs.get_mut(&table).expect("a table of the stratum");
            was.insert(table, tab.first.len());
            for set in sets {
                let n = tab.first.len() as Value;
                if n >= tab.limit {
                    return Err(PlanError::SetLimit {
                        table: tab.name.clone(),
                        limit: tab.limit,
                    });
                }
                let mut row = vec![n; tab.width + 1];
                for elem in set.chunks(tab.width) {
                    row[1..].copy_from_slice(elem);
                    tab.rows.insert(&row);
                    added += 1;
                }
                tab.index.insert(set.to_vec(), n);
                tab.first.push((RelId(u32::MAX), Vec::new(), round));
            }
        }
        for (r, groups) in batch {
            let rule = p.rule_at(r);
            let Some(Aggregate {
                group,
                agg: Agg::SetNumber { out, table, .. },
            }) = &rule.agg
            else {
                unreachable!("a numbering rule")
            };
            let head = rule.head.rel;
            let hvars: Vec<Var> = group.iter().copied().chain([*out]).collect();
            let vars = rule.vars();
            let set = total.get_mut(&head).expect("the head's facts");
            let mut rows = prov.get_mut(&head).map(|pv| {
                let slot = pv.slot(r, &hvars, &rule.head.terms);
                pv.rows(slot)
            });
            let tab = tabs.get_mut(table).expect("a table of the stratum");
            let from = was.get(table).copied().unwrap_or(usize::MAX);
            let mut hb: Vec<Value> = vec![0; hvars.len()];
            let mut row: Vec<Value> = vec![0; rule.head.terms.len()];
            for g in groups {
                let n = tab.index[&g.set];
                hb[..g.key.len()].copy_from_slice(&g.key);
                hb[g.key.len()] = n;
                for (x, term) in row.iter_mut().zip(&rule.head.terms) {
                    *x = match *term {
                        Term::Const(c) => c,
                        Term::Var(v) => hb[hvars.iter().position(|&w| w == v).expect("given")],
                    };
                }
                if n as usize >= from {
                    let first = &mut tab.first[n as usize];
                    let lower = (head.index(), &row[..]) < (first.0.index(), &first.1[..]);
                    if first.0 == RelId(u32::MAX) || lower {
                        *first = (head, row.clone(), round);
                    }
                }
                if set.insert(&row)
                    && let Some(rows) = rows.as_mut()
                {
                    let members = g
                        .members
                        .iter()
                        .map(|b| vars.iter().copied().zip(b.iter().copied()).collect())
                        .collect();
                    rows.push(
                        &hb,
                        Some(AggWhy {
                            members,
                            size: g.size,
                        }),
                    );
                }
            }
            if let (Some(rows), Some(pv)) = (rows, prov.get_mut(&head)) {
                pv.append_rows(rows, round);
            }
        }
        Ok(added)
    }

    /// A stratum of set numbers ([`Stratum::Sets`]): its numbered heads and tables, read by
    /// none of its rules. The heads' other rules run once; every numbering rule's groups
    /// are numbered in one moment.
    pub(super) fn sets_stratum(
        &self,
        p: &Plan,
        st: &mut State,
        rels: &[RelId],
        rules: &[RuleId],
    ) -> Result<StratumReport> {
        let t0 = Instant::now();
        let mut tabs: HashMap<RelId, Tab> = HashMap::new();
        let mut total: HashMap<RelId, RowSet> = HashMap::new();
        for &r in rels {
            if p.set_limit(r).is_some() {
                tabs.insert(r, Tab::new(p, r));
            } else {
                total.insert(r, RowSet::new(p.relation_info(r).arity));
            }
        }
        let mut prov: HashMap<RelId, ProvBuilder> = if self.explain {
            total.keys().map(|&r| (r, ProvBuilder::default())).collect()
        } else {
            HashMap::new()
        };
        let mut ix = Indexes::new();
        let (numbering, plain): (Vec<RuleId>, Vec<RuleId>) = rules
            .iter()
            .partition(|&&r| numbers_into(p.rule_at(r)).is_some());
        let mut batch = Vec::with_capacity(numbering.len());
        for &r in &numbering {
            batch.push((r, self.set_groups(p, st, r, &[], None, &mut ix)?));
        }
        self.give_numbers(p, &mut tabs, batch, &mut total, &mut prov, 0)?;
        let rounds = if plain.is_empty() {
            1
        } else {
            self.fixpoint(
                p,
                st,
                &plain,
                &mut total,
                &mut prov,
                0,
                &mut ix,
                None,
                &mut |_, _| {},
            )?
        };
        let mut n = 0;
        for (r, s) in total {
            let (facts, order) = s.finish(&self.par, prov.contains_key(&r));
            n += facts.len();
            if let (Some(pv), Some(why)) = (prov.remove(&r), st.why.as_mut()) {
                why.derived.insert(r, pv.finish(facts.clone(), order));
            }
            st.derived.insert(r, facts);
        }
        n += self.finish_tabs(st, tabs);
        Ok(StratumReport {
            kind: "",
            relations: Vec::new(),
            rounds,
            facts: n,
            prepare: Duration::ZERO,
            compute: t0.elapsed(),
            renumbered: false,
            continued: false,
            peak_rows: 0,
            proof_rows: 0,
            indexed_rows: 0,
            range_joins: 0,
            next_rows: 0,
        })
    }

    /// The tables' final facts (sorted) and their first facts kept for the why; returns
    /// their rows.
    pub(super) fn finish_tabs(&self, st: &mut State, tabs: HashMap<RelId, Tab>) -> usize {
        let mut n = 0;
        for (rel, tab) in tabs {
            let (facts, _) = tab.rows.finish(&self.par, false);
            n += facts.len();
            st.derived.insert(rel, facts);
            if let Some(why) = st.why.as_mut() {
                why.sets.insert(rel, tab.first);
            }
        }
        n
    }
}