Files
leleka/crates/model-format/src/ple_reader/read_queue.rs
T

260 lines
9.9 KiB
Rust

//! `State` of the PLE reader: its queue of row reads, tickets, latency record, keep-alive and failure, and
//! `Shared::run`, the worker loop that serves the queue.
//! Apart from `row_reading`, which is what a caller uses.
use super::{
AlignedBuf, Arc, Duration, Instant, Job, LATENCY_RING, MutexGuard, PAGE, PlannedRead, PleError, Shared, State,
Ticket, io, lock, read_full_at, thread,
};
impl State {
pub(super) fn record_latency(&mut self, us: f64) {
self.stats.read_us_sum += us;
if self.stats.read_us.len() < LATENCY_RING {
self.stats.read_us.push(us as f32);
} else {
self.stats.read_us[self.ring_pos % LATENCY_RING] = us as f32;
self.ring_pos += 1;
}
}
/// A job that will never run: its ticket no longer waits for it.
pub(super) fn cancel_queued(&mut self) {
let queued: Vec<Job> = self.queue.drain(..).collect();
for job in queued {
self.release(job.ticket);
}
}
/// Queues the reads of a ticket; returns how many it now waits for (none once the reader has failed:
/// `collect` reports the error and nothing is queued).
pub(super) fn enqueue(&mut self, reads: Vec<PlannedRead>, ticket: u32) -> usize {
if self.error.is_some() {
return 0;
}
let pending = reads.len();
for read in reads {
self.queue.push_back(Job { read, ticket, keepalive: false });
}
pending
}
pub(super) fn release(&mut self, ticket: u32) {
if let Some(t) = self.tickets.get_mut(&ticket) {
t.pending = t.pending.saturating_sub(1);
}
}
pub(super) fn fail(&mut self, message: &str) {
if self.error.is_none() {
self.error = Some(PleError(format!("PleReader: {message}")));
}
self.cancel_queued();
}
/// A keep-alive read finished: a failure turns the keep-alive off, not the reader.
pub(super) fn finish_keepalive(&mut self, read: io::Result<usize>, elapsed_us: f64) {
match read {
Ok(_) => {
self.stats.keepalive_reads += 1;
self.stats.keepalive_us_max = self.stats.keepalive_us_max.max(elapsed_us);
}
Err(_) => self.keep.period = Duration::ZERO,
}
}
/// A ticket read finished: its rows go to the ticket and the cache, or the reader fails; the ticket is released.
pub(super) fn finish_read(&mut self, job: &Job, read: io::Result<usize>, elapsed_us: f64, data: (&[u8], usize)) {
match read {
Err(e) => self.fail(&format!("a table read failed ({e})")),
Ok(bytes) => {
self.record_latency(elapsed_us);
self.stats.bytes += bytes as u64;
if job.read.uses.iter().any(|u| u.in_page + data.1 > bytes) {
self.fail("short read inside the table");
} else {
self.store_rows(job, data);
}
}
}
self.release(job.ticket);
}
/// Copies the rows of a finished read into the ticket's buffer and the cache.
fn store_rows(&mut self, job: &Job, (data, rb): (&[u8], usize)) {
for u in &job.read.uses {
let row = &data[u.in_page..u.in_page + rb];
if let Some(t) = self.tickets.get_mut(&job.ticket) {
t.out[u.slot * rb..(u.slot + 1) * rb].copy_from_slice(row);
}
self.cache.insert(u.row, row);
}
}
/// When the next keep-alive read is due, or `None` when none is: it is off,
/// the reader failed, or no rows were asked for within the window (the SSD
/// may then sleep; the next `issue` re-arms it).
pub(super) fn keepalive_due(&self, now: Instant) -> Option<Instant> {
let k = &self.keep;
let issued = k.last_issue?;
if k.period.is_zero() || self.error.is_some() || now.duration_since(issued) > k.window {
return None;
}
Some(k.last_read.unwrap_or(issued) + k.period)
}
}
impl Shared {
/// Run one job: the read happens outside the lock.
pub(super) fn run(&self, job: Job, issued: Instant, delay: Duration) {
let mut buf = AlignedBuf::new(2 * PAGE);
let length = job.read.length;
// A source that panics is a failed read like any other: the worker survives, the reader fails and every ticket
// is released.
// Unwinding past this point would end the worker with the job's ticket still pending, and its `collect` would
// wait for ever.
let read = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
read_full_at(self.source.as_ref(), buf.window(length), job.read.offset)
}))
.unwrap_or_else(|_| Err(io::Error::other("the page source panicked")));
let late = sleep_until_delay(issued, delay);
let mut st = lock(&self.state);
st.inflight -= 1;
if late {
st.stats.late_injected += 1;
}
let elapsed_us = issued.elapsed().as_secs_f64() * 1e6;
if job.keepalive {
st.finish_keepalive(read, elapsed_us);
} else {
st.finish_read(&job, read, elapsed_us, (buf.window(length), self.cfg.row_bytes));
}
drop(st);
self.work.notify_all();
self.done.notify_all();
}
/// Waits until the ticket has no read pending. Without workers (`inline`) this thread performs the reads itself.
pub(super) fn wait_for_ticket<'a>(&'a self, mut st: MutexGuard<'a, State>, id: u32) -> MutexGuard<'a, State> {
loop {
let pending = st.tickets.get(&id).map_or(0, |t| t.pending);
if pending == 0 {
return st;
}
if self.inline
&& let Some((job, issued, delay)) = self.start(&mut st)
{
drop(st);
self.run(job, issued, delay);
st = lock(&self.state);
continue;
}
st = self.done.wait(st).unwrap_or_else(|p| p.into_inner());
}
}
/// The same-FD size observation the verified GGUF reader makes around its streams.
pub(super) fn check_expected_len(&self) -> Result<(), PleError> {
let Some(expected) = self.cfg.expected_len else {
return Ok(());
};
match self.source.len() {
Ok(len) if len == expected => Ok(()),
_ => {
let mut st = lock(&self.state);
st.fail("the table file changed size after verification");
Err(st.error.clone().unwrap_or_else(|| PleError("PleReader: size check failed".into())))
}
}
}
/// Take the next job (marking it in flight) or `None` when there is none.
pub(super) fn start(&self, st: &mut State) -> Option<(Job, Instant, Duration)> {
let job = st.queue.pop_front()?;
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let now = Instant::now();
st.inflight += 1;
st.keep.last_read = Some(now);
if !job.keepalive {
st.stats.reads += 1;
}
Some((job, now, st.delay))
}
pub(super) fn worker(self: &Arc<Self>) {
loop {
let started = {
let mut st = lock(&self.state);
loop {
if st.stop && st.queue.is_empty() {
return;
}
if let Some(started) = self.start(&mut st) {
break started;
}
st = self.work.wait(st).unwrap_or_else(|p| p.into_inner());
}
};
self.run(started.0, started.1, started.2);
}
}
pub(super) fn keepalive_worker(self: &Arc<Self>) {
let mut st = lock(&self.state);
while !st.stop {
let now = Instant::now();
match st.keepalive_due(now) {
None => st = self.keep_cv.wait(st).unwrap_or_else(|p| p.into_inner()),
Some(due) if now >= due => {
if st.queue.is_empty() && st.inflight == 0 {
self.queue_keepalive_page(&mut st);
}
// Re-evaluate after the period (or when woken).
let wait = st.keep.period.max(Duration::from_millis(1));
st = self.keep_cv.wait_timeout(st, wait).unwrap_or_else(|p| p.into_inner()).0;
}
Some(due) => {
let wait = (due - now).max(Duration::from_millis(1));
st = self.keep_cv.wait_timeout(st, wait).unwrap_or_else(|p| p.into_inner()).0;
}
}
}
}
/// One page of the table, a different one each time, so the
/// SSD really reads (not its controller's buffer).
fn queue_keepalive_page(&self, st: &mut State) {
st.keep.rng ^= st.keep.rng << 13;
st.keep.rng ^= st.keep.rng >> 7;
st.keep.rng ^= st.keep.rng << 17;
let first = self.cfg.table_offset / PAGE as u64;
let end = (self.cfg.table_offset + self.cfg.n_rows * self.cfg.row_bytes as u64) / PAGE as u64;
let page = first + if end > first { st.keep.rng % (end - first) } else { 0 };
st.queue.push_back(Job {
read: PlannedRead { offset: page * PAGE as u64, length: PAGE, uses: Vec::new() },
ticket: 0,
keepalive: true,
});
self.work.notify_one();
}
}
/// Fault injection: sleeps until `delay` has passed since `issued`; true when it had to sleep.
fn sleep_until_delay(issued: Instant, delay: Duration) -> bool {
if delay.is_zero() {
return false;
}
let spent = issued.elapsed();
if spent >= delay {
return false;
}
thread::sleep(delay - spent);
true
}
impl Drop for Ticket {
fn drop(&mut self) {
lock(&self.shared.state).tickets.remove(&self.id);
}
}