Repository navigation
perf(core): erase spawn_cpu closure type to reduce monomorphization - #10716
Conversation
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.
## 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]>
There was a problem hiding this comment.
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.
Xuanwo
left a comment
There was a problem hiding this comment.
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 againstmainremains exactlyrust/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/ORcases pass 5/5;lance-datafusion--all-featurespasses 431/431; bothspawn_cputests pass, including the original panic payload. cargo fmt --all --checkand the full workspacecargo clippy --profile ci --all --tests --benches -D warningsboth 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.rschanged (bindings=false), and Arrow ordering compatibility is gated off becauseCargo.lockhas no ordering-relevant change. tokiostays 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.
…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]>
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
Summary
spawn_cpupassed each caller's closure straight tospawn_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 oneArc<CpuTask<F, T>>and hands it to a non-genericspawn_erased(Arc<dyn RunOnce>), so that machinery is instantiated once inlance-core.This revives #10444 with a cheaper design: one allocation per task instead of two, and no
Anydowncast or locks. It followsstd::thread::spawn, which erases the closure but keeps the result typed. Panics still propagate with their original payload through theJoinError(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:lancelance-indexRuntime benchmarks (the
spawn_cpumicrobenchmark from #10444 and thelance-encodingbenches 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. Everyspawn_cpucall pays one allocation and one indirect call. TheUnsafeCellfields are sequenced by the task lifecycle (worker writesoutput, caller reads it only after the join handle resolves) instead of locked.