Skip to content

Run C API work on the runtime's worker threads, not the caller's stack - #76

Open
yuvalif wants to merge 1 commit into
lancedb:mainfrom
yuvalif:spawn-hop-rework
Open

yuvalif wants to merge 1 commit into
lancedb:mainfrom
yuvalif:spawn-hop-rework

Conversation

@yuvalif

@yuvalif yuvalif commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator

Every database-executing entry point is still synchronous for the caller, but its work now runs on the library's own tokio worker threads; the calling thread only parks until the operation completes. The caller's stack is never used for lance/datafusion planning or execution, so the API is safe to call from threads, coroutines and fibers with small fixed-size stacks (Ceph RGW's beast coroutines use 512 KiB).

Runtime bridge

  • runtime::run_blocking spawns the future onto the runtime and blocks the caller on its JoinHandle. All entry points in connection, table, query and index go through it.
  • A panic inside a task, and a call made from inside a tokio async context, are reported as LANCEDB_RUNTIME instead of aborting the process. A rejected nested call never dispatches its work.
  • The runtime is created on first use. Initialization failures are reported as LANCEDB_RUNTIME and are not cached, so a later call can retry.
  • Arrow objects handed to the library may be consumed and released on a worker thread, i.e. not the thread that produced them.

Runtime configuration

  • lancedb_runtime_configure() sets worker_threads, worker_stack_size and max_blocking_threads once, before the first database call. Repeated or late configuration returns LANCEDB_RUNTIME.
  • Fields left at 0 fall back to the defaults: number of CPUs (or TOKIO_WORKER_THREADS), 8 MiB and 512.
  • The worker stack has a 2 MiB floor (LANCEDB_MIN_WORKER_STACK_SIZE). Smaller nonzero values are rejected by the configure call with LANCEDB_INVALID_ARGUMENT; smaller environment values are clamped. The floor is an acceptance threshold, not a guarantee that every query fits.
  • Worker counts above 65535, stack sizes above isize::MAX and overflowing worker/blocking totals are rejected.
  • These options size the wrapper's runtime only, not Lance's separate CPU pool, and do not bound queued work or process-wide CPU use.

Removed

  • lancedb_run_on_stack() and the stacker dependency. stacker measures remaining stack against the OS thread's bounds, which do not describe a coroutine's separately mapped stack, and it is no longer needed. examples/asio_coroutine.cpp calls the API directly from the coroutine.

Claude-Session: https://claude.ai/code/session_01E63tgb7eXHwzmaQBSErFWu

Every database-executing entry point is still synchronous for the caller,
but its work now runs on the library's own tokio worker threads; the
calling thread only parks until the operation completes. The caller's
stack is never used for lance/datafusion planning or execution, so the API
is safe to call from threads, coroutines and fibers with small fixed-size
stacks (Ceph RGW's beast coroutines use 512 KiB).

Runtime bridge
- runtime::run_blocking spawns the future onto the runtime and blocks the
  caller on its JoinHandle. All entry points in connection, table, query
  and index go through it.
- A panic inside a task, and a call made from inside a tokio async context,
  are reported as LANCEDB_RUNTIME instead of aborting the process. A
  rejected nested call never dispatches its work.
- The runtime is created on first use. Initialization failures are reported
  as LANCEDB_RUNTIME and are not cached, so a later call can retry.
- Arrow objects handed to the library may be consumed and released on a
  worker thread, i.e. not the thread that produced them.

Runtime configuration
- lancedb_runtime_configure() sets worker_threads, worker_stack_size and
  max_blocking_threads once, before the first database call. Repeated or
  late configuration returns LANCEDB_RUNTIME.
- Fields left at 0 fall back to the defaults:
  number of CPUs (or TOKIO_WORKER_THREADS), 8 MiB and 512.
- The worker stack has a 2 MiB floor (LANCEDB_MIN_WORKER_STACK_SIZE).
  Smaller nonzero values are rejected by the configure call with
  LANCEDB_INVALID_ARGUMENT; smaller environment values are clamped. The
  floor is an acceptance threshold, not a guarantee that every query fits.
- Worker counts above 65535, stack sizes above isize::MAX and overflowing
  worker/blocking totals are rejected.
- These options size the wrapper's runtime only, not Lance's separate CPU
  pool, and do not bound queued work or process-wide CPU use.

Removed
- lancedb_run_on_stack() and the stacker dependency. stacker measures
  remaining stack against the OS thread's bounds, which do not describe a
  coroutine's separately mapped stack, and it is no longer needed.
  examples/asio_coroutine.cpp calls the API directly from the coroutine.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01E63tgb7eXHwzmaQBSErFWu
Signed-off-by: Andrew Altshuler <[email protected]>
@Xuanwo

Xuanwo commented Nov 21, 2026

Copy link
Copy Markdown
Member

@aaltshuler @yuvalif Two open PRs now cover the same runtime/stack work: #69 (five commits, six behind main; macOS and coverage checks failing at 11e8072) and #76 (one squashed commit on current main; all checks green). Could you two agree on which PR should carry the work, and which fixes and tests from the other must be kept before the surviving PR goes to review?

The visible differences: #69 keeps the LANCEDB_C_* environment overrides and the test-hooks C++ tests for panic and nested runtime entry. #76 drops those overrides and hooks, keeps a panic test through the connection path, and has no nested-entry C++ test. #69's description also says its Ceph validation PR is still outstanding; if real-client validation is expected before merge, please say which PR carries it.

Both PRs remove lancedb_run_on_stack, which main's public header still declares and documents, so please also state how existing callers are handled. I have not changed either branch.

@Xuanwo

Xuanwo commented Nov 21, 2026

Copy link
Copy Markdown
Member

Resolving my earlier question: under the loop's duplicate-PR rule, #76 is the surviving PR, and #69 has been closed as the duplicate with the comparison linked there. No choice or follow-up is needed from either author.

Review notes carried from #69: it had LANCEDB_C_* environment overrides and precedence tests, a test-hooks nested-entry C++ test, an environment-recovery retry test and an ignored worker-stack memory sampler. #76 deliberately drops the env overrides and test hooks, keeps nested-entry coverage in the Rust tests and panic coverage through the real S3-signing connection path, and includes the Rust tests in coverage. Separately, main's public header still declares lancedb_run_on_stack; I am carrying that compatibility question into #76's review rather than treating removal as accepted.

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

Reviewed at 59ca9d7. The runtime bridge is applied consistently, and I am not asking to change the design or hold this PR. Three documentation/migration follow-ups:

  1. C ABI migration note. Removing lancedb_run_on_stack is a real source/ABI migration for Ceph, not just a cleanup: create_index, remove_indexes, create_vector_bucket and put_vectors pass a stack-owned context into the wrapper and read ctx.result synchronously after it returns (put_vectors: https://github.com/ceph/ceph/blob/065d8cb97eb606fc3fec028107a98a6adf1658a0/src/rgw/rgw_s3vector.cc#L2168-L2185). The wrapper also did the caller-stack growth for them. Please add a short note the next 0.x minor release can carry (PR description is fine) saying existing C/C++ callers must recompile, and that users of lancedb_run_on_stack must remove the wrapper and handle the remaining caller-side work explicitly. ceph/ceph#72652 still pins lancedb-c at the closed #69 head 11e8072, so it does not validate this head; please state whether RGW validation was run against 59ca9d7. The 256 KiB C++ stack tests are useful coverage for the wrapper, but they do not exercise the Ceph SAL path.

  2. Inline note on the empty-name failure path: with valid Arrow data and an empty table name, lancedb_table_create takes the reader and then drops it inside run_blocking, so its arrays release on a worker. The public wording should say that explicitly and keep input ArrowSchema distinct from consumed readers.

  3. Inline note on the threading paragraph: lancedb_table_version and lancedb_table_count_rows return 0 on failure, so they cannot report LANCEDB_RUNTIME like error-returning functions.

No performance claims here.

Comment thread include/lancedb.h
Comment on lines +825 to +827
* Do not call this API from within a tokio async context (e.g. from a task
* running on the library's own runtime); doing so is reported as
* LANCEDB_RUNTIME.

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.

This paragraph currently covers the whole API, but lancedb_table_version and lancedb_table_count_rows return 0 on failure and have no error channel. Please qualify the nested-call sentence.

Suggested change
* Do not call this API from within a tokio async context (e.g. from a task
* running on the library's own runtime); doing so is reported as
* LANCEDB_RUNTIME.
* Do not call this API from within a tokio async context (e.g. from a task
* running on the library's own runtime). A rejected call to a function that
* returns LanceDBError is reported as LANCEDB_RUNTIME;
* lancedb_table_version() and lancedb_table_count_rows() return 0 instead,
* since they have no error channel.

Comment thread include/lancedb.h
Comment on lines +829 to +833
* Arrow objects handed to the library (record batch readers, schemas) may be
* consumed and released on those worker threads, i.e. on a different thread
* than the one that produced them. Producers must therefore tolerate
* release callbacks from another thread — the Arrow C data interface does
* not require this by itself.

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.

This is the right place to distinguish ownership, because the failure path below drops a consumed reader on a worker. Suggested wording:

Suggested change
* Arrow objects handed to the library (record batch readers, schemas) may be
* consumed and released on those worker threads, i.e. on a different thread
* than the one that produced them. Producers must therefore tolerate
* release callbacks from another thread — the Arrow C data interface does
* not require this by itself.
* Record batch readers handed to the library may be consumed and released
* on those worker threads, i.e. on a different thread than the one that
* produced them, including when a call fails after ownership transfer.
* Producers must therefore tolerate release callbacks from another thread —
* the Arrow C data interface does not require this by itself. Input
* ArrowSchema pointers are read, not consumed, and remain caller-owned.

Comment thread src/connection.rs
Comment on lines +660 to +661
// Take ownership of the reader
let reader_box = Box::from_raw(reader);

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.

lancedb_table_create takes ownership here, then validate_table_name fails inside run_blocking for an empty name, so the reader is dropped on a worker even though the table was never created. The error code is unchanged (LANCEDB_INVALID_TABLE_NAME); the new part is where the drop happens. Please keep that ownership/release detail next to the transfer:

Suggested change
// Take ownership of the reader
let reader_box = Box::from_raw(reader);
// Take ownership of the reader. It is dropped on a worker if
// validate_table_name() fails below, so its release callbacks must
// tolerate a worker thread. Input ArrowSchema above is borrowed.
let reader_box = Box::from_raw(reader);

@Xuanwo

Xuanwo commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

@yuvalif Integration note after #80 merged (main is now 5c444729): the new lancedb_table_version_with_status and lancedb_table_count_rows_with_status still import get_runtime from connection and call runtime.block_on (src/table.rs L19, L361-L381, L421-L441). #76 removes get_runtime from connection.rs and already runs the neighboring lancedb_table_version and lancedb_table_count_rows through run_blocking (src/table.rs L339-L368).

The branches auto-merge cleanly because the new functions sit outside the edited hunks, so the conflict-free merge would hide an unresolved get_runtime import and the old block_on path until compilation. Please convert both new functions to run_blocking(async move { ... }) when rebasing and drop get_runtime from the table import; the final combined-head CI is the handoff check. No other newly merged main change touches this path.

Additional main change: #83 is now merged at 68ecf54b, and its new lancedb_table_prewarm_index also uses get_runtime + runtime.block_on (src/index.rs L20, L524-L546). It needs the same owned-data run_blocking conversion #76 already gives lancedb_table_drop_index (src/index.rs L540-L543): clone the table handle and own the index name before the hop, then call run_blocking(async move { tbl.prewarm_index(&index_name).await }). This getter has the same clean-merge, compile-time-only failure mode.

Additional integration point: #84 is now merged at 60083346, and #76 now conflicts only in src/query.rs. Both EXPLAIN paths (lancedb_query_explain_plan and lancedb_vector_query_explain_plan) must keep the new SQL fallback after the DataFusion filter and copy/own query_ref.filter before run_blocking; the current #76 pre-hop snapshot copies only df_filter (#76 src/query.rs L544-L567, main L532-L647). The combined-head CI validates the resolved rebase.

The SDK upgrade is now on main at 2b2b3df and adds a conflict in src/connection.rs. Keep list_namespaces collecting the SDK stream with TryStreamExt inside run_blocking, with the owned parent namespace moved into the worker closure. In both vector execution and EXPLAIN, propagate nprobes(nprobes)? so invalid probe counts retain the new SDK error. The namespace path and vector builders show the landed behavior.

@aaltshuler

Copy link
Copy Markdown

RGW validation at 59ca9d7, as asked in the review above. I ran it on ceph/ceph#73919 with the submodule pointer moved to this head; the full table is in ceph/ceph#73919 (comment).

  • With both RGW coroutine stacks cut to 128 KiB, 59ca9d7 passes the rgw/s3vectors suite (117 pass, 1 fail) and 1,764 of 1,776 concurrent stress calls, with radosgw up throughout.
  • b837f67 (Ceph's current pointer) with the same 128 KiB stacks and no lancedb_run_on_stack calls dies on the first CreateVectorBucket: a stack overflow in lancedb::connection::execute under block_on.
  • At 512 KiB / 256 KiB both versions pass the same.

The failures are Ceph-side and also occur on Ceph's base without this change: one test that needs a rebuild slower than this hardware produces, and a DeleteIndex / background-rebuild race.

Scope: aarch64, Debug build, one run per variant. lancedb_runtime_configure() was not called, so the defaults were in effect.

@yuvalif on your question in #69 about keeping only the configure API: fine by me. Drop the LANCEDB_C_* environment overrides and keep lancedb_runtime_configure().

@Xuanwo

Xuanwo commented Nov 24, 2026

Copy link
Copy Markdown
Member

Thanks for testing 59ca9d7 in RGW and documenting the limits of the run. This answers the earlier question about whether that exact revision had been exercised in Ceph. The AArch64 Debug run with the default runtime configuration shows that RGW stayed up with both coroutine stacks set to 128 KiB. The detailed results also identify the suite and stress failures that occur on the Ceph baseline. RGW results

The PR branch still needs to be integrated with current main, and the migration and Arrow release-thread notes from the review still apply. The RGW result gives us a baseline to compare against once the integrated revision is available.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants