inky-engine 3.0.0

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
//! The spill writer: the disk half of a spill, off the scheduler thread.
//!
//! The scheduler queues work with [`SpillWriter::push`] and collects results with [`SpillWriter::try_recv`]. It
//! waits for neither: the queue lock is held only to move a job in or out, never across file I/O.
//!
//! A queued block write reads its K/V bytes straight from the pool slot ([`SpillBytes::Pinned`]), so whoever
//! queues it holds a reference on that slot (the write pin) from `push` until one of two things has happened,
//! and drops it no sooner:
//!  - the write's result came back through `try_recv`, or
//!  - [`SpillWriter::cancel`] removed the job from the queue before the writer took it.
//!
//! Taking a job and cancelling it both happen under the queue lock, so exactly one of them wins: a block the
//! writer has taken stays pinned to the end of its write, and a cancelled block is never read.
//! `specs/SpillWriteBehind.tla` models this hand-off, with a reversed witness for each way to free a block early.

use super::*;
use std::collections::VecDeque;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::{Arc, Condvar, Mutex};

/// Where a block write's K/V bytes come from.
pub enum SpillBytes {
    /// `len` bytes at `ptr` inside a sealed pool slot. They are valid and unchanged for as long as the write
    /// pin on that slot is held (see the module comment).
    Pinned { ptr: *const u8, len: usize },
    Owned(Vec<u8>),
}

// SAFETY: `Pinned` is a read-only view of a sealed pool slot. The pool's slabs never move once the pool is
// built, a sealed slot's bytes change only when the slot is taken again, and a slot is taken again only at
// zero references. The write pin keeps a reference until the writer is done with the job or provably never
// had it, and `SpillWriter::stop` joins the writer before the pool can go away.
unsafe impl Send for SpillBytes {}

/// One unit of spill disk work.
pub enum SpillIo {
    /// Write one `.blk` file ([`write_block_to_dir`]).
    Block {
        key: SpillKey,
        generation: u64,
        kv: SpillBytes,
        state: Option<Vec<u8>>,
        refuse_existing: bool,
    },
    /// Unlink a block the index has already forgotten ([`unlink_block_in_dir`]).
    Unlink { key: SpillKey },
    /// Build and write `spill-index.bin` ([`write_index_to_dir`]). The image is built on the writer.
    Index { build: Box<dyn FnOnce() -> Vec<u8> + Send> },
}

/// The result of one [`SpillIo`], in the order the writer finished them.
pub enum SpillIoDone {
    Block { key: SpillKey, raw: RawDiskWrite },
    Unlink { key: SpillKey, result: io::Result<bool> },
    Index { result: io::Result<()> },
}

#[cfg(test)]
type BlockHook = Arc<dyn Fn(SpillKey) + Send + Sync>;

struct Queue {
    jobs: HashMap<u64, SpillIo>,
    // Job ids in arrival order. An id whose job is gone (cancelled) is skipped when it reaches the front.
    urgent: VecDeque<u64>,
    bulk: VecDeque<u64>,
    closed: bool,
}

impl Queue {
    fn take_next(&mut self) -> Option<SpillIo> {
        while let Some(id) = self.urgent.pop_front() {
            if let Some(job) = self.jobs.remove(&id) {
                return Some(job);
            }
        }
        while let Some(id) = self.bulk.pop_front() {
            if let Some(job) = self.jobs.remove(&id) {
                return Some(job);
            }
        }
        None
    }
}

struct Shared {
    queue: Mutex<Queue>,
    ready: Condvar,
}

impl Shared {
    fn lock(&self) -> std::sync::MutexGuard<'_, Queue> {
        self.queue.lock().unwrap_or_else(|e| e.into_inner())
    }
}

fn run_spill_io(dir: &Path, kvb: u32, job: SpillIo) -> SpillIoDone {
    match job {
        SpillIo::Block { key, generation, kv, state, refuse_existing } => {
            let kv_bytes: &[u8] = match &kv {
                // SAFETY: the write pin on this slot is held until this job's result is received.
                SpillBytes::Pinned { ptr, len } => unsafe { std::slice::from_raw_parts(*ptr, *len) },
                SpillBytes::Owned(bytes) => bytes,
            };
            let raw = write_block_to_dir(dir, kvb, key, generation, kv_bytes, state.as_deref(), refuse_existing);
            SpillIoDone::Block { key, raw }
        }
        SpillIo::Unlink { key } => SpillIoDone::Unlink { key, result: unlink_block_in_dir(dir, key) },
        SpillIo::Index { build } => SpillIoDone::Index { result: write_index_to_dir(dir, &build()) },
    }
}

