From 5373da57607f745f22da244b32385e74523c6190 Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Wed, 2 Dec 2026 12:15:59 +0800 Subject: [PATCH] fix: explain Flight SQL endpoint errors during function registration (#5342) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Function registration uses Flight SQL. If the SDK has no usable SQL URI or cannot establish a connection, it points to the cluster’s published Flight SQL URI and the Public SQL or PrivateLink SQL settings. The diagnostic retains the original exception type, cause text, and request ID when present. ## Validation - Built main (`0abc7d48`) and the SDK change (`4bfdbb217`) in the same isolated Linux VM with the locked Python environment. The final commit updates only the test assertion for platform-dependent connection errors. - Compared 22 calls against a healthy HTTPS REST fixture and Flight endpoints. The expected five registration failures gained the hint. After accounting for request IDs, all original errors and successful results matched. - New regression tests on main had two expected failures and three passing controls. The SDK change passed 86 tests with 16 skipped across registration, Function catalog, SQL, and view creation. Rust formatting and Ruff passed. - All 50 GitHub checks passed on `7c2dad8bc`, including the [Python workflow](https://github.com/lancedb/lancedb/actions/runs/46796061600) and the [Rust macOS 26 rerun](https://github.com/lancedb/lancedb/actions/runs/46796061943/job/143185732469). --- .../tests/test_function_registration_sql.py | 94 +++++++++++++++++++ rust/lancedb/src/remote/sql.rs | 58 +++++++++--- rust/lancedb/src/remote/sql/function.rs | 30 +++--- .../src/remote/sql/materialized_view.rs | 6 +- rust/lancedb/src/remote/sql/objects.rs | 17 +++- rust/lancedb/src/remote/sql_test.rs | 6 +- 6 files changed, 175 insertions(+), 36 deletions(-) create mode 100644 python/python/tests/test_function_registration_sql.py diff --git a/python/python/tests/test_function_registration_sql.py b/python/python/tests/test_function_registration_sql.py new file mode 100644 index 000000000..a2d0ae053 --- /dev/null +++ b/python/python/tests/test_function_registration_sql.py @@ -0,0 +1,94 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import socket + +import pytest + +import lancedb +from lancedb.functions import function +from lancedb.remote.errors import SqlError + + +@function +def identity(value: int) -> int: + return value + + +@pytest.mark.parametrize("sql_host_override", [None, "grpc://127.0.0.1/bad-path"]) +def test_function_registration_sql_address(sql_host_override): + db = lancedb.connect( + "db://catalog", + api_key="test-key", + host_override="https://127.0.0.1", + sql_host_override=sql_host_override, + ) + with pytest.raises(ValueError) as query_error: + db.execute_query("SELECT 1") + with pytest.raises(ValueError) as registration_error: + db.create_function(identity) + + assert type(registration_error.value) is type(query_error.value) + assert registration_error.value.__cause__ is query_error.value.__cause__ + assert "Public SQL" not in str(query_error.value) + if sql_host_override is None: + assert "sql_host_override is required" in str(query_error.value) + assert str(registration_error.value).startswith(str(query_error.value)) + assert "Public SQL or PrivateLink SQL" in str(registration_error.value) + else: + assert str(registration_error.value) == str(query_error.value) + + +@pytest.mark.asyncio +async def test_function_registration_unreachable_sql(): + # Hold the port open without listening so another process cannot claim it. + # Depending on the OS, connecting to this port is refused or times out. + connect_error = ( + r"(?i)request_id=[0-9a-f-]{36}\): " + r"(?:transport error: [^\n]*(?:refused|deadline has elapsed)" + r"|SQL connection timed out)" + ) + with socket.socket() as sql_socket: + sql_socket.bind(("127.0.0.1", 0)) + db = await lancedb.connect_async( + "db://catalog", + api_key="test-key", + host_override="https://127.0.0.1", + sql_host_override=f"grpc://127.0.0.1:{sql_socket.getsockname()[1]}", + client_config={"timeout_config": {"connect_timeout": 5}}, + ) + with pytest.raises(RuntimeError, match=connect_error) as exc: + await db.create_function_async(identity) + assert type(exc.value) is RuntimeError + assert exc.value.__cause__ is None + assert "Public SQL or PrivateLink SQL" in str(exc.value) + with pytest.raises(RuntimeError, match=connect_error) as exc: + await db.execute_query("SELECT 1") + assert "Public SQL" not in str(exc.value) + + +@pytest.mark.parametrize( + ("exception_type", "grpc_code"), + [("FlightUnauthenticatedError", 16), ("FlightUnavailableError", 14)], +) +def test_function_registration_preserves_flight_status(exception_type, grpc_code): + flight = pytest.importorskip("pyarrow.flight") + error = getattr(flight, exception_type) + + class RejectRegistration(flight.FlightServerBase): + def do_get(self, context, ticket): + assert b'CREATE FUNCTION "identity" FROM' in ticket.ticket + raise error("registration rejected by Flight server") + + with RejectRegistration("grpc://127.0.0.1:0") as server: + db = lancedb.connect( + "db://catalog", + api_key="test-key", + host_override="https://127.0.0.1", + sql_host_override=f"grpc://127.0.0.1:{server.port}", + ) + with pytest.raises(SqlError) as exc: + db.create_function(identity) + assert exc.value.grpc_code == grpc_code + assert "registration rejected by Flight server" in str(exc.value) + assert "Public SQL" not in str(exc.value) diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index fda450e2c..59aa52825 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -61,6 +61,10 @@ const MAX_SQL_MESSAGE_SIZE: usize = 1024 * 1024 * 1024; const SQL_JOB_ID_METADATA_KEY: &str = "x-lancedb-sql-job-id"; const TERMINAL_QUERY_RETENTION: Duration = Duration::from_secs(300); const ABANDONED_QUERY_RETENTION: Duration = Duration::from_secs(24 * 60 * 60); +const FUNCTION_SQL_ENDPOINT_HINT: &str = "\nFunction registration requires Flight SQL. \ + If your cluster publishes a Flight SQL endpoint, pass its URI as sql_host_override \ + and verify that your client can reach it. If no endpoint is published, check the \ + Public SQL or PrivateLink SQL setting for your network."; #[derive(Clone)] pub(super) struct SqlClient { @@ -68,9 +72,16 @@ pub(super) struct SqlClient { queries: Arc, } -pub(super) struct SubmittedQuery { - pub(super) query: Query, - pub(super) materialized_view_job_handle_supported: bool, +struct SubmittedQuery { + query: Query, + materialized_view_job_handle_supported: bool, +} + +#[derive(Clone, Copy)] +enum SqlSubmission { + Query, + FunctionRegistration, + MaterializedViewJob, } #[derive(Clone)] @@ -84,6 +95,7 @@ struct SqlClientInner { client: Arc>, deadline: Option, cancel_on_drop: bool, + endpoint_hint: &'static str, } struct SqlConnection { @@ -222,6 +234,7 @@ impl SqlClient { client: Arc::new(OnceCell::new()), deadline: None, cancel_on_drop: false, + endpoint_hint: "", }), queries: Arc::new(QueryRegistry::new()), } @@ -278,17 +291,20 @@ impl SqlClient { pub(super) async fn execute(&self, request: ExecuteQueryRequest) -> Result { Ok(self - .execute_with_materialized_view_job_handle(request, false) + .execute_with_submission(request, SqlSubmission::Query) .await? .query) } - pub(super) async fn execute_with_materialized_view_job_handle( + async fn execute_with_submission( &self, request: ExecuteQueryRequest, - materialized_view_job_handle: bool, + submission: SqlSubmission, ) -> Result { let mut client = self.inner.as_ref().clone(); + if matches!(submission, SqlSubmission::FunctionRegistration) { + client.endpoint_hint = FUNCTION_SQL_ENDPOINT_HINT; + } client.deadline = request .options .timeout @@ -319,7 +335,7 @@ impl SqlClient { &request.query, request.parameters, &request.default_namespace_path, - materialized_view_job_handle, + matches!(submission, SqlSubmission::MaterializedViewJob), ) .await?; let stream::OpenedSubmission { @@ -717,8 +733,11 @@ impl SqlClientInner { let target = resolve_sql_host_override( self.host_override.as_deref(), self.sql_host_override.as_deref(), + self.endpoint_hint, )?; - let channel = connect_channel(&target, &self.client_config, request_id).await?; + let channel = + connect_channel(&target, &self.client_config, request_id, self.endpoint_hint) + .await?; let client = FlightServiceClient::new(channel.clone()) .max_decoding_message_size(MAX_SQL_MESSAGE_SIZE); Ok::<_, Error>(SqlConnection { channel, client }) @@ -1728,27 +1747,33 @@ struct SqlTarget { fn resolve_sql_host_override( host_override: Option<&str>, sql_host_override: Option<&str>, + endpoint_hint: &str, ) -> Result { if let Some(uri) = sql_host_override { return normalize_sql_host_override(uri); } let host_override = host_override.ok_or_else(|| Error::InvalidInput { - message: "sql_host_override is required when the SQL service endpoint cannot be derived from host_override".to_string(), + message: format!( + "sql_host_override is required when the SQL service endpoint cannot be derived from host_override{endpoint_hint}" + ), })?; let parsed = url::Url::parse(host_override).map_err(|err| Error::InvalidInput { message: format!("Invalid host_override: {err}"), })?; if parsed.scheme() != "http" { return Err(Error::InvalidInput { - message: "sql_host_override is required for TLS or non-HTTP host overrides".to_string(), + message: format!( + "sql_host_override is required for TLS or non-HTTP host overrides{endpoint_hint}" + ), }); } validate_endpoint_url(&parsed, "host_override")?; let port = match parsed.port().or(explicit_port(host_override)) { Some(u16::MAX) => { return Err(Error::InvalidInput { - message: "sql_host_override is required when host_override uses port 65535" - .to_string(), + message: format!( + "sql_host_override is required when host_override uses port 65535{endpoint_hint}" + ), }); } Some(port) => port + 1, @@ -1842,6 +1867,7 @@ async fn connect_channel( target: &SqlTarget, config: &ClientConfig, request_id: &str, + endpoint_hint: &str, ) -> Result { let connect_timeout = resolve_timeout( config.timeout_config.connect_timeout, @@ -1859,7 +1885,12 @@ async fn connect_channel( } tokio::time::timeout(connect_timeout, endpoint.connect()) .await - .map_err(|_| sql_error(request_id, "SQL connection timed out"))? + .map_err(|_| { + sql_error( + request_id, + format!("SQL connection timed out{endpoint_hint}"), + ) + })? .map_err(|err| { // tonic's Display only says "transport error"; preserve the source chain // so callers can distinguish DNS, refused connections, and TLS failures. @@ -1870,6 +1901,7 @@ async fn connect_channel( message.push_str(&error.to_string()); source = error.source(); } + message.push_str(endpoint_hint); sql_error(request_id, message) }) } diff --git a/rust/lancedb/src/remote/sql/function.rs b/rust/lancedb/src/remote/sql/function.rs index cd570a1b8..0e9ea5cbf 100644 --- a/rust/lancedb/src/remote/sql/function.rs +++ b/rust/lancedb/src/remote/sql/function.rs @@ -2,7 +2,7 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors use super::{ - SqlClient, + SqlClient, SqlSubmission, materialized_view::quote_identifier, objects::{definition, description, literal, string_lists, strings}, }; @@ -74,19 +74,21 @@ impl SqlClient { })?; body.as_object_mut().unwrap().remove("name"); body.as_object_mut().unwrap().remove("exist_ok"); - self.object_job( - ExecuteQueryRequest { - query: format!( - "CREATE FUNCTION{if_not_exists} {name} FROM {}", - literal(&body.to_string()) - ), - default_namespace_path: namespace.to_vec(), - parameters: None, - options: Default::default(), - }, - definition, - ) - .await + let submitted = self + .execute_with_submission( + ExecuteQueryRequest { + query: format!( + "CREATE FUNCTION{if_not_exists} {name} FROM {}", + literal(&body.to_string()) + ), + default_namespace_path: namespace.to_vec(), + parameters: None, + options: Default::default(), + }, + SqlSubmission::FunctionRegistration, + ) + .await?; + Ok(Self::object_job_from_query(submitted.query, definition)) } pub(in crate::remote) async fn describe_function( &self, diff --git a/rust/lancedb/src/remote/sql/materialized_view.rs b/rust/lancedb/src/remote/sql/materialized_view.rs index b8b9fc2f7..22cab114f 100644 --- a/rust/lancedb/src/remote/sql/materialized_view.rs +++ b/rust/lancedb/src/remote/sql/materialized_view.rs @@ -7,7 +7,7 @@ use arrow_array::{Array, StringArray}; use futures::TryStreamExt; use super::receipt::ReceiptRow; -use super::{SqlClient, objects::description}; +use super::{SqlClient, SqlSubmission, objects::description}; use crate::database::ExecuteQueryRequest; use crate::error::{Error, Result}; use crate::listing::{ListingOptions, ListingPage}; @@ -37,14 +37,14 @@ impl SqlClient { namespace: Vec, ) -> Result { let submitted = self - .execute_with_materialized_view_job_handle( + .execute_with_submission( ExecuteQueryRequest { query: statement, default_namespace_path: namespace, parameters: None, options: Default::default(), }, - true, + SqlSubmission::MaterializedViewJob, ) .await?; if !submitted.materialized_view_job_handle_supported { diff --git a/rust/lancedb/src/remote/sql/objects.rs b/rust/lancedb/src/remote/sql/objects.rs index cbf40f576..e33e96801 100644 --- a/rust/lancedb/src/remote/sql/objects.rs +++ b/rust/lancedb/src/remote/sql/objects.rs @@ -210,17 +210,28 @@ impl SqlClient { T: Clone + Serialize + DeserializeOwned + Send + Sync + 'static, F: FnOnce(Vec) -> Result + Send + 'static, { - let query = Arc::new(self.execute(request).await?); + Ok(Self::object_job_from_query( + self.execute(request).await?, + decode, + )) + } + + pub(super) fn object_job_from_query(query: crate::sql::Query, decode: F) -> Job + where + T: Clone + Serialize + DeserializeOwned + Send + Sync + 'static, + F: FnOnce(Vec) -> Result + Send + 'static, + { + let query = Arc::new(query); let id = query.id(); let execution = query.clone(); let task = tokio::spawn(async move { let reader = execution.reader().await?; decode(reader.try_collect().await?) }); - Ok(Job::from_query_task(id, task, move || { + Job::from_query_task(id, task, move || { let query = query.clone(); async move { query.cancel().await } - })) + }) } } diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 5802cce81..46029f56d 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -2655,14 +2655,14 @@ fn normalizes_supported_uris() { #[test] fn derives_plaintext_endpoint_from_host_override() { assert_eq!( - resolve_sql_host_override(Some("http://localhost:10024"), None).unwrap(), + resolve_sql_host_override(Some("http://localhost:10024"), None, "").unwrap(), SqlTarget { uri: "http://localhost:10025".to_string(), tls: false, } ); assert_eq!( - resolve_sql_host_override(Some("http://localhost:80"), None).unwrap(), + resolve_sql_host_override(Some("http://localhost:80"), None, "").unwrap(), SqlTarget { uri: "http://localhost:81".to_string(), tls: false, @@ -2675,7 +2675,7 @@ fn rejects_unsafe_or_ambiguous_endpoints() { assert!(normalize_sql_host_override("ftp://localhost").is_err()); assert!(normalize_sql_host_override("grpc://user@localhost").is_err()); assert!(normalize_sql_host_override("grpc://localhost/path").is_err()); - assert!(resolve_sql_host_override(Some("https://localhost"), None).is_err()); + assert!(resolve_sql_host_override(Some("https://localhost"), None, "").is_err()); } #[test]