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

nordisk/kleene

crates/kleene-iceberg/src/sink.rs

//! kleene as a bifröst sink: a round's graph rows kept in memory, nothing written anywhere.

use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;

use arrow_array::cast::AsArray;
use arrow_array::types::{
    Int8Type, Int16Type, Int32Type, Int64Type, UInt8Type, UInt16Type, UInt32Type, UInt64Type,
};
use arrow_array::{Array, ArrayRef, RecordBatch, UInt64Array};
use arrow_schema::{DataType, Field, Schema};
use kleene_index::{Store, Stored};
use kleene_plan::{Catalog, Source, Type};
use kleene_sparse::{BoolOrAnd, Csr};
use knut_bifrost::sink::GraphSink;
use knut_bifrost::{GraphMutation, SinkReport};

use crate::{Error, Result};

/// The rows of one node label: its id column's name and the batches as they came.
#[derive(Clone, Debug, Default)]
struct Nodes {
    id: String,
    batches: Vec<RecordBatch>,
}

/// The rows of one edge label: batches of `src`, `dst` and the property columns.
#[derive(Clone, Debug, Default)]
struct Edges {
    batches: Vec<RecordBatch>,
}

/// A graph's rows as bifröst's transforms hand them ([`GraphSink`]): per node label its
/// rows (the id column and the properties), per edge label its rows (`src`, `dst`, the
/// properties). [`GraphRows::catalog`] gives them as kleene-plan's catalog.
#[derive(Clone, Debug, Default)]
pub struct GraphRows {
    nodes: BTreeMap<String, Nodes>,
    edges: BTreeMap<String, Edges>,
}

#[async_trait::async_trait]
impl GraphSink for GraphRows {
    async fn apply(&mut self, m: &GraphMutation) -> knut_bifrost::Result<SinkReport> {
        Ok(self.add_mutation(m))
    }
}

/// One step of a table's window, in commit order: rows inserted, or rows removed (whole
/// rows, or rows named by the key columns of an equality delete alone).
#[derive(Clone, Debug)]
pub(crate) enum Change {
    /// Rows inserted, through the table's pipeline.
    Insert(GraphRows),
    /// Rows removed: `whole` each takes out one row equal to it in every column, `keyed`
    /// each takes out every row equal to it in its columns that are not null.
    Remove { whole: GraphRows, keyed: GraphRows },
}

/// A table's rows after a window of changes ([`GraphRows::changed`]).
#[derive(Clone, Debug, Default)]
pub(crate) struct Changed {
    /// The rows now.
    pub now: GraphRows,
    /// The rows the window added that are still there.
    pub added: GraphRows,
    /// The rows of before the window that it removed.
    pub removed: GraphRows,
}

/// What a set lost at the level of the graph ([`GraphRows::gone`]): per edge label the
/// pairs no row holds now; per label (node or edge) whether a removed id or pair is still
/// held by another row (its facts are then compared whole, not given as removed).
#[derive(Clone, Debug, Default)]
pub(crate) struct Gone {
    pub pairs: BTreeMap<String, (Vec<u32>, Vec<u32>)>,
    pub still_held: HashSet<String>,
}

/// The name of the kept rows in a [`Store`].
const KEPT: &str = "rows";

/// Column `a` as a mapped chunk holds it (integers and bytes, no nulls): integers as they
/// are, floats by their bits, booleans as bytes, strings as their bytes; its nulls (if any)
/// as a column of their own (1: a value). The kind names how to read it back; `None` for a
/// column of another type (the rows are then not kept on disk).
fn storable(a: &ArrayRef) -> Result<Option<(&'static str, ArrayRef, Option<ArrayRef>)>> {
    let err = |e: arrow_schema::ArrowError| Error::Table(format!("kept rows: {e}"));
    let as_type = |t: DataType| -> Result<ArrayRef> {
        let d = a
            .to_data()
            .into_builder()
            .data_type(t)
            .nulls(None)
            .build()
            .map_err(err)?;
        Ok(arrow_array::make_array(d))
    };
    let (kind, values) = match a.data_type() {
        d if d.is_integer() => ("int", as_type(d.clone())?),
        DataType::Float64 => ("f64", as_type(DataType::UInt64)?),
        DataType::Float32 => ("f32", as_type(DataType::UInt32)?),
        DataType::Utf8 => ("str", as_type(DataType::Binary)?),
        DataType::LargeUtf8 => ("lstr", as_type(DataType::LargeBinary)?),
        DataType::Binary | DataType::LargeBinary => ("bytes", as_type(a.data_type().clone())?),
        DataType::Boolean => {
            let b = a.as_boolean();
            let v: arrow_array::UInt8Array = (0..b.len()).map(|i| Some(b.value(i) as u8)).collect();
            ("bool", Arc::new(v) as ArrayRef)
        }
        _ => return Ok(None),
    };
    let valid = a.logical_nulls().map(|n| {
        Arc::new(arrow_array::UInt8Array::from_iter_values(
            n.iter().map(u8::from),
        )) as ArrayRef
    });
    Ok(Some((kind, values, valid)))
}

