Repository navigation
Run C API work on the runtime's worker threads, not the caller's stack - #69
aaltshuler wants to merge 5 commits into
Conversation
082b4ff to
7fb3b1b
Compare
| /// Upstream measured ~552 KB of stack for a merge_insert in | ||
| /// `examples/asio_coroutine.cpp`; tokio's default of 2 MiB leaves little margin | ||
| /// for debug builds, so we allocate 8 MiB. Stacks are mmap'd and committed | ||
| /// lazily, so the cost is virtual address space, not RSS. |
There was a problem hiding this comment.
can you measure how much more memory consumption this adds?
note that we may use high concurrency client count (e.g. 1K) - this is 8GB vs. 2GB.
There was a problem hiding this comment.
Measured (ignored test measure_worker_stack_memory, numbers in the PR description). Two things the numbers show:
- Resident memory is the same at 2 MiB and 8 MiB in every scenario, within 0.1 MB: peak VmRSS 18 MB (256 callers, async), 25 MB (256 blocking in
block_in_place), 33 MB (1024 async), 47 MB (1024 blocking). Thread stacks are reserved lazily, only the pages a thread touches become resident. - What the stack size changes is address space: +0.4 GB VmSize for the idle 12-worker pool, up to +3.2 GB with 1024 callers all blocking a worker at the same time.
- The thread count does not depend on the stack size, and on the normal async path it does not depend on the client count either: the pool stays at 12 workers (the extra threads in that row are the test's own caller threads). It grows with concurrent blocking callers only in
block_in_placemode, and is capped bymax_blocking_threads(default 512; 1550 = 1024 callers + 14 + 512).
So the stack size is not what scales with client count: worker threads are a fixed pool (CPU count by default), and thread stacks are reserved lazily, so 8 MiB vs 2 MiB shows up in VmSize, not RSS. What does grow with concurrent blocking callers is the thread count, becauseblock_in_placehands the core to a fresh thread — that is the Ceph object-store path, not the normal async path, and it is bounded bymax_blocking_threads, which the newlancedb_runtime_configure()exposes alongside the stack size and worker count. I left the default at 8 MiB and added a 1 MiB floor; if you prefer 2 MiB as the default I can flip it, the floor keeps that safe.
There was a problem hiding this comment.
Correction to my earlier reply, incorporated in 11e8072:
The minimum worker stack is now 2 MiB, with the default still 8 MiB.
The regression suite crashes at 1 MiB; all five operations pass at 2 MiB in
the tested Linux arm64 Debug build. The saved fault trace does not establish
which operation caused the 1 MiB crash. The floor is an acceptance threshold,
not a guarantee that every query fits, and my earlier claim that it made
2 MiB safe was too strong.
The memory results are samples from a synthetic sleeping-task harness,
not peaks or measurements of real Ceph clients. There is no Lance planning,
database I/O or SAL work in that benchmark. Sampled RSS differed by at most
0.1 MB between 2 and 8 MiB stacks, but the ~47 MB result does not estimate
memory for 1K real clients. Stack pages become resident as touched. Also,
12 workers × 6 MiB is 72 MiB, so I cannot attribute the whole 0.4 GB idle
VmSize difference to worker stacks.
max_blocking_threads bounds additional threads in this wrapper's runtime;
it excludes the configured workers and does not limit queued work, admitted
clients or other pools. The PR description and benchmark wording now reflect
these limits. Real Ceph concurrency and memory validation remains outstanding.
There was a problem hiding this comment.
🔵 Needs a closer look
It changes core runtime/threading behavior across many FFI entry points and warrants careful human validation despite the added tests.
Pull request overview
This PR changes the C bindings’ execution model so synchronous C entry points no longer block_on futures on the caller’s stack, but instead spawn the work onto dedicated Tokio worker threads (with configurable worker count and stack size) and block the caller only on completion—preventing stack overflows in small-stack hosts (e.g., coroutines/fibers).
Changes:
- Introduces a dedicated Tokio runtime +
run_blocking/run_blocking_infalliblebridge that catches panics and converts them toError::Runtime. - Converts C API entry points from direct
runtime.block_on(...)torun_blocking(...), copying/owning raw-pointer inputs before hopping threads where needed. - Adds documentation of the threading model to the C header and adds a new small-stack regression test suite wired into CMake/CTest.
File summaries
| File | Description |
|---|---|
src/runtime.rs |
Adds explicit multi-thread Tokio runtime construction and the run_blocking bridge with panic-to-error handling plus unit tests. |
src/connection.rs |
Switches connection/session entry points to run_blocking and removes the old runtime singleton from this module. |
src/table.rs |
Converts table entry points to run_blocking, cloning/owning inputs to avoid crossing worker threads with raw pointers. |
src/index.rs |
Converts index-related entry points to run_blocking, owning config-derived values before thread hop. |
src/query.rs |
Converts query execution/result conversion to run_blocking. |
src/lib.rs |
Exposes the new internal runtime module. |
include/lancedb.h |
Documents the threading model, runtime-context restriction, and cross-thread Arrow release implications. |
tests/test_stack.cpp |
Adds regression tests that run operations on 256 KiB pthread stacks to validate no caller-stack polling. |
CMakeLists.txt |
Builds and registers the new lancedb_stack_tests executable in CTest. |
Review details
- Files reviewed: 9/9 changed files
- Comments generated: 1
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
could you please add a test that covers that?
we should probably create a combined PR, that allows passing stack size, thread count (and maybe other parameters) from C into the runtime creation. using a env variable used when the process tarts gived very little flexibility. the thread count paramerter may be even more critical as we run reindexign and compaction in out background process, and we want to avoid it taking too much CPU. |
|
could you please prepare a ceph/s3vectors PR that point to this change as its lancedb-c submodule (temporarily)? |
|
Will do — a Ceph PR pointing the submodule at this branch with the four |
|
Tests added: On the too-small stack: agreed, and that is why it is now rejected rather than trusted — On the combined PR: this round adds |
Every database-executing entry point used Runtime::block_on on the calling thread, so lance/datafusion planning ran on whatever stack the caller had. Hosts that call the C API from small fixed-size stacks (Ceph RGW's beast coroutines use 512 KiB) overflow; lancedb_run_on_stack() cannot reliably help there because stacker measures remaining stack against the OS thread's bounds, which do not describe a coroutine's separately mapped stack. Introduce runtime::run_blocking: spawn the future onto the runtime and park the caller until the JoinHandle completes (the pattern Lance's Python bindings use in BackgroundExecutor::spawn). Build the runtime explicitly with an 8 MiB worker stack (LANCEDB_C_WORKER_STACK_SIZE / LANCEDB_C_WORKER_THREADS override it). Runtime initialization runs inside the panic boundary, and construction errors become LANCEDB_RUNTIME. Only successful initialization is cached, so failed attempts can be retried. Validate block_on entry before spawning the operation: rejected nested calls cannot dispatch work. Task panics and unsupported runtime entry also return LANCEDB_RUNTIME. Convert all 39 call sites. Raw C pointers are read before the hop (table_create, merge_insert); the explain-plan entry points, which do not consume the query, copy its parameters out before the hop; the table-metadata entry points copy the entries out while holding the dataset read guard on the worker; futures without a Result output use run_blocking_infallible. Add tests/test_stack.cpp, which runs merge_insert, a nested SQL delete, vector search, scalar index creation and the metadata round trip from a 256 KiB pthread. Against the previous design the merge_insert, nested delete and scalar-index sections segfault (planning exceeds the caller's stack); with this change all five pass. Rust unit tests cover the helper itself. Document the threading model in lancedb.h; lancedb_run_on_stack() is kept for compatibility. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01E63tgb7eXHwzmaQBSErFWu Signed-off-by: Andrew Altshuler <[email protected]>
The function grew the caller's stack with stacker::maybe_grow, which decides whether to grow from the remaining space of the *OS thread's* stack (pthread_getattr_np). That says nothing about a coroutine or fiber stack, so callers on small fixed-size stacks were protected only by luck of mapping order. Now that every entry point runs its work on the runtime's worker threads the function has no remaining purpose; drop it rather than keep an API that cannot deliver what it promises. Breaking change for callers of lancedb_run_on_stack(): remove the wrapper, the inner calls are safe to make directly. - src/connection.rs, include/lancedb.h: remove the function and its docs - Cargo.toml, Cargo.lock: drop stacker and the crates only it pulled in - examples/asio_coroutine.cpp: call the operations directly from the coroutines - tests/test_table.cpp: remove the run_on_stack wrapping test Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Andrew Altshuler <[email protected]>
Allow embedding applications to configure the wrapper's process-wide Tokio runtime once, before the first database call. Serialize configuration with initialization so accepted options cannot race with startup. - Expose worker_threads, worker_stack_size and max_blocking_threads. Nonzero C values take precedence over LANCEDB_C_* environment settings; zero uses the environment/default. Preserve TOKIO_WORKER_THREADS as the fallback when no C or LANCEDB_C worker count is set. - Enforce a 2 MiB worker stack floor, with the 8 MiB default unchanged. Explicit nonzero stacks below the floor return LANCEDB_INVALID_ARGUMENT; smaller positive environment settings are clamped. The Linux arm64 Debug regression suite crashes at 1 MiB and passes at 2 MiB. This is a tested acceptance threshold, not a guarantee for every query or build. - Reject worker counts above 65535, stacks above isize::MAX, and overflowing combined worker/blocking counts. Validate resolved settings again before runtime construction and per-worker allocation. Lazy initialization failures return LANCEDB_RUNTIME; repeated or late configuration does too. - Document that reserved stack pages become resident as touched. These options size the wrapper's runtime, not Lance's separate CPU pool, and do not bound queued work or process-wide CPU use. Keep the floor and late-configuration unit test with the new API. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Andrew Altshuler <[email protected]>
- Add the test-hooks Cargo feature for C entry points that panic or make an unsupported nested call. CMake test builds enable it, including Release test builds; builds without the feature do not export these hooks. - C++ runtime tests cover null, undersized and oversized options, late configuration, task panics, nested entry, and a successful database call after a panic. - Move Rust runtime tests into their own module. Fresh-process tests cover configuration/environment precedence, actual worker counts and stacks, blocking-pool limits, invalid resolved settings, C initialization errors, and retry after an environment correction. Deterministically verify a rejected nested future is never polled and is dropped before returning; keep entered-handle and block_in_place callers supported. - Run Rust library tests in the Ubuntu shared-library CI job with cargo test --release --lib --features test-hooks, reusing build/target. - Register the stack suite both at the default and at the 2 MiB worker-stack minimum, in separate processes and Valgrind logs. Stack and runtime suites use the same Valgrind flags as the other suites, or run natively without it. - Free returned error strings on every stack-test path with RAII. Local Linux arm64 Debug validation: 14 Rust tests, 12 CTest suites and zero reported errors across all 10 registered Valgrind suites. Formatting and clippy with test-hooks and -D warnings are clean. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Andrew Altshuler <[email protected]>
runtime::tests::measure_worker_stack_memory drives concurrent OS-thread
callers through run_blocking with tasks that sleep asynchronously or in
block_in_place. It prints thread count, VmRSS, VmHWM and VmSize from
/proc/self/status before, during and after the workload (Linux only).
The loaded observations are samples after a 150 ms delay, not measured
peaks. The harness performs no Lance planning, database I/O or Ceph SAL
calls; its results do not estimate real-client memory. Reserved stack pages
become resident as touched, and process VmSize includes other mappings.
Run the ignored test alone, once per stack size:
LANCEDB_C_WORKER_STACK_SIZE=2097152 cargo test --lib -- --ignored \
--nocapture measure_worker_stack_memory
LANCEDB_C_MEASURE_CALLERS sets the caller count (default 256).
Keep this in the crate's unit tests because an example cannot name the
library: the lib target and the lancedb dependency share the crate name,
so rustc sees two lancedb candidates (E0464).
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Andrew Altshuler <[email protected]>
|
@yuvalif Correction to my earlier reply, incorporated in
Local Linux arm64 Debug validation passed 14 Rust tests, 12/12 CTest I also overstated the explanation and expected outcome for the coverage drop. |
Do not merge. This tests lancedb/lancedb-c#69 with RGW as a real client before that PR merges, as requested in its review. With lancedb-c#69, every C API call runs its async work on the lancedb-c runtime's worker threads (8 MiB stacks by default) and the caller only blocks until it completes, so the caller's stack size no longer matters. The PR removes lancedb_run_on_stack() and the stacker dependency. - point the lancedb-c submodule at the PR head, 11e8072, fetched from the aaltshuler/lancedb-c fork until the PR merges - call create_index_impl(), remove_indexes_impl(), create_vector_bucket_impl() and put_vectors_impl() directly - drop stacker, psm, ar_archive_writer and object from src/rgw/Cargo.lock Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Andrew Altshuler <[email protected]>
|
@aaltshuler i did some cleanup to this PR here: #76
please let me know what you think. |
|
Closing as the duplicate in favor of #76, which carries the same runtime/stack change on current The material unique to this PR — the |
Problem
Database-executing C entry points polled Lance/DataFusion work on the calling
thread. Ceph RGW calls from 512 KiB coroutine stacks; the unwrapped regression
suite reproduces stack overflows during merge-insert, nested delete and scalar
index creation.
lancedb_run_on_stack()cannot reliably protect coroutinestacks because stacker's remaining-stack calculation uses OS-thread bounds,
which do not describe a coroutine's separately mapped stack.
Change
run_blockingand convert all 39 database-executingblock_onsites, including Add explain-plan FFI for query and vector query #70's two explain-plan entry points. Operations run on
runtime workers; callers wait for their results. Raw-pointer inputs are
prepared before the hop, and Arrow objects may be released on workers.
failures as
LANCEDB_RUNTIME. Entry is validated before spawning work, so arejected nested call cannot dispatch its operation. Failed initialization
remains retryable, and configuration is serialized with initialization.
lancedb_run_on_stack()and
stacker; callers remove the wrapper. Update the asio example.lancedb_runtime_configure(const LanceDBRuntimeOptions*, char**)forworker_threads,worker_stack_sizeandmax_blocking_threads, once beforethe first database call. Nonzero C values take precedence over the
LANCEDB_C_*environment settings. Zero selects the environment/default;TOKIO_WORKER_THREADSremains the worker-count fallback before CPU count.Repeated or late configuration returns
LANCEDB_RUNTIME.C stack values return
LANCEDB_INVALID_ARGUMENT; smaller positive environmentvalues are clamped. Reject worker counts above 65,535, stack sizes above
isize::MAX, and combined worker/blocking counts that overflowusize.Revalidate resolved settings before runtime construction. The minimum is an
acceptance threshold, not a guarantee that every workload fits.
The original 1 MiB minimum was rejected by testing: the regression suite
crashes at 1 MiB, while all five operations pass at 2 MiB in the tested Linux
arm64 Debug build. The saved fault trace does not establish which operation
caused the 1 MiB crash; no operation-specific attribution or measured safety
margin is claimed.
Validation
search, scalar-index creation and metadata on 256 KiB caller stacks.
CTest also runs those operations in a separate process with 2 MiB worker
stacks. Both runs use Valgrind; returned error strings are freed by RAII.
nested runtime entry. Panic/misuse hooks are gated by
test-hooks, enabledby CMake test builds.
nested future is polled, supported entered-handle/
block_in_placecallers,and a 64 KiB caller stack. Fresh-process cases verify configuration and
environment precedence, actual thread/stack settings, blocking-pool limits,
initialization failures through C, and recovery after an environment fix.
cargo test --release --lib.measurement; 12/12 CTest suites passed, including the minimum-stack run;
zero errors in all 10 registered Valgrind suites. Fmt and clippy
(
--all-targets --features test-hooks -- -D warnings) passed.11e8072. All five rewritten commits passedcargo fmt --checkandcargo check --all-targets; commits 4 and 5 also passed the check withtest-hooks.approval (
action_required). These local results do not establish thecoverage percentage or guarantee an improvement.
Synthetic memory samples
The ignored
measure_worker_stack_memorytest uses OS-thread callers whosetasks sleep for 300 ms, asynchronously or inside
block_in_place. It performsno Lance planning, database I/O or Ceph SAL calls. Loaded rows are single
samples about 150 ms after callers are created, not observed peaks; thread
counts include the harness's caller threads. Linux arm64, 12 runtime workers:
The sampled RSS difference is at most 0.1 MB in this shallow waiting workload.
Reserved stack pages become resident as touched; these results do not predict
real-client memory use. Twelve workers with 6 MiB larger stacks account for
72 MiB of extra reservation, so the entire 0.4 GB idle VmSize difference cannot
be attributed to stacks.
block_in_placemay add replacement workers up tothe runtime's additional-thread limit (
max_blocking_threads, default 512).That limit does not bound queued tasks, in-flight clients or other pools.
Follow-ups and scope
CPU pool controlled by
LANCE_CPU_THREADS; compaction has its own taskparallelism setting. This API alone does not satisfy process-wide CPU
control for background reindexing/compaction. That remains an open review
item requiring workload validation.
call supplies wrapper stack/thread settings now; an explicit handle can be
a follow-up, subject to reviewer preference.
lancedb_run_on_stackcallsremoved) remains outstanding, including real SAL concurrency/memory tests.
Blocking object stores must use appropriate
block_in_place/spawn_blockinghandling; the companion Ceph change addresses that path.
cargo testhas a pre-existing doctest E0464 failure onmain: thelibrary and its
lancedbdependency share a crate name. This PR runs unittests with
--lib; changing doctest configuration remains separate.Series
lancedb_run_on_stack()and the stacker dependencylancedb_runtime_configure()and a worker stack floor