Merge branch 'merge-insert-source-stats' into merge-insert-source-stats-bindings

# Conflicts:
#	python/python/tests/test_table.py
This commit is contained in:
Will Jones
2026-11-10 02:14:38 +00:00
474 changed files with 44681 additions and 10005 deletions
+13
View File
@@ -262,6 +262,19 @@ impl AuthzObject {
}))
}
#[staticmethod]
fn storage_integration(
database: &str,
namespace: &Bound<'_, PyAny>,
name: &str,
) -> PyResult<Self> {
Self::validated(Object::StorageIntegration(StorageIntegrationObject {
database: database.into(),
namespace: namespace_path(namespace)?,
storage_integration: name.into(),
}))
}
#[staticmethod]
fn function(database: &str, namespace: &Bound<'_, PyAny>, name: &str) -> PyResult<Self> {
Self::validated(Object::Function(FunctionObject {
+222
View File
@@ -24,6 +24,8 @@ use lancedb::{
connection::NamespaceClientPushdownOperation,
database::namespace::LanceNamespaceDatabase,
database::{CreateTableMode, Database, ReadConsistency},
function::GpuClass as LanceGpuClass,
graph::PropertyGraphDefinition,
};
use pyo3::{
Bound, FromPyObject, Py, PyAny, PyRef, PyResult, Python,
@@ -37,6 +39,62 @@ pub struct Connection {
inner: Option<LanceConnection>,
}
/// Configured hardware and worker limits of a Function GPU class.
#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)]
#[derive(Clone, Debug)]
pub struct GpuClass {
pub name: String,
pub resource_name: String,
pub gpu_model: Option<String>,
pub gpu_memory_bytes: Option<u64>,
pub max_gpu_count_per_worker: Option<u32>,
pub cpu_millis: Option<u64>,
pub memory_bytes: Option<u64>,
pub ephemeral_storage_bytes: Option<u64>,
}
impl From<LanceGpuClass> for GpuClass {
fn from(class: LanceGpuClass) -> Self {
Self {
name: class.name,
resource_name: class.resource_name,
gpu_model: class.gpu_model,
gpu_memory_bytes: class.gpu_memory_bytes,
max_gpu_count_per_worker: class.max_gpu_count_per_worker,
cpu_millis: class.cpu_millis,
memory_bytes: class.memory_bytes,
ephemeral_storage_bytes: class.ephemeral_storage_bytes,
}
}
}
#[pymethods]
impl GpuClass {
fn __repr__(&self) -> String {
let gpu_model = self
.gpu_model
.as_ref()
.map_or_else(|| "None".to_string(), |value| format!("{value:?}"));
let optional = |value: Option<u64>| {
value.map_or_else(|| "None".to_string(), |value| value.to_string())
};
let max_gpu_count = self
.max_gpu_count_per_worker
.map_or_else(|| "None".to_string(), |value| value.to_string());
format!(
"GpuClass(name={:?}, resource_name={:?}, gpu_model={gpu_model}, \
gpu_memory_bytes={}, max_gpu_count_per_worker={max_gpu_count}, \
cpu_millis={}, memory_bytes={}, ephemeral_storage_bytes={})",
self.name,
self.resource_name,
optional(self.gpu_memory_bytes),
optional(self.cpu_millis),
optional(self.memory_bytes),
optional(self.ephemeral_storage_bytes),
)
}
}
impl Connection {
pub(crate) fn new(inner: LanceConnection) -> Self {
Self { inner: Some(inner) }
@@ -870,6 +928,23 @@ impl Connection {
})
}
#[pyo3(signature = (name, version, namespace_path=None))]
pub fn _drop_function_with_warnings(
self_: PyRef<'_, Self>,
name: String,
version: String,
namespace_path: Option<Vec<String>>,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.get_inner()?.clone();
let namespace_path = namespace_path.unwrap_or_default();
future_into_py(self_.py(), async move {
inner
.drop_function_with_warnings(name, version, &namespace_path)
.await
.infer_error()
})
}
#[pyo3(signature = (name, version, namespace_path=None))]
pub fn drop_function_async(
self_: PyRef<'_, Self>,
@@ -888,6 +963,72 @@ impl Connection {
})
}
#[pyo3(signature = (name, request, namespace_path=None))]
pub fn create_storage_integration<'py>(
&self,
py: Python<'py>,
name: String,
request: String,
namespace_path: Option<Vec<String>>,
) -> PyResult<Bound<'py, PyAny>> {
let inner = self.get_inner()?.clone();
let request: lancedb::storage_integration::CreateStorageIntegrationRequest =
serde_json::from_str(&request)
.map_err(|error| PyValueError::new_err(error.to_string()))?;
future_into_py(py, async move {
let info = inner
.create_storage_integration(name, request, &namespace_path.unwrap_or_default())
.await
.infer_error()?;
serde_json::to_string(&info).map_err(|error| PyValueError::new_err(error.to_string()))
})
}
#[pyo3(signature = (name, namespace_path=None))]
pub fn describe_storage_integration<'py>(
&self,
py: Python<'py>,
name: String,
namespace_path: Option<Vec<String>>,
) -> PyResult<Bound<'py, PyAny>> {
let inner = self.get_inner()?.clone();
future_into_py(py, async move {
let info = inner
.describe_storage_integration(name, &namespace_path.unwrap_or_default())
.await
.infer_error()?;
serde_json::to_string(&info).map_err(|error| PyValueError::new_err(error.to_string()))
})
}
#[pyo3(signature = (*, namespace_path=None, page_token=None, page_limit=None))]
pub fn list_storage_integrations(
&self,
namespace_path: Option<Vec<String>>,
page_token: Option<String>,
page_limit: Option<u32>,
) -> PyResult<crate::listing::NameListing> {
Ok(crate::listing::NameListing::new(
self.get_inner()?.list_storage_integrations(
&namespace_path.unwrap_or_default(),
crate::listing::options(page_token, page_limit),
),
))
}
#[pyo3(signature = (name, namespace_path=None))]
pub fn drop_storage_integration<'py>(
&self,
py: Python<'py>,
name: String,
namespace_path: Option<Vec<String>>,
) -> PyResult<Bound<'py, PyAny>> {
let inner = self.get_inner()?.clone();
future_into_py(py, async move {
inner
.drop_storage_integration(name, &namespace_path.unwrap_or_default())
.await
.infer_error()
})
}
#[pyo3(signature = (name, value, namespace_path=None))]
pub fn create_secret(
self_: PyRef<'_, Self>,
@@ -1050,6 +1191,79 @@ impl Connection {
))
}
/// Create a property graph from its definition's JSON, and return its
/// description's JSON. The Python layer names the fields; the JSON keeps
/// the binding free of classes kept in step with the Rust structs.
#[pyo3(signature = (name, definition_json, namespace_path=None))]
pub fn create_property_graph(
self_: PyRef<'_, Self>,
name: String,
definition_json: String,
namespace_path: Option<Vec<String>>,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.get_inner()?.clone();
let namespace_path = namespace_path.unwrap_or_default();
future_into_py(self_.py(), async move {
let definition = PropertyGraphDefinition::from_json(&definition_json).infer_error()?;
inner
.create_property_graph(name, &definition, &namespace_path)
.await
.infer_error()?
.to_json()
.infer_error()
})
}
/// The JSON description of the property graph named `name`.
#[pyo3(signature = (name, namespace_path=None))]
pub fn describe_property_graph(
self_: PyRef<'_, Self>,
name: String,
namespace_path: Option<Vec<String>>,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.get_inner()?.clone();
let namespace_path = namespace_path.unwrap_or_default();
future_into_py(self_.py(), async move {
inner
.describe_property_graph(name, &namespace_path)
.await
.infer_error()?
.to_json()
.infer_error()
})
}
#[pyo3(signature = (name, namespace_path=None))]
pub fn drop_property_graph(
self_: PyRef<'_, Self>,
name: String,
namespace_path: Option<Vec<String>>,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.get_inner()?.clone();
let namespace_path = namespace_path.unwrap_or_default();
future_into_py(self_.py(), async move {
inner
.drop_property_graph(name, &namespace_path)
.await
.infer_error()
})
}
#[pyo3(signature = (namespace_path=None, *, page_token=None, page_limit=None))]
pub fn list_property_graphs(
&self,
namespace_path: Option<Vec<String>>,
page_token: Option<String>,
page_limit: Option<u32>,
) -> PyResult<crate::listing::NameListing> {
Ok(crate::listing::NameListing::new(
self.get_inner()?.list_property_graphs(
&namespace_path.unwrap_or_default(),
crate::listing::options(page_token, page_limit),
),
))
}
#[pyo3(signature = (*, page_token=None, page_limit=None))]
pub fn list_jobs(
&self,
@@ -1062,6 +1276,14 @@ impl Connection {
))
}
pub fn list_gpu_classes(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.get_inner()?.clone();
future_into_py(self_.py(), async move {
let classes = inner.list_gpu_classes().await.infer_error()?;
Ok(classes.into_iter().map(GpuClass::from).collect::<Vec<_>>())
})
}
pub fn cancel_job(self_: PyRef<'_, Self>, job_id: String) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.get_inner()?.clone();
future_into_py(self_.py(), async move {
+498 -14
View File
@@ -2,13 +2,13 @@
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
use pyo3::{
PyErr, PyResult, Python,
Bound, PyAny, PyErr, PyResult, Python,
exceptions::{PyIOError, PyNotImplementedError, PyOSError, PyRuntimeError, PyValueError},
intern,
types::{PyAnyMethods, PyNone},
};
use lancedb::error::Error as LanceError;
use lancedb::error::{Error as LanceError, HttpErrorDetails, RemoteErrorMetadata};
pub trait PythonErrorExt<T> {
/// Convert to a python error based on the Lance error type
@@ -28,12 +28,67 @@ impl<T> PythonErrorExt<T> for std::result::Result<T, LanceError> {
Err(err) => match err {
LanceError::InvalidInput { .. }
| LanceError::InvalidTableName { .. }
| LanceError::TableNotFound { .. }
| LanceError::NotAMaterializedView { .. }
| LanceError::Schema { .. }
| LanceError::DatabaseNotFound { .. }
| LanceError::DatabaseAlreadyExists { .. }
| LanceError::TableAlreadyExists { .. } => self.value_error(),
LanceError::TableNotFound { source, .. } => {
let Some(
request_error @ LanceError::Http {
request_id,
status_code,
source: http_source,
},
) = source.downcast_ref::<LanceError>()
else {
return self.value_error();
};
Python::attach(|py| {
let status_code = status_code.map(|s| s.as_u16());
let metadata = request_error.remote_error_metadata();
let details = request_error.http_error_details();
let py_err = if details.is_some()
|| metadata.is_some_and(|metadata| metadata.error_code.is_some())
{
new_py_http_error(
py,
http_source.to_string(),
request_id,
status_code,
details,
metadata,
false,
)?
} else {
let cls = py
.import(intern!(py, "lancedb.remote.errors"))?
.getattr(intern!(py, "TableNotFoundError"))?;
let error = cls.call1((err.to_string(), request_id, status_code))?;
error.setattr(
"job_id",
metadata.and_then(|value| value.job_id.as_deref()),
)?;
error.setattr(
"job_request_id",
metadata.and_then(|value| value.job_request_id.as_deref()),
)?;
error
};
let cause =
http_from_rust_error(py, source.as_ref(), request_id, status_code)?;
py_err.setattr(intern!(py, "__cause__"), cause)?;
Err(PyErr::from_value(py_err))
})
}
LanceError::ColumnNotFound { .. } | LanceError::FieldNotFound { .. } => {
Python::attach(|py| {
let cls = py
.import(intern!(py, "lancedb.exceptions"))?
.getattr(intern!(py, "ColumnNotFoundError"))?;
Err(PyErr::from_value(cls.call1((err.to_string(),))?))
})
}
LanceError::CreateDir { .. } => self.os_error(),
LanceError::ObjectStore { .. } => Err(PyIOError::new_err(err.to_string())),
LanceError::NotSupported { .. } => {
@@ -44,15 +99,23 @@ impl<T> PythonErrorExt<T> for std::result::Result<T, LanceError> {
source,
status_code,
} => Python::attach(|py| {
let message = err.to_string();
let http_err_cls = py
.import(intern!(py, "lancedb.remote.errors"))?
.getattr(intern!(py, "HttpError"))?;
let err = http_err_cls.call1((
let message = if err
.remote_error_metadata()
.is_some_and(|metadata| metadata.error_code.is_some())
{
source.to_string()
} else {
err.to_string()
};
let err = new_py_http_error(
py,
message,
request_id,
status_code.map(|s| s.as_u16()),
))?;
err.http_error_details(),
err.remote_error_metadata(),
is_transport_error(source.as_ref()),
)?;
if let Some(cause) = source.source() {
// The HTTP error already includes the first cause. But
@@ -105,11 +168,68 @@ impl<T> PythonErrorExt<T> for std::result::Result<T, LanceError> {
err.setattr(intern!(py, "__cause__"), cause_err)?;
Err(PyErr::from_value(err))
}),
LanceError::JobFailed { .. } => Python::attach(|py| {
LanceError::ResponseInterrupted {
request_id,
batches,
rows,
table_version,
source,
} => Python::attach(|py| {
let error = py
.import(intern!(py, "lancedb.remote.errors"))?
.getattr(intern!(py, "ResponseInterruptedError"))?
.call1((
err.to_string(),
request_id,
*batches,
*rows,
*table_version,
is_transport_error(&**source),
))?;
let cause = http_from_rust_error(py, &**source, request_id, None)?;
error.setattr(intern!(py, "__cause__"), cause)?;
Err(PyErr::from_value(error))
}),
LanceError::Sql {
message,
request_id,
grpc_code,
metadata,
} => Python::attach(|py| {
Err(PyErr::from_value(new_py_sql_error(
py, message, request_id, *grpc_code, metadata,
)?))
}),
LanceError::JobFailed { job_id, failure } => Python::attach(|py| {
let cls = py
.import(intern!(py, "lancedb.exceptions"))?
.getattr(intern!(py, "JobFailedError"))?;
Err(PyErr::from_value(cls.call1((err.to_string(),))?))
let sql_source = match failure.source.as_deref() {
Some(LanceError::Sql {
message,
request_id,
grpc_code,
metadata,
}) => Some((
new_py_sql_error(py, message, request_id, *grpc_code, metadata)?,
request_id.as_str(),
metadata.job_request_id.as_deref(),
)),
_ => None,
};
let error = cls.call1((
err.to_string(),
job_id.clone(),
failure.sql_job_id.clone(),
sql_source.as_ref().map(|(_, request_id, _)| *request_id),
sql_source
.as_ref()
.and_then(|(_, _, request_id)| *request_id),
))?;
if let Some((cause, _, _)) = sql_source {
error.setattr(intern!(py, "__cause__"), cause)?;
}
Err(PyErr::from_value(error))
}),
LanceError::JobCancelled { .. } => Python::attach(|py| {
let cls = py
@@ -143,13 +263,24 @@ impl<T> PythonErrorExt<T> for std::result::Result<T, LanceError> {
fn http_from_rust_error(
py: Python<'_>,
err: &dyn std::error::Error,
err: &(dyn std::error::Error + 'static),
request_id: &str,
status_code: Option<u16>,
) -> PyResult<PyErr> {
let message = err.to_string();
let http_err_cls = py.import("lancedb.remote.errors")?.getattr("HttpError")?;
let py_err = http_err_cls.call1((message, request_id, status_code))?;
let details = err
.downcast_ref::<LanceError>()
.and_then(LanceError::http_error_details);
let py_err = new_py_http_error(
py,
message,
request_id,
status_code,
details,
err.downcast_ref::<LanceError>()
.and_then(LanceError::remote_error_metadata),
is_transport_error(err),
)?;
// Reset the traceback since it doesn't provide additional information.
let py_err = py_err.call_method1(intern!(py, "with_traceback"), (PyNone::get(py),))?;
@@ -161,3 +292,356 @@ fn http_from_rust_error(
Ok(PyErr::from_value(py_err))
}
fn new_py_http_error<'py>(
py: Python<'py>,
message: String,
request_id: &str,
status_code: Option<u16>,
details: Option<&HttpErrorDetails>,
metadata: Option<&RemoteErrorMetadata>,
is_transport_error: bool,
) -> PyResult<Bound<'py, PyAny>> {
let error_code = metadata
.and_then(|metadata| metadata.error_code.as_deref())
.or_else(|| details.map(|details| details.error_code.as_str()));
let resource_kind = details.map(|details| details.resource_kind.as_str());
let resource_name = details.map(|details| details.resource_name.as_str());
let namespace_path = details.map(|details| details.namespace_path.clone());
py.import("lancedb.remote.errors")?
.getattr("HttpError")?
.call1((
message,
request_id,
status_code,
error_code,
resource_kind,
resource_name,
namespace_path,
is_transport_error,
metadata.and_then(|metadata| metadata.job_id.as_deref()),
metadata.and_then(|metadata| metadata.job_request_id.as_deref()),
))
}
fn new_py_sql_error<'py>(
py: Python<'py>,
message: &str,
request_id: &str,
grpc_code: i32,
metadata: &RemoteErrorMetadata,
) -> PyResult<Bound<'py, PyAny>> {
if sql_has_resource_error(metadata, grpc_code) {
return new_py_sql_resource_error(py, message, request_id, grpc_code, metadata);
}
py.import("lancedb.remote.errors")?
.getattr("SqlError")?
.call1((
message,
request_id,
grpc_code,
metadata.error_code.as_deref(),
metadata.job_id.as_deref(),
metadata.job_request_id.as_deref(),
))
}
fn new_py_sql_resource_error<'py>(
py: Python<'py>,
message: &str,
request_id: &str,
grpc_code: i32,
metadata: &RemoteErrorMetadata,
) -> PyResult<Bound<'py, PyAny>> {
let resource = metadata.resource.as_ref().unwrap();
py.import("lancedb.remote.errors")?
.getattr("HttpError")?
.call1((
message,
request_id,
grpc_code_to_http_status(grpc_code),
metadata.error_code.as_deref(),
resource.kind.as_str(),
resource.name.as_str(),
resource.namespace_path.clone(),
false,
metadata.job_id.as_deref(),
metadata.job_request_id.as_deref(),
))
}
fn sql_has_resource_error(metadata: &RemoteErrorMetadata, grpc_code: i32) -> bool {
metadata.resource.is_some()
&& matches!(
(metadata.error_code.as_deref(), grpc_code),
// These are gRPC status codes, not HTTP status codes.
(Some("not_found"), 5) | (Some("already_exists"), 6)
)
}
fn grpc_code_to_http_status(grpc_code: i32) -> Option<u16> {
match grpc_code {
3 => Some(400),
5 => Some(404),
6 => Some(409),
7 => Some(403),
9 => Some(400),
12 => Some(501),
_ => None,
}
}
// Preserve the typed transport classification across the Python boundary.
// A missing status code alone also covers malformed job responses, which
// waiting longer cannot repair.
fn is_transport_error(err: &(dyn std::error::Error + 'static)) -> bool {
if let Some(error) = err.downcast_ref::<reqwest::Error>() {
return error.is_connect()
|| error.is_timeout()
|| error.is_request()
|| error.is_body()
|| error.is_decode();
}
err.source().is_some_and(is_transport_error)
}
#[cfg(test)]
mod tests {
use std::ffi::CString;
use std::sync::{Arc, Once};
use lancedb::error::{JobFailure, RemoteResourceIdentity};
use pyo3::types::{PyAnyMethods, PyModule};
use super::*;
static INSTALL_PYTHON_ERROR_MODULES: Once = Once::new();
fn install_python_error_modules(py: Python<'_>) -> PyResult<()> {
// Load the checked-in error classes without requiring an installed wheel.
// The namespace exception is only a base for an unrelated remote class.
PyModule::from_code(
py,
c"import sys\n\nimport types\n\n\
lancedb = types.ModuleType('lancedb')\n\
lancedb.__path__ = []\n\
lancedb_remote = types.ModuleType('lancedb.remote')\n\
lancedb_remote.__path__ = []\n\
lancedb.remote = lancedb_remote\n\
namespace = types.ModuleType('lance_namespace')\n\
namespace_errors = types.ModuleType('lance_namespace.errors')\n\
namespace_errors.TableNotFoundError = RuntimeError\n\
namespace.errors = namespace_errors\n\
sys.modules['lancedb'] = lancedb\n\
sys.modules['lancedb.remote'] = lancedb_remote\n\
sys.modules['lance_namespace'] = namespace\n\
sys.modules['lance_namespace.errors'] = namespace_errors",
c"error_test_bootstrap.py",
c"lancedb_error_test_bootstrap",
)?;
let exceptions_code =
CString::new(include_str!("../../python/python/lancedb/exceptions.py")).unwrap();
let exceptions = PyModule::from_code(
py,
&exceptions_code,
c"exceptions.py",
c"lancedb.exceptions",
)?;
let lancedb = py.import("lancedb")?;
lancedb.setattr("exceptions", &exceptions)?;
py.import("sys")?
.getattr("modules")?
.set_item("lancedb.exceptions", &exceptions)?;
let remote_errors_code =
CString::new(include_str!("../../python/python/lancedb/remote/errors.py")).unwrap();
let remote_errors = PyModule::from_code(
py,
&remote_errors_code,
c"remote/errors.py",
c"lancedb.remote.errors",
)?;
lancedb
.getattr("remote")?
.setattr("errors", &remote_errors)?;
py.import("sys")?
.getattr("modules")?
.set_item("lancedb.remote.errors", &remote_errors)?;
Ok(())
}
fn ensure_python_error_modules() {
Python::initialize();
// Once waits without holding the GIL; only its one-time closure attaches.
INSTALL_PYTHON_ERROR_MODULES.call_once(|| {
Python::attach(install_python_error_modules).unwrap();
});
}
#[test]
fn generic_job_failure_retains_the_named_resource_as_its_cause() {
ensure_python_error_modules();
let source = LanceError::Sql {
message: "Function 'missing' was not found".into(),
request_id: "current-request".into(),
grpc_code: 5,
metadata: Box::new({
let mut metadata = RemoteErrorMetadata::default();
metadata.error_code = Some("not_found".into());
metadata.job_id = Some("outer-job".into());
metadata.job_request_id = Some("worker-request".into());
metadata.resource = Some(RemoteResourceIdentity::new(
"function",
"missing",
vec!["ns".into()],
));
metadata
}),
};
let error = LanceError::JobFailed {
job_id: Some("outer-job".into()),
failure: Box::new(JobFailure {
message: Some("Function 'missing' was not found".into()),
traceback: None,
sql_job_id: Some("outer-job".into()),
source: Some(Arc::new(source)),
..Default::default()
}),
};
let py_err = Python::attach(|_| {
let result: std::result::Result<(), LanceError> = Err(error);
result.infer_error().unwrap_err()
});
Python::attach(|py| {
let value = py_err.value(py);
let job_failed = py
.import("lancedb.exceptions")
.unwrap()
.getattr("JobFailedError")
.unwrap();
assert!(value.is_instance(&job_failed).unwrap(), "{py_err:?}");
let cause = value.getattr("__cause__").unwrap();
let function_not_found = py
.import("lancedb.remote.errors")
.unwrap()
.getattr("FunctionNotFoundError")
.unwrap();
assert!(
cause.is_instance(&function_not_found).unwrap(),
"{py_err:?}"
);
assert_eq!(
cause
.getattr("error_code")
.unwrap()
.extract::<String>()
.unwrap(),
"not_found"
);
assert_eq!(
cause
.getattr("resource_kind")
.unwrap()
.extract::<String>()
.unwrap(),
"function"
);
assert_eq!(
cause
.getattr("resource_name")
.unwrap()
.extract::<String>()
.unwrap(),
"missing"
);
assert_eq!(
cause
.getattr("namespace_path")
.unwrap()
.extract::<Vec<String>>()
.unwrap(),
["ns"]
);
assert_eq!(
cause
.getattr("status_code")
.unwrap()
.extract::<u16>()
.unwrap(),
404
);
assert_eq!(
cause
.getattr("request_id")
.unwrap()
.extract::<String>()
.unwrap(),
"current-request"
);
assert_eq!(
cause
.getattr("job_id")
.unwrap()
.extract::<String>()
.unwrap(),
"outer-job"
);
assert_eq!(
cause
.getattr("job_request_id")
.unwrap()
.extract::<String>()
.unwrap(),
"worker-request"
);
});
}
#[test]
fn direct_catalog_lookup_is_raised_as_the_named_resource_error() {
ensure_python_error_modules();
for (kind, name, namespace_path, exception) in [
(
"function",
"missing",
vec!["ns".into()],
"FunctionNotFoundError",
),
("namespace", "ns", Vec::new(), "NamespaceNotFoundError"),
] {
let mut metadata = RemoteErrorMetadata::default();
metadata.error_code = Some("not_found".into());
metadata.resource = Some(RemoteResourceIdentity::new(kind, name, namespace_path));
let error = LanceError::Sql {
message: format!("{kind} '{name}' was not found"),
request_id: "current-request".into(),
grpc_code: 5,
metadata: Box::new(metadata),
};
let py_err = Python::attach(|_| {
let result: std::result::Result<(), LanceError> = Err(error);
result.infer_error().unwrap_err()
});
Python::attach(|py| {
let value = py_err.value(py);
let class = py
.import("lancedb.remote.errors")
.unwrap()
.getattr(exception)
.unwrap();
assert!(value.is_instance(&class).unwrap(), "{py_err:?}");
assert_eq!(
value
.getattr("resource_name")
.unwrap()
.extract::<String>()
.unwrap(),
name
);
});
}
}
}
+99 -3
View File
@@ -8,7 +8,9 @@ use lancedb::index::vector::{
};
use lancedb::index::{
Index as LanceDbIndex,
scalar::{BTreeIndexBuilder, DocumentGranularity, FmIndexBuilder, FtsIndexBuilder},
scalar::{
BTreeIndexBuilder, DocumentGranularity, FmIndexBuilder, FtsIndexBuilder, NGramIndexBuilder,
},
};
use pyo3::IntoPyObject;
use pyo3::types::PyStringMethods;
@@ -33,6 +35,80 @@ pub fn class_name(ob: &'_ Bound<'_, PyAny>) -> PyResult<String> {
}
}
/// Code-analyzer options shared by `FTS` and `tokenize`.
#[derive(Default)]
pub struct CodeAnalyzerOptions {
pub analyzer: Option<String>,
pub split_identifiers: Option<bool>,
pub split_on_numerics: Option<bool>,
pub preserve_original: Option<bool>,
pub index_operators: Option<bool>,
}
impl CodeAnalyzerOptions {
/// Check the options against the requested base tokenizer and return the
/// base tokenizer to use. `analyzer="code"` selects the code tokenizer when
/// `base_tokenizer` is left at its default of `"simple"`.
pub fn resolve_base_tokenizer(&self, base_tokenizer: String) -> PyResult<String> {
let uses_code = match self.analyzer.as_deref() {
None | Some("text") => base_tokenizer == "code",
Some("code") => true,
Some(other) => {
return Err(PyValueError::new_err(format!(
"analyzer must be 'text' or 'code', got '{other}'"
)));
}
};
match self.analyzer.as_deref() {
Some("text") if base_tokenizer == "code" => {
return Err(PyValueError::new_err(
"base_tokenizer='code' requires analyzer='code'",
));
}
Some("code") if base_tokenizer != "code" && base_tokenizer != "simple" => {
return Err(PyValueError::new_err(format!(
"analyzer='code' requires base_tokenizer='code', got '{base_tokenizer}'"
)));
}
_ => {}
}
let flags = [
self.split_identifiers,
self.split_on_numerics,
self.preserve_original,
self.index_operators,
];
if !uses_code && flags.into_iter().flatten().any(|value| value) {
return Err(PyValueError::new_err(
"split_identifiers, split_on_numerics, preserve_original and \
index_operators require analyzer='code'",
));
}
Ok(if uses_code {
"code".to_string()
} else {
base_tokenizer
})
}
/// Apply the explicit flags on top of the tokenizer defaults.
pub fn apply(&self, mut params: FtsIndexBuilder) -> FtsIndexBuilder {
if let Some(value) = self.split_identifiers {
params = params.split_identifiers(value);
}
if let Some(value) = self.split_on_numerics {
params = params.split_on_numerics(value);
}
if let Some(value) = self.preserve_original {
params = params.preserve_original(value);
}
if let Some(value) = self.index_operators {
params = params.index_operators(value);
}
params
}
}
pub fn extract_index_params(source: &Option<Bound<'_, PyAny>>) -> PyResult<LanceDbIndex> {
if let Some(source) = source {
match class_name(source)?.as_str() {
@@ -40,10 +116,19 @@ pub fn extract_index_params(source: &Option<Bound<'_, PyAny>>) -> PyResult<Lance
"Bitmap" => Ok(LanceDbIndex::Bitmap(Default::default())),
"LabelList" => Ok(LanceDbIndex::LabelList(Default::default())),
"Fm" => Ok(LanceDbIndex::Fm(FmIndexBuilder::default())),
"NGram" => Ok(LanceDbIndex::NGram(NGramIndexBuilder::default())),
"FTS" => {
let params = source.extract::<FtsParams>()?;
let code_options = CodeAnalyzerOptions {
analyzer: params.analyzer,
split_identifiers: params.split_identifiers,
split_on_numerics: params.split_on_numerics,
preserve_original: params.preserve_original,
index_operators: params.index_operators,
};
let base_tokenizer = code_options.resolve_base_tokenizer(params.base_tokenizer)?;
let mut inner_opts = FtsIndexBuilder::default()
.base_tokenizer(params.base_tokenizer)
.base_tokenizer(base_tokenizer)
.language(&params.language)
.map_err(|_| {
PyValueError::new_err(format!(
@@ -75,6 +160,7 @@ pub fn extract_index_params(source: &Option<Bound<'_, PyAny>>) -> PyResult<Lance
if let Some(num_workers) = params.num_workers {
inner_opts = inner_opts.num_workers(num_workers);
}
let inner_opts = code_options.apply(inner_opts);
let inner_opts = inner_opts
.block_size(params.block_size)
.map_err(|err| PyValueError::new_err(err.to_string()))?;
@@ -205,7 +291,7 @@ pub fn extract_index_params(source: &Option<Bound<'_, PyAny>>) -> PyResult<Lance
Ok(LanceDbIndex::IvfHnswFlat(hnsw_flat_builder))
}
not_supported => Err(PyValueError::new_err(format!(
"Invalid index type '{}'. Must be one of BTree, Bitmap, LabelList, Fm, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat",
"Invalid index type '{}'. Must be one of BTree, Bitmap, LabelList, Fm, NGram, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat",
not_supported
))),
}
@@ -232,6 +318,11 @@ struct FtsParams {
memory_limit: Option<u64>,
num_workers: Option<usize>,
document_granularity: String,
analyzer: Option<String>,
split_identifiers: Option<bool>,
split_on_numerics: Option<bool>,
preserve_original: Option<bool>,
index_operators: Option<bool>,
}
#[derive(FromPyObject)]
@@ -493,6 +584,11 @@ mod tests {
memory_limit = 2048
num_workers = 7
document_granularity = 'row'
analyzer = None
split_identifiers = None
split_on_numerics = None
preserve_original = None
index_operators = None
config = FTS()",
None,
+75 -5
View File
@@ -10,7 +10,7 @@ use arrow::{
};
use lancedb::job::JobEventsRequest;
use pyo3::{
Bound, PyAny, PyRef, PyResult, Python,
Bound, Py, PyAny, PyRef, PyResult, Python,
exceptions::PyValueError,
pyclass, pymethods,
types::{PyAnyMethods, PyDict, PyDictMethods},
@@ -94,10 +94,30 @@ impl Job {
)
}
pub fn wait(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
#[pyo3(signature = (progress=None))]
pub fn wait(self_: PyRef<'_, Self>, progress: Option<Py<PyAny>>) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner.clone();
future_into_py(self_.py(), async move {
let result = inner.wait().await.infer_error()?;
let result = if let Some(progress) = progress {
let observer = move |description: &lancedb::database::JobDescription| {
Python::attach(|py| {
let snapshot = description.progress_snapshot();
let callback_result: PyResult<()> = (|| {
let raw = snapshot.to_string();
let parsed = parse_json_payload(py, Some(&raw))?
.ok_or_else(|| PyValueError::new_err("missing progress"))?;
progress.bind(py).call1((parsed,))?;
Ok(())
})();
if let Err(error) = callback_result {
log::warn!("job progress callback error: {error}");
}
});
};
inner.wait_with_progress(observer).await.infer_error()?
} else {
inner.wait().await.infer_error()?
};
result
.map_err(|message| lancedb::Error::Runtime { message })
.infer_error()
@@ -164,6 +184,8 @@ pub struct JobInfo {
job_type: String,
state: String,
created_at_millis: i64,
_progress_json: Option<String>,
paused: bool,
}
#[pymethods]
@@ -174,16 +196,32 @@ impl JobInfo {
self.job_id, self.table, self.job_type, self.state, self.created_at_millis
)
}
/// Structured progress for job types that report it. Missing fields are
/// unknown, not zero.
#[getter]
fn progress<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyAny>>> {
parse_json_payload(py, self._progress_json.as_deref())
}
/// Whether an operator has parked this job.
#[getter]
fn paused(&self) -> bool {
self.paused
}
}
impl From<lancedb::database::JobInfo> for JobInfo {
fn from(info: lancedb::database::JobInfo) -> Self {
let progress = info.progress_snapshot().to_string();
Self {
job_id: info.job_id,
table: info.table,
job_type: info.job_type,
state: info.state,
created_at_millis: info.created_at_millis,
_progress_json: Some(progress),
paused: info.paused,
}
}
}
@@ -194,15 +232,35 @@ impl From<lancedb::database::JobInfo> for JobInfo {
pub struct JobFailureInfo {
phase: Option<String>,
message: Option<String>,
/// User-code traceback, possibly truncated by the server.
traceback: Option<String>,
retryable: Option<bool>,
sql_job_id: Option<String>,
}
#[pymethods]
impl JobFailureInfo {
fn __repr__(&self) -> String {
let phase = self
.phase
.as_ref()
.map_or_else(|| "None".to_string(), |value| format!("{value:?}"));
let message = self
.message
.as_ref()
.map_or_else(|| "None".to_string(), |value| format!("{value:?}"));
let retryable = match self.retryable {
Some(true) => "True",
Some(false) => "False",
None => "None",
};
let sql_job_id = self
.sql_job_id
.as_ref()
.map_or_else(|| "None".to_string(), |value| format!("{value:?}"));
format!(
"JobFailureInfo(phase={:?}, message={:?}, retryable={:?})",
self.phase, self.message, self.retryable
"JobFailureInfo(phase={phase}, message={message}, retryable={retryable}, \
sql_job_id={sql_job_id})"
)
}
}
@@ -219,6 +277,7 @@ pub struct JobDescription {
_spec_json: Option<String>,
/// Internal: the wire form behind the `result` property.
_result_json: Option<String>,
_progress_json: Option<String>,
failure: Option<JobFailureInfo>,
}
@@ -236,6 +295,13 @@ impl JobDescription {
parse_json_payload(py, self._result_json.as_deref())
}
/// Structured progress snapshot. Lifecycle and queue fields are present
/// even when a job type or older server supplies no counters.
#[getter]
fn progress<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyAny>>> {
parse_json_payload(py, self._progress_json.as_deref())
}
fn __repr__(&self, py: Python<'_>) -> PyResult<String> {
let mut fields = vec![
format!("job_id={:?}", self.job_id),
@@ -263,6 +329,7 @@ impl JobDescription {
impl From<lancedb::database::JobDescription> for JobDescription {
fn from(description: lancedb::database::JobDescription) -> Self {
let progress_json = description.progress_snapshot().to_string();
Self {
job_id: description.job_id,
job_type: description.job_type,
@@ -273,10 +340,13 @@ impl From<lancedb::database::JobDescription> for JobDescription {
.result
.filter(|result| !result.is_null())
.map(|result| result.to_string()),
_progress_json: Some(progress_json),
failure: description.failure.map(|failure| JobFailureInfo {
phase: failure.phase,
message: failure.message,
traceback: failure.traceback,
retryable: failure.retryable,
sql_job_id: failure.sql_job_id,
}),
}
}
+22
View File
@@ -58,13 +58,31 @@ fn shutdown_runtime(py: Python<'_>) {
py.detach(|| runtime::shutdown(std::time::Duration::from_secs(5)));
}
#[pyfunction]
fn _doc_url(campaign: &str) -> PyResult<String> {
let link = lancedb::docs::DocLink::from_campaign(campaign).ok_or_else(|| {
pyo3::exceptions::PyValueError::new_err(format!("unknown doc link campaign: {campaign}"))
})?;
Ok(link.url())
}
#[pyfunction]
fn _append_doc_url(message: &str, campaign: &str) -> PyResult<String> {
let link = lancedb::docs::DocLink::from_campaign(campaign).ok_or_else(|| {
pyo3::exceptions::PyValueError::new_err(format!("unknown doc link campaign: {campaign}"))
})?;
Ok(link.append_to(message))
}
#[pymodule]
pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
lancedb::docs::set_sdk_ident("python", env!("CARGO_PKG_VERSION"));
let env = Env::new()
.filter_or("LANCEDB_LOG", "warn")
.write_style("LANCEDB_LOG_STYLE");
env_logger::init_from_env(env);
m.add_class::<Connection>()?;
m.add_class::<connection::GpuClass>()?;
m.add_class::<catalog::Catalog>()?;
m.add_class::<catalog::DatabaseNames>()?;
m.add_class::<listing::NameListing>()?;
@@ -127,10 +145,14 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(table::tokenize, m)?)?;
m.add_function(wrap_pyfunction!(permutation::async_permutation_builder, m)?)?;
m.add_function(wrap_pyfunction!(util::validate_table_name, m)?)?;
m.add_function(wrap_pyfunction!(util::validate_function_retry_policy, m)?)?;
m.add_function(wrap_pyfunction!(util::parse_field_path, m)?)?;
m.add_function(wrap_pyfunction!(query::fts_query_to_json, m)?)?;
m.add_function(wrap_pyfunction!(expr_col, m)?)?;
m.add_function(wrap_pyfunction!(expr_lit, m)?)?;
m.add_function(wrap_pyfunction!(expr_func, m)?)?;
m.add_function(wrap_pyfunction!(_doc_url, m)?)?;
m.add_function(wrap_pyfunction!(_append_doc_url, m)?)?;
m.add("__version__", env!("CARGO_PKG_VERSION"))?;
m.add(
"_experimental_functions_enabled",
+5 -1
View File
@@ -70,7 +70,11 @@ fn get_dict_with_model_dump_class(py: Python<'_>) -> PyResult<Bound<'_, PyAny>>
py.run(
c"class DictWithModelDump(dict):
def model_dump(self):
return dict(self)",
return dict(self)
def __getattr__(self, name):
if name.startswith('__'):
raise AttributeError(name)
return self.get(name)",
None,
Some(&locals),
)?;
+2 -2
View File
@@ -67,7 +67,7 @@ impl TryFrom<PyOAuthConfig> for OAuthConfig {
}
OAuthFlow::AuthorizationCode(options)
}
"device_code" => OAuthFlow::DeviceCode,
"device_code" => OAuthFlow::DeviceCode(Default::default()),
"azure_managed_identity" => OAuthFlow::AzureManagedIdentity {
client_id: py.managed_identity_client_id,
},
@@ -327,7 +327,7 @@ mod tests {
fn test_device_code_conversion() {
let config = base_config();
let converted = OAuthConfig::try_from(config).unwrap();
assert!(matches!(converted.flow, OAuthFlow::DeviceCode));
assert!(matches!(converted.flow, OAuthFlow::DeviceCode(options) if !options.use_pkce));
}
#[test]
+18
View File
@@ -16,6 +16,7 @@ use arrow::array::make_array;
use arrow::pyarrow::FromPyArrow;
use arrow::pyarrow::IntoPyArrow;
use arrow::pyarrow::ToPyArrow;
use lancedb::ApproxMode;
use lancedb::index::scalar::{
BooleanQuery, BoostQuery, CombinedFieldsQuery, DocumentGranularity, FtsQuery,
FullTextSearchQuery, MatchQuery, MultiMatchQuery, Occur, Operator, PhraseQuery,
@@ -354,6 +355,7 @@ pub struct PyQueryRequest {
pub limit: Option<usize>,
pub offset: Option<usize>,
pub take_offsets: Option<Vec<u64>>,
pub take_row_ids: Option<Vec<u64>>,
pub filter: Option<PyQueryFilter>,
pub full_text_search: Option<PyLanceDB<FtsQuery>>,
pub select: PySelect,
@@ -370,6 +372,7 @@ pub struct PyQueryRequest {
pub lower_bound: Option<f32>,
pub upper_bound: Option<f32>,
pub ef: Option<usize>,
pub approx_mode: Option<String>,
pub refine_factor: Option<u32>,
pub distance_type: Option<String>,
pub bypass_vector_index: Option<bool>,
@@ -385,6 +388,7 @@ impl From<AnyQuery> for PyQueryRequest {
limit: query_request.limit,
offset: query_request.offset,
take_offsets: query_request.take_offsets,
take_row_ids: query_request.take_row_ids,
filter: query_request.filter.map(PyQueryFilter),
full_text_search: query_request
.full_text_search
@@ -403,6 +407,7 @@ impl From<AnyQuery> for PyQueryRequest {
lower_bound: None,
upper_bound: None,
ef: None,
approx_mode: None,
refine_factor: None,
distance_type: None,
bypass_vector_index: None,
@@ -416,6 +421,7 @@ impl From<AnyQuery> for PyQueryRequest {
limit: vector_query.base.limit,
offset: vector_query.base.offset,
take_offsets: vector_query.base.take_offsets,
take_row_ids: vector_query.base.take_row_ids,
filter: vector_query.base.filter.map(PyQueryFilter),
full_text_search: None,
select_source_columns: PySelect::source_columns(&vector_query.base.select),
@@ -432,6 +438,7 @@ impl From<AnyQuery> for PyQueryRequest {
lower_bound: vector_query.lower_bound,
upper_bound: vector_query.upper_bound,
ef: vector_query.ef,
approx_mode: vector_query.approx_mode.map(|m| m.to_string()),
refine_factor: vector_query.refine_factor,
distance_type: vector_query.distance_type.map(|d| d.to_string()),
bypass_vector_index: Some(!vector_query.use_index),
@@ -1069,6 +1076,12 @@ impl VectorQuery {
self.inner = self.inner.clone().ef(ef as usize);
}
pub fn approx_mode(&mut self, approx_mode: String) -> PyResult<()> {
let approx_mode = ApproxMode::try_from(approx_mode.as_str()).infer_error()?;
self.inner = self.inner.clone().approx_mode(approx_mode);
Ok(())
}
pub fn bypass_vector_index(&mut self) {
self.inner = self.inner.clone().bypass_vector_index()
}
@@ -1246,6 +1259,10 @@ impl HybridQuery {
self.inner_vec.ef(ef);
}
pub fn approx_mode(&mut self, approx_mode: String) -> PyResult<()> {
self.inner_vec.approx_mode(approx_mode)
}
pub fn bypass_vector_index(&mut self) {
self.inner_vec.bypass_vector_index();
}
@@ -1291,6 +1308,7 @@ impl HybridQuery {
req.maximum_nprobes = vec_req.maximum_nprobes;
req.search_effort = vec_req.search_effort;
req.ef = vec_req.ef;
req.approx_mode = vec_req.approx_mode;
req.refine_factor = vec_req.refine_factor;
req.lower_bound = vec_req.lower_bound;
req.upper_bound = vec_req.upper_bound;
+323 -40
View File
@@ -14,13 +14,14 @@ use crate::{
connection::Connection,
error::PythonErrorExt,
expr::PyExpr,
index::{IndexConfig, extract_index_params},
index::{CodeAnalyzerOptions, IndexConfig, extract_index_params},
query::{Query, TakeQuery},
table::scannable::PyScannable,
};
use arrow::{
array::{Array, LargeBinaryArray},
array::{Array, LargeBinaryArray, RecordBatchIterator, RecordBatchReader},
datatypes::{DataType, Schema},
ffi_stream::ArrowArrayStreamReader,
pyarrow::{FromPyArrow, PyArrowType, ToPyArrow},
};
use lancedb::blob::{BlobDescriptor, BlobFile, BlobRangeRequest};
@@ -28,8 +29,8 @@ use lancedb::connection::LanceFileVersion;
use lancedb::index::scalar::FtsIndexBuilder;
use lancedb::table::{
AddDataMode, ColumnAlteration, CompactionMode, CompactionOptions, Duration,
FieldMetadataUpdate, FtsToken as LanceDbFtsToken, IndexRemapMode, NewColumnTransform,
OptimizeAction, OptimizeOptions, Ref, Table as LanceDbTable,
FieldMetadataUpdate, FtsToken as LanceDbFtsToken, IndexRemapMode, NewColumnTransform, Ref,
RefreshColumnOptions, Table as LanceDbTable,
};
use lancedb::tokenize as lancedb_tokenize;
use pyo3::{
@@ -41,6 +42,95 @@ use pyo3::{
mod scannable;
/// Keyword arguments shared by `refresh_column` and `refresh_column_async`.
struct RefreshColumnArgs {
where_clause: Option<String>,
batch_size: Option<i64>,
gpu_class: Option<String>,
gpu_count: Option<i64>,
retry_policy: Option<String>,
error_policy: Option<String>,
max_failed_fraction: Option<f64>,
max_failed_rows: Option<i64>,
row_timeout_seconds: Option<f64>,
init_timeout_seconds: Option<f64>,
num_workers: Option<i64>,
max_executor_processes_per_worker: Option<i64>,
}
fn positive_count<T: TryFrom<i64>>(value: Option<i64>, name: &str) -> PyResult<Option<T>> {
value
.map(|v| {
T::try_from(v)
.ok()
.filter(|_| v > 0)
.ok_or_else(|| PyValueError::new_err(format!("{name} must be greater than zero")))
})
.transpose()
}
fn refresh_column_options(args: RefreshColumnArgs) -> PyResult<RefreshColumnOptions> {
let RefreshColumnArgs {
where_clause,
batch_size,
gpu_class,
gpu_count,
retry_policy,
error_policy,
max_failed_fraction,
max_failed_rows,
row_timeout_seconds,
init_timeout_seconds,
num_workers,
max_executor_processes_per_worker,
} = args;
let mut options = RefreshColumnOptions::default();
options.where_clause = where_clause;
options.max_failed_fraction = max_failed_fraction;
options.max_failed_rows = max_failed_rows
.map(u64::try_from)
.transpose()
.map_err(|_| PyValueError::new_err("max_failed_rows must be a non-negative integer"))?;
options.row_timeout_seconds = row_timeout_seconds;
options.init_timeout_seconds = init_timeout_seconds;
options.num_workers = positive_count(num_workers, "num_workers")?;
options.max_executor_processes_per_worker = positive_count(
max_executor_processes_per_worker,
"max_executor_processes_per_worker",
)?;
options.retry_policy = retry_policy
.map(|json| {
serde_json::from_str(&json)
.map_err(|error| PyValueError::new_err(format!("invalid retry_policy: {error}")))
})
.transpose()?;
options.error_policy = error_policy
.map(|value| {
serde_json::from_value(serde_json::Value::String(value))
.map_err(|error| PyValueError::new_err(format!("invalid error_policy: {error}")))
})
.transpose()?;
options.batch_size = batch_size
.map(usize::try_from)
.transpose()
.map_err(|_| PyValueError::new_err("batch_size must be greater than zero"))?;
options.gpu_class = gpu_class;
options.gpu_count = gpu_count
.map(|count| {
u32::try_from(count)
.ok()
.filter(|count| *count > 0)
.ok_or_else(|| {
PyValueError::new_err(
"gpu_count must be a positive integer no greater than u32::MAX",
)
})
})
.transpose()?;
options.validate().infer_error()?;
Ok(options)
}
/// Convert `RTEStats` to a Python dict, preserving the per-table-shard list.
///
/// Deliberately not flattened to a table-level summary: a table is N
@@ -583,27 +673,39 @@ impl From<lancedb::table::RefreshColumnResult> for RefreshColumnResult {
#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)]
#[derive(Clone, Debug)]
pub struct FunctionErrorRecord {
pub attempts: Option<u32>,
pub job_id: String,
pub fragment_id: u64,
pub row_offset: Option<u32>,
pub row_id: Option<u64>,
pub row_address: Option<u64>,
pub column: String,
pub function: String,
pub function_version: String,
pub table_version: u64,
pub error_type: String,
pub error_message: String,
/// User-code traceback, possibly truncated by the server.
pub traceback: Option<String>,
pub created_at_millis: i64,
}
#[pymethods]
impl FunctionErrorRecord {
pub fn __repr__(&self) -> String {
let row_offset = self
.row_offset
.map_or_else(|| "None".to_string(), |value| value.to_string());
let row_address = self
.row_address
.map_or_else(|| "None".to_string(), |value| value.to_string());
format!(
"FunctionErrorRecord(job_id={:?}, fragment_id={}, row_offset={:?}, column={:?}, \
error_type={:?}, error_message={:?})",
"FunctionErrorRecord(job_id={:?}, fragment_id={}, row_offset={}, row_address={}, \
column={:?}, error_type={:?}, error_message={:?})",
self.job_id,
self.fragment_id,
self.row_offset,
row_offset,
row_address,
self.column,
self.error_type,
self.error_message
@@ -614,15 +716,19 @@ impl FunctionErrorRecord {
impl From<lancedb::function::FunctionErrorRecord> for FunctionErrorRecord {
fn from(record: lancedb::function::FunctionErrorRecord) -> Self {
Self {
attempts: record.attempts,
job_id: record.job_id,
fragment_id: record.fragment_id,
row_offset: record.row_offset,
row_id: record.row_id,
row_address: record.row_address,
column: record.column,
function: record.function,
function_version: record.function_version,
table_version: record.table_version,
error_type: record.error_type,
error_message: record.error_message,
traceback: record.traceback,
created_at_millis: record.created_at_millis,
}
}
@@ -993,7 +1099,12 @@ impl From<LanceDbFtsToken> for FtsToken {
ascii_folding = true,
ngram_min_length = 3,
ngram_max_length = 3,
prefix_only = false
prefix_only = false,
analyzer = None,
split_identifiers = None,
split_on_numerics = None,
preserve_original = None,
index_operators = None
))]
#[allow(clippy::too_many_arguments)]
pub fn tokenize(
@@ -1009,7 +1120,20 @@ pub fn tokenize(
ngram_min_length: u32,
ngram_max_length: u32,
prefix_only: bool,
analyzer: Option<String>,
split_identifiers: Option<bool>,
split_on_numerics: Option<bool>,
preserve_original: Option<bool>,
index_operators: Option<bool>,
) -> PyResult<Vec<FtsToken>> {
let code_options = CodeAnalyzerOptions {
analyzer,
split_identifiers,
split_on_numerics,
preserve_original,
index_operators,
};
let base_tokenizer = code_options.resolve_base_tokenizer(base_tokenizer)?;
let mut params = FtsIndexBuilder::default()
.base_tokenizer(base_tokenizer)
.language(&language)
@@ -1032,6 +1156,7 @@ pub fn tokenize(
if let Some(remove_stop_words) = remove_stop_words {
params = params.remove_stop_words(remove_stop_words);
}
let params = code_options.apply(params);
let tokens = lancedb_tokenize(&query, &params).infer_error()?;
Ok(tokens.into_iter().map(FtsToken::from).collect())
}
@@ -1713,6 +1838,10 @@ impl Table {
compaction_options: Option<&Bound<'py, PyDict>>,
) -> PyResult<Bound<'py, PyAny>> {
let inner = self_.inner_ref()?.clone();
let target_specified = compaction_options
.map(|options| options.contains("target_rows_per_fragment"))
.transpose()?
.unwrap_or(false);
let compaction_options = parse_compaction_options(compaction_options)?;
let older_than = if let Some(ms) = cleanup_since_ms {
if ms > i64::MAX as u64 {
@@ -1727,31 +1856,24 @@ impl Table {
None
};
future_into_py(self_.py(), async move {
let compaction_stats = inner
.optimize(OptimizeAction::Compact {
options: compaction_options,
remap_options: None,
})
.await
.infer_error()?
.compaction
.unwrap();
let prune_stats = inner
.optimize(OptimizeAction::Prune {
older_than,
delete_unverified,
error_if_tagged_old_versions: None,
})
.await
.infer_error()?
.prune
.unwrap();
inner
.optimize(lancedb::table::OptimizeAction::Index(
OptimizeOptions::default(),
))
.await
.infer_error()?;
let stats = if inner.as_native().is_some() {
inner
.optimize_full(compaction_options, older_than, None, delete_unverified)
.await
} else {
let mut overrides =
lancedb::table::optimize::CompactionOverrides::try_from(compaction_options)
.infer_error()?;
if !target_specified {
overrides.target_rows_per_fragment = None;
}
inner
.optimize_full_with_overrides(overrides, older_than, None, delete_unverified)
.await
}
.infer_error()?;
let compaction_stats = stats.compaction.unwrap();
let prune_stats = stats.prune.unwrap();
Ok(OptimizeStats {
compaction: CompactionStats {
files_added: compaction_stats.files_added as u64,
@@ -1850,6 +1972,45 @@ impl Table {
})
}
pub fn get_table_overrides(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner_ref()?.clone();
future_into_py(self_.py(), async move {
let overrides = inner.get_table_overrides().await.infer_error()?;
serde_json::to_string(&overrides).map_err(|err| {
PyRuntimeError::new_err(format!("Failed to serialize table overrides: {err}"))
})
})
}
pub fn update_table_overrides<'a>(
self_: PyRef<'a, Self>,
overrides_json: String,
) -> PyResult<Bound<'a, PyAny>> {
let inner = self_.inner_ref()?.clone();
future_into_py(self_.py(), async move {
let overrides = serde_json::from_str(&overrides_json).map_err(|err| {
PyValueError::new_err(format!("Invalid table overrides JSON: {err}"))
})?;
let overrides = inner
.update_table_overrides(overrides)
.await
.infer_error()?;
serde_json::to_string(&overrides).map_err(|err| {
PyRuntimeError::new_err(format!("Failed to serialize table overrides: {err}"))
})
})
}
pub fn reset_table_overrides(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner_ref()?.clone();
future_into_py(self_.py(), async move {
let overrides = inner.reset_table_overrides().await.infer_error()?;
serde_json::to_string(&overrides).map_err(|err| {
PyRuntimeError::new_err(format!("Failed to serialize table overrides: {err}"))
})
})
}
/// Whether a hybrid query on this table has already been refused `_rowid`.
/// Learned from a previous refusal, never probed, so this is free.
///
@@ -1923,7 +2084,7 @@ impl Table {
inner
.as_native()
.ok_or_else(|| lancedb::Error::NotSupported {
message: "uses_v2_manifest_paths is not supported in LanceDB Distributed."
message: "uses_v2_manifest_paths is not supported in LanceDB Enterprise."
.into(),
})
.infer_error()?
@@ -1939,7 +2100,7 @@ impl Table {
inner
.as_native()
.ok_or_else(|| lancedb::Error::NotSupported {
message: "migrate_manifest_paths_v2 is not supported in LanceDB Distributed."
message: "migrate_manifest_paths_v2 is not supported in LanceDB Enterprise."
.into(),
})
.infer_error()?
@@ -1967,6 +2128,29 @@ impl Table {
})
}
pub fn add_columns_from_reader<'a>(
self_: PyRef<'a, Self>,
data: Bound<'a, PyAny>,
) -> PyResult<Bound<'a, PyAny>> {
let reader = ArrowArrayStreamReader::from_pyarrow_bound(&data)?;
let schema = reader.schema();
// Lance's surplus-row check treats trailing empty batches as extra data.
let reader = RecordBatchIterator::new(
reader.filter(|batch| !batch.as_ref().is_ok_and(|batch| batch.num_rows() == 0)),
schema,
);
let inner = self_.inner_ref()?.clone();
future_into_py(self_.py(), async move {
let result = inner
.add_columns()
.transform(NewColumnTransform::Reader(Box::new(reader)))
.execute()
.await
.infer_error()?;
Ok(AddColumnsResult::from(result))
})
}
#[pyo3(signature = (columns, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))]
pub fn add_computed_columns(
self_: PyRef<'_, Self>,
@@ -2024,21 +2208,86 @@ impl Table {
})
}
pub fn refresh_column(self_: PyRef<'_, Self>, column: String) -> PyResult<Bound<'_, PyAny>> {
#[pyo3(signature = (column, *, r#where=None, batch_size=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))]
#[allow(clippy::too_many_arguments)]
pub fn refresh_column(
self_: PyRef<'_, Self>,
column: String,
r#where: Option<String>,
batch_size: Option<i64>,
gpu_class: Option<String>,
gpu_count: Option<i64>,
retry_policy: Option<String>,
error_policy: Option<String>,
max_failed_fraction: Option<f64>,
max_failed_rows: Option<i64>,
row_timeout_seconds: Option<f64>,
init_timeout_seconds: Option<f64>,
num_workers: Option<i64>,
max_executor_processes_per_worker: Option<i64>,
) -> PyResult<Bound<'_, PyAny>> {
let options = refresh_column_options(RefreshColumnArgs {
where_clause: r#where,
batch_size,
gpu_class,
gpu_count,
retry_policy,
error_policy,
max_failed_fraction,
max_failed_rows,
row_timeout_seconds,
init_timeout_seconds,
num_workers,
max_executor_processes_per_worker,
})?;
let inner = self_.inner_ref()?.clone();
future_into_py(self_.py(), async move {
let result = inner.refresh_column(column).await.infer_error()?;
let result = inner
.refresh_column_with_options(column, options)
.await
.infer_error()?;
Ok(RefreshColumnResult::from(result))
})
}
#[pyo3(signature = (column, *, r#where=None, batch_size=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))]
#[allow(clippy::too_many_arguments)]
pub fn refresh_column_async(
self_: PyRef<'_, Self>,
column: String,
r#where: Option<String>,
batch_size: Option<i64>,
gpu_class: Option<String>,
gpu_count: Option<i64>,
retry_policy: Option<String>,
error_policy: Option<String>,
max_failed_fraction: Option<f64>,
max_failed_rows: Option<i64>,
row_timeout_seconds: Option<f64>,
init_timeout_seconds: Option<f64>,
num_workers: Option<i64>,
max_executor_processes_per_worker: Option<i64>,
) -> PyResult<Bound<'_, PyAny>> {
let options = refresh_column_options(RefreshColumnArgs {
where_clause: r#where,
batch_size,
gpu_class,
gpu_count,
retry_policy,
error_policy,
max_failed_fraction,
max_failed_rows,
row_timeout_seconds,
init_timeout_seconds,
num_workers,
max_executor_processes_per_worker,
})?;
let inner = self_.inner_ref()?.clone();
future_into_py(self_.py(), async move {
let job = inner.refresh_column_async(column).await.infer_error()?;
let job = inner
.refresh_column_async_with_options(column, options)
.await
.infer_error()?;
Ok(crate::job::Job::new_typed(job))
})
}
@@ -2062,11 +2311,16 @@ impl Table {
})
}
#[pyo3(signature = (source_version=None, *, full=false))]
#[pyo3(signature = (source_version=None, *, full=false, cpu_millis=None, memory_bytes=None, gpu_count=None, gpu_class=None))]
#[allow(clippy::too_many_arguments)]
pub fn refresh_materialized_view(
self_: PyRef<'_, Self>,
source_version: Option<u64>,
full: bool,
cpu_millis: Option<u64>,
memory_bytes: Option<u64>,
gpu_count: Option<u32>,
gpu_class: Option<String>,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner_ref()?.clone();
future_into_py(self_.py(), async move {
@@ -2074,6 +2328,18 @@ impl Table {
.await
.infer_error()?;
let mut builder = view.refresh().full(full);
if let Some(value) = cpu_millis {
builder = builder.cpu_millis(value);
}
if let Some(value) = memory_bytes {
builder = builder.memory_bytes(value);
}
if let Some(value) = gpu_count {
builder = builder.gpu_count(value);
}
if let Some(value) = gpu_class {
builder = builder.gpu_class(value);
}
if let Some(version) = source_version {
builder = builder.source_version(version);
}
@@ -2082,11 +2348,16 @@ impl Table {
})
}
#[pyo3(signature = (source_version=None, *, full=false))]
#[pyo3(signature = (source_version=None, *, full=false, cpu_millis=None, memory_bytes=None, gpu_count=None, gpu_class=None))]
#[allow(clippy::too_many_arguments)]
pub fn refresh_materialized_view_async(
self_: PyRef<'_, Self>,
source_version: Option<u64>,
full: bool,
cpu_millis: Option<u64>,
memory_bytes: Option<u64>,
gpu_count: Option<u32>,
gpu_class: Option<String>,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner_ref()?.clone();
future_into_py(self_.py(), async move {
@@ -2094,6 +2365,18 @@ impl Table {
.await
.infer_error()?;
let mut builder = view.refresh().full(full);
if let Some(value) = cpu_millis {
builder = builder.cpu_millis(value);
}
if let Some(value) = memory_bytes {
builder = builder.memory_bytes(value);
}
if let Some(value) = gpu_count {
builder = builder.gpu_count(value);
}
if let Some(value) = gpu_class {
builder = builder.gpu_class(value);
}
if let Some(version) = source_version {
builder = builder.source_version(version);
}
+17
View File
@@ -61,6 +61,23 @@ pub fn validate_table_name(table_name: &str) -> PyResult<()> {
.map_err(|e| PyValueError::new_err(e.to_string()))
}
/// Parse field references with the same identifier syntax as Lance writes.
#[pyfunction(name = "_parse_field_path")]
pub fn parse_field_path(path: &str) -> PyResult<Vec<String>> {
lance_core::datatypes::parse_field_path(path).map_err(|e| PyValueError::new_err(e.to_string()))
}
/// A wrapper around a LanceDB type to allow it to be used in Python
#[derive(Debug, Clone)]
pub struct PyLanceDB<T>(pub T);
/// Validate the Function retry wire contract using the same rules as Rust APIs.
#[pyo3::pyfunction]
pub fn validate_function_retry_policy(json: &str) -> pyo3::PyResult<()> {
let policy: lancedb::function::FunctionRetryPolicy =
serde_json::from_str(json).map_err(|error| {
pyo3::exceptions::PyValueError::new_err(format!("invalid retry_policy: {error}"))
})?;
policy
.validate()
.map_err(|error| pyo3::exceptions::PyValueError::new_err(error.to_string()))
}