/// A column [`storable`] made, read back as it was (`ty` its Arrow type).
fn restored(
    kind: &str,
    ty: &DataType,
    values: &ArrayRef,
    valid: Option<&ArrayRef>,
) -> Result<ArrayRef> {
    let err = |e: arrow_schema::ArrowError| Error::Table(format!("kept rows: {e}"));
    let nulls = valid.map(|v| {
        let v = v.as_primitive::<UInt8Type>();
        arrow_buffer::NullBuffer::from(v.values().iter().map(|&x| x == 1).collect::<Vec<bool>>())
    });
    if kind == "bool" {
        let v = values.as_primitive::<UInt8Type>();
        let b = arrow_array::BooleanArray::new(
            arrow_buffer::BooleanBuffer::from(
                v.values().iter().map(|&x| x == 1).collect::<Vec<bool>>(),
            ),
            nulls,
        );
        return Ok(Arc::new(b));
    }
    let d = values
        .to_data()
        .into_builder()
        .data_type(ty.clone())
        .nulls(nulls)
        .build()
        .map_err(err)?;
    Ok(arrow_array::make_array(d))
}

/// An Arrow type by the name [`type_name`] gave it.
fn type_named(name: &str) -> Option<DataType> {
    Some(match name {
        "i8" => DataType::Int8,
        "i16" => DataType::Int16,
        "i32" => DataType::Int32,
        "i64" => DataType::Int64,
        "u8" => DataType::UInt8,
        "u16" => DataType::UInt16,
        "u32" => DataType::UInt32,
        "u64" => DataType::UInt64,
        "f32" => DataType::Float32,
        "f64" => DataType::Float64,
        "bool" => DataType::Boolean,
        "str" => DataType::Utf8,
        "lstr" => DataType::LargeUtf8,
        "bytes" => DataType::Binary,
        "lbytes" => DataType::LargeBinary,
        _ => return None,
    })
}

/// The name of an Arrow type [`type_named`] reads (`None`: not kept).
fn type_name(t: &DataType) -> Option<&'static str> {
    Some(match t {
        DataType::Int8 => "i8",
        DataType::Int16 => "i16",
        DataType::Int32 => "i32",
        DataType::Int64 => "i64",
        DataType::UInt8 => "u8",
        DataType::UInt16 => "u16",
        DataType::UInt32 => "u32",
        DataType::UInt64 => "u64",
        DataType::Float32 => "f32",
        DataType::Float64 => "f64",
        DataType::Boolean => "bool",
        DataType::Utf8 => "str",
        DataType::LargeUtf8 => "lstr",
        DataType::Binary => "bytes",
        DataType::LargeBinary => "lbytes",
        _ => return None,
    })
}

impl GraphRows {
    /// Rows of node labels and edge labels in all.
    pub fn len(&self) -> usize {
        let rows = |b: &[RecordBatch]| b.iter().map(RecordBatch::num_rows).sum::<usize>();
        self.nodes.values().map(|n| rows(&n.batches)).sum::<usize>()
            + self.edges.values().map(|e| rows(&e.batches)).sum::<usize>()
    }

    /// Whether there are no rows.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Join `other`'s rows into these (the tables of a set, read one by one).
    pub(crate) fn extend(&mut self, other: &GraphRows) {
        for (label, n) in &other.nodes {
            let mine = self.nodes.entry(label.clone()).or_default();
            mine.id.clone_from(&n.id);
            mine.batches.extend(n.batches.iter().cloned());
        }
        for (label, e) in &other.edges {
            let mine = self.edges.entry(label.clone()).or_default();
            mine.batches.extend(e.batches.iter().cloned());
        }
    }

