Skip to content

perf(core): type-erase spawn_cpu to reduce monomorphization - #10444

Closed
wjones127 wants to merge 1 commit into
mainfrom
perf/type-erase-spawn-cpu
Closed

wjones127 wants to merge 1 commit into
mainfrom
perf/type-erase-spawn-cpu

Conversation

@wjones127

Copy link
Copy Markdown
Contributor

Summary

spawn_cpu passed each caller's closure straight to spawn_blocking, so every distinct closure instantiated tokio's blocking-task machinery (task cell, harness, raw vtable, drop glue) in the calling crate. In lance, the generic IvfIndexBuilder<S, Q> / IVFIndex<S, Q> matrix turns 24 call sites into 399 instantiations of about 1.8K IR lines each. This PR boxes the closure and its output and hands them to a non-generic spawn_cpu_erased, so that machinery is instantiated once in lance-core. Panic propagation is unchanged (spawn_cpu_reraises_the_closure_panic still passes).

spawn_cpu<E, F, R>(func)                    // generic over F: tiny shim
  -> spawn_cpu_erased(Box<dyn FnOnce() -> Box<dyn Any + Send> + Send>)  // non-generic
  .map(downcast_output::<Result<R, E>>)     // fn item: generic over R, E only

Evidence

Compile cost: dev profile, CARGO_INCREMENTAL=0, single-crate rebuild. IR from cargo llvm-lines --lib; time is the rustc -Z time-passes total.

crate LLVM IR lines (main → PR) spawn_cpu rows spawn_cpu instantiations rustc total, s (main → PR)
lance 7,972,391 → 7,298,969 (−8.4%) 707,613 → 32,250 399 → 266 110.2, 109.0, 109.9, 108.4 → 104.5, 103.9 (−4.7%)
lance-index 4,129,382 → 3,984,616 (−3.5%) 172,892 → 27,058 90 → 60 25.6, 25.7 → 24.9, 24.7 (−3.0%)

(Two additional lance-index baseline runs taken while the host was loaded, 27.9 and 29.6 s, are excluded.)

Runtime: bench profile, main and PR binaries run alternately and pinned with taskset (4 cores for the first two groups, 8 for FTS) on a 16-vCPU host. Values are mean ± stdev of criterion point estimates.

bench main PR Δ n
spawn_cpu round trip, no-op closure (ad hoc, below) 3.38 ± 0.03 µs 3.45 ± 0.04 µs +2.2% (~70 ns) 6
1024 concurrent tasks, ~100 ns of work each (ad hoc) 447 ± 21 µs 480 ± 9 µs +7% (~32 ns/task) 4
1024 concurrent tasks, ~10 µs of work each (ad hoc) 1.867 ms 1.871 ms +0.2% 4
lance-index invert_search(1000000) 8.68 ± 0.03 ms 8.72 ± 0.11 ms +0.5% (noise) 7
lance-index invert_phrase_search(1000000) 2.56 ± 0.07 ms 2.57 ± 0.02 ms +0.5% (noise) 7
lance-encoding encode_compressed/zstd_strings_10cols 4.641 s 4.660 s +0.4% 3
lance-encoding encode_compressed/lz4_strings_10cols 1.591 s 1.591 s 0% 3
lance-encoding encode_structural_pages/sparse_boolean_list 1.401 ms 1.406 ms +0.3% 4
lance-encoding encode_structural_pages/dense_boolean_list 1.819 ± 0.015 ms 1.898 ± 0.009 ms +4.4% 4
lance-encoding variable_offsets/delta/v2.3 6.83 ms 6.98 ms +2.2% 3

The erasure adds two small allocations and one indirect call per task, about 70 ns on a ~3.4 µs round trip. That cost is invisible once a task does about 10 µs of work, and FTS search, which calls spawn_cpu per partition per query, shows no measurable change. The two encoder regressions are reproducible, but per-call overhead does not explain them. Each iteration encodes one or two pages (default max_page_bytes is 32 MiB), so there are only one or two spawn_cpu calls, while the gap is about 80 µs. A codegen or inlining shift in the encode path is more likely, but this is not confirmed (perf is unavailable on this host).

Ad hoc spawn_cpu microbenchmark (not committed)
fn sum_work(n: u64) -> u64 {
    (0..n).fold(0u64, |acc, x| acc.wrapping_add(black_box(x) * 31))
}

