Skip to content

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

Merged
wjones127 merged 7 commits into
lance-format:mainfrom
wjones127:perf/spawn-cpu-erased-task
Nov 11, 2026
Merged

wjones127 merged 7 commits into
lance-format:mainfrom
wjones127:perf/spawn-cpu-erased-task

Conversation

@wjones127

@wjones127 wjones127 commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

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.

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.

@wjones127
wjones127 marked this pull request as ready for review November 4, 2026 18:22

@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 pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Nov 4, 2026
The erased task stores the closure's output in a slot shared with the
caller, so pin the success contract next to the existing panic test: the
caller receives exactly the value the closure returned, moved out of the
task rather than re-created.
@lance-gatekeeper lance-gatekeeper Bot removed K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Nov 11, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Nov 11, 2026
Xuanwo added a commit that referenced this pull request Nov 11, 2026
## Summary

`Planner::parse_filter` rewrites `array_any_match` lambdas before
planning (#10947). Both rewrite passes use sqlparser's recursive
visitors, but a filter such as `a AND b AND ...` parses as a chain as
deep as its number of operands. The visitors therefore overflowed the
stack in `planner::tests::test_parse_deep_logical_filter`, aborting the
test process on current main (`67b2821`) and on #10716's integrated
head, before #7510's iterative `flatten_logical_binary_exprs` /
`balanced_binary_expr` protection could run.

This change balances each `AND`/`OR` chain in the parsed SQL AST before
those visitors traverse it. Balancing uses an explicit stack and
rebuilds a chain only with the same operator, so `AND` and `OR` are
never mixed. `binary_expr` already rebuilds the same chains balanced
after parsing, so parsed expressions and evaluation are unchanged. The
pre-pass also makes a deep lambda body shallow before it is cloned,
checked and printed. The function documentation now states this
regrouping and why it bounds visitor depth.

## Tests

Added regressions in `udf::element` using the existing `any_element`
fixture:

- a 1000-operand `OR` chain of real `array_any_match` calls below `NOT`,
evaluated against independent expected rows;
- a lambda body with 1000 `OR` predicates, covering the body
clone/check/format path.

Added the far-end-lambda AST regression adapted from #10953 (thanks
@sarwarbhuiyan): a 1000-condition `AND`/`OR` chain with a lambda at the
end is walked by its leaves with an explicit stack, checking that the
last leaf is the rewritten `any_element` call and that no lambda
remains. The walk does not assume the parsed left-deep shape, which this
change rebalances.

All three abort with SIGABRT on unfixed main and pass with this change.
The existing 1000-operand `AND`/`OR` `test_parse_deep_logical_filter` is
unchanged in depth and assertions.

Commands run on this head:

- `cargo test --profile ci -p lance-datafusion --lib` (381 passed)
- `cargo test --profile ci -p lance-datafusion --all-features --lib`
(431 passed)
- `cargo test --profile ci -p lance --lib --
dataset::tests::dataset_scanner::test_any_element` (13 passed)
- `cargo test --profile ci -p lance --lib --
dataset::tests::dataset_scanner::test_lambda_filter_rejects_unsupported_forms`
(2 passed)
- `cargo fmt --all -- --check`
- `cargo clippy --profile ci --all --tests --benches -- -D warnings`

## Context

Regression introduced by #10947 over the deep-filter protection added
for #7510. This PR repairs that base failure and does not close either
issue. No performance measurement is claimed: the regrouping cost is
only derived statically as O(n log n) per logical node.

---------

Co-authored-by: Sarwar Bhuiyan <[email protected]>
@lance-gatekeeper lance-gatekeeper Bot removed K-risk Latest Gatekeeper recommendation includes a non-blocking risk. K-approved Latest Gatekeeper recommendation permits acceptance. labels Nov 11, 2026

@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.

The helper and its tests are unchanged by the upstream merges, and the focused tests still pass. The single-allocation design remains a reasonable tradeoff for reducing monomorphization.

Runtime impact remains workload-dependent: earlier comparisons showed about 1.5% slower dense-boolean encoding and 1.3% faster delta-offset encoding. Those measurements predate these merges; current-head runtime has not been remeasured, and the reported compile-size savings still use an older baseline.

Keep the documented ~100 µs task-size floor. Reverting the helper remains a straightforward fallback if runtime cost outweighs the 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 Nov 11, 2026

@Xuanwo Xuanwo left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@approval-body.md

@Xuanwo Xuanwo left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Approving the merge of current main (fbfea4f8c) into this branch.

Verified on 8c315a6c3:

  • The merge delta is byte-identical to main's own delta (67b282155..fbfea4f8c, 2 files, +160/-3), so no conflict resolution changed behavior. The PR delta against main remains exactly rust/lance-core/src/utils/tokio.rs (+77/-14).
  • New runs on this tree: the deep-filter planner test, the deep lambda/body tests, and the adapted tail-lambda AND/OR cases pass 5/5; lance-datafusion --all-features passes 431/431; both spawn_cpu tests pass, including the original panic payload.
  • cargo fmt --all --check and the full workspace cargo clippy --profile ci --all --tests --benches -D warnings both exit 0.
  • Hosted checks are terminal with no failures. The five skips are conditional and genuine: the four Python-side jobs are gated off because only rust/lance-core/src/utils/tokio.rs changed (bindings=false), and Arrow ordering compatibility is gated off because Cargo.lock has no ordering-relevant change.
  • tokio stays at 1.53.1; no lockfile, toolchain, or cargo config change.