    /// These rows (added to `old`) as a catalog of their own: each edge label's edges, each
    /// node label's ids and properties when none of its ids is one of `old`'s (a repeated
    /// id updates a row: that label is left out, to be compared whole).
    pub(crate) fn added_catalog(&self, old: &GraphRows) -> Result<Catalog> {
        let mut keep = GraphRows {
            nodes: BTreeMap::new(),
            edges: self.edges.clone(),
        };
        for (label, n) in &self.nodes {
            let was: std::collections::HashSet<u64> = match old.nodes.get(label) {
                Some(o) => match column(&o.batches, &o.id)? {
                    Some(a) => ids(&a, "an old id column")?.into_iter().collect(),
                    None => Default::default(),
                },
                None => Default::default(),
            };
            let new = match column(&n.batches, &n.id)? {
                Some(a) => ids(&a, "a new id column")?,
                None => Vec::new(),
            };
            if new.iter().all(|x| !was.contains(x)) {
                keep.nodes.insert(label.clone(), n.clone());
            }
        }
        keep.catalog(None)
    }

    /// These rows changed by `steps` in order: inserted rows added, removed ones taken out
    /// of the rows there at that step (those inserted in the window first, then those of
    /// before it). `None` when a removed row names no node or edge (its id or an end is
    /// null, an equality delete on columns the mapping does not read): the table is then
    /// read whole.
    pub(crate) fn changed(&self, steps: &[Change]) -> Result<Option<Changed>> {
        // per label: the id column (an edge's `src`), its rows of before, of the window, and
        // the rows of before taken out
        type Work = (String, Vec<RecordBatch>, Vec<RecordBatch>, Vec<RecordBatch>);
        let mut nodes: BTreeMap<String, Work> = self
            .nodes
            .iter()
            .map(|(l, n)| {
                (
                    l.clone(),
                    (n.id.clone(), n.batches.clone(), Vec::new(), Vec::new()),
                )
            })
            .collect();
        let mut edges: BTreeMap<String, Work> = self
            .edges
            .iter()
            .map(|(l, e)| {
                let w = ("src".to_string(), e.batches.clone(), Vec::new(), Vec::new());
                (l.clone(), w)
            })
            .collect();
        for step in steps {
            match step {
                Change::Insert(g) => {
                    for (l, n) in &g.nodes {
                        let w = nodes
                            .entry(l.clone())
                            .or_insert_with(|| (n.id.clone(), Vec::new(), Vec::new(), Vec::new()));
                        w.2.extend(n.batches.iter().cloned());
                    }
                    for (l, e) in &g.edges {
                        let w = edges.entry(l.clone()).or_insert_with(|| {
                            ("src".to_string(), Vec::new(), Vec::new(), Vec::new())
                        });
                        w.2.extend(e.batches.iter().cloned());
                    }
                }
                Change::Remove { whole, keyed } => {
                    for (g, one_each) in [(whole, true), (keyed, false)] {
                        for (l, n) in &g.nodes {
                            // one pass over the label's rows for all of the step's removals
                            if let Some(w) = nodes.get_mut(l)
                                && let Some(d) = joined(&n.batches)?
                                && !remove_rows(w, &d, one_each)?
                            {
                                return Ok(None);
                            }
                        }
                        for (l, e) in &g.edges {
                            // one pass over the label's rows for all of the step's removals
                            if let Some(w) = edges.get_mut(l)
                                && let Some(d) = joined(&e.batches)?
                                && !remove_rows(w, &d, one_each)?
                            {
                                return Ok(None);
                            }
                        }
                    }
                }
            }
        }
        let mut out = Changed::default();
        for (l, (id, old, new, gone)) in nodes {
            let part = |b: Vec<RecordBatch>| Nodes {
                id: id.clone(),
                batches: b,
            };
            let mut now = old;
            now.extend(new.iter().cloned());
            out.now.nodes.insert(l.clone(), part(now));
            if !new.is_empty() {
                out.added.nodes.insert(l.clone(), part(new));
            }
            if !gone.is_empty() {
                out.removed.nodes.insert(l, part(gone));
            }
        }
        for (l, (_, old, new, gone)) in edges {
            let mut now = old;
            now.extend(new.iter().cloned());
            out.now.edges.insert(l.clone(), Edges { batches: now });
            if !new.is_empty() {
                out.added.edges.insert(l.clone(), Edges { batches: new });
            }
            if !gone.is_empty() {
                out.removed.edges.insert(l, Edges { batches: gone });
            }
        }
        Ok(Some(out))
    }