/// The queue of spill disk work and, once [`SpillWriter::start_thread`] is called, the thread that drains it.
/// Without a thread the queued work runs only when [`SpillWriter::run_queued`] is called.
pub struct SpillWriter {
    shared: Arc<Shared>,
    dir: PathBuf,
    kvb: u32,
    done_tx: Sender<SpillIoDone>,
    done_rx: Receiver<SpillIoDone>,
    next_id: u64,
    join: Option<std::thread::JoinHandle<()>>,
    #[cfg(test)]
    block_hook: Option<BlockHook>,
}

impl SpillWriter {
    pub fn new(dir: &Path, kvb: u32) -> Self {
        let (done_tx, done_rx) = channel();
        Self {
            shared: Arc::new(Shared {
                queue: Mutex::new(Queue {
                    jobs: HashMap::new(),
                    urgent: VecDeque::new(),
                    bulk: VecDeque::new(),
                    closed: false,
                }),
                ready: Condvar::new(),
            }),
            dir: dir.to_path_buf(),
            kvb,
            done_tx,
            done_rx,
            next_id: 1,
            join: None,
            #[cfg(test)]
            block_hook: None,
        }
    }

    /// Start the writer thread. `wake` runs on it after each result is sent.
    pub fn start_thread(&mut self, wake: Arc<dyn Fn() + Send + Sync>) {
        if self.join.is_some() {
            return;
        }
        let shared = self.shared.clone();
        let dir = self.dir.clone();
        let kvb = self.kvb;
        let done = self.done_tx.clone();
        let join = std::thread::Builder::new()
            .name("inky-spill-write".into())
            .spawn(move || loop {
                let job = {
                    let mut q = shared.lock();
                    loop {
                        if let Some(job) = q.take_next() {
                            break job;
                        }
                        if q.closed {
                            return;
                        }
                        q = shared.ready.wait(q).unwrap_or_else(|e| e.into_inner());
                    }
                };
                if done.send(run_spill_io(&dir, kvb, job)).is_err() {
                    return;
                }
                wake();
            })
            .expect("spawn inky-spill-write worker");
        self.join = Some(join);
    }

    pub fn has_thread(&self) -> bool {
        self.join.is_some()
    }

    /// Queue `job` and return its id. `urgent` work runs before everything that is not.
    pub fn push(&mut self, job: SpillIo, urgent: bool) -> u64 {
        let id = self.next_id;
        self.next_id += 1;
        {
            let mut q = self.shared.lock();
            q.jobs.insert(id, job);
            if urgent {
                q.urgent.push_back(id);
            } else {
                q.bulk.push_back(id);
            }
        }
        self.shared.ready.notify_one();
        id
    }

    /// Take job `id` back out of the queue. `true`: the writer never had it and never will, so its write pin
    /// can be dropped now. `false`: the writer took it (its result will arrive, or already did).
    pub fn cancel(&self, id: u64) -> bool {
        self.shared.lock().jobs.remove(&id).is_some()
    }

    /// The next finished job, if any. Never waits.
    pub fn try_recv(&self) -> Option<SpillIoDone> {
        self.done_rx.try_recv().ok()
    }

    /// Jobs still in the queue (not yet taken).
    pub fn queued(&self) -> usize {
        self.shared.lock().jobs.len()
    }

    /// Run up to `max` queued jobs on the calling thread, in queue order; their results go where the thread's
    /// would. The writer with no thread: the synchronous spill, and tests that pace the disk by hand.
    pub fn run_queued(&self, max: usize) -> usize {
        let mut ran = 0;
        while ran < max {
            let Some(job) = self.shared.lock().take_next() else { break };
            #[cfg(test)]
            if let (Some(hook), SpillIo::Block { key, .. }) = (&self.block_hook, &job) {
                hook(*key);
            }
            let _ = self.done_tx.send(run_spill_io(&self.dir, self.kvb, job));
            ran += 1;
        }
        ran
    }

    /// Run `hook` just before each block write [`SpillWriter::run_queued`] performs (a fake slow disk).
    #[cfg(test)]
    pub fn set_block_hook(&mut self, hook: Option<BlockHook>) {
        self.block_hook = hook;
    }

    /// Take every job still queued back out of the queue, then wait for the writer thread to finish the one it
    /// holds, if any. After this the writer reads no pool memory; results already sent stay readable through
    /// `try_recv`, and the caller owns the unread jobs.
    pub fn stop(&mut self) -> Vec<SpillIo> {
        let mut dropped = Vec::new();
        {
            let mut q = self.shared.lock();
            while let Some(job) = q.take_next() {
                dropped.push(job);
            }
            q.jobs.clear();
            q.closed = true;
        }
        self.shared.ready.notify_all();
        if let Some(join) = self.join.take() {
            let _ = join.join();
        }
        dropped
    }
}

impl Drop for SpillWriter {
    fn drop(&mut self) {
        let _ = self.stop();
    }
}