fix: explain Function catalog SDK compatibility errors (#5250)

An older Function catalog can reject the query generated by
`get_function` at `FORMAT`, or by `list_functions` at `LIMIT`. When the
operation receives its exact trailing-input diagnostic at submission,
append guidance on matching the Python SDK to the Enterprise build. Keep
the original SQL error, request ID, gRPC status and any build metadata
supplied by the server.

Compared 24 loopback Flight responses through the public synchronous and
asynchronous Python APIs against the published b38 wheel. Eight lookups
and listings gained the pairing guidance. The other 16 responses
preserved their error types and diagnostics, including authorization,
missing resources and unrelated parser failures. The candidate passed
122 Python tests and four Rust tests. Current catalog reads and opaque
continuation tokens also worked after build discovery returned 404.
This commit is contained in:
Xuanwo
2026-11-28 08:30:52 +08:00
committed by GitHub
parent 6283f83a92
commit c55eaae0dc
3 changed files with 322 additions and 2 deletions
@@ -0,0 +1,181 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
from collections import deque
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
from pathlib import Path
import lancedb
from lancedb.remote.errors import SqlError
import pyarrow as pa
import pytest
from utils import start_server_thread
DESCRIBE = 'DESCRIBE FUNCTION "embed" FORMAT JSON'
DESCRIBE_VERSION = "DESCRIBE FUNCTION \"embed\" WITH (version = '1') FORMAT JSON"
LIST = 'SHOW FUNCTIONS HISTORY IN "public" LIMIT 1000'
CONTINUE = "SHOW FUNCTIONS HISTORY IN \"public\" LIMIT 1 FROM 'opaque''cursor'"
TRAILING_INPUT = "unexpected trailing input after the statement: "
@pytest.fixture
def flight_catalog():
flight = pytest.importorskip("pyarrow.flight")
class Catalog(flight.FlightServerBase):
def __init__(self):
super().__init__("grpc://127.0.0.1:0")
self.replies = deque()
self.requests = []
def do_get(self, context, ticket):
statement, response = self.replies.popleft()
assert ticket.ticket.endswith(statement.encode()), ticket.ticket
self.requests.append(statement)
if isinstance(response, Exception):
raise response
return flight.RecordBatchStream(response)
with Catalog() as server:
yield server
assert not server.replies
@pytest.fixture
def discovery_404():
paths = []
class Discovery(BaseHTTPRequestHandler):
def do_GET(self):
paths.append(self.path)
self.send_response(404)
self.end_headers()
with ThreadingHTTPServer(("127.0.0.1", 0), Discovery) as server:
thread = start_server_thread(server)
try:
yield f"http://127.0.0.1:{server.server_port}", paths
finally:
server.shutdown()
thread.join()
async def connect(server, asynchronous, endpoint="http://127.0.0.1:1"):
options = {
"api_key": "test-key",
"host_override": endpoint,
"sql_host_override": f"grpc://127.0.0.1:{server.port}",
"client_config": {"retry_config": {"retries": 0}},
}
if asynchronous:
return await lancedb.connect_async("db://catalog", **options)
return lancedb.connect("db://catalog", **options)
@pytest.mark.parametrize(
("statement", "exception_type", "diagnostic", "code"),
[
(DESCRIBE, "ArrowInvalid", TRAILING_INPUT + "LIMIT", 3),
(LIST, "ArrowInvalid", TRAILING_INPUT + "FORMAT", 3),
(DESCRIBE, "ArrowInvalid", TRAILING_INPUT + "FORMATTER", 3),
(DESCRIBE, "ArrowKeyError", "Function 'embed' was not found", 5),
(DESCRIBE, "FlightUnauthorizedError", TRAILING_INPUT + "FORMAT", 7),
(LIST, "FlightUnavailableError", TRAILING_INPUT + "LIMIT", 14),
("SELECT 1", "ArrowInvalid", TRAILING_INPUT + "FORMAT", 3),
],
)
def test_function_catalog_preserves_other_sql_errors(
flight_catalog, statement, exception_type, diagnostic, code
):
flight = pytest.importorskip("pyarrow.flight")
failure_type = getattr(
pa if exception_type.startswith("Arrow") else flight, exception_type
)
flight_catalog.replies.append((statement, failure_type(diagnostic)))
db = lancedb.connect(
"db://catalog",
api_key="test-key",
host_override="http://127.0.0.1:1",
sql_host_override=f"grpc://127.0.0.1:{flight_catalog.port}",
client_config={"retry_config": {"retries": 0}},
)
with pytest.raises(SqlError) as exc:
if statement == DESCRIBE:
db.get_function("embed")
elif statement == LIST:
next(db.list_functions())
else:
db.execute_query(statement).read_all()
assert diagnostic in str(exc.value)
assert "lancedb==" not in str(exc.value)
assert exc.value.grpc_code == code
assert flight_catalog.requests == [statement]
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
async def test_function_catalog_reads_and_pages_after_discovery_404(
flight_catalog, discovery_404, asynchronous
):
endpoint, discovery_requests = discovery_404
fixture = (
Path(__file__).resolve().parents[3]
/ "rust/lancedb/tests/fixtures/first_class_functions/v1"
/ "remote_function_version.canonical.json"
)
first = json.loads(fixture.read_text())
second = {**first, "version": "2"}
description = pa.table(
{"description": [json.dumps(first)]}
).replace_schema_metadata({"lancedb.describe.format": "json"})
page = pa.table({"definition": [json.dumps(first)]}).replace_schema_metadata(
{"lancedb.next_page_token": "opaque'cursor"}
)
flight_catalog.replies.extend(
[
(DESCRIBE_VERSION, description),
('SHOW FUNCTIONS HISTORY IN "public" LIMIT 1', page),
(CONTINUE, pa.table({"definition": [json.dumps(second)]})),
]
)
db = await connect(flight_catalog, asynchronous, endpoint)
assert discovery_requests == []
with pytest.raises((NotImplementedError, RuntimeError), match="returned 404"):
if asynchronous:
await db.server_info()
else:
db.server_info()
assert discovery_requests == ["/v1/server/info"]
description = db.get_function("embed", version="1")
if asynchronous:
description = await description
assert (description.name, description.version) == ("embed", "1")
listing = db.list_functions(page_limit=1)
assert flight_catalog.requests == [DESCRIBE_VERSION]
original = await anext(listing) if asynchronous else next(listing)
assert (original.name, original.version) == ("embed", "1")
assert listing.num_page_results() == 0
assert listing.page_token() == "opaque'cursor"
later = await anext(listing) if asynchronous else next(listing)
assert (later.name, later.version) == ("embed", "2")
assert listing.page_token() is None
assert ([item async for item in listing] if asynchronous else list(listing)) == []
assert discovery_requests == ["/v1/server/info"]
@pytest.mark.asyncio
async def test_function_catalog_keeps_malformed_result_errors(flight_catalog):
flight_catalog.replies.extend(
[
(DESCRIBE, pa.table({"name": ["embed"], "version": ["1"]})),
(LIST, pa.table({"name": ["embed"]})),
]
)
db = await connect(flight_catalog, True)
with pytest.raises(RuntimeError, match="requires one UTF8 description column"):
await db.get_function("embed")
with pytest.raises(RuntimeError, match="missing string column 'definition'"):
await anext(db.list_functions())
+37 -2
View File
@@ -15,6 +15,37 @@ use crate::{
utils::{validate_function_name, validate_namespace},
};
// These parser diagnostics identify a rejected clause emitted by this SDK.
// They do not identify the server build.
fn with_catalog_pairing(mut error: Error, clause: &str) -> Error {
if let Error::Sql {
message,
grpc_code,
metadata,
..
} = &mut error
&& *grpc_code == tonic::Code::InvalidArgument as i32
&& metadata.error_code.is_none()
&& metadata.resource.is_none()
{
let diagnostic = metadata.server.as_ref().map_or(message.as_str(), |build| {
message
.strip_suffix(&format!(" [server: {build}]"))
.unwrap_or(message)
});
if diagnostic.strip_prefix("unexpected trailing input after the statement: ")
== Some(clause)
{
message.push_str(
". Check the Python SDK version paired with your LanceDB Enterprise build. \
For a build paired with b8, install lancedb==0.42.0b8. \
To use lancedb==0.42.0b38, connect to a LanceDB Enterprise build that pins b38.",
);
}
}
error
}
/// The SQL result of one Function drop, before the public boolean wrapper
/// discards the advisory details.
#[derive(Clone, serde::Deserialize, serde::Serialize)]
@@ -69,6 +100,7 @@ impl SqlClient {
Some(version) => format!(" WITH (version = {})", literal(version)),
None => String::new(),
};
let with_pairing = |error| with_catalog_pairing(error, "FORMAT");
self.object_job(
ExecuteQueryRequest {
query: format!(
@@ -81,9 +113,11 @@ impl SqlClient {
},
description,
)
.await?
.await
.map_err(with_pairing)?
.wait()
.await
.map_err(with_pairing)
}
pub(in crate::remote) async fn list_functions(
&self,
@@ -92,7 +126,8 @@ impl SqlClient {
) -> Result<ListingPage<FunctionVersion>> {
let (batches, page_token) = self
.listing_page("SHOW FUNCTIONS HISTORY", namespace, options)
.await?;
.await
.map_err(|error| with_catalog_pairing(error, "LIMIT"))?;
let items = strings(&batches, "definition")?
.into_iter()
.map(|value| {
+104
View File
@@ -143,6 +143,7 @@ struct TestSqlService {
gate_refresh_release: Arc<Notify>,
exchanges: ReceivedExchanges,
result_overrides: Arc<std::sync::Mutex<HashMap<String, RecordBatch>>>,
submission_errors: HashMap<&'static str, Status>,
materialized_view_job_handle_supported: bool,
optimize_error: Option<Status>,
prewarm_error: Option<Status>,
@@ -326,6 +327,7 @@ impl Default for TestSqlService {
gate_refresh_release: Arc::new(Notify::new()),
exchanges: Arc::new(std::sync::Mutex::new(Vec::new())),
result_overrides: Arc::new(std::sync::Mutex::new(HashMap::new())),
submission_errors: HashMap::new(),
materialized_view_job_handle_supported: false,
optimize_error: None,
prewarm_error: None,
@@ -538,6 +540,9 @@ impl FlightService for TestSqlService {
return Err(Status::invalid_argument("invalid statement"));
}
self.capture_headers(request.metadata());
if let Some(error) = self.submission_errors.get(command.query.as_str()) {
return Err(error.clone());
}
assert_eq!(
request.metadata().get(PROTOCOL_HEADER).unwrap(),
PROTOCOL_VERSION
@@ -4138,6 +4143,105 @@ async fn secret_listing_preserves_empty_continuations_and_validates_page_options
shutdown.send(()).unwrap();
}
#[tokio::test]
async fn function_catalog_reports_pairing_for_rejected_clauses() {
const FORMAT: &str = "unexpected trailing input after the statement: FORMAT";
const LIMIT: &str = "unexpected trailing input after the statement: LIMIT";
const DESCRIBE: &str = "DESCRIBE FUNCTION \"embed\" FORMAT JSON";
const DESCRIBE_VERSION: &str = "DESCRIBE FUNCTION \"embed\" WITH (version = '1') FORMAT JSON";
const LIST: &str = "SHOW FUNCTIONS HISTORY IN \"public\" LIMIT 1000";
const CONTINUATION: &str = "SHOW FUNCTIONS HISTORY IN \"public\" LIMIT 1 FROM 'cursor'";
let mut describe_version_error = Status::invalid_argument(FORMAT);
describe_version_error.metadata_mut().insert_bin(
"x-lancedb-server-build-bin",
tonic::metadata::MetadataValue::from_bytes(
br#"{"release":"1.2.3","git_sha":"0123456789ab","build_date":"2024-01-01T00:00:00Z"}"#,
),
);
let service = TestSqlService {
submission_errors: HashMap::from([
(DESCRIBE, Status::invalid_argument(FORMAT)),
(DESCRIBE_VERSION, describe_version_error),
(LIST, Status::invalid_argument(LIMIT)),
(CONTINUATION, Status::invalid_argument(LIMIT)),
]),
..Default::default()
};
let statements = service.statements.clone();
let headers = service.headers.clone();
let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await;
let db = RemoteDatabase::new_mock(|_| -> http::Response<String> {
panic!("unexpected REST request");
})
.with_sql_client(client);
let connection = Connection::new(Arc::new(db), Arc::new(MemoryRegistry::new()));
let errors = [
connection
.get_function_latest("embed", &[])
.await
.unwrap_err(),
connection
.get_function("embed", "1", &[])
.await
.unwrap_err(),
connection
.list_functions(&[], Default::default())
.next_page()
.await
.unwrap_err(),
connection
.list_functions(
&[],
crate::listing::ListingOptions::default()
.page_limit(1)
.page_token("cursor"),
)
.next_page()
.await
.unwrap_err(),
];
assert_eq!(
*statements.lock().unwrap(),
[DESCRIBE, DESCRIBE_VERSION, LIST, CONTINUATION]
);
let headers = headers.lock().unwrap();
for (index, (error, diagnostic)) in errors
.into_iter()
.zip([FORMAT, FORMAT, LIMIT, LIMIT])
.enumerate()
{
let Error::Sql {
message,
request_id,
grpc_code,
metadata,
} = error
else {
panic!("unexpected catalog error: {error}")
};
assert_eq!(grpc_code, tonic::Code::InvalidArgument as i32);
assert_eq!(request_id, headers[index].request_id);
assert_eq!(metadata.error_code, None);
let original = if let Some(server) = &metadata.server {
assert_eq!(index, 1);
assert_eq!(server.release, "1.2.3");
format!("{diagnostic} [server: {server}]")
} else {
assert_ne!(index, 1);
diagnostic.to_owned()
};
assert!(message.starts_with(&format!("{original}. ")), "{message}");
assert!(message.contains("lancedb==0.42.0b8"), "{message}");
assert!(message.contains("lancedb==0.42.0b38"), "{message}");
assert!(
message.contains("LanceDB Enterprise build that pins b38"),
"{message}"
);
}
shutdown.send(()).unwrap();
}
#[tokio::test]
async fn function_listing_uses_server_tokens_for_numeric_revision_pages() {
const VERSION: &str = include_str!(