    /// What `removed` (rows these rows no longer hold) took out of the graph: per edge label
    /// the pairs of `removed` no row here holds, and the labels a removed id or pair of
    /// which another row here still holds.
    pub(crate) fn gone(&self, removed: &GraphRows) -> Result<Gone> {
        let mut out = Gone::default();
        for (l, r) in &removed.nodes {
            let Some(was) = column(&r.batches, &r.id)? else {
                continue;
            };
            let was: HashSet<u64> = ids(&was, "a removed id column")?.into_iter().collect();
            if let Some(n) = self.nodes.get(l)
                && let Some(now) = column(&n.batches, &n.id)?
                && ids(&now, "an id column")?.iter().any(|x| was.contains(x))
            {
                out.still_held.insert(l.clone());
            }
        }
        for (l, r) in &removed.edges {
            let pairs = |b: &[RecordBatch], what: &str| -> Result<Vec<(u64, u64)>> {
                let (Some(s), Some(d)) = (column(b, "src")?, column(b, "dst")?) else {
                    return Ok(Vec::new());
                };
                Ok(ids(&s, what)?.into_iter().zip(ids(&d, what)?).collect())
            };
            let mut was: Vec<(u64, u64)> = pairs(&r.batches, "a removed edge end")?;
            was.sort_unstable();
            was.dedup();
            let mut held: HashSet<(u64, u64)> = HashSet::new();
            if let Some(e) = self.edges.get(l) {
                let want: HashSet<(u64, u64)> = was.iter().copied().collect();
                for p in pairs(&e.batches, "an edge end")? {
                    if want.contains(&p) {
                        held.insert(p);
                    }
                }
            }
            if !held.is_empty() {
                out.still_held.insert(l.clone());
            }
            let (src, dst): (Vec<u32>, Vec<u32>) = was
                .into_iter()
                .filter(|p| !held.contains(p))
                .map(|(a, b)| (a as u32, b as u32))
                .unzip();
            out.pairs.insert(l.clone(), (src, dst));
        }
        Ok(out)
    }

    /// These removed rows as a catalog of the facts the set lost: each label's removed ids
    /// (or pairs) and their properties, a label left out when `gone` says another row still
    /// holds one of them (that label is then compared whole).
    pub(crate) fn removed_catalog(&self, gone: &Gone) -> Result<Catalog> {
        let keep = GraphRows {
            nodes: self
                .nodes
                .iter()
                .filter(|(l, _)| !gone.still_held.contains(*l))
                .map(|(l, n)| (l.clone(), n.clone()))
                .collect(),
            edges: self
                .edges
                .iter()
                .filter(|(l, _)| !gone.still_held.contains(*l))
                .map(|(l, e)| (l.clone(), e.clone()))
                .collect(),
        };
        keep.catalog(None)
    }

    /// Keep these rows in `store`: each label's rows one batch, each column its own file
    /// ([`storable`]), and a list naming them (`n` or `e`, the label, the id column, then
    /// per column its name, its type, its kind and whether its nulls are kept beside). A
    /// column of a type not listed keeps nothing (the rows are read again next time).
    pub(crate) fn save(&self, store: &Store) -> Result<()> {
        let mut parts = Vec::new();
        let mut cols: Vec<(String, ArrayRef)> = Vec::new();
        let mut one =
            |kind: &str, label: &str, id: &str, batches: &[RecordBatch]| -> Result<bool> {
                let Some(first) = batches.first() else {
                    return Ok(true);
                };
                // (column by column: the batches of one label may differ in nullability)
                let schema = first.schema();
                let joined = schema
                    .fields()
                    .iter()
                    .map(|f| {
                        column(batches, f.name())?.ok_or_else(|| {
                            Error::Table(format!("`{}` is missing in a batch", f.name()))
                        })
                    })
                    .collect::<Result<Vec<ArrayRef>>>()?;
                let fields: Vec<Field> = schema
                    .fields()
                    .iter()
                    .zip(&joined)
                    .map(|(f, a)| Field::new(f.name(), a.data_type().clone(), true))
                    .collect();
                let b = RecordBatch::try_new(Arc::new(Schema::new(fields)), joined)
                    .map_err(|e| Error::Table(e.to_string()))?;
                let k = parts.len();
                let mut line = vec![kind.to_string(), label.to_string(), id.to_string()];
                for (j, f) in b.schema().fields().iter().enumerate() {
                    let (Some(ty), Some((how, values, valid))) =
                        (type_name(f.data_type()), storable(b.column(j))?)
                    else {
                        return Ok(false);
                    };
                    line.extend([f.name().clone(), ty.to_string(), how.to_string()]);
                    line.push(if valid.is_some() { "nulls" } else { "-" }.to_string());
                    cols.push((format!("p{k}.{j}"), values));
                    if let Some(v) = valid {
                        cols.push((format!("p{k}.{j}.valid"), v));
                    }
                }
                parts.push(line.join("\t"));
                Ok(true)
            };
        for (label, n) in &self.nodes {
            if !one("n", label, &n.id, &n.batches)? {
                return Ok(());
            }
        }
        for (label, e) in &self.edges {
            if !one("e", label, "", &e.batches)? {
                return Ok(());
            }
        }
        let list: ArrayRef = Arc::new(arrow_array::BinaryArray::from_iter_values(
            parts.iter().map(|p| p.as_bytes()),
        ));
        let mut named: Vec<(&str, ArrayRef)> = vec![("parts", list)];
        named.extend(cols.iter().map(|(n, a)| (n.as_str(), a.clone())));
        store.save(KEPT, named)?;
        Ok(())
    }