fn bench_spawn_cpu(c: &mut Criterion) {
    let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(2).build().unwrap();
    let mut group = c.benchmark_group("spawn_cpu");
    group.bench_function("sequential_noop", |b| {
        b.iter(|| rt.block_on(async {
            spawn_cpu(|| -> Result<u64, std::io::Error> { Ok(black_box(1)) }).await.unwrap()
        }))
    });
    const TASKS: usize = 1024;
    for work in [100u64, 10_000] {
        group.bench_with_input(BenchmarkId::new("burst", work), &work, |b, &work| {
            b.iter(|| rt.block_on(async {
                join_all((0..TASKS).map(|_| spawn_cpu(move || -> Result<Vec<u64>, std::io::Error> {
                    Ok(vec![sum_work(work); 4])
                }))).await
            }))
        });
    }
}

Merge Risk

Door: two-way. spawn_cpu's signature and panic behavior are unchanged, and there is no format change.
Blast Radius: perf. Every spawn_cpu caller pays the small per-task cost shown above.

🤖 Generated with Claude Code

spawn_cpu passed each caller's closure straight to spawn_blocking, so every
distinct closure instantiated tokio's blocking-task machinery in the calling
crate (399 instantiations in lance). Box the closure and its output and hand
them to a non-generic spawn_cpu_erased instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@wjones127
wjones127 marked this pull request as ready for review October 28, 2026 23:37

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude Code Review

This repository is configured for manual code reviews. Comment @claude review for a one-time review, or @claude review always to subscribe this PR to a review on every future push.

Tip: disable this comment in your organization's Code Review settings.

@lance-gatekeeper lance-gatekeeper Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Gate recommendation: approve with a non-blocking risk.

Full erasure is reasonable for the measured compile savings. The reported 2.2–4.4% encoder slowdowns remain an unexplained, non-blocking performance risk. Erasing only the closure would avoid the result allocation, while retaining task machinery per result type; that is an alternative if runtime cost becomes more important than maximizing compile savings.

@lance-gatekeeper lance-gatekeeper Bot added K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Oct 28, 2026
@wjones127 wjones127 closed this Nov 2, 2026
wjones127 added a commit that referenced this pull request Nov 11, 2026
…10716)

## Summary

`spawn_cpu` passed each caller's closure straight to `spawn_blocking`,
so tokio's blocking-task machinery (task cell, harness, vtable, drop
glue) was instantiated once per closure type in every calling crate.
This PR puts the closure and a slot for its output in one
`Arc<CpuTask<F, T>>` and hands it to a non-generic `spawn_erased(Arc<dyn
RunOnce>)`, so that machinery is instantiated once in `lance-core`.

```text
spawn_cpu<E, F, R>(func)
  Arc<CpuTask { func: UnsafeCell<Option<F>>, output: UnsafeCell<Option<Result<R, E>>> }>
  -> spawn_erased(Arc<dyn RunOnce>) -> JoinHandle<()>   // non-generic, only tokio call
  .map(|_| task.output.take())                           // typed, no downcast
```

This revives #10444 with a cheaper design: one allocation per task
instead of two, and no `Any` downcast or locks. It follows
`std::thread::spawn`, which erases the closure but keeps the result
typed. Panics still propagate with their original payload through the
`JoinError` (`spawn_cpu_reraises_the_closure_panic`).

## Evidence

LLVM IR lines, `cargo llvm-lines --lib`, dev profile. The main baseline
was measured at 839b1a5, 85 upstream commits behind the branch's base
at measurement time, so the deltas are approximate:

| crate | main | PR | Δ |
|---|---|---|---|
| `lance` | 7,378,036 | 6,848,859 | −7.2% |
| `lance-index` | 4,145,525 | 4,041,401 | −2.5% |

Runtime benchmarks (the `spawn_cpu` microbenchmark from #10444 and the
`lance-encoding` benches that regressed there) are not yet run.

## Merge Risk

**Door:** two-way. `spawn_cpu`'s signature and panic behavior are
unchanged; no format change.
**Blast Radius:** `perf`. Every `spawn_cpu` call pays one allocation and
one indirect call. The `UnsafeCell` fields are sequenced by the task
lifecycle (worker writes `output`, caller reads it only after the join
handle resolves) instead of locked.

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Xuanwo <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. performance

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant