crates/kleene-iceberg/src/set.rs
//! A set of Iceberg tables, read through bifröst into kleene's catalog.
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use kleene_index::Store;
use kleene_plan::Catalog;
use knut_bifrost::delivery::IcebergLake;
use knut_bifrost::{
IcebergSource, MappingSpec, TableContext, Transform, TransformRegistry, partition_change_rows,
};
use crate::sink::{Change, GraphRows};
use crate::{Error, Result};
/// A version of a set: the snapshot id of each table that has one (a table with no snapshot
/// yet is empty).
pub type Version = BTreeMap<String, i64>;
/// The tables a bifröst mapping names, read where they lie ([`IcebergSet::snapshot`]).
pub struct IcebergSet {
lake: IcebergLake,
source: IcebergSource,
/// Each table's pipeline, compiled once.
tables: Vec<(String, Vec<Arc<dyn Transform>>)>,
read: AtomicU64,
/// The rows each table gave at a snapshot, kept: (table, snapshot id).
kept: Mutex<BTreeMap<(String, i64), Arc<GraphRows>>>,
/// Where kept rows are stored too (a directory per table keyed by its snapshot id).
store: Option<PathBuf>,
}
impl std::fmt::Debug for IcebergSet {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("IcebergSet")
.field("lake", &self.lake.describe())
.field(
"tables",
&self.tables.iter().map(|t| &t.0).collect::<Vec<_>>(),
)
.finish()
}
}
/// A set at one version: the graph's rows as bifröst handed them, and the catalog they fill.
#[derive(Clone, Debug)]
pub struct Snapshot {
version: Version,
/// Each table's rows at its snapshot.
tables: BTreeMap<String, Arc<GraphRows>>,
rows: GraphRows,
catalog: Catalog,
}
/// A set's next version read from an earlier one ([`IcebergSet::advance`]): the new
/// snapshot, the rows added since and the facts removed since, each as a catalog of its own
/// (for `Engine::continue_with`'s `added` and `removed`).
#[derive(Clone, Debug)]
pub struct Delta {
/// The set at its new version.
pub snapshot: Snapshot,
/// The rows the tables gained: each node label's new ids and their properties, each edge
/// label's new edges. A label whose new rows repeat an old id (or a table read whole
/// again) is left out: a run continuing from it compares that input instead.
pub added: Catalog,
/// The facts the tables lost: each node label's ids no row holds now and their
/// properties, each edge label's pairs no row holds now and their properties. A label
/// one of whose removed ids (or pairs) another row still holds, or one of a table read
/// whole again, is left out: a run continuing from it compares that input instead.
pub removed: Catalog,
/// The tables read whole again, by name: a window whose removed rows name no node or
/// edge of the mapping (an equality delete on other columns), or one skade cannot read
/// as rows.
pub reread: Vec<String>,
}
impl Snapshot {
/// The catalog: node labels, edge labels and properties, as kleene-plan's clients read
/// a set ([`kleene_plan::Catalog`]).
pub fn catalog(&self) -> &Catalog {
&self.catalog
}
/// The snapshot id of each table read.
pub fn version(&self) -> &Version {
&self.version
}
/// The rows of each label as read.
pub fn rows(&self) -> &GraphRows {
&self.rows
}
}
impl IcebergSet {
/// The set `spec` maps (its tables' pipelines of `vertex`, `edge` and `fk_edges` steps;
/// a `custom` step is refused, it names a transform kleene does not register), its
/// tables found in `lake`.
pub fn new(spec: &MappingSpec, lake: IcebergLake) -> Result<Self> {
let registry = TransformRegistry::new();
let tables = spec
.tables
.iter()
.map(|t| Ok((t.table.clone(), t.compile(®istry)?)))
.collect::<Result<_>>()?;
Ok(IcebergSet {
source: IcebergSource::from_lake(lake.clone()),
lake,
tables,
read: AtomicU64::new(0),
kept: Mutex::new(BTreeMap::new()),
store: None,
})
}
/// Keep each table's rows also in `dir`, in kleene-index's [`Store`]: one directory per
/// table, keyed by the snapshot id it was read at where a set's index directory is keyed
/// by the set's root hash. Another set opened on the same lake and `dir` then reads no
/// data file for a table at a snapshot already kept; a table read at another snapshot
/// replaces its directory.
pub fn keep_in(mut self, dir: impl Into<PathBuf>) -> Self {
self.store = Some(dir.into());
self
}
/// The store of table `t` at snapshot `id` ([`IcebergSet::keep_in`]); in memory only
/// when none was given.
fn store_of(&self, t: &str, id: i64) -> Result<Store> {
let Some(dir) = &self.store else {
return Ok(Store::memory());
};
let name: String = t
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' {
c
} else {
'_'
}
})
.collect();
Ok(Store::keyed(
dir.join(format!("{name}.kix")),
format!("iceberg {t} snapshot {id}"),
)?)
}
/// The rows table `t` gives at snapshot `to`: kept in memory, kept in the store, or
/// read (its history up to `to`, its removals applied in commit order; or, when that
/// cannot be read as rows, its live rows at `to`), then kept.
async fn rows_of(
&self,
t: &str,
transforms: &[Arc<dyn Transform>],
to: i64,
) -> Result<Arc<GraphRows>> {
let key = (t.to_string(), to);
if let Some(r) = self.kept.lock().expect("not poisoned").get(&key) {
return Ok(r.clone());
}
let store = self.store_of(t, to)?;
let rows = match GraphRows::load(&store)? {
Some(r) => r,
None => {
let r = match self.window(t, transforms, None, to).await? {
Some(steps) => GraphRows::default().changed(&steps)?.map(|c| c.now),
None => None,
};
let r = match r {
Some(r) => r,
None => self.live(t, transforms, to).await?,
};
r.save(&store)?;
r
}
};
let rows = Arc::new(rows);
self.kept
.lock()
.expect("not poisoned")
.insert(key, rows.clone());
Ok(rows)
}
/// The rows of table `t` live at snapshot `to` (bifröst's [`IcebergSource::read_at`]:
/// its deletes applied), handed through its pipeline.
async fn live(&self, t: &str, transforms: &[Arc<dyn Transform>], to: i64) -> Result<GraphRows> {
let batches = self.source.read_at(t, to).await?;
let ctx = TableContext {
table: t.to_string(),
};
let mut rows = GraphRows::default();
for tr in transforms {
rows.add_mutation(&tr.apply(&ctx, &batches)?);
}
Ok(rows)
}
/// What table `t`'s window after snapshot `from` (from the start for `None`) up to
/// `to` changed, in commit order, through its pipeline (bifröst's
/// [`IcebergSource::ingest_changes`]): rows inserted, rows removed (whole rows, or rows
/// named by an equality delete's key columns alone). `None` when skade cannot read the
/// window as rows.
async fn window(
&self,
t: &str,
transforms: &[Arc<dyn Transform>],
from: Option<i64>,
to: i64,
) -> Result<Option<Vec<Change>>> {
let c = self.source.ingest_changes(t, from, to).await?;
self.read
.fetch_add(c.plan.added_files.len() as u64, Ordering::Relaxed);
if c.plan.needs_full_reload {
return Ok(None);
}
let ctx = TableContext {
table: t.to_string(),
};
let through = |batches: &[arrow_array::RecordBatch]| -> Result<GraphRows> {
let mut rows = GraphRows::default();
for tr in transforms {
rows.add_mutation(&tr.apply(&ctx, batches)?);
}
Ok(rows)
};
// the batches in runs of one kind (rows added, rows removed), each run one step:
// removals next to each other take out what they would one after the other
let mut runs: Vec<(bool, Vec<arrow_array::RecordBatch>)> = Vec::new();
for b in &c.batches {
let change = partition_change_rows(std::slice::from_ref(b))?;
for (removes, part) in [(false, change.upserts), (true, change.deletes)] {
let part: Vec<_> = part.into_iter().filter(|b| b.num_rows() > 0).collect();
if part.is_empty() {
continue;
}
match runs.last_mut() {
Some((k, run)) if *k == removes => run.extend(part),
_ => runs.push((removes, part)),
}
}
}
let mut steps = Vec::with_capacity(runs.len());
for (removes, run) in runs {
if !removes {
steps.push(Change::Insert(through(&run)?));
continue;
}
let (whole, keyed) = split_keyed(&run, &c.key_columns)?;
// (rows named by key columns the pipeline does not read may not map at all: the
// table is then read whole)
let Ok(keyed) = through(&keyed) else {
return Ok(None);
};
steps.push(Change::Remove {
whole: through(&whole)?,
keyed,
});
}
Ok(Some(steps))
}
/// How many data files this set has read so far.
pub fn files_read(&self) -> u64 {
self.read.load(Ordering::Relaxed)
}
/// The version of the set now: each table's current snapshot, or the snapshot `pins`
/// gives it (a table `pins` names must be one of the mapping's). Reads metadata only.
pub async fn version(&self, pins: &Version) -> Result<Version> {
if let Some(t) = pins
.keys()
.find(|t| !self.tables.iter().any(|(n, _)| n == *t))
{
return Err(Error::Mapping(format!("no table `{t}` in the mapping")));
}
let mut v = Version::new();
for (t, _) in &self.tables {
let table = self.lake.locate(t).load().await?;
let at = match pins.get(t) {
Some(&id) => {
if table.metadata().snapshot_by_id(id).is_none() {
return Err(Error::Table(format!("table `{t}` has no snapshot {id}")));
}
Some(id)
}
None => table.metadata().current_snapshot_id(),
};
if let Some(id) = at {
v.insert(t.clone(), id);
}
}
Ok(v)
}
/// The set at its current snapshots, or at those `pins` gives: each table's data files
/// up to its snapshot read once, its rows handed through the table's pipeline to
/// kleene's sink ([`GraphRows`]), the catalog filled. A table at a snapshot read before
/// (by this set, or kept in its store) reads no data file again.
pub async fn snapshot(&self, pins: &Version) -> Result<Snapshot> {
let version = self.version(pins).await?;
let mut tables = BTreeMap::new();
let mut rows = GraphRows::default();
for (t, transforms) in &self.tables {
if let Some(&to) = version.get(t) {
let r = self.rows_of(t, transforms, to).await?;
rows.extend(&r);
tables.insert(t.clone(), r);
}
}
let catalog = rows.catalog(None)?;
Ok(Snapshot {
version,
tables,
rows,
catalog,
})
}
/// The set at its current snapshots (or those `pins` gives), read from `from`: a table
/// at the same snapshot as there reads nothing, a later one only what its window
/// changed (bifröst's changelog read, [`IcebergSource::ingest_changes`] from `from`'s
/// snapshot: the data files added, and the rows equality deletes, position deletes,
/// deletion vectors and rewrites removed, applied in commit order); each edge label's
/// graph is `from`'s with the new edges added and the pairs no row holds now taken out
/// ([`kleene_sparse::Csr::with_changes`]). A table whose window cannot be read as rows
/// of the mapping is read whole again (named in [`Delta::reread`]).
pub async fn advance(&self, from: &Snapshot, pins: &Version) -> Result<Delta> {
let version = self.version(pins).await?;
let mut tables = BTreeMap::new();
let mut rows = GraphRows::default();
let mut added = GraphRows::default();
let mut removed = GraphRows::default();
let mut reread = Vec::new();
for (t, transforms) in &self.tables {
let Some(&to) = version.get(t) else {
continue;
};
let old = from.tables.get(t).zip(from.version.get(t));
let r = match old {
Some((r, &at)) if at == to => r.clone(),
Some((r, &at)) => {
let changed = match self.window(t, transforms, Some(at), to).await? {
Some(steps) => r.changed(&steps)?,
None => None,
};
match changed {
Some(c) => {
added.extend(&c.added);
removed.extend(&c.removed);
let now = Arc::new(c.now);
now.save(&self.store_of(t, to)?)?;
self.kept
.lock()
.expect("not poisoned")
.insert((t.clone(), to), now.clone());
now
}
None => {
reread.push(t.clone());
self.rows_of(t, transforms, to).await?
}
}
}
None => {
reread.push(t.clone());
self.rows_of(t, transforms, to).await?
}
};
rows.extend(&r);
tables.insert(t.clone(), r);
}
let gone = rows.gone(&removed)?;
let catalog = if reread.is_empty() {
rows.catalog_changed(Some((&from.catalog, &added, Some(&gone))))?
} else {
rows.catalog(None)?
};
let (added, removed) = if reread.is_empty() {
(
added.added_catalog(&from.rows)?,
removed.removed_catalog(&gone)?,
)
} else {
(Catalog::new(), Catalog::new())
};
Ok(Delta {
snapshot: Snapshot {
version,
tables,
rows,
catalog,
},
added,
removed,
reread,
})
}
}
/// Split removed rows into whole rows and rows named by the key columns `keys` alone (every
/// other column null: an equality delete's identity). With no key columns every row is
/// whole.
fn split_keyed(
batches: &[arrow_array::RecordBatch],
keys: &[String],
) -> Result<(Vec<arrow_array::RecordBatch>, Vec<arrow_array::RecordBatch>)> {
use arrow_array::Array;
if keys.is_empty() {
return Ok((batches.to_vec(), Vec::new()));
}
let err = |e: arrow_schema::ArrowError| Error::Table(format!("removed rows: {e}"));
let (mut whole, mut keyed) = (Vec::new(), Vec::new());
for b in batches {
let others: Vec<&arrow_array::ArrayRef> = b
.schema()
.fields()
.iter()
.zip(b.columns())
.filter(|(f, _)| !keys.iter().any(|k| k == f.name()))
.map(|(_, c)| c)
.collect();
let is_key: Vec<bool> = (0..b.num_rows())
.map(|r| !others.is_empty() && others.iter().all(|c| c.is_null(r)))
.collect();
let key_mask = arrow_array::BooleanArray::from(is_key.clone());
let whole_mask: arrow_array::BooleanArray = is_key.iter().map(|&k| Some(!k)).collect();
keyed.push(arrow_select::filter::filter_record_batch(b, &key_mask).map_err(err)?);
whole.push(arrow_select::filter::filter_record_batch(b, &whole_mask).map_err(err)?);
}
Ok((whole, keyed))
}