    /// The rows kept in `store` by [`GraphRows::save`], if they are there whole; their
    /// columns are mapped from the files.
    pub(crate) fn load(store: &Store) -> Result<Option<GraphRows>> {
        let Some(stored) = store.load(KEPT)? else {
            return Ok(None);
        };
        Ok(Some(Self::from_stored(&stored)?))
    }

    fn from_stored(stored: &Stored) -> Result<GraphRows> {
        let bad = |why: String| Error::Table(format!("kept rows: {why}"));
        let list = stored.array("parts")?;
        let list = list
            .as_binary_opt::<i32>()
            .ok_or_else(|| bad("the list is not bytes".into()))?;
        let mut g = GraphRows::default();
        for (k, line) in list.iter().enumerate() {
            let line = std::str::from_utf8(line.unwrap_or_default())
                .map_err(|e| bad(format!("part {k}: {e}")))?;
            let line: Vec<&str> = line.split('\t').collect();
            let [kind, label, id, rest @ ..] = line.as_slice() else {
                return Err(bad(format!("part {k} is cut short")));
            };
            if rest.len() % 4 != 0 {
                return Err(bad(format!("part {k} is cut short")));
            }
            let mut fields = Vec::with_capacity(rest.len() / 4);
            let mut arrays = Vec::with_capacity(rest.len() / 4);
            for (j, c) in rest.chunks(4).enumerate() {
                let ty = type_named(c[1]).ok_or_else(|| bad(format!("a type `{}`", c[1])))?;
                let values = stored.array(&format!("p{k}.{j}"))?;
                let valid = match c[3] {
                    "nulls" => Some(stored.array(&format!("p{k}.{j}.valid"))?),
                    _ => None,
                };
                let a = restored(c[2], &ty, &values, valid.as_ref())?;
                fields.push(Field::new(c[0], ty, valid.is_some()));
                arrays.push(a);
            }
            let b = RecordBatch::try_new(Arc::new(Schema::new(fields)), arrays)
                .map_err(|e| bad(e.to_string()))?;
            match *kind {
                "n" => {
                    let n = g.nodes.entry(label.to_string()).or_default();
                    n.id = id.to_string();
                    n.batches.push(b);
                }
                _ => g
                    .edges
                    .entry(label.to_string())
                    .or_default()
                    .batches
                    .push(b),
            }
        }
        Ok(g)
    }

