inference-engine 0.1.0-alpha.13

Native Rust RDF inference engine with a shared command-line interface
Documentation
use super::{args::Args, quota::QuotaBackend};
use crate::reasoning::Inference;
use redb::{Database, ReadableTable, TableDefinition, WriteTransaction};
use serde::{Deserialize, Serialize};
use std::{
    fs::OpenOptions,
    io,
    path::Path,
    sync::{
        Arc, Mutex,
        atomic::{AtomicU64, Ordering},
    },
};
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub(super) struct Id(pub u64);
pub(super) type Key = (u64, u64, u64, u64);
pub(super) const INDEX: [TableDefinition<Key, ()>; 3] = [
    TableDefinition::new("spo"),
    TableDefinition::new("pos"),
    TableDefinition::new("osp"),
];
pub(super) const ASSERTED: TableDefinition<Key, ()> = TableDefinition::new("asserted");
pub(super) const PROOFS: TableDefinition<Key, &[u8]> = TableDefinition::new("proofs");
pub(super) const TEXT: TableDefinition<&str, u64> = TableDefinition::new("term_to_id");
pub(super) const TERMS: TableDefinition<u64, (u8, &str)> = TableDefinition::new("id_to_term");
pub(super) const GRAPHS: TableDefinition<u64, ()> = TableDefinition::new("graphs");
pub(super) struct State {
    pub db: Arc<Database>,
    pub writer: Option<WriteTransaction>,
    pub asserted: u64,
    pub inferred: u64,
    next_id: u64,
    pending: usize,
    pending_bytes: usize,
    max_inferred: u64,
}
pub(super) type Shared = Arc<Mutex<State>>;
pub(super) struct Work {
    steps: AtomicU64,
    limit: u64,
}
impl Work {
    pub fn new(limit: u64) -> Self {
        Self {
            steps: AtomicU64::new(0),
            limit,
        }
    }
    pub fn step(&self) -> io::Result<()> {
        self.steps
            .try_update(Ordering::Relaxed, Ordering::Relaxed, |n| {
                (n < self.limit).then(|| n + 1)
            })
            .map(|_| ())
            .map_err(|_| io::Error::other("aggregate work step limit exceeded"))
    }
}
pub(super) fn key(g: u64, t: [Id; 3], index: usize) -> Key {
    let [s, p, o] = t.map(|id| id.0);
    match index {
        0 => (g, s, p, o),
        1 => (g, p, o, s),
        2 => (g, o, s, p),
        _ => panic!("fixed index"),
    }
}
pub(super) fn tuple(k: Key, index: usize) -> [Id; 3] {
    let (_, a, b, c) = k;
    match index {
        0 => [Id(a), Id(b), Id(c)],
        1 => [Id(c), Id(a), Id(b)],
        2 => [Id(b), Id(c), Id(a)],
        _ => panic!("fixed index"),
    }
}
impl State {
    pub fn create(path: &Path, args: &Args) -> io::Result<Self> {
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .create_new(true)
            .open(path)?;
        let db = Arc::new(
            Database::builder()
                .set_cache_size(64 * 1024 * 1024)
                .create_with_backend(QuotaBackend::new(file, args.max_scratch_bytes.get()))
                .map_err(io::Error::other)?,
        );
        let w = db.begin_write().map_err(io::Error::other)?;
        for i in INDEX {
            w.open_table(i).map_err(io::Error::other)?;
        }
        w.open_table(ASSERTED).map_err(io::Error::other)?;
        w.open_table(PROOFS).map_err(io::Error::other)?;
        w.open_table(TEXT).map_err(io::Error::other)?;
        w.open_table(TERMS).map_err(io::Error::other)?;
        w.open_table(GRAPHS).map_err(io::Error::other)?;
        w.commit().map_err(io::Error::other)?;
        Ok(Self {
            db,
            writer: None,
            asserted: 0,
            inferred: 0,
            next_id: 1,
            pending: 0,
            pending_bytes: 0,
            max_inferred: args.max_inferred.get(),
        })
    }
    pub fn write(&mut self) -> io::Result<&WriteTransaction> {
        if self.writer.is_none() {
            self.writer = Some(self.db.begin_write().map_err(io::Error::other)?);
        }
        Ok(self.writer.as_ref().expect("writer initialized"))
    }
    pub fn flush(&mut self) -> io::Result<()> {
        if let Some(w) = self.writer.take() {
            w.commit().map_err(io::Error::other)?;
        }
        self.pending = 0;
        self.pending_bytes = 0;
        Ok(())
    }
    pub fn resolve(&mut self, text: &str, kind: u8) -> io::Result<Id> {
        let found = self
            .write()?
            .open_table(TEXT)
            .map_err(io::Error::other)?
            .get(text)
            .map_err(io::Error::other)?
            .map(|v| v.value());
        if let Some(id) = found {
            return Ok(Id(id));
        }
        let id = self.next_id;
        self.next_id = id
            .checked_add(1)
            .ok_or_else(|| io::Error::other("term ID overflow"))?;
        self.write()?
            .open_table(TEXT)
            .map_err(io::Error::other)?
            .insert(text, id)
            .map_err(io::Error::other)?;
        self.write()?
            .open_table(TERMS)
            .map_err(io::Error::other)?
            .insert(id, (kind, text))
            .map_err(io::Error::other)?;
        Ok(Id(id))
    }
    pub fn contains(&mut self, g: u64, t: [Id; 3]) -> io::Result<bool> {
        Ok(self
            .write()?
            .open_table(INDEX[0])
            .map_err(io::Error::other)?
            .get(key(g, t, 0))
            .map_err(io::Error::other)?
            .is_some())
    }
    pub fn insert(
        &mut self,
        g: u64,
        t: [Id; 3],
        proof: Option<&Inference<Id>>,
    ) -> io::Result<bool> {
        if self.contains(g, t)? {
            return Ok(false);
        }
        if proof.is_some() && self.inferred == self.max_inferred {
            return Err(io::Error::other("aggregate inferred tuple limit exceeded"));
        }
        for (i, table) in INDEX.iter().enumerate() {
            self.write()?
                .open_table(*table)
                .map_err(io::Error::other)?
                .insert(key(g, t, i), ())
                .map_err(io::Error::other)?;
        }
        if let Some(proof) = proof {
            let bytes = postcard::to_allocvec(proof).map_err(io::Error::other)?;
            self.write()?
                .open_table(PROOFS)
                .map_err(io::Error::other)?
                .insert(key(g, t, 0), bytes.as_slice())
                .map_err(io::Error::other)?;
            self.inferred += 1;
        } else {
            self.write()?
                .open_table(ASSERTED)
                .map_err(io::Error::other)?
                .insert(key(g, t, 0), ())
                .map_err(io::Error::other)?;
            self.write()?
                .open_table(GRAPHS)
                .map_err(io::Error::other)?
                .insert(g, ())
                .map_err(io::Error::other)?;
            self.asserted += 1;
        }
        self.pending += 1;
        if self.pending >= 128 || self.pending_bytes >= 4 * 1024 * 1024 {
            self.flush()?;
        }
        Ok(true)
    }
    pub fn add_bytes(&mut self, n: usize) -> io::Result<()> {
        if self.pending > 0 && self.pending_bytes.saturating_add(n) > 4 * 1024 * 1024 {
            self.flush()?;
        }
        self.pending_bytes += n;
        Ok(())
    }
}
pub(super) async fn access<T: Send + 'static>(
    state: &Shared,
    f: impl FnOnce(&mut State) -> io::Result<T> + Send + 'static,
) -> io::Result<T> {
    let state = state.clone();
    tokio::task::spawn_blocking(move || {
        let mut state = state
            .lock()
            .map_err(|_| io::Error::other("scratch state lock poisoned"))?;
        f(&mut state)
    })
    .await
    .map_err(io::Error::other)?
}