use relate_core::NodeId;
use super::rebuild::RelRow;
const MIN_ROWS_PER_SHARD: usize = 20_000;
fn rebuild_workers(rows: usize) -> usize {
#[cfg(test)]
if let Some(forced) = forced_workers() {
return forced;
}
let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
(rows / MIN_ROWS_PER_SHARD).clamp(1, cores)
}
pub(super) fn shard_rows(rows: &[RelRow], endpoint: impl Fn(&RelRow) -> NodeId) -> Vec<Vec<usize>> {
let workers = rebuild_workers(rows.len());
let mut shards: Vec<Vec<usize>> = vec![Vec::new(); workers];
for (index, row) in rows.iter().enumerate() {
let bucket = (endpoint(row).unsigned_abs() % workers as u64) as usize;
shards[bucket].push(index);
}
shards
}
pub(super) fn run_shards<R: Send>(
shards: &[Vec<usize>],
f: impl Fn(&[usize]) -> R + Sync,
) -> Vec<R> {
#[cfg(test)]
SHARDS_RUN.with(|ran| ran.set(ran.get() + shards.len()));
if shards.len() <= 1 {
return shards.iter().map(|shard| f(shard)).collect();
}
std::thread::scope(|scope| {
let handles: Vec<_> = shards
.iter()
.map(|shard| scope.spawn(|| f(shard)))
.collect();
handles
.into_iter()
.map(|handle| match handle.join() {
Ok(result) => result,
Err(panic) => std::panic::resume_unwind(panic),
})
.collect()
})
}
#[cfg(test)]
thread_local! {
static FORCED_WORKERS: std::cell::Cell<Option<usize>> =
const { std::cell::Cell::new(None) };
static SHARDS_RUN: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
#[cfg(test)]
fn forced_workers() -> Option<usize> {
FORCED_WORKERS.with(std::cell::Cell::get)
}
#[cfg(test)]
pub(super) fn with_workers<R>(workers: usize, f: impl FnOnce() -> R) -> R {
assert!(workers > 0, "a shard count is non-zero");
struct Reset(Option<usize>);
impl Drop for Reset {
fn drop(&mut self) {
FORCED_WORKERS.with(|pin| pin.set(self.0));
}
}
let previous = FORCED_WORKERS.with(|pin| pin.replace(Some(workers)));
let _reset = Reset(previous);
f()
}
#[cfg(test)]
pub(super) fn take_shards_run() -> usize {
SHARDS_RUN.with(|ran| ran.replace(0))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_panicking_shard_resurfaces_its_own_payload() {
let shards = vec![vec![0usize], vec![1], vec![2]];
let caught = std::panic::catch_unwind(|| {
run_shards(&shards, |shard| {
if shard[0] == 1 {
panic!("shard one failed");
}
shard[0]
})
});
let payload = caught.expect_err("the failed shard must propagate");
assert_eq!(
payload.downcast_ref::<&str>().copied(),
Some("shard one failed")
);
}
#[test]
fn a_single_shard_panic_propagates_on_the_calling_thread() {
let shards = vec![vec![0usize]];
let caught =
std::panic::catch_unwind(|| run_shards(&shards, |_| -> usize { panic!("only") }));
assert!(caught.is_err());
}
}