    /// Keep the rows of `m` (upserts only: removals are taken out by [`GraphRows::changed`]).
    pub(crate) fn add_mutation(&mut self, m: &GraphMutation) -> SinkReport {
        let mut r = SinkReport::default();
        for v in &m.vertices {
            let n = self.nodes.entry(v.label.clone()).or_default();
            n.id.clone_from(&v.id_column);
            r.vertices_written += v.batch.num_rows();
            n.batches.push(v.batch.clone());
        }
        for e in &m.edges {
            r.edges_written += e.batch.num_rows();
            self.edges
                .entry(e.edge_type.clone())
                .or_default()
                .batches
                .push(e.batch.clone());
        }
        r
    }
}
/// Take `del`'s rows out of the label's rows `w` (its id column, its rows of before, of the
/// window, and the rows of before taken out so far): with `whole` each row of `del` takes
/// out one row equal to it in every column, without it every row equal to it in its
/// columns that are not null; the window's rows are looked through first. `false` when a
/// row of `del` has no id (its key column is null or missing).
fn remove_rows(
    w: &mut (String, Vec<RecordBatch>, Vec<RecordBatch>, Vec<RecordBatch>),
    del: &RecordBatch,
    whole: bool,
) -> Result<bool> {
    if del.num_rows() == 0 {
        return Ok(true);
    }
    let Some(key) = del.column_by_name(&w.0) else {
        return Ok(false);
    };
    if key.null_count() > 0 {
        return Ok(false);
    }
    let err = |e: arrow_schema::ArrowError| Error::Table(format!("removing rows: {e}"));
    // the rows of `del` by the columns they name (all of them with `whole`, else those not
    // null), each set of columns one group whose rows are matched by their encoded values
    let n = del.num_columns();
    let mut sets: Vec<(Vec<usize>, Encoded)> = Vec::new();
    let mut set_of: HashMap<Vec<bool>, usize> = HashMap::new();
    let mut encoded: HashMap<Vec<usize>, arrow_row::Rows> = HashMap::new();
    for j in 0..del.num_rows() {
        let on: Vec<bool> = (0..n).map(|c| whole || !del.column(c).is_null(j)).collect();
        let g = *set_of.entry(on.clone()).or_insert_with(|| {
            sets.push(((0..n).filter(|&c| on[c]).collect(), HashMap::new()));
            sets.len() - 1
        });
        let cols = sets[g].0.clone();
        if !encoded.contains_key(&cols) {
            let picked: Vec<ArrayRef> = cols.iter().map(|&c| del.column(c).clone()).collect();
            encoded.insert(cols.clone(), encode(&picked).map_err(err)?);
        }
        let key = encoded[&cols].row(j).as_ref().to_vec();
        sets[g].1.entry(key).or_default().push(j);
    }
    for (_, m) in sets.iter_mut() {
        // one row of `del` taken out per equal row, the first ones first
        for js in m.values_mut() {
            js.reverse();
        }
    }
    let schema = del.schema();
    // the ids `del` names: a row with another id is never encoded
    let named: HashSet<u64> = ids(key, "a removed row's id")?.into_iter().collect();
    let mut cut = |batches: &mut Vec<RecordBatch>, out: Option<&mut Vec<RecordBatch>>| {
        let mut taken = Vec::new();
        for b in batches.iter_mut() {
            let Some(bk) = b.column_by_name(&w.0) else {
                continue;
            };
            let at: Vec<u32> = ids(bk, "an id column")?
                .iter()
                .enumerate()
                .filter(|(_, k)| named.contains(k))
                .map(|(r, _)| r as u32)
                .collect();
            if at.is_empty() {
                continue;
            }
            let at = arrow_array::UInt32Array::from(at);
            let mut keep = vec![true; b.num_rows()];
            let mut any = false;
            for (cols, m) in sets.iter_mut() {
                if m.values().all(Vec::is_empty) {
                    continue;
                }
                // the batch's columns of the same names and types, else nothing of it matches
                let picked: Option<Vec<ArrayRef>> = cols
                    .iter()
                    .map(|&c| {
                        let f = schema.field(c);
                        b.column_by_name(f.name())
                            .filter(|a| a.data_type() == f.data_type())
                            .map(|a| arrow_select::take::take(a, &at, None))
                    })
                    .collect::<Option<std::result::Result<_, _>>>()
                    .transpose()
                    .map_err(err)?;
                let Some(picked) = picked else {
                    continue;
                };
                let rows = encode(&picked).map_err(err)?;
                for (i, &r) in at.values().iter().enumerate() {
                    let k = &mut keep[r as usize];
                    if !*k {
                        continue;
                    }
                    let Some(js) = m.get_mut(rows.row(i).as_ref()) else {
                        continue;
                    };
                    if whole && js.pop().is_none() {
                        continue;
                    }
                    *k = false;
                    any = true;
                }
            }
            if any {
                let out_mask: arrow_array::BooleanArray = keep.iter().map(|&k| Some(!k)).collect();
                let mask = arrow_array::BooleanArray::from(keep);
                taken.push(arrow_select::filter::filter_record_batch(b, &out_mask).map_err(err)?);
                *b = arrow_select::filter::filter_record_batch(b, &mask).map_err(err)?;
            }
        }
        batches.retain(|b| b.num_rows() > 0);
        if let Some(out) = out {
            out.extend(taken);
        }
        Ok::<(), Error>(())
    };
    cut(&mut w.2, None)?;
    let mut gone = Vec::new();
    cut(&mut w.1, Some(&mut gone))?;
    w.3.extend(gone);
    Ok(true)
}

/// `batches` as one batch (`None`: no rows), column by column (the batches of one label may
/// differ in nullability), every column nullable.
fn joined(batches: &[RecordBatch]) -> Result<Option<RecordBatch>> {
    let Some(first) = batches.iter().find(|b| b.num_rows() > 0) else {
        return Ok(None);
    };
    if batches.len() == 1 {
        return Ok(Some(first.clone()));
    }
    let schema = first.schema();
    let cols = schema
        .fields()
        .iter()
        .map(|f| {
            column(batches, f.name())?
                .ok_or_else(|| Error::Table(format!("`{}` is missing in a batch", f.name())))
        })
        .collect::<Result<Vec<ArrayRef>>>()?;
    let fields: Vec<Field> = schema
        .fields()
        .iter()
        .zip(&cols)
        .map(|(f, a)| Field::new(f.name(), a.data_type().clone(), true))
        .collect();
    RecordBatch::try_new(Arc::new(Schema::new(fields)), cols)
        .map(Some)
        .map_err(|e| Error::Table(e.to_string()))
}

