1use std::panic::{self, AssertUnwindSafe};
13use std::sync::Arc;
14use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicU32, AtomicUsize, Ordering};
15
16use rayon::{ThreadPool, ThreadPoolBuilder};
17
18use crate::error::{ItzmaError, Result};
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub(crate) enum Lane {
23 Query,
25 Maintenance,
27}
28
29#[derive(Debug, Clone, Copy)]
31pub(crate) enum Cost {
32 Distances { rows: usize, dim: usize },
34 Bytes(usize),
36}
37
38impl Cost {
39 pub(crate) fn units(self) -> usize {
40 match self {
41 Cost::Distances { rows, dim } => rows.saturating_mul(dim),
42 Cost::Bytes(n) => n.saturating_mul(3),
45 }
46 }
47}
48
49pub(crate) const INLINE_BELOW: usize = 1_250_000;
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59#[non_exhaustive]
60pub struct CpuThreads {
61 pub query: usize,
63 pub maintenance: usize,
65}
66
67impl Default for CpuThreads {
68 fn default() -> Self {
70 let cores = std::thread::available_parallelism().map_or(1, usize::from);
71 CpuThreads {
72 query: cores,
73 maintenance: (cores / 4).max(1),
74 }
75 }
76}
77
78impl CpuThreads {
79 pub fn query(mut self, n: usize) -> Self {
81 self.query = n;
82 self
83 }
84
85 pub fn maintenance(mut self, n: usize) -> Self {
87 self.maintenance = n;
88 self
89 }
90}
91
92static STARTED: AtomicU32 = AtomicU32::new(0);
96
97static QUERY_THREADS: AtomicUsize = AtomicUsize::new(0);
99static MAINTENANCE_THREADS: AtomicUsize = AtomicUsize::new(0);
100
101pub fn configure_cpu(threads: CpuThreads) -> Result<()> {
118 configure_cpu_for(std::process::id(), threads)
119}
120
121fn configure_cpu_for(pid: u32, threads: CpuThreads) -> Result<()> {
122 if threads.query == 0 || threads.maintenance == 0 {
123 return Err(ItzmaError::InvalidConfig(
124 "each compute lane needs at least one thread",
125 ));
126 }
127 let refused = || {
128 Err(ItzmaError::InvalidConfig(
129 "the compute pools are already running; configure them before the first call",
130 ))
131 };
132 if published_for(pid).is_some() {
133 return refused();
134 }
135 QUERY_THREADS.store(threads.query, Ordering::SeqCst);
136 MAINTENANCE_THREADS.store(threads.maintenance, Ordering::SeqCst);
137 if STARTED.load(Ordering::SeqCst) == pid {
141 return refused();
142 }
143 Ok(())
144}
145
146pub(crate) struct Pools {
148 pid: u32,
149 query: ThreadPool,
150 maintenance: ThreadPool,
151}
152
153static PUBLISHED: AtomicPtr<Pools> = AtomicPtr::new(std::ptr::null_mut());
158
159fn published_for(pid: u32) -> Option<&'static Pools> {
160 let ptr = PUBLISHED.load(Ordering::Acquire);
161 let pools = unsafe { ptr.as_ref() }?;
164 (pools.pid == pid).then_some(pools)
165}
166
167fn pools() -> &'static Pools {
168 pools_for(std::process::id())
169}
170
171fn pools_for(pid: u32) -> &'static Pools {
172 loop {
173 let seen = PUBLISHED.load(Ordering::Acquire);
174 if let Some(pools) = published_for(pid) {
175 return pools;
176 }
177 STARTED.store(pid, Ordering::SeqCst);
178 let defaults = CpuThreads::default();
179 let pick = |set: &AtomicUsize, default: usize| match set.load(Ordering::SeqCst) {
180 0 => default,
181 n => n,
182 };
183 let (query, maintenance) = (
184 pick(&QUERY_THREADS, defaults.query),
185 pick(&MAINTENANCE_THREADS, defaults.maintenance),
186 );
187 #[cfg(test)]
188 tests::pause_build_of(pid);
189 let built = Box::new(Pools {
190 pid,
191 query: build("itzma-query", query),
192 maintenance: build("itzma-maint", maintenance),
193 });
194 let ours = Box::into_raw(built);
195 match PUBLISHED.compare_exchange(seen, ours, Ordering::AcqRel, Ordering::Acquire) {
196 Ok(_) => return unsafe { &*ours },
201 Err(_) => {
202 drop(unsafe { Box::from_raw(ours) });
208 }
209 }
210 }
211}
212
213fn build(prefix: &'static str, threads: usize) -> ThreadPool {
214 let pool = |threads: usize| {
215 ThreadPoolBuilder::new()
216 .num_threads(threads)
217 .thread_name(move |i| format!("{prefix}-{i}"))
218 .build()
219 };
220 pool(threads)
223 .or_else(|_| pool(1))
224 .unwrap_or_else(|e| panic!("cannot start a compute thread: {e}"))
225}
226
227pub(crate) async fn run<F, T>(lane: Lane, cost: Cost, f: F) -> T
231where
232 F: FnOnce() -> T + Send + 'static,
233 T: Send + 'static,
234{
235 if cost.units() < INLINE_BELOW {
236 return f();
237 }
238 let pools = pools();
239 let pool = match lane {
240 Lane::Query => &pools.query,
241 Lane::Maintenance => &pools.maintenance,
242 };
243 let (send, receive) = futures::channel::oneshot::channel();
244 let cancel = Arc::new(AtomicBool::new(false));
245 let job_cancel = cancel.clone();
246 pool.spawn(move || {
247 let result = with_cancel(&job_cancel, || panic::catch_unwind(AssertUnwindSafe(f)));
248 let _ = send.send(result);
250 });
251 let _cancel_on_drop = CancelOnDrop(cancel);
254 match receive.await {
255 Ok(Ok(value)) => value,
256 Ok(Err(payload)) => panic::resume_unwind(payload),
257 Err(_) => panic!("a compute thread exited without an answer"),
260 }
261}
262
263pub(crate) const FLAT_CHUNK: usize = 16_384;
266
267pub(crate) fn chunked<I, R, F>(items: &[I], chunk: usize, f: F) -> Vec<R>
272where
273 I: Sync,
274 R: Send,
275 F: Fn(&[I]) -> R + Sync,
276{
277 use rayon::prelude::*;
278 let chunk = chunk.max(1);
279 if rayon::current_thread_index().is_none() {
280 return items.chunks(chunk).map(f).collect();
281 }
282 let cancel = CANCEL.with(|c| c.borrow().clone());
285 items
286 .par_chunks(chunk)
287 .map(|one| match &cancel {
288 None => f(one),
289 Some(cancel) => {
290 stop_if_cancelled(cancel);
291 with_cancel(cancel, || f(one))
292 }
293 })
294 .collect()
295}
296
297struct Cancelled;
300
301thread_local! {
302 static CANCEL: std::cell::RefCell<Option<Arc<AtomicBool>>> =
304 const { std::cell::RefCell::new(None) };
305}
306
307fn with_cancel<T>(cancel: &Arc<AtomicBool>, f: impl FnOnce() -> T) -> T {
310 let previous = CANCEL.with(|c| c.replace(Some(cancel.clone())));
311 let out = panic::catch_unwind(AssertUnwindSafe(f));
312 CANCEL.with(|c| *c.borrow_mut() = previous);
313 out.unwrap_or_else(|payload| panic::resume_unwind(payload))
314}
315
316fn stop_if_cancelled(cancel: &AtomicBool) {
319 if cancel.load(Ordering::Relaxed) {
320 panic::resume_unwind(Box::new(Cancelled));
321 }
322}
323
324struct CancelOnDrop(Arc<AtomicBool>);
327
328impl Drop for CancelOnDrop {
329 fn drop(&mut self) {
330 self.0.store(true, Ordering::Relaxed);
331 }
332}
333
334#[cfg(test)]
336pub(crate) fn on_pool_thread() -> Option<Lane> {
337 let name = std::thread::current().name()?.to_owned();
338 if name.starts_with("itzma-query-") {
339 Some(Lane::Query)
340 } else if name.starts_with("itzma-maint-") {
341 Some(Lane::Maintenance)
342 } else {
343 None
344 }
345}
346
347#[cfg(test)]
350#[allow(clippy::await_holding_lock)]
351mod tests {
352 use super::*;
353 use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering};
354 use std::sync::{Arc, RwLock};
355
356 const BIG: Cost = Cost::Distances {
357 rows: 1_000_000,
358 dim: 128,
359 };
360 const SMALL: Cost = Cost::Distances { rows: 10, dim: 8 };
361
362 static PAUSED_PID: AtomicU32 = AtomicU32::new(0);
365 static RELEASE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
366
367 pub(super) fn pause_build_of(pid: u32) {
368 if PAUSED_PID.load(Ordering::SeqCst) == pid {
369 while !RELEASE.load(Ordering::SeqCst) {
370 std::thread::sleep(std::time::Duration::from_millis(1));
371 }
372 }
373 }
374
375 #[test]
376 fn a_configure_racing_the_first_build_is_never_ok_and_ignored() {
377 let _g = PID_SWAP.write().unwrap_or_else(|e| e.into_inner());
378 let racing = u32::MAX - 5;
379 PAUSED_PID.store(racing, Ordering::SeqCst);
380 RELEASE.store(false, Ordering::SeqCst);
381 let build = std::thread::spawn(move || pools_for(racing).query.current_num_threads());
383 std::thread::sleep(std::time::Duration::from_millis(50));
384 let configured = configure_cpu_for(racing, CpuThreads::default().query(3));
385 RELEASE.store(true, Ordering::SeqCst);
386 let threads = build.join().expect("build");
387 PAUSED_PID.store(0, Ordering::SeqCst);
388 QUERY_THREADS.store(0, Ordering::SeqCst);
389 MAINTENANCE_THREADS.store(0, Ordering::SeqCst);
390 let _ = pools();
391 if configured.is_ok() {
392 assert_eq!(threads, 3, "configure said Ok but the pools ignored it");
393 }
394 }
395
396 #[test]
397 fn a_build_left_half_done_never_blocks_another_pid() {
398 let _g = PID_SWAP.write().unwrap_or_else(|e| e.into_inner());
399 let (stuck, fresh) = (u32::MAX - 3, u32::MAX - 4);
400 PAUSED_PID.store(stuck, Ordering::SeqCst);
401 RELEASE.store(false, Ordering::SeqCst);
402 let parent = std::thread::spawn(move || {
403 pools_for(stuck);
404 });
405 std::thread::sleep(std::time::Duration::from_millis(50));
406 let (send, receive) = std::sync::mpsc::channel();
407 std::thread::spawn(move || {
408 let _ = send.send(pools_for(fresh).pid);
409 });
410 let got = receive.recv_timeout(std::time::Duration::from_secs(10));
411 RELEASE.store(true, Ordering::SeqCst);
412 parent
413 .join()
414 .expect("the paused build finishes once released");
415 PAUSED_PID.store(0, Ordering::SeqCst);
416 let _ = pools();
417 assert_eq!(
418 got.ok(),
419 Some(fresh),
420 "the child's build waited on the parent's"
421 );
422 }
423
424 static PID_SWAP: RwLock<()> = RwLock::new(());
427
428 fn shared() -> std::sync::RwLockReadGuard<'static, ()> {
429 PID_SWAP.read().unwrap_or_else(|e| e.into_inner())
430 }
431
432 #[tokio::test]
433 async fn big_work_runs_on_its_lane() {
434 let _g = shared();
435 assert_eq!(
436 run(Lane::Query, BIG, on_pool_thread).await,
437 Some(Lane::Query)
438 );
439 assert_eq!(
440 run(Lane::Maintenance, BIG, on_pool_thread).await,
441 Some(Lane::Maintenance)
442 );
443 }
444
445 #[test]
446 fn decoding_a_few_hundred_kilobytes_is_worth_a_hand_off() {
447 assert!(Cost::Bytes(1 << 20).units() >= INLINE_BELOW);
450 assert!(Cost::Bytes(512 << 10).units() >= INLINE_BELOW);
451 assert!(Cost::Bytes(64 << 10).units() < INLINE_BELOW);
452 }
453
454 #[tokio::test]
455 async fn small_work_runs_inline() {
456 let _g = shared();
457 assert_eq!(run(Lane::Query, SMALL, on_pool_thread).await, None);
458 }
459
460 #[tokio::test]
461 async fn maintenance_never_uses_more_threads_than_its_lane() {
462 let _g = shared();
463 let lane = pools().maintenance.current_num_threads();
464 let busy = Arc::new(AtomicUsize::new(0));
465 let peak = Arc::new(AtomicUsize::new(0));
466 let runs = (0..lane * 4).map(|_| {
467 let (busy, peak) = (busy.clone(), peak.clone());
468 run(Lane::Maintenance, BIG, move || {
469 let now = busy.fetch_add(1, Ordering::SeqCst) + 1;
470 peak.fetch_max(now, Ordering::SeqCst);
471 std::thread::sleep(std::time::Duration::from_millis(5));
472 busy.fetch_sub(1, Ordering::SeqCst);
473 })
474 });
475 futures::future::join_all(runs).await;
476 let peak = peak.load(Ordering::SeqCst);
477 assert!(peak >= 1 && peak <= lane, "peak {peak}, lane {lane}");
478 }
479
480 #[tokio::test]
481 async fn a_panic_resumes_on_the_caller_and_the_pool_survives() {
482 let _g = shared();
483 let caught = tokio::spawn(run(Lane::Query, BIG, || -> u32 { panic!("kernel bug") }))
484 .await
485 .expect_err("the panic comes back");
486 let payload = caught.into_panic();
487 assert_eq!(payload.downcast_ref::<&str>(), Some(&"kernel bug"));
488 assert_eq!(run(Lane::Query, BIG, || 7).await, 7);
489 }
490
491 #[tokio::test]
492 async fn a_dropped_caller_stops_its_chunked_work_early() {
493 let _g = shared();
494 let items: Vec<u32> = (0..5_000).collect();
495 let done = Arc::new(AtomicUsize::new(0));
496 let counted = done.clone();
497 let job = run(Lane::Query, BIG, move || {
500 chunked(&items, 1, |_| {
501 std::thread::sleep(std::time::Duration::from_millis(1));
502 counted.fetch_add(1, Ordering::SeqCst);
503 })
504 .len()
505 });
506 let timed_out = tokio::time::timeout(std::time::Duration::from_millis(20), job).await;
507 assert!(timed_out.is_err());
508 tokio::time::sleep(std::time::Duration::from_millis(1_500)).await;
509 let ran = done.load(Ordering::SeqCst);
510 assert!(
511 ran < 2_500,
512 "{ran} of 5,000 chunks ran after the caller left"
513 );
514 assert_eq!(
515 run(Lane::Query, BIG, || 1).await,
516 1,
517 "the pool still serves"
518 );
519 }
520
521 #[tokio::test]
522 async fn dropping_the_caller_does_not_hang_the_pool() {
523 let _g = shared();
524 let slow = run(Lane::Query, BIG, || {
525 std::thread::sleep(std::time::Duration::from_millis(50));
526 });
527 let timed_out = tokio::time::timeout(std::time::Duration::from_millis(5), slow).await;
528 assert!(timed_out.is_err());
529 assert_eq!(run(Lane::Query, BIG, || 1).await, 1);
530 }
531
532 #[test]
533 fn another_pid_gets_new_pools() {
534 let _g = PID_SWAP.write().unwrap_or_else(|e| e.into_inner());
535 let here: *const Pools = pools_for(u32::MAX - 1);
536 assert_eq!(pools_for(u32::MAX - 1) as *const Pools, here);
537 assert_ne!(pools_for(u32::MAX - 2) as *const Pools, here);
538 let _ = pools();
540 }
541
542 #[test]
543 fn configure_refuses_zero_and_a_running_pool() {
544 let _g = shared();
545 assert!(matches!(
546 configure_cpu(CpuThreads::default().query(0)),
547 Err(ItzmaError::InvalidConfig(_))
548 ));
549 assert!(matches!(
550 configure_cpu(CpuThreads::default().maintenance(0)),
551 Err(ItzmaError::InvalidConfig(_))
552 ));
553 let _ = pools();
554 assert!(matches!(
555 configure_cpu(CpuThreads::default()),
556 Err(ItzmaError::InvalidConfig(_))
557 ));
558 }
559
560 fn sums(items: &[f64]) -> Vec<f64> {
561 chunked(items, 1000, |c| c.iter().sum::<f64>())
562 }
563
564 #[test]
565 fn chunked_is_the_same_on_every_thread_count() {
566 let items: Vec<f64> = (0..10_007).map(|i| (i as f64).sin() * 1e-3).collect();
567 let sequential = sums(&items);
568 assert_eq!(sequential.len(), 11);
569 for threads in [1, 2, 8] {
570 let pool = ThreadPoolBuilder::new()
571 .num_threads(threads)
572 .thread_name(|i| format!("itzma-query-{i}"))
573 .build()
574 .expect("pool");
575 assert_eq!(
576 pool.install(|| sums(&items)),
577 sequential,
578 "{threads} threads"
579 );
580 }
581 }
582
583 #[test]
584 fn chunked_keeps_chunk_order() {
585 let items: Vec<u32> = (0..5000).collect();
586 let pool = ThreadPoolBuilder::new()
587 .num_threads(4)
588 .build()
589 .expect("pool");
590 let firsts = pool.install(|| chunked(&items, 1024, |c| (c.len(), c[0])));
591 assert_eq!(
592 firsts,
593 vec![
594 (1024, 0),
595 (1024, 1024),
596 (1024, 2048),
597 (1024, 3072),
598 (904, 4096)
599 ]
600 );
601 }
602
603 #[test]
604 fn chunked_runs_in_parallel_only_on_a_pool_thread() {
605 let items = [0u8; 64];
606 let outside = chunked(&items, 1, |_| rayon::current_thread_index());
607 assert!(
608 outside.iter().all(Option::is_none),
609 "never on rayon's global pool"
610 );
611 let pool = ThreadPoolBuilder::new()
612 .num_threads(2)
613 .build()
614 .expect("pool");
615 let inside = pool.install(|| chunked(&items, 1, |_| rayon::current_thread_index()));
616 assert!(inside.iter().all(Option::is_some));
617 }
618
619 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
621 #[ignore]
622 async fn measure_handoff() {
623 let _g = shared();
624 let rounds: u32 = 2_000;
625 let start = std::time::Instant::now();
626 for _ in 0..rounds {
627 std::hint::black_box(run(Lane::Query, BIG, || 1u32).await);
628 }
629 println!("hand-off, back to back: {:?}", start.elapsed() / rounds);
630 let mut cold = std::time::Duration::ZERO;
631 for _ in 0..200 {
632 std::thread::sleep(std::time::Duration::from_millis(2));
633 let start = std::time::Instant::now();
634 std::hint::black_box(run(Lane::Query, BIG, || 1u32).await);
635 cold += start.elapsed();
636 }
637 println!("hand-off, pool asleep: {:?}", cold / 200);
638 let q = vec![0.5f32; 128];
639 let rows: Vec<f32> = (0..100_000 * 128)
640 .map(|i| (i % 977) as f32 * 1e-3)
641 .collect();
642 let work = move || {
643 let mut s = 0f32;
644 for row in rows.chunks_exact(128) {
645 s += crate::search::distance(crate::document::Metric::L2, &q, row);
646 }
647 s
648 };
649 let work = std::sync::Arc::new(work);
650 for _ in 0..3 {
651 let w = work.clone();
652 let start = std::time::Instant::now();
653 std::hint::black_box(w());
654 let inline = start.elapsed();
655 let w = work.clone();
656 let start = std::time::Instant::now();
657 std::hint::black_box(run(Lane::Query, BIG, move || w()).await);
658 println!(
659 "100k x 128 inline {inline:?}, on the pool {:?}",
660 start.elapsed()
661 );
662 }
663 let small_rows: Vec<f32> = (0..500 * 128).map(|i| i as f32 * 1e-4).collect();
664 let q = vec![0.5f32; 128];
665 let start = std::time::Instant::now();
666 for _ in 0..200 {
667 for row in small_rows.chunks_exact(128) {
668 std::hint::black_box(crate::search::distance(
669 crate::document::Metric::L2,
670 &q,
671 row,
672 ));
673 }
674 }
675 println!("500 x 128 inline: {:?}", start.elapsed() / 200);
676
677 let mut layer = crate::layer::Layer::new();
681 let mut ops = Vec::new();
682 for i in 0..4_000usize {
683 let doc = crate::document::Document {
684 id: format!("d{i:06}"),
685 vector: (0..128).map(|d| ((i * 31 + d) % 97) as f32).collect(),
686 attrs: (i % 3 == 0).then(|| serde_json::json!({ "n": i, "tag": "x" })),
687 sparse: None,
688 };
689 ops.push(crate::document::WalOp::Upsert(doc.clone()));
690 layer.apply(crate::document::WalOp::Upsert(doc));
691 }
692 let segment = crate::segment::encode_as(&layer, 128, 2).expect("encode");
693 let start = std::time::Instant::now();
694 for _ in 0..20 {
695 std::hint::black_box(crate::segment::decode("p", &segment, 128).expect("decode"));
696 }
697 let per = start.elapsed() / 20;
698 println!(
699 "segment decode: {} bytes in {per:?}, {:.1} ns per byte",
700 segment.len(),
701 per.as_nanos() as f64 / segment.len() as f64
702 );
703 let wal = crate::wal_codec::encode(&ops, usize::MAX).expect("encode");
704 let start = std::time::Instant::now();
705 for _ in 0..20 {
706 std::hint::black_box(crate::wal_codec::decode("p", &wal).expect("decode"));
707 }
708 let per = start.elapsed() / 20;
709 println!(
710 "wal decode: {} bytes in {per:?}, {:.1} ns per byte",
711 wal.len(),
712 per.as_nanos() as f64 / wal.len() as f64
713 );
714 }
715}