diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 6bdcfffd1..eb8536f3e 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -575,6 +575,7 @@ class Table: def _is_native(self) -> bool: ... def close(self) -> None: ... async def schema(self) -> pa.Schema: ... + def schema_sync(self) -> pa.Schema: ... async def add( self, data: pa.RecordBatchReader, @@ -976,6 +977,9 @@ class Query: async def execute_to_reader( self, max_batch_length: Optional[int], timeout: Optional[timedelta] ) -> pa.RecordBatchReader: ... + def execute_to_reader_sync( + self, max_batch_length: Optional[int], timeout: Optional[timedelta] + ) -> pa.RecordBatchReader: ... async def explain_plan(self, verbose: Optional[bool]) -> str: ... async def analyze_plan( self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None @@ -1021,6 +1025,9 @@ class FTSQuery: async def execute_to_reader( self, max_batch_length: Optional[int], timeout: Optional[timedelta] ) -> pa.RecordBatchReader: ... + def execute_to_reader_sync( + self, max_batch_length: Optional[int], timeout: Optional[timedelta] + ) -> pa.RecordBatchReader: ... async def explain_plan(self, verbose: Optional[bool]) -> str: ... async def analyze_plan( self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None @@ -1033,6 +1040,9 @@ class VectorQuery: async def execute_to_reader( self, max_batch_length: Optional[int], timeout: Optional[timedelta] ) -> pa.RecordBatchReader: ... + def execute_to_reader_sync( + self, max_batch_length: Optional[int], timeout: Optional[timedelta] + ) -> pa.RecordBatchReader: ... def where(self, filter: str): ... def where_expr(self, expr: PyExpr): ... def select(self, columns: List[Tuple[str, str]]): ... diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 6d3cf818b..19e9051f7 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -4033,6 +4033,26 @@ class AsyncQueryBase(object): self._blob_paths = tuple(blob_v2_projection_sources(schema, projection).keys()) self._inner.with_row_id() + def _maybe_add_blob_row_id_sync(self) -> None: + if self._table is None: + self._blob_auto_row_id = False + self._blob_paths = () + return + + req = self._inner.to_query_request() + schema = self._table._schema_sync() + projection = _query_request_projection(req) + self._blob_auto_row_id = blob_auto_row_id_for_scan( + schema, + projection, + with_row_id=self._with_row_id, + ) + if not self._blob_auto_row_id: + self._blob_paths = () + return + self._blob_paths = tuple(blob_v2_projection_sources(schema, projection).keys()) + self._inner.with_row_id() + async def _can_fetch_plain_legacy_blobs(self, blob_mode: BlobMode) -> bool: if blob_mode != "bytes" or self._table is None: return False @@ -4220,6 +4240,18 @@ class AsyncQueryBase(object): reader = await self._inner.execute_to_reader(None, timeout) return pa.Table.from_batches(reader, schema=reader.schema) + def _execute_eager_sync( + self, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + """Execute with the synchronous native eager collector.""" + self._ensure_fragment_constraints_supported("to_arrow()") + if not self._blob_row_id_prepared: + self._maybe_add_blob_row_id_sync() + reader = self._inner.execute_to_reader_sync(None, timeout) + return pa.Table.from_batches(reader, schema=reader.schema) + async def _execute_batches( self, *, @@ -5118,6 +5150,22 @@ class AsyncFTSQuery(AsyncStandardQuery): results = _merge_query_snapshot(results, source) return results + def _execute_eager_sync( + self, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + try: + results = super()._execute_eager_sync(timeout=timeout) + except Exception as error: + _add_fts_position_error_note(error) + raise + if self._reranker: + source = results + results = self._reranker.rerank_fts(self.get_query(), results) + results = _merge_query_snapshot(results, source) + return results + async def _execute_batches( self, *, @@ -5480,6 +5528,18 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase): results = _merge_query_snapshot(results, source) return results + def _execute_eager_sync( + self, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + results = super()._execute_eager_sync(timeout=timeout) + if self._reranker: + source = results + results = self._reranker.rerank_vector(self._query_string, results) + results = _merge_query_snapshot(results, source) + return results + async def _execute_batches( self, *, diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 52ae6b9fd..fdcea6aa8 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -4533,7 +4533,10 @@ class LanceTable(Table): ------- pa.Schema A PyArrow schema object.""" - return LOOP.run(self._table.schema()) + schema_sync = getattr(self._table, "_schema_sync", None) + if schema_sync is None: + return LOOP.run(self._table.schema()) + return schema_sync() def list_versions(self) -> List[Dict[str, Any]]: """List all versions of the table""" @@ -6060,6 +6063,13 @@ class LanceTable(Table): async_query = self._table._sync_query_to_async(query) async_query._blob_row_id_prepared = query._blob_row_id_prepared + if ( + self._table._inner._is_native() + and self._namespace_client is None + and not self._route_pushdown_to_rust + and isinstance(async_query, (AsyncQuery, AsyncVectorQuery, AsyncFTSQuery)) + ): + return async_query._execute_eager_sync(timeout=timeout) return LOOP.run(async_query._execute_eager(timeout=timeout)) def _explain_plan(self, query: Query, verbose: Optional[bool] = False) -> str: @@ -7430,6 +7440,9 @@ class AsyncTable: """ return _restore_blob_extensions(await self._inner.schema()) + def _schema_sync(self) -> pa.Schema: + return _restore_blob_extensions(self._inner.schema_sync()) + async def embedding_functions(self) -> Dict[str, EmbeddingFunctionConfig]: """ Get the embedding functions for the table diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index ec747bd40..c01b3f9dc 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -2676,14 +2676,14 @@ def test_sync_query_prepares_schema_once_per_execution(tmp_path, monkeypatch): ) calls = 0 - original = AsyncTable.schema + original = AsyncTable._schema_sync - async def counted(self): + def counted(self): nonlocal calls calls += 1 - return await original(self) + return original(self) - monkeypatch.setattr(AsyncTable, "schema", counted) + monkeypatch.setattr(AsyncTable, "_schema_sync", counted) table.search().where("id = 1").select(["id"]).to_arrow() assert calls <= 1 diff --git a/python/python/tests/test_sync_query_direct.py b/python/python/tests/test_sync_query_direct.py new file mode 100644 index 000000000..9863f66c4 --- /dev/null +++ b/python/python/tests/test_sync_query_direct.py @@ -0,0 +1,160 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import signal +import os +import subprocess +import sys +import threading +from datetime import timedelta + +import pyarrow as pa +import pytest + +import lancedb +from lancedb import background_loop +from lancedb.index import BTree, FTS, IvfFlat + + +def _direct_query_table(tmp_path): + table = lancedb.connect(tmp_path).create_table( + "direct", + pa.table( + { + "id": pa.array([1, 2, 3, 4], pa.int64()), + "text": ["alpha beta", "alpha gamma", "beta gamma", "delta epsilon"], + "vector": pa.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + pa.list_(pa.float32(), 4), + ), + } + ), + ) + table.create_index("id", config=BTree()) + table.create_index("vector", config=IvfFlat(distance_type="l2", num_partitions=1)) + table.create_index("text", config=FTS(with_position=True)) + return table + + +def test_direct_sync_queries_do_not_use_background_loop(tmp_path, monkeypatch): + table = _direct_query_table(tmp_path) + expected_empty_schema = table.search().where("id < 0").output_schema() + + def fail(*_args, **_kwargs): + raise AssertionError("LOOP.run must not be used by direct sync queries") + + monkeypatch.setattr(background_loop.LOOP, "run", fail) + + point = table.search().where("id = 1").select(["id", "text"]).to_arrow() + assert point.to_pylist() == [{"id": 1, "text": "alpha beta"}] + + with_row_id = ( + table.search().where("id = 1").select(["id"]).with_row_id(True).to_arrow() + ) + assert with_row_id["_rowid"].to_pylist() == [0] + + # The vector column is inferred from the sync schema binding. + vector = table.search([0.9, 0.1, 0.0, 0.0]).limit(2).to_arrow() + assert vector["id"].to_pylist() == [1, 2] + assert "_distance" in vector.column_names + + fts = table.search("alpha", query_type="fts").select(["id"]).to_arrow() + assert sorted(fts["id"].to_pylist()) == [1, 2] + assert "_score" in fts.column_names + + phrase = table.search('"alpha beta"', query_type="fts").select(["id"]).to_arrow() + assert phrase["id"].to_pylist() == [1] + + empty = table.search().where("id < 0").to_arrow() + assert empty.num_rows == 0 + assert empty.schema == expected_empty_schema + + with pytest.raises(Exception, match="Query timeout"): + table.search([1.0, 0.0, 0.0, 0.0]).to_arrow(timeout=timedelta(0)) + + +@pytest.mark.skipif(sys.platform != "linux", reason="needs sched_setaffinity") +def test_direct_sync_query_from_single_worker_progress_callback(tmp_path): + script = r""" +import os +import sys + +try: + cpus = sorted(os.sched_getaffinity(0)) + if not cpus: + print("SKIP") + sys.exit(0) + os.sched_setaffinity(0, {cpus[0]}) +except OSError: + print("SKIP") + sys.exit(0) + +import lancedb + +db = lancedb.connect("memory:///") +target = db.create_table( + "target", + [{"id": 1, "value": "one"}, {"id": 2, "value": "two"}], +) +source = db.create_table("source", [{"id": 1}]) +seen = [] + +def progress(_update): + if not seen: + seen.append( + target.search() + .where("id = 1") + .select(["value"]) + .to_arrow() + .to_pylist() + ) + +source.add([{"id": 2}], progress=progress) +assert seen == [[{"value": "one"}]], seen +print("OK") +""" + result = subprocess.run( + [sys.executable, "-c", script], + cwd=tmp_path, + capture_output=True, + text=True, + timeout=30, + ) + if "SKIP" in result.stdout: + pytest.skip("sched_setaffinity did not leave a usable CPU") + assert result.returncode == 0, result.stdout + result.stderr + assert "OK" in result.stdout + + +@pytest.mark.slow +def test_direct_sync_query_sigint_aborts_and_reuses_runtime(tmp_path): + rows = 500_000 + table = lancedb.connect(tmp_path).create_table( + "sigint", + pa.table( + { + "id": pa.array(range(rows), pa.int64()), + "text": pa.array([f"row-{row}" for row in range(rows)]), + } + ), + ) + # Warm the runtime and page cache so the timed call is long enough to observe. + table.search().select(["id"]).to_arrow() + + timer = threading.Timer(0.001, os.kill, args=(os.getpid(), signal.SIGINT)) + timer.start() + try: + with pytest.raises(KeyboardInterrupt): + table.search().select(["id", "text"]).to_arrow() + finally: + timer.cancel() + timer.join() + + # The shared runtime and its generation counter remain usable. + after = table.search().where("id = 1").select(["id", "text"]).to_arrow() + assert after.to_pylist() == [{"id": 1, "text": "row-1"}] diff --git a/python/src/arrow.rs b/python/src/arrow.rs index 0384f2b2a..a4de3a911 100644 --- a/python/src/arrow.rs +++ b/python/src/arrow.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use std::time::Duration; use crate::error::PythonErrorExt; -use crate::runtime::future_into_py; +use crate::runtime::{block_on_interruptible, future_into_py}; use arrow::{ datatypes::SchemaRef, pyarrow::{IntoPyArrow, ToPyArrow}, @@ -89,18 +89,45 @@ where Q: ExecutableQuery + Send + 'static, { future_into_py(py, async move { - let mut options = QueryExecutionOptions::default(); - // `None` means the caller wants one eager result, not the core's - // default batch size. An explicit value is still honored. - options.max_batch_length = max_batch_length.unwrap_or(0); - options.timeout = timeout; - let stream = query.execute_with_options(options).await.infer_error()?; - let schema = stream.schema(); - let batches = stream.try_collect::>().await.infer_error()?; - let reader: Box = Box::new(RecordBatchIterator::new( - batches.into_iter().map(Ok), - schema, - )); + let reader = collect_to_reader(query, max_batch_length, timeout).await?; Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind())) }) } + +/// Synchronous counterpart of [`execute_to_reader`]. +/// +/// The returned reader owns the collected batches; the caller converts it to +/// Python after reattaching to the interpreter. The wait releases the GIL and +/// keeps Python signal handlers on the calling thread. +pub fn execute_to_reader_sync( + query: Q, + max_batch_length: Option, + timeout: Option, +) -> PyResult> +where + Q: ExecutableQuery + Send + 'static, +{ + block_on_interruptible(collect_to_reader(query, max_batch_length, timeout)) +} + +async fn collect_to_reader( + query: Q, + max_batch_length: Option, + timeout: Option, +) -> PyResult> +where + Q: ExecutableQuery + Send + 'static, +{ + let mut options = QueryExecutionOptions::default(); + // `None` means the caller wants one eager result, not the core's + // default batch size. An explicit value is still honored. + options.max_batch_length = max_batch_length.unwrap_or(0); + options.timeout = timeout; + let stream = query.execute_with_options(options).await.infer_error()?; + let schema = stream.schema(); + let batches = stream.try_collect::>().await.infer_error()?; + Ok(Box::new(RecordBatchIterator::new( + batches.into_iter().map(Ok), + schema, + ))) +} diff --git a/python/src/query.rs b/python/src/query.rs index 2c1a606eb..7a7e34416 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -33,6 +33,7 @@ use lancedb::query::{HasQuery, QueryBase}; use lancedb::table::AnyQuery; use pyo3::Bound; use pyo3::IntoPyObject; +use pyo3::Py; use pyo3::PyAny; use pyo3::PyRef; use pyo3::PyResult; @@ -65,6 +66,20 @@ fn analyze_plan_options(distributed_metrics: Option<&str>) -> PyResult( + py: Python<'_>, + query: Q, + max_batch_length: Option, + timeout: Option, +) -> PyResult> +where + Q: ExecutableQuery + Send + 'static, +{ + let reader = + py.detach(move || crate::arrow::execute_to_reader_sync(query, max_batch_length, timeout))?; + Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind())) +} + impl<'a, 'py> FromPyObject<'a, 'py> for PyLanceDB { type Error = PyErr; @@ -713,6 +728,15 @@ impl Query { crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout) } + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader_sync( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + execute_to_reader_sync(self_.py(), self_.inner.clone(), max_batch_length, timeout) + } + pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { @@ -966,6 +990,23 @@ impl FTSQuery { ) } + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader_sync( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + execute_to_reader_sync( + self_.py(), + self_ + .inner + .clone() + .full_text_search(self_.fts_query.clone()), + max_batch_length, + timeout, + ) + } + pub fn count_rows(self_: PyRef<'_, Self>) -> PyResult> { let mut inner = self_ .inner @@ -1219,6 +1260,15 @@ impl VectorQuery { crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout) } + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader_sync( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + execute_to_reader_sync(self_.py(), self_.inner.clone(), max_batch_length, timeout) + } + pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { diff --git a/python/src/runtime.rs b/python/src/runtime.rs index 85d536939..436b0d40b 100644 --- a/python/src/runtime.rs +++ b/python/src/runtime.rs @@ -93,15 +93,19 @@ //! `Arc` clone from becoming the final owner that drops it. use std::future::Future; +use std::panic::{AssertUnwindSafe, catch_unwind}; use std::pin::Pin; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::mpsc::{self, RecvTimeoutError}; use std::time::{Duration, Instant}; use arc_swap::ArcSwapOption; -use pyo3::{Bound, PyAny, PyResult, Python, conversion::IntoPyObject}; +use futures::FutureExt; +use pyo3::{Bound, PyAny, PyResult, Python, conversion::IntoPyObject, exceptions::PyRuntimeError}; use pyo3_async_runtimes::{ TaskLocals, + err::RustPanic, generic::{ContextExt, JoinError, Runtime}, }; use tokio::{runtime, task}; @@ -282,6 +286,111 @@ pub fn block_on(fut: F) -> F::Output { get_runtime().block_on(fut) } +/// How often an interruptible wait returns to the Python caller for signal checks. +const SIGNAL_CHECK_INTERVAL: Duration = Duration::from_millis(25); + +/// Block on `fut` while keeping the Python caller responsive to signals. +/// +/// The query task lives on the shared runtime and carries an [`OutstandingGuard`]. +/// The caller waits on the result channel without holding the GIL and periodically +/// reacquires it to run CPython's signal handlers on the same thread. A signal +/// exception aborts the task and drops the result receiver. +/// +/// A synchronous callback already running on a multi-threaded Tokio worker uses +/// [`tokio::task::block_in_place`] so the core can be handed off while the callback +/// waits. Current-thread runtimes and contexts that reject blocking are returned as +/// Python errors instead of falling back to the Python event loop. +pub fn block_on_interruptible(fut: F) -> PyResult +where + F: Future> + Send + 'static, + T: Send + 'static, +{ + block_on_interruptible_with(fut, || Python::attach(|py| py.check_signals())) +} + +fn block_on_interruptible_with(fut: F, check: C) -> PyResult +where + F: Future> + Send + 'static, + T: Send + 'static, + C: FnMut() -> PyResult<()>, +{ + match runtime::Handle::try_current() { + Ok(handle) => match handle.runtime_flavor() { + runtime::RuntimeFlavor::MultiThread => { + let result = catch_unwind(AssertUnwindSafe(|| { + task::block_in_place(|| block_on_interruptible_inner(fut, check)) + })); + match result { + Ok(result) => result, + Err(payload) => Err(PyRuntimeError::new_err(format!( + "synchronous query cannot block in this Tokio context: {}", + panic_message(payload.as_ref()) + ))), + } + } + _ => Err(PyRuntimeError::new_err( + "synchronous query execution cannot block on a current-thread Tokio runtime; use the async API", + )), + }, + Err(_) => block_on_interruptible_inner(fut, check), + } +} + +fn block_on_interruptible_inner(fut: F, mut check: C) -> PyResult +where + F: Future> + Send + 'static, + T: Send + 'static, + C: FnMut() -> PyResult<()>, +{ + let guard = OutstandingGuard::new(); + let (tx, rx) = mpsc::sync_channel(1); + let task = async move { + let _guard = guard; + let result = AssertUnwindSafe(fut).catch_unwind().await; + // Dropping a completed result is enough when the caller has already + // returned on an interrupt; the task's guard is dropped with it. + let _ = tx.send(result); + }; + let handle = get_runtime().spawn(task); + + loop { + match rx.recv_timeout(SIGNAL_CHECK_INTERVAL) { + Ok(Ok(result)) => { + check()?; + return result; + } + Ok(Err(payload)) => { + check()?; + return Err(RustPanic::new_err(format!( + "rust future panicked: {}", + panic_message(payload.as_ref()) + ))); + } + Err(RecvTimeoutError::Timeout) => { + if let Err(error) = check() { + handle.abort(); + return Err(error); + } + } + Err(RecvTimeoutError::Disconnected) => { + return Err(PyRuntimeError::new_err( + "query task stopped before producing a result", + )); + } + } + } +} + +fn panic_message(payload: &(dyn std::any::Any + Send)) -> &str { + if let Some(message) = payload.downcast_ref::<&str>() { + message + } else if let Some(message) = payload.downcast_ref::() { + message.as_str() + } else { + "unknown error" + } +} + /// Run a detached task, including when the caller is already on a runtime worker. /// Keep it visible to [`shutdown`] until it finishes. pub fn spawn_background(fut: F) @@ -571,6 +680,95 @@ mod tests { shutdown(Duration::from_secs(5)); } + #[test] + fn test_block_on_interruptible_aborts_and_drops_future() { + use std::sync::mpsc; + + Python::initialize(); + let _lock = lock_runtime_state_for_test(); + let (started_tx, started_rx) = mpsc::channel(); + let (dropped_tx, dropped_rx) = mpsc::channel(); + + struct DropNotify(Option>); + impl Drop for DropNotify { + fn drop(&mut self) { + if let Some(tx) = self.0.take() { + let _ = tx.send(()); + } + } + } + + let fut = async move { + started_tx.send(()).unwrap(); + let _notify = DropNotify(Some(dropped_tx)); + std::future::pending::<()>().await; + #[allow(unreachable_code)] + Ok::<(), pyo3::PyErr>(()) + }; + let result = block_on_interruptible_with(fut, || { + Err(pyo3::exceptions::PyRuntimeError::new_err("interrupted")) + }); + + assert!(result.is_err()); + started_rx + .recv_timeout(Duration::from_secs(2)) + .expect("query task never started"); + dropped_rx + .recv_timeout(Duration::from_secs(2)) + .expect("interrupted query future was not dropped"); + shutdown(Duration::from_secs(5)); + } + + #[test] + fn test_block_on_interruptible_maps_panic() { + Python::initialize(); + let result = block_on_interruptible(async { + panic!("boom"); + #[allow(unreachable_code)] + Ok::<(), pyo3::PyErr>(()) + }); + assert!( + result + .expect_err("panic must become a Python exception") + .to_string() + .contains("rust future panicked: boom") + ); + } + + #[test] + fn test_block_on_interruptible_rejects_current_thread_runtime() { + Python::initialize(); + let runtime = runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("current-thread runtime"); + let error = runtime + .block_on(async { block_on_interruptible(async { Ok::<_, pyo3::PyErr>(1) }) }) + .expect_err("current-thread runtime must be rejected"); + assert!(error.to_string().contains("current-thread")); + } + + #[cfg(target_os = "linux")] + #[test] + fn test_block_on_interruptible_from_single_worker_runtime() { + Python::initialize(); + let _lock = lock_runtime_state_for_test(); + let _worker_threads = TestWorkerThreads::new(1); + shutdown(Duration::from_secs(5)); + + let (done_tx, done_rx) = mpsc::channel(); + drop(get_runtime().spawn(async move { + let result = block_on_interruptible(async { Ok::<_, pyo3::PyErr>(42) }); + let _ = done_tx.send(result.map_err(|error| error.to_string())); + })); + + let result = done_rx + .recv_timeout(Duration::from_secs(10)) + .expect("single-worker runtime made no progress"); + assert_eq!(result.expect("single-worker query failed"), 42); + shutdown(Duration::from_secs(5)); + } + // Adapted from the concurrent reproducer that found the original bug: // many threads hammering the runtime while shutdown races them, not // just the sequential rebuild path above. Before every reader held its diff --git a/python/src/table.rs b/python/src/table.rs index a4611d80c..f9c81d5a3 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -9,7 +9,7 @@ use std::{ }, }; -use crate::runtime::{block_on, future_into_py, spawn_background}; +use crate::runtime::{block_on, block_on_interruptible, future_into_py, spawn_background}; use crate::{ connection::Connection, error::PythonErrorExt, @@ -1619,6 +1619,14 @@ impl Table { }) } + pub fn schema_sync(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + let schema = self_.py().detach(move || { + block_on_interruptible(async move { inner.schema().await.infer_error() }) + })?; + Python::attach(|py| schema.to_pyarrow(py).map(|obj| obj.unbind())) + } + #[pyo3(signature = (data, mode, progress=None, write_parallelism=None, allow_external_blob_outside_bases=false, retries=None))] pub fn add<'a>( self_: PyRef<'a, Self>,