/// Rows by their encoded values: the rows of `del` with each.
type Encoded = HashMap<Vec<u8>, Vec<usize>>;

/// The rows of `cols` encoded so that equal rows (nulls equal to nulls) have equal bytes.
fn encode(cols: &[ArrayRef]) -> std::result::Result<arrow_row::Rows, arrow_schema::ArrowError> {
    let fields = cols
        .iter()
        .map(|a| arrow_row::SortField::new(a.data_type().clone()))
        .collect();
    arrow_row::RowConverter::new(fields)?.convert_columns(cols)
}

/// The ids in integer column `a` (`what` names it in a refusal): each at least 0, no null.
fn ids(a: &ArrayRef, what: &str) -> Result<Vec<u64>> {
    if a.null_count() > 0 {
        return Err(Error::Table(format!("{what} has nulls")));
    }
    let signed = |v: Vec<i64>| -> Result<Vec<u64>> {
        v.into_iter()
            .map(|x| {
                u64::try_from(x).map_err(|_| Error::Table(format!("{what} has id {x} below 0")))
            })
            .collect()
    };
    Ok(match a.data_type() {
        DataType::Int8 => signed(
            a.as_primitive::<Int8Type>()
                .values()
                .iter()
                .map(|&x| x as i64)
                .collect(),
        )?,
        DataType::Int16 => signed(
            a.as_primitive::<Int16Type>()
                .values()
                .iter()
                .map(|&x| x as i64)
                .collect(),
        )?,
        DataType::Int32 => signed(
            a.as_primitive::<Int32Type>()
                .values()
                .iter()
                .map(|&x| x as i64)
                .collect(),
        )?,
        DataType::Int64 => signed(a.as_primitive::<Int64Type>().values().to_vec())?,
        DataType::UInt8 => a
            .as_primitive::<UInt8Type>()
            .values()
            .iter()
            .map(|&x| x as u64)
            .collect(),
        DataType::UInt16 => a
            .as_primitive::<UInt16Type>()
            .values()
            .iter()
            .map(|&x| x as u64)
            .collect(),
        DataType::UInt32 => a
            .as_primitive::<UInt32Type>()
            .values()
            .iter()
            .map(|&x| x as u64)
            .collect(),
        DataType::UInt64 => a.as_primitive::<UInt64Type>().values().to_vec(),
        d => {
            return Err(Error::Table(format!(
                "{what} is an Arrow {d} column: ids are integers (string ids are not read yet)"
            )));
        }
    })
}

/// Column `name` of `batches` as one array (`None` when no batch has it).
fn column(batches: &[RecordBatch], name: &str) -> Result<Option<ArrayRef>> {
    let parts: Vec<&ArrayRef> = batches
        .iter()
        .filter_map(|b| b.column_by_name(name))
        .collect();
    if parts.len() != batches.len() {
        return Ok(None);
    }
    Ok(Some(match parts.as_slice() {
        [] => return Ok(None),
        [one] => (*one).clone(),
        many => {
            let refs: Vec<&dyn Array> = many.iter().map(|a| a.as_ref()).collect();
            arrow_select::concat::concat(&refs).map_err(|e| Error::Table(e.to_string()))?
        }
    }))
}

/// The other columns of `batches` (the first batch's names): the properties.
fn properties(batches: &[RecordBatch], not: &[&str]) -> Vec<String> {
    batches.first().map_or_else(Vec::new, |b| {
        b.schema()
            .fields()
            .iter()
            .map(|f| f.name().clone())
            .filter(|n| !not.contains(&n.as_str()))
            .collect()
    })
}

impl GraphRows {
    /// The rows as a catalog: each node label its ids (one id space for every label, the
    /// ids as the tables hold them) and properties, each edge label a graph over that id
    /// space (by source and by destination) and its properties; every property read by its
    /// type as kleene-gar reads a set's columns ([`kleene_gar::column_type`]).
    pub fn catalog(&self, grow: Option<(&Catalog, &GraphRows)>) -> Result<Catalog> {
        self.catalog_changed(grow.map(|(c, a)| (c, a, None)))
    }

