Skip to main content

itzma_core/
cpu.rs

1//! Where CPU work runs.
2//!
3//! Two private rayon pools: the query lane (every core) and the maintenance
4//! lane (a quarter of them), so an index build or a merge cannot take the cores
5//! queries need. Work below [`INLINE_BELOW`] runs on the caller's thread, since
6//! a hand-off costs more than it.
7//!
8//! The pools are keyed by process id. A fork copies no threads, so a pool from
9//! the parent would wait forever; the first call in a new process builds new
10//! pools and leaks the old ones, as `itzma-python`'s runtime does for tokio.
11
12use 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/// Which pool a piece of work belongs to.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub(crate) enum Lane {
23    /// Queries, filters and scans: every core.
24    Query,
25    /// Compaction, index builds, maintenance and recovery: a quarter of them.
26    Maintenance,
27}
28
29/// A rough size of a piece of work, to decide whether to hand it off.
30#[derive(Debug, Clone, Copy)]
31pub(crate) enum Cost {
32    /// Distance computations of `dim` values each.
33    Distances { rows: usize, dim: usize },
34    /// Bytes to decode or encode (for a compressed object, what it decodes to).
35    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            // A segment decodes at about 0.4 ns per byte (`measure_handoff`),
43            // so three units a byte puts the hand-off near 400 KB.
44            Cost::Bytes(n) => n.saturating_mul(3),
45        }
46    }
47}
48
49/// Work under this many units stays on the caller. Measured (`measure_handoff`
50/// below, release, Apple M-series): a hand-off costs 8 µs back to back and
51/// 14 µs when the pool sleeps, and 64,000 units (500 rows at dimension 128)
52/// take about 7 µs. Work is handed off only when
53/// it is worth ten hand-offs, about 140 µs. Measured on one machine only;
54/// Linux x86 is
55pub(crate) const INLINE_BELOW: usize = 1_250_000;
56
57/// Thread counts for this process's two compute pools.
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59#[non_exhaustive]
60pub struct CpuThreads {
61    /// Threads of the query lane: queries, filters and scans.
62    pub query: usize,
63    /// Threads of the maintenance lane: compaction, index builds, recovery.
64    pub maintenance: usize,
65}
66
67impl Default for CpuThreads {
68    /// Every core for queries, a quarter of them (at least one) for maintenance.
69    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    /// Set the query lane's thread count.
80    pub fn query(mut self, n: usize) -> Self {
81        self.query = n;
82        self
83    }
84
85    /// Set the maintenance lane's thread count.
86    pub fn maintenance(mut self, n: usize) -> Self {
87        self.maintenance = n;
88        self
89    }
90}
91
92/// The pid that last began building pools, set before the build reads the
93/// thread counts, so a `configure_cpu` that stores counts after that read sees
94/// it and refuses instead of reporting success for counts nobody will use.
95static STARTED: AtomicU32 = AtomicU32::new(0);
96
97/// 0 means "not configured": use `CpuThreads::default()`.
98static QUERY_THREADS: AtomicUsize = AtomicUsize::new(0);
99static MAINTENANCE_THREADS: AtomicUsize = AtomicUsize::new(0);
100
101/// Set the thread counts of this process's compute pools. The pools belong to
102/// the process, not to a [`Namespace`](crate::Namespace), so this is called
103/// once, before the first query or build. A forked child has no pools yet and
104/// may call it again.
105///
106/// # Errors
107///
108/// [`ItzmaError::InvalidConfig`] for a count of 0, or when this process's
109/// pools already exist.
110///
111/// ```
112/// use itzma_core::{CpuThreads, configure_cpu};
113///
114/// // In a process that has not run any Itzma work yet.
115/// configure_cpu(CpuThreads::default().query(4).maintenance(1)).unwrap();
116/// ```
117pub 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    // A build that began before the stores may have read the old counts.
138    // Either it marked itself started first and this refuses, or it reads
139    // the counts just stored: never an `Ok` that the pools ignore.
140    if STARTED.load(Ordering::SeqCst) == pid {
141        return refused();
142    }
143    Ok(())
144}
145
146/// This process's two pools.
147pub(crate) struct Pools {
148    pid: u32,
149    query: ThreadPool,
150    maintenance: ThreadPool,
151}
152
153/// The pools of the latest process that asked. No lock guards it, not even
154/// while pools are built: a fork can copy a held lock into the child without
155/// the thread that would release it, and the child's first hand-off would wait
156/// forever. Builders race instead, and the loser drops what it built.
157static 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    // SAFETY: `PUBLISHED` only ever holds null or a pointer from `Box::leak`,
162    // which is never freed.
163    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            // What `seen` pointed at, if anything, is leaked on purpose: another
197            // thread may still hold a reference to it.
198            // SAFETY: `ours` came from `Box::into_raw` just above and is now
199            // published, so it is never freed.
200            Ok(_) => return unsafe { &*ours },
201            Err(_) => {
202                // Another thread published first. `ours` was never shared, so
203                // it is dropped here (its threads exit), and the loop reads
204                // what won.
205                // SAFETY: `ours` came from `Box::into_raw` above and was not
206                // published.
207                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    // A process at its thread limit gets one thread; if even that cannot
221    // start, no work can run at all and there is no caller to tell but this.
222    pool(threads)
223        .or_else(|_| pool(1))
224        .unwrap_or_else(|e| panic!("cannot start a compute thread: {e}"))
225}
226
227/// Run `f` on `lane`'s pool and wait for it, or inline when `cost` is below
228/// [`INLINE_BELOW`]. A panic in `f` resumes on the caller. Dropping the
229/// returned future does not stop `f`; its result is thrown away.
230pub(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        // The receiver is gone when the caller was dropped; nothing to do.
249        let _ = send.send(result);
250    });
251    // Dropping this future before the answer comes marks the job cancelled,
252    // so `chunked` starts no more chunks for it.
253    let _cancel_on_drop = CancelOnDrop(cancel);
254    match receive.await {
255        Ok(Ok(value)) => value,
256        Ok(Err(payload)) => panic::resume_unwind(payload),
257        // The closure always sends, even after a panic, so a dropped sender
258        // means its thread was killed from outside.
259        Err(_) => panic!("a compute thread exited without an answer"),
260    }
261}
262
263/// Documents per chunk of a flat scan: a constant, never derived
264/// from the thread count, so a result does not depend on the machine.
265pub(crate) const FLAT_CHUNK: usize = 16_384;
266
267/// `f` over `items` in chunks of `chunk`, results in chunk order. Parallel only
268/// on a pool thread (inside [`run`]); anywhere else the same chunks run one
269/// after another, so the answer is the same either way and rayon's global pool
270/// is never started.
271pub(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    // Chunks run on other pool threads, which do not see this thread's job;
283    // each takes the job's cancel flag along, so a nested `chunked` sees it too.
284    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
297/// The payload a cancelled job unwinds with. Nobody sees it: the caller that
298/// would have is gone.
299struct Cancelled;
300
301thread_local! {
302    /// The cancel flag of the `run` job this pool thread is working for.
303    static CANCEL: std::cell::RefCell<Option<Arc<AtomicBool>>> =
304        const { std::cell::RefCell::new(None) };
305}
306
307/// Run `f` with `cancel` as this thread's job flag, then put back what was
308/// there (a thread can work for several jobs in turn).
309fn 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
316/// Stop the job here if its caller left. `resume_unwind` skips the panic
317/// hook, so a cancelled job prints nothing.
318fn stop_if_cancelled(cancel: &AtomicBool) {
319    if cancel.load(Ordering::Relaxed) {
320        panic::resume_unwind(Box::new(Cancelled));
321    }
322}
323
324/// Marks a job cancelled when the future waiting for it is dropped. Set also
325/// after a normal answer, when nothing reads it any more.
326struct CancelOnDrop(Arc<AtomicBool>);
327
328impl Drop for CancelOnDrop {
329    fn drop(&mut self) {
330        self.0.store(true, Ordering::Relaxed);
331    }
332}
333
334/// The lane of the pool thread this runs on, if any.
335#[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// The `PID_SWAP` read guard is held across awaits on purpose: each test has its
348// own runtime, readers share the lock, and the one writer is a sync test.
349#[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    /// A pid whose pool build stops (inside `pools_for`, before the pools
363    /// are made) until `RELEASE` is set: a build a fork left half done.
364    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        // The build has read its thread counts and is about to make the pools.
382        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    /// `another_pid_gets_new_pools` repoints the published pools at a fake
425    /// pid; the other tests must not run on two pools across that swap.
426    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        // Measured in `measure_handoff`: a segment decodes at about 0.4 ns
448        // per byte, so ten hand-offs (about 140 µs) is about 400 KB.
449        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        // 5,000 chunks of a millisecond: about half a second on a 10-core
498        // lane if nothing stops it.
499        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        // Hand the real process its pools back before the lock is released.
539        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    /// `cargo test -p itzma-core --release --lib cpu::tests::measure_handoff -- --ignored --nocapture`
620    #[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        // Decode cost per byte, for `Cost::Bytes`: a segment of 4,000
678        // documents at dimension 128, every third with attributes, and the
679        // same documents as one WAL object.
680        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}