kar ple: a decode token reads its 16 rows on the calling thread when the archive answers from memory (8 threads otherwise, as before)

`VerifiedKarPleArtifact::read_rows` (one token's 16 rows, 48 positional reads) started and joined eight scoped threads on every call.
The speedtrain-ab spans show ple.read_rows at 0.119 ms per call and 2.1 calls per round (0.25 ms of a 15.0 ms round, before the window
launches), while a memory-served pread of 10-20 bytes takes about a microsecond. The call now reads the first row itself and times
it: at 20 us or less (a row is three reads) the other fifteen rows are read on the same thread; slower means the file waits for a
device, and the previous eight-thread read runs, with the next 256 calls skipping the probe so a cold archive pays one probe per 256
tokens at most. The prefill's batch and read-ahead paths are untouched.

Output identity argument: the same `read_rows_chunk` reads the same offsets into the same packet slots in every path, with the same
bounds, length and non-finite-scale refusals; only the number of threads differs. The test reads random rows of a two-partition
synthetic file through the probing, the post-cold-verdict parallel and the non-probing paths and compares every packet with the
single-thread reference, plus the refusals (row outside the table, changed archive length, row beyond the partitions).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-29 10:20:39 +01:00
co-authored by Claude Sonnet 5.5
parent 2f267df973
commit 8735bbc5d5
+107 -4
View File
@@ -1196,8 +1196,11 @@ impl VerifiedKarPleArtifact {
if self.reader.file.metadata().map_err(KarError::Io)?.len() != self.archive_bytes() {
return Err(KarError::Integrity("KAR archive length changed"));
}
// 16 rows are 48 random reads of a cold file: eight threads on handles of their own, two rows each
let packets = read_rows_parallel(self.row_handles(), &self.parts, self.archive_bytes(), rows, 8, 2)?;
// 16 rows are 48 random reads of a cold file: eight threads on handles of their own, two rows each. A file the page cache
// holds answers each read in about a microsecond, and eight thread starts and joins then cost more than the reads
// (about 0.1 ms per token of a decode window); `warm_probe` reads the first row on this thread, times it, and reads the
// other fifteen here too when it was served from memory.
let packets = read_rows_parallel(self.row_handles(), &self.parts, self.archive_bytes(), rows, 8, 2, true)?;
let mut out = [KarPleRowPacket {
payload: [0; 50],
partition: 0,
@@ -1214,7 +1217,7 @@ impl VerifiedKarPleArtifact {
/// scale refusals, but positional (`pread`, no seek) and split over a few threads, because the batched prefill
/// reads every row of a chunk the cache does not hold at once (tens of thousands on a cold chunk).
pub fn read_rows_batch(&self, rows: &[u64]) -> Result<Vec<KarPleRowPacket>, KarError> {
read_rows_parallel(self.row_handles(), &self.parts, self.archive_bytes(), rows, 32, 512)
read_rows_parallel(self.row_handles(), &self.parts, self.archive_bytes(), rows, 32, 512, false)
}
/// An owned reader of the same rows (handles of its own and a copy of the partition table) that another thread
/// can use while this artifact is busy: the prefill reads the rows of the next chunk ahead.
@@ -1264,9 +1267,15 @@ pub struct KarPleRowReader {
impl KarPleRowReader {
/// `max_threads` positional-read threads at most (one per 512 rows).
pub fn read_rows(&self, rows: &[u64], max_threads: usize) -> Result<Vec<KarPleRowPacket>, KarError> {
read_rows_parallel(&self.files, &self.parts, self.archive_bytes, rows, max_threads, 512)
read_rows_parallel(&self.files, &self.parts, self.archive_bytes, rows, max_threads, 512, false)
}
}
/// A row read (three positional reads) that a warm file serves in this many nanoseconds or less takes the single-thread path.
/// Memory-served reads of 10-20 bytes take about 1 us each; a read that waits for a device takes tens of microseconds or more.
const WARM_ROW_NS: u128 = 20_000;
/// After a cold verdict the next calls read in parallel without probing (a cold file would pay the probe's latency each time).
const COLD_SKIP_CALLS: u32 = 256;
static COLD_SKIP: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
fn read_rows_parallel(
files: &[File],
parts: &[VerifiedPart],
@@ -1274,6 +1283,7 @@ fn read_rows_parallel(
rows: &[u64],
max_threads: usize,
min_rows_per_thread: usize,
warm_probe: bool,
) -> Result<Vec<KarPleRowPacket>, KarError> {
let Some(first) = files.first() else {
return Err(KarError::Io(std::io::ErrorKind::NotFound.into()));
@@ -1297,6 +1307,20 @@ fn read_rows_parallel(
);
// positional reads of a file that is not in the page cache are latency-bound: many in flight
let workers = (rows.len() / min_rows_per_thread.max(1)).clamp(1, max_threads.max(1));
if warm_probe && workers > 1 {
use std::sync::atomic::Ordering;
if COLD_SKIP.load(Ordering::Relaxed) > 0 {
COLD_SKIP.fetch_sub(1, Ordering::Relaxed);
} else {
let started = std::time::Instant::now();
read_rows_chunk(first, parts, &rows[..1], &mut packets[..1])?;
if started.elapsed().as_nanos() <= WARM_ROW_NS {
read_rows_chunk(first, parts, &rows[1..], &mut packets[1..])?;
return Ok(packets);
}
COLD_SKIP.store(COLD_SKIP_CALLS, Ordering::Relaxed);
}
}
if workers == 1 {
read_rows_chunk(first, parts, rows, &mut packets)?;
} else {
@@ -1407,3 +1431,82 @@ mod tests;
#[cfg(test)]
#[path = "../tests/kar_crc_slicing.rs"]
mod crc_slicing_tests;
#[cfg(test)]
mod row_read_tests {
use super::*;
use std::io::Write;
use std::sync::atomic::Ordering;
/// Two partitions over one synthetic file; every byte is below 0x70 so no scale reads as non-finite.
fn synthetic() -> (File, Vec<VerifiedPart>, u64, std::path::PathBuf) {
let (n0, n1) = (1000u64, 500u64);
let scales0 = 0u64;
let planes0 = scales0 + n0 * 10;
let stride0 = n0 * 20;
let scales1 = planes0 + 2 * stride0;
let planes1 = scales1 + n1 * 10;
let stride1 = n1 * 20;
let total = planes1 + 2 * stride1;
let mut x = 0x9E37_79B9_7F4A_7C15u64;
let bytes: Vec<u8> = (0..total)
.map(|_| {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
(x % 0x70) as u8
})
.collect();
let path = std::env::temp_dir().join(format!("leleka-kar-rows-{}-{:x}", std::process::id(), x));
File::create(&path).unwrap().write_all(&bytes).unwrap();
let parts = vec![
VerifiedPart { row_base: 0, row_count: n0, scales: scales0, planes: planes0, stride: stride0 },
VerifiedPart { row_base: n0, row_count: n1, scales: scales1, planes: planes1, stride: stride1 },
];
(File::open(&path).unwrap(), parts, total, path)
}
fn same(a: &[KarPleRowPacket], b: &[KarPleRowPacket]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.payload == y.payload && x.partition == y.partition)
}
#[test]
fn the_warm_single_thread_read_returns_exactly_the_parallel_packets() {
let (file, parts, total, path) = synthetic();
let files = vec![file.try_clone().unwrap(), file.try_clone().unwrap(), file.try_clone().unwrap()];
let mut x = 7u64;
for case in 0..40 {
let rows: Vec<u64> = (0..16)
.map(|_| {
x = x.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(x >> 33) % 1500
})
.collect();
// the reference: one thread, no probe
let mut reference = vec![KarPleRowPacket { payload: [0; 50], partition: 0 }; 16];
read_rows_chunk(&file, &parts, &rows, &mut reference).unwrap();
// the file is in the page cache: the probe takes the single-thread path (or, on a loaded machine, falls back to threads;
// the packets are the same either way)
COLD_SKIP.store(0, Ordering::Relaxed);
let probed = read_rows_parallel(&files, &parts, total, &rows, 8, 2, true).unwrap();
assert!(same(&probed, &reference), "case {case}: probing read");
// after a cold verdict the next calls skip the probe and read in parallel
COLD_SKIP.store(3, Ordering::Relaxed);
let parallel = read_rows_parallel(&files, &parts, total, &rows, 8, 2, true).unwrap();
assert!(same(&parallel, &reference), "case {case}: parallel read after a cold verdict");
assert_eq!(COLD_SKIP.load(Ordering::Relaxed), 2, "a skipped probe uses up one of the skip calls");
let unprobed = read_rows_parallel(&files, &parts, total, &rows, 8, 2, false).unwrap();
assert!(same(&unprobed, &reference), "case {case}: no probe");
}
COLD_SKIP.store(0, Ordering::Relaxed);
// the refusals are the same as before: a row outside the table, a changed archive length
let bad = vec![PLE_ROWS; 16];
assert!(matches!(read_rows_parallel(&files, &parts, total, &bad, 8, 2, true), Err(KarError::Range(_))));
assert!(matches!(read_rows_parallel(&files, &parts, total + 1, &[1, 2], 8, 2, true), Err(KarError::Integrity(_))));
// a row beyond the partitions' last row is a range error on the probe path as well
let beyond: Vec<u64> = (0..16).map(|i| 1500 + i).collect();
assert!(read_rows_parallel(&files, &parts, total, &beyond, 8, 2, true).is_err());
drop(files);
let _ = std::fs::remove_file(path);
}
}