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

210 lines
7.6 KiB
Rust

//! Moved out of the parent module by STRA-338: impl PleReader.
#[allow(unused_imports)]
use super::*;
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> {
check_config(&cfg)?;
check_table(source.as_ref(), &cfg)?;
let threads = match cfg.io_threads {
None => cfg.max_inflight.min(DEFAULT_IO_THREADS),
Some(n) => n.min(cfg.max_inflight),
};
let state = initial_state(&cfg);
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 pending = st.enqueue(reads, id);
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");
}
st = shared.wait_for_ticket(st, ticket.id);
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);
shared.check_expected_len()?;
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();
}
}
}
fn check_config(cfg: &PleReaderConfig) -> Result<(), 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");
}
Ok(())
}
/// The table fits in the file from `table_offset`, and the file is the size it was verified at.
fn check_table<S: PageSource + ?Sized>(source: &S, cfg: &PleReaderConfig) -> Result<(), PleError> {
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");
}
Ok(())
}
fn initial_state(cfg: &PleReaderConfig) -> State {
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);
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() },
}
}