The runtime risk recorded by the gate stays as stated: the encoding comparisons predate these merges, current-head runtime was not remeasured, and the compile-size numbers still use an older baseline. Keeping the documented ~100 µs task-size floor is the remaining operational constraint.

@wjones127
wjones127 merged commit c0f6020 into lance-format:main Nov 11, 2026
44 of 46 checks passed
wjones127 added a commit that referenced this pull request Nov 11, 2026
…0721)

## Summary

Each distinct future passed to `tokio::spawn` instantiates tokio's task
machinery (task cell, harness, vtable, `catch_unwind`, drop glue, about
1.7K LLVM IR lines), and every `async` block is its own type. This PR
adds `lance_core::utils::tokio::spawn`, which hands tokio a single
non-generic future type, so that machinery is instantiated once for the
whole program. Library `tokio::spawn` / `tokio::task::spawn` calls in
`lance`, `lance-index`, `lance-io`, `lance-encoding`, `lance-table`,
`lance-datafusion` and `lance-datafusion-exec` now use it. Test and
bench code is unchanged.

```text
spawn<T>(future)
  Arc<SpawnedTask { stage: UnsafeCell<Running(F) | Finished(T) | Consumed> }>
  -> tokio::spawn(ErasedTask(Arc<dyn PollErased>))   // one tokio instantiation
  -> lance_core::utils::tokio::JoinHandle<T>         // wraps JoinHandle<()>, reads T on completion
```

`spawn` returns `lance_core::utils::tokio::JoinHandle<T>` instead of
`tokio::task::JoinHandle<T>`. It resolves to `Result<T, JoinError>` and
forwards `abort`, `abort_handle` and `is_finished`. Fields that stored
tokio's handle type now store this one.

The stage is shared without locks; access is sequenced by the task
lifecycle. While the task is alive only tokio touches it, through the
exclusive `ErasedTask`. Tokio drops the future before reporting
completion (`Harness::poll_future` stores the output, replacing the
future, before `complete()`), and the handle reads the stage only after
a successful completion. `ErasedTask`'s `Drop` drops an unfinished
future in place, so abort and shutdown release it immediately rather
than when the last handle goes away.

This is the same approach as #10716 (`spawn_cpu`), applied to async
tasks.

## Evidence

LLVM IR lines, `cargo llvm-lines --lib`, dev profile, both on 663f8c7
(a historical baseline; the head has since merged newer main):

| crate | main | PR | Δ |
|---|---|---|---|
| `lance` | 7,480,131 | 7,024,845 | −6.1% |
| `lance-encoding` | 962,417 | 870,958 | −9.5% |
| `lance-index` | 4,183,905 | 4,050,445 | −3.2% |

New tests in `lance-core` cover output, panic payload propagation, and
abort dropping the in-flight future while the handle is still alive
(verified to fail without `ErasedTask`'s `Drop`).

## Merge Risk

**Door:** two-way. `spawn` is new; call sites can switch back
individually. No format change.
**Blast Radius:** `perf`, `concurrency`. One extra allocation per
spawned task, and new `unsafe` whose soundness relies on tokio dropping
a task's future before completing it.

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Xuanwo <[email protected]>
Xuanwo added a commit that referenced this pull request Nov 16, 2026
The `test_create_ivf_hnsw_pq` fixture is stochastic: its live index
build samples four IVF training rows and initializes the IVF and PQ
k-means models from OS entropy. Recall is therefore a random variable,
and the existing `recall >= 0.5` assertion occasionally sees `0.45`. The
same test failed with that signature on ARM in #10977 and on x86 in
#10716; the test, training and lockfile inputs are identical at those
heads, their bases and current `main`.

This is a test-only change. The test now trains the IVF model from four
fixed rows of the same fixture with `train_ivf_model_from_sample`,
trains the PQ codebook on the corresponding residuals with
`PQBuildParams::build`, and passes both models to `create_index`. The
live build therefore no longer consumes training entropy, while the
index parameters (`nlist=2`, `sample_rate=2`, `max_iters=2`, PQ 4x8,
HNSW 3/8/32), the query (`k=20`, `nprobes=2`, `ef=64`), the `recall >=
0.5` threshold, ground truth, HNSW construction, PQ encoding and scan
path are unchanged.

Training coverage is retained: both production trainers execute in this
test, and their independent exact-output tests remain
(`vector::kmeans::tests::test_flat_kmeans_seed_is_reproducible`,
`vector::pq::builder::tests`, and the `train_ivf_from_sample_*` cases).

Validation:
- Before: 15 independent-process runs passed with instrumented recall
0.60-0.85; the `0.45` CI tail was not reproduced locally, matching the
prior 200-run measurement.
- After: 10 independent-process runs of the fixed-model fixture produced
identical results with recall 0.80; the final test code passed 15/15
unmodified runs (5 before and 10 after the temporary recall print was
removed).
- Neighbor tests: IVF/HNSW/PQ lifecycle cases,
`test_create_index_nulls`, PQ builder and seeded-kmeans tests passed.
- `cargo fmt --all -- --check`
- `cargo clippy --all --tests --benches --profile ci --locked --features
"$ALL_FEATURES" -- -D warnings`

Limits: the failing CI run did not log its sampled rows or initial
centroids, so the exact draw cannot be replayed. ARM was not run
locally; the hosted Rust ARM job on this PR is the platform check.

Refs #8764
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.

2 participants