    /// [`GraphRows::catalog`], each edge label's graph (when `grow` gives the catalog
    /// before) that graph with the added rows' edges added and the pairs `grow.2` says are
    /// gone taken out ([`Csr::with_changes`]).
    pub(crate) fn catalog_changed(
        &self,
        grow: Option<(&Catalog, &GraphRows, Option<&Gone>)>,
    ) -> Result<Catalog> {
        let mut c = Catalog::new();
        let mut n: u64 = 0;
        for (label, rows) in &self.nodes {
            let what = format!("id column `{}` of `{label}`", rows.id);
            let Some(id) = column(&rows.batches, &rows.id)? else {
                continue;
            };
            let v = ids(&id, &what)?;
            n = n.max(v.iter().max().map_or(0, |&x| x + 1));
            let a: ArrayRef = Arc::new(UInt64Array::from(v));
            c.label(label, Source::Columns(vec![a.clone()]));
            for p in properties(&rows.batches, &[rows.id.as_str()]) {
                let Some(values) = column(&rows.batches, &p)? else {
                    continue;
                };
                match kleene_gar::column_type(&values, "column") {
                    Ok((Type::U64, values)) => {
                        c.property(label, &p, Source::Columns(vec![a.clone(), values]));
                    }
                    Ok((ty, values)) => {
                        c.typed_property(label, &p, Source::Columns(vec![a.clone(), values]), ty);
                    }
                    Err(why) => {
                        c.refused_property(label, &p, &why);
                    }
                }
            }
        }
        let mut ends = Vec::with_capacity(self.edges.len());
        for (label, rows) in &self.edges {
            let end = |k: &str| -> Result<Vec<u64>> {
                let what = format!("`{k}` of edge label `{label}`");
                let a = column(&rows.batches, k)?
                    .ok_or_else(|| Error::Table(format!("{what} is missing")))?;
                ids(&a, &what)
            };
            let (from, to) = (end("src")?, end("dst")?);
            n = n.max(from.iter().chain(&to).max().map_or(0, |&x| x + 1));
            ends.push((label, rows, from, to));
        }
        if n > u64::from(u32::MAX) {
            return Err(Error::Table(format!(
                "node ids up to {}: a graph's vertices are u32",
                n - 1
            )));
        }
        let n = n as usize;
        for (label, rows, from, to) in ends {
            let (out, inn) = match grow
                .and_then(|(prev, added, gone)| Some((prev.relation(label).ok()?.0, added, gone)))
            {
                // the graph before, grown by the new edges
                Some((
                    Source::Graph {
                        out: before,
                        inn: back,
                    },
                    added,
                    gone,
                )) => {
                    let (src, dst) = match added.edges.get(label.as_str()) {
                        Some(e) => {
                            let end = |k: &str| -> Result<Vec<u32>> {
                                let what = format!("`{k}` of edge label `{label}`");
                                let a = column(&e.batches, k)?
                                    .ok_or_else(|| Error::Table(format!("{what} is missing")))?;
                                Ok(ids(&a, &what)?.into_iter().map(|x| x as u32).collect())
                            };
                            (end("src")?, end("dst")?)
                        }
                        None => (Vec::new(), Vec::new()),
                    };
                    let empty = (Vec::new(), Vec::new());
                    let (gs, gd) = gone
                        .and_then(|g| g.pairs.get(label.as_str()))
                        .unwrap_or(&empty);
                    let out = before.with_changes(n, n, (&src, &dst), (gs, gd))?;
                    let inn = match back {
                        Some(b) => b.with_changes(n, n, (&dst, &src), (gd, gs))?,
                        None => out.transpose(),
                    };
                    (out, inn)
                }
                _ => {
                    let src: Vec<u32> = from.iter().map(|&x| x as u32).collect();
                    let dst: Vec<u32> = to.iter().map(|&x| x as u32).collect();
                    let out = Csr::<u8>::from_edges(n, n, &src, &dst, None, BoolOrAnd)?;
                    let inn = out.transpose();
                    (out, inn)
                }
            };
            c.edge(
                label,
                Source::Graph {
                    out,
                    inn: Some(inn),
                },
            );
            let (fa, ta): (ArrayRef, ArrayRef) = (
                Arc::new(UInt64Array::from(from)),
                Arc::new(UInt64Array::from(to)),
            );
            for p in properties(&rows.batches, &["src", "dst"]) {
                let Some(values) = column(&rows.batches, &p)? else {
                    continue;
                };
                let source = |values| Source::Columns(vec![fa.clone(), ta.clone(), values]);
                match kleene_gar::column_type(&values, "edge property") {
                    Ok((Type::U64, values)) => {
                        c.edge_property(label, &p, source(values));
                    }
                    Ok((ty, values)) => {
                        c.typed_edge_property(label, &p, source(values), ty);
                    }
                    Err(why) => {
                        c.refused_edge_property(label, &p, &why);
                    }
                }
            }
        }
        Ok(c)
    }
}