Files
leleka/crates/model-format/src/ple_reader.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 a1c5e352f9 Normalize line endings: convert 10 CRLF files back to LF, add narrow .gitattributes
Ten files touched by this branch had been rewritten with CRLF line endings
(base versions are LF), inflating the diff against the merge-base to
13685/13039 lines. Content is otherwise unchanged: the diff ignoring line
endings was and remains 661 insertions / 15 deletions.

.gitattributes: crates/**/*.rs and scripts/gpu-bringup/**/*.py are text=auto
eol=lf, so CRLF cannot re-enter these LF files at commit time. text=auto leaves
files that are already CRLF in the index untouched.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 08:51:22 +01:00

891 lines
30 KiB
Rust

//! Asynchronous row reader for the per-layer n-gram (PLE) table, port of
//! `ngram/ple_reader.{hpp,cpp}` over `std` positional reads.
//!
//! The table is 320,001,536 rows of 90 bytes (IQ4_NL, 26.8 GiB) and never
//! lives in RAM. A token needs 16 rows on 16 different pages, all derived from
//! the token itself, so the only time to hide the reads is the embedding plus
//! layer 0; hence the split API:
//!
//! ```text
//! let ticket = reader.issue(&rows); // as soon as the token id is known
//! ... // embedding, layer 0
//! let bytes = reader.collect(ticket)?; // before layer 1 reads the rows
//! ```
//!
//! `issue` also serves prefill: pass all `16 x N` rows of a chunk. Rows are
//! served from the row cache when possible, the rest are grouped by 4 KiB page
//! (rows sharing a page share one read; a row straddling a page boundary reads
//! two pages), the reads are sorted by offset so a chunk reads the SSD in
//! near-sequential order, and a pool of I/O threads keeps at most
//! `max_inflight` of them outstanding.
//!
//! The row cache is not the table. It keeps rows this process already fetched
//! (8-way set associative, round-robin inside a set, bounded by construction;
//! capacity 0 disables it).
//!
//! Safety properties kept from the original: an out-of-range row reads as zero
//! bytes (the mmap path's behaviour); a short read inside the table, a failed
//! read or a source whose size changed is an error that sticks to the reader
//! (every later `collect` fails). Unsafe code is forbidden workspace-wide, so
//! reads go through [`PageSource`] (`pread` via `std`), and O_DIRECT, when
//! wanted, is the source's business: the reader always reads 4 KiB-aligned
//! offsets and lengths into 4 KiB-aligned buffers, as an unbuffered file
//! requires.
use std::collections::{HashMap, VecDeque};
use std::fmt;
use std::fs::File;
use std::io;
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
/// An IQ4_NL row; `open` takes the table's own row size.
pub const ROW_BYTES: usize = 90;
pub const PAGE: usize = 4096;
const WAYS: usize = 8;
const EMPTY: u32 = 0xFFFF_FFFF;
const LATENCY_RING: usize = 65536;
const DEFAULT_IO_THREADS: usize = 16;
/// A positional-read file. Reads may be short only at end of file.
pub trait PageSource: Send + Sync + 'static {
fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize>;
/// Current length of the underlying file, for the size-unchanged check.
fn len(&self) -> io::Result<u64>;
fn is_empty(&self) -> io::Result<bool> {
Ok(self.len()? == 0)
}
}
impl PageSource for File {
fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
#[cfg(unix)]
{
std::os::unix::fs::FileExt::read_at(self, buf, offset)
}
#[cfg(windows)]
{
std::os::windows::fs::FileExt::seek_read(self, buf, offset)
}
#[cfg(not(any(unix, windows)))]
{
let _ = (buf, offset);
Err(io::Error::new(
io::ErrorKind::Unsupported,
"positional reads unavailable",
))
}
}
fn len(&self) -> io::Result<u64> {
Ok(self.metadata()?.len())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PleError(pub String);
impl fmt::Display for PleError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for PleError {}
fn err<T>(message: impl Into<String>) -> Result<T, PleError> {
Err(PleError(format!("PleReader: {}", message.into())))
}
#[derive(Clone, Debug)]
pub struct PleReaderConfig {
/// Byte offset of row 0 in the file.
pub table_offset: u64,
pub n_rows: u64,
/// One row's size in the file (90 IQ4_NL, 160 FP8), at most one page.
pub row_bytes: usize,
/// Reads outstanding at once, 1..=1024.
pub max_inflight: usize,
/// Row cache capacity in rows (rounded down to whole 8-row sets); 0 disables.
pub cache_rows: u64,
/// I/O threads; `None` picks `min(max_inflight, 16)`, `Some(0)` runs every
/// read on the thread that calls `collect` (no workers, no keep-alive).
pub io_threads: Option<usize>,
/// Required length of the source; a different length at `collect` is an error.
pub expected_len: Option<u64>,
}
impl PleReaderConfig {
pub fn new(table_offset: u64, n_rows: u64) -> Self {
Self {
table_offset,
n_rows,
row_bytes: ROW_BYTES,
max_inflight: 64,
cache_rows: 0,
io_threads: None,
expected_len: None,
}
}
}
#[derive(Clone, Debug, Default)]
pub struct ReaderStats {
/// Rows asked for.
pub requests: u64,
/// Rows served from the row cache.
pub cache_hits: u64,
/// Rows that shared a page already being read in the same ticket.
pub dedup_rows: u64,
/// SSD read requests issued.
pub reads: u64,
/// Bytes read from the SSD.
pub bytes: u64,
/// Time `collect` spent blocked, microseconds.
pub wait_us: f64,
/// Sum of per-read latencies (issue to completion), microseconds.
pub read_us_sum: f64,
/// Reads delayed by fault injection.
pub late_injected: u64,
/// Pages read only to keep the SSD awake (not in `reads`, `bytes` or latencies).
pub keepalive_reads: u64,
/// The slowest of them, microseconds.
pub keepalive_us_max: f64,
/// Last <= 65,536 read latencies, for percentiles.
pub read_us: Vec<f32>,
}
impl ReaderStats {
pub fn percentile(&self, q: f64) -> f64 {
if self.read_us.is_empty() {
return 0.0;
}
let mut v = self.read_us.clone();
let k = ((q * (v.len() - 1) as f64 + 0.5) as usize).min(v.len() - 1);
v.select_nth_unstable_by(k, f32::total_cmp);
f64::from(v[k])
}
}
/// Set-associative row cache: 8 ways per set, round-robin replacement inside a
/// set. Bounded by construction.
#[derive(Debug, Default)]
pub struct RowCache {
sets: u64,
rb: usize,
keys: Vec<u32>,
data: Vec<u8>,
next: Vec<u8>,
used: u64,
}
impl RowCache {
pub fn new(rows: u64, row_bytes: usize) -> Self {
let sets = rows / WAYS as u64;
let slots = (sets as usize) * WAYS;
Self {
sets,
rb: row_bytes,
keys: vec![EMPTY; slots],
data: vec![0; slots * row_bytes],
next: vec![0; sets as usize],
used: 0,
}
}
fn mix(row: u32) -> u64 {
let x = u64::from(row).wrapping_mul(0x9E37_79B9_7F4A_7C15);
x ^ (x >> 29)
}
pub fn capacity(&self) -> u64 {
self.sets * WAYS as u64
}
pub fn len(&self) -> u64 {
self.used
}
pub fn is_empty(&self) -> bool {
self.used == 0
}
pub fn find(&self, row: u32) -> Option<&[u8]> {
if self.sets == 0 {
return None;
}
let s = (Self::mix(row) % self.sets) as usize;
(0..WAYS)
.find(|&w| self.keys[s * WAYS + w] == row)
.map(|w| {
let at = (s * WAYS + w) * self.rb;
&self.data[at..at + self.rb]
})
}
pub fn insert(&mut self, row: u32, bytes: &[u8]) {
if self.sets == 0 || self.find(row).is_some() {
return;
}
debug_assert_eq!(bytes.len(), self.rb);
let s = (Self::mix(row) % self.sets) as usize;
let w = usize::from(self.next[s]);
self.next[s] = ((w + 1) % WAYS) as u8;
if self.keys[s * WAYS + w] == EMPTY {
self.used += 1;
}
self.keys[s * WAYS + w] = row;
let at = (s * WAYS + w) * self.rb;
self.data[at..at + self.rb].copy_from_slice(bytes);
}
}
/// One row inside a read.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Use {
pub row: u32,
/// Byte offset of the row inside the read buffer.
pub in_page: usize,
/// Row slot in the ticket's output.
pub slot: usize,
}
/// One read: an aligned file offset and one or two pages.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PlannedRead {
pub offset: u64,
pub length: usize,
pub uses: Vec<Use>,
}
/// Plan the reads of a ticket exactly as `PleReader::issue` does: cache hits
/// and out-of-range rows are resolved into `out` immediately, the rest are
/// grouped by first page (a later row on the page may widen the read to two
/// pages) and sorted by offset.
pub fn plan_reads(
rows: &[u32],
cfg: &PleReaderConfig,
cache: &RowCache,
out: &mut [u8],
stats: &mut ReaderStats,
) -> Vec<PlannedRead> {
let rb = cfg.row_bytes;
let mut by_page: HashMap<u64, usize> = HashMap::new();
let mut jobs: Vec<PlannedRead> = Vec::new();
for (i, &row) in rows.iter().enumerate() {
let dst = &mut out[i * rb..(i + 1) * rb];
stats.requests += 1;
if u64::from(row) >= cfg.n_rows {
dst.fill(0);
continue;
}
if let Some(hit) = cache.find(row) {
dst.copy_from_slice(hit);
stats.cache_hits += 1;
continue;
}
let at = cfg.table_offset + u64::from(row) * rb as u64;
let first = at / PAGE as u64 * PAGE as u64;
let length = ((at + rb as u64 - 1) / PAGE as u64 * PAGE as u64 - first) as usize + PAGE;
let used = Use {
row,
in_page: (at - first) as usize,
slot: i,
};
if let Some(&j) = by_page.get(&first) {
jobs[j].length = jobs[j].length.max(length);
jobs[j].uses.push(used);
stats.dedup_rows += 1;
} else {
by_page.insert(first, jobs.len());
jobs.push(PlannedRead {
offset: first,
length,
uses: vec![used],
});
}
}
// Sorted by offset: prefill chunks then read the SSD in near-sequential order.
jobs.sort_by_key(|job| job.offset);
jobs
}
struct Job {
read: PlannedRead,
ticket: u32,
keepalive: bool,
}
struct TicketState {
pending: usize,
out: Vec<u8>,
}
#[derive(Default)]
struct KeepAlive {
period: Duration,
window: Duration,
last_issue: Option<Instant>,
last_read: Option<Instant>,
rng: u64,
}
struct State {
queue: VecDeque<Job>,
tickets: HashMap<u32, TicketState>,
next_ticket: u32,
cache: RowCache,
stats: ReaderStats,
ring_pos: usize,
delay: Duration,
error: Option<PleError>,
stop: bool,
inflight: usize,
keep: KeepAlive,
}
struct Shared {
source: Arc<dyn PageSource>,
cfg: PleReaderConfig,
inline: bool,
state: Mutex<State>,
work: Condvar,
done: Condvar,
keep_cv: Condvar,
}
fn lock(m: &Mutex<State>) -> MutexGuard<'_, State> {
// A panicking worker must not wedge the reader: the data is still coherent
// (every mutation is completed before the lock is released) and the error
// path reports failures through `State::error`.
m.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
/// Heap buffer whose usable window starts on a 4 KiB boundary, for unbuffered sources.
struct AlignedBuf {
raw: Vec<u8>,
start: usize,
len: usize,
}
impl AlignedBuf {
fn new(len: usize) -> Self {
let raw = vec![0u8; len + PAGE];
let start = (PAGE - raw.as_ptr() as usize % PAGE) % PAGE;
Self { raw, start, len }
}
fn window(&mut self, len: usize) -> &mut [u8] {
&mut self.raw[self.start..self.start + len.min(self.len)]
}
}
/// Whether `source` serves one page-aligned page read at the page holding
/// `offset`, through a 4 KiB-aligned buffer. Used to accept an unbuffered
/// (O_DIRECT) handle only once it demonstrably works on this filesystem.
pub fn probe_aligned_read(source: &dyn PageSource, offset: u64) -> bool {
let mut buf = AlignedBuf::new(PAGE);
let page = offset / PAGE as u64 * PAGE as u64;
matches!(read_full_at(source, buf.window(PAGE), page), Ok(n) if n > 0)
}
fn read_full_at(source: &dyn PageSource, buf: &mut [u8], offset: u64) -> io::Result<usize> {
let mut total = 0;
while total < buf.len() {
match source.read_at(&mut buf[total..], offset + total as u64) {
Ok(0) => break,
Ok(n) => total += n,
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
}
Ok(total)
}
impl State {
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.
fn cancel_queued(&mut self) {
let queued: Vec<Job> = self.queue.drain(..).collect();
for job in queued {
self.release(job.ticket);
}
}
fn release(&mut self, ticket: u32) {
if let Some(t) = self.tickets.get_mut(&ticket) {
t.pending = t.pending.saturating_sub(1);
}
}
fn fail(&mut self, message: &str) {
if self.error.is_none() {
self.error = Some(PleError(format!("PleReader: {message}")));
}
self.cancel_queued();
}
/// 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).
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.
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 mut late = false;
if !delay.is_zero() {
let spent = issued.elapsed();
if spent < delay {
late = true;
thread::sleep(delay - spent);
}
}
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 {
// A failed keep-alive turns the keep-alive off, not the reader.
match read {
Ok(_) => {
st.stats.keepalive_reads += 1;
st.stats.keepalive_us_max = st.stats.keepalive_us_max.max(elapsed_us);
}
Err(_) => st.keep.period = Duration::ZERO,
}
drop(st);
self.work.notify_all();
self.done.notify_all();
return;
}
match read {
Err(e) => {
st.fail(&format!("a table read failed ({e})"));
st.release(job.ticket);
}
Ok(bytes) => {
st.record_latency(elapsed_us);
st.stats.bytes += bytes as u64;
let rb = self.cfg.row_bytes;
if job.read.uses.iter().any(|u| u.in_page + rb > bytes) {
st.fail("short read inside the table");
st.release(job.ticket);
} else {
let data = buf.window(length);
for u in &job.read.uses {
let row = &data[u.in_page..u.in_page + rb];
if let Some(t) = st.tickets.get_mut(&job.ticket) {
t.out[u.slot * rb..(u.slot + 1) * rb].copy_from_slice(row);
}
st.cache.insert(u.row, row);
}
st.release(job.ticket);
}
}
}
drop(st);
self.work.notify_all();
self.done.notify_all();
}
/// Take the next job (marking it in flight) or `None` when there is none.
fn start(&self, st: &mut State) -> Option<(Job, Instant, Duration)> {
let job = st.queue.pop_front()?;
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))
}
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);
}
}
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 {
// One page of the table, a different one each time, so the
// SSD really reads (not its controller's buffer).
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();
}
// 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;
}
}
}
}
}
/// Handle to a ticket issued by [`PleReader::issue`]. Dropping it without
/// collecting abandons the rows (reads in flight still warm the cache).
pub struct Ticket {
id: u32,
shared: Arc<Shared>,
}
impl Drop for Ticket {
fn drop(&mut self) {
lock(&self.shared.state).tickets.remove(&self.id);
}
}
pub struct PleReader {
shared: Arc<Shared>,
workers: Vec<JoinHandle<()>>,
keepalive: Option<JoinHandle<()>>,
}
impl PleReader {
/// `source` is the table's file. The table must fit exactly in it from
/// `table_offset` (the caller's GGUF parse checks that; the length is
/// checked here too).
pub fn open(source: Arc<dyn PageSource>, cfg: PleReaderConfig) -> Result<Self, PleError> {
if cfg.max_inflight == 0 || cfg.max_inflight > 1024 {
return err("max_inflight must be 1..1024");
}
if cfg.row_bytes == 0 || cfg.row_bytes > PAGE {
return err("row_bytes must be 1..4096");
}
if cfg.n_rows > u64::from(EMPTY) {
return err("the row count exceeds the 32-bit row index");
}
let table_end = cfg
.n_rows
.checked_mul(cfg.row_bytes as u64)
.and_then(|bytes| bytes.checked_add(cfg.table_offset));
let len = source
.len()
.map_err(|e| PleError(format!("PleReader: cannot size the table file ({e})")))?;
if table_end.is_none_or(|end| end > len) {
return err("the table extends past the end of the file");
}
if cfg.expected_len.is_some_and(|expected| expected != len) {
return err("the table file changed size after verification");
}
let threads = match cfg.io_threads {
None => cfg.max_inflight.min(DEFAULT_IO_THREADS),
Some(n) => n.min(cfg.max_inflight),
};
let seed = 0x9E37_79B9_7F4A_7C15
^ std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(1, |d| d.as_micros() as u64);
let state = State {
queue: VecDeque::new(),
tickets: HashMap::new(),
next_ticket: 1,
cache: RowCache::new(cfg.cache_rows, cfg.row_bytes),
stats: ReaderStats::default(),
ring_pos: 0,
delay: Duration::ZERO,
error: None,
stop: false,
inflight: 0,
keep: KeepAlive {
rng: if seed == 0 { 1 } else { seed },
..KeepAlive::default()
},
};
let shared = Arc::new(Shared {
source,
inline: threads == 0,
cfg,
state: Mutex::new(state),
work: Condvar::new(),
done: Condvar::new(),
keep_cv: Condvar::new(),
});
let mut reader = Self {
shared: Arc::clone(&shared),
workers: Vec::new(),
keepalive: None,
};
for index in 0..threads {
let worker = Arc::clone(&shared);
let spawned = thread::Builder::new()
.name(format!("ple-reader-{index}"))
.spawn(move || worker.worker());
match spawned {
Ok(handle) => reader.workers.push(handle),
Err(e) => return err(format!("cannot create I/O worker: {e}")),
}
}
Ok(reader)
}
pub fn row_bytes(&self) -> usize {
self.shared.cfg.row_bytes
}
pub fn rows(&self) -> u64 {
self.shared.cfg.n_rows
}
/// Start fetching `rows`; row `i`'s raw bytes land at `row_bytes * i` of
/// the buffer `collect` returns. Out-of-range rows produce zero bytes.
pub fn issue(&self, rows: &[u32]) -> Ticket {
let shared = &self.shared;
let rb = shared.cfg.row_bytes;
let mut st = lock(&shared.state);
let id = st.next_ticket;
st.next_ticket = st.next_ticket.wrapping_add(1).max(1);
let now = Instant::now();
let rearm = !st.keep.period.is_zero()
&& st
.keep
.last_issue
.is_none_or(|last| now.duration_since(last) > st.keep.window);
st.keep.last_issue = Some(now);
let mut out = vec![0u8; rows.len() * rb];
let State { cache, stats, .. } = &mut *st;
let reads = plan_reads(rows, &shared.cfg, cache, &mut out, stats);
let mut pending = reads.len();
if st.error.is_some() {
pending = 0; // the reader failed: `collect` reports it, nothing is queued
} else {
for read in reads {
st.queue.push_back(Job {
read,
ticket: id,
keepalive: false,
});
}
}
st.tickets.insert(id, TicketState { pending, out });
drop(st);
if pending > 0 {
shared.work.notify_all();
}
if rearm || pending > 0 {
shared.keep_cv.notify_all();
}
Ticket {
id,
shared: Arc::clone(shared),
}
}
/// Block until every row of the ticket is in the returned buffer.
pub fn collect(&self, ticket: Ticket) -> Result<Vec<u8>, PleError> {
let shared = &self.shared;
if !Arc::ptr_eq(&ticket.shared, shared) {
return err("ticket from another reader");
}
let start = Instant::now();
let mut st = lock(&shared.state);
if !st.tickets.contains_key(&ticket.id) {
return err("unknown ticket");
}
loop {
let pending = st.tickets.get(&ticket.id).map_or(0, |t| t.pending);
if pending == 0 {
break;
}
if shared.inline {
// No workers: this thread performs the reads itself.
if let Some((job, issued, delay)) = shared.start(&mut st) {
drop(st);
shared.run(job, issued, delay);
st = lock(&shared.state);
continue;
}
}
st = shared.done.wait(st).unwrap_or_else(|p| p.into_inner());
}
if let Some(e) = st.error.clone() {
return Err(e);
}
st.stats.wait_us += start.elapsed().as_secs_f64() * 1e6;
let out = st.tickets.remove(&ticket.id).map(|t| t.out);
drop(st);
// The same-FD size observation the verified GGUF reader makes around its streams.
if let Some(expected) = shared.cfg.expected_len {
match shared.source.len() {
Ok(len) if len == expected => {}
_ => {
let mut st = lock(&shared.state);
st.fail("the table file changed size after verification");
return Err(st
.error
.clone()
.unwrap_or_else(|| PleError("PleReader: size check failed".into())));
}
}
}
out.ok_or_else(|| PleError("PleReader: unknown ticket".into()))
}
/// `issue` then `collect`.
pub fn read_rows(&self, rows: &[u32]) -> Result<Vec<u8>, PleError> {
self.collect(self.issue(rows))
}
/// Keep the SSD awake while the table is in use (worker mode only; call
/// after `open`): when no read has gone out for `period`, one page of the
/// table is read, until `window` after the last `issue`. A keep-alive read
/// that fails turns it off. A zero period turns it off.
pub fn set_keepalive(&mut self, period: Duration, window: Duration) {
let threaded = !self.shared.inline;
{
let mut st = lock(&self.shared.state);
st.keep.period = if threaded { period } else { Duration::ZERO };
st.keep.window = window;
}
if threaded && !period.is_zero() && self.keepalive.is_none() {
let worker = Arc::clone(&self.shared);
if let Ok(handle) = thread::Builder::new()
.name("ple-reader-keepalive".into())
.spawn(move || worker.keepalive_worker())
{
self.keepalive = Some(handle);
}
}
self.shared.keep_cv.notify_all();
}
/// Fault injection for tests and for the plan's P2 exit check: every read
/// completes no earlier than `delay` after it was issued. Zero disables.
pub fn set_injected_delay(&self, delay: Duration) {
lock(&self.shared.state).delay = delay;
}
/// A consistent copy of the counters.
pub fn snapshot(&self) -> ReaderStats {
lock(&self.shared.state).stats.clone()
}
pub fn reset_stats(&self) {
let mut st = lock(&self.shared.state);
st.stats = ReaderStats::default();
st.ring_pos = 0;
}
pub fn cache_capacity(&self) -> u64 {
lock(&self.shared.state).cache.capacity()
}
pub fn cache_size(&self) -> u64 {
lock(&self.shared.state).cache.len()
}
/// Stop the workers (unsubmitted work is dropped, reads in flight finish).
pub fn close(&mut self) {
{
let mut st = lock(&self.shared.state);
st.stop = true;
st.cancel_queued();
}
self.shared.work.notify_all();
self.shared.keep_cv.notify_all();
self.shared.done.notify_all();
for handle in self.workers.drain(..) {
let _ = handle.join();
}
if let Some(handle) = self.keepalive.take() {
let _ = handle.join();
}
}
}
impl fmt::Debug for PleReader {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PleReader")
.field("rows", &self.shared.cfg.n_rows)
.field("workers", &self.workers.len())
.finish()
}
}
impl Drop for PleReader {
fn drop(&mut self) {
self.close();
}
}
#[cfg(test)]
mod tests;