From 02eee69130098f6b5bffcaaa572ea2f398665209 Mon Sep 17 00:00:00 2001 From: Bruno Ramirez Date: Tue, 24 Nov 2026 11:30:48 -0800 Subject: [PATCH] fix(sdk): validate materialized view job receipts (#5176) Materialized-view create and refresh could return a registry handle for a whitespace-only job ID. A trailing empty Arrow batch could also erase `already_exists`, causing `CREATE MATERIALIZED VIEW IF NOT EXISTS` to fail after the server had reported a successful no-op. This follows #5175 and uses its single-row receipt logic for both operations. - Read the one status row through the end of the Flight stream. Empty batches may appear before or after it. - Preserve valid job IDs verbatim. An empty ID with `already_exists` completes create without a registry job. Refresh reports the create-only status as an error. - Use the existing query-backed handle when the server does not advertise early materialized-view handles. --- rust/lancedb/src/remote/sql.rs | 1 + .../src/remote/sql/materialized_view.rs | 86 +++++---------- rust/lancedb/src/remote/sql/receipt.rs | 60 +++++++++++ rust/lancedb/src/remote/sql_test.rs | 101 +++++++++++++++++- rust/lancedb/src/remote/table/receipt.rs | 32 ++---- 5 files changed, 198 insertions(+), 82 deletions(-) create mode 100644 rust/lancedb/src/remote/sql/receipt.rs diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index b2ca5651f..68f53b10e 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -38,6 +38,7 @@ use crate::sql::{Query, QueryDescription, QueryHandle, QueryStatus}; mod function; pub(super) mod materialized_view; mod objects; +pub(super) mod receipt; mod secret; pub(super) use secret::SecretWriteOperation; mod stream; diff --git a/rust/lancedb/src/remote/sql/materialized_view.rs b/rust/lancedb/src/remote/sql/materialized_view.rs index eb29e62af..c87adc9ec 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, RecordBatch, StringArray}; use futures::TryStreamExt; use super::SqlClient; -use crate::arrow::SendableRecordBatchStream; +use super::receipt::ReceiptRow; use crate::database::ExecuteQueryRequest; use crate::error::{Error, Result}; use crate::listing::{ListingOptions, ListingPage}; @@ -60,66 +60,38 @@ impl SqlClient { true, ) .await?; - let query = Arc::new(submitted.query); if !submitted.materialized_view_job_handle_supported { - return Ok(MaterializedViewJobSubmission::Query(query)); + return Ok(MaterializedViewJobSubmission::Query(Arc::new( + submitted.query, + ))); } - let mut reader: SendableRecordBatchStream = query.reader().await?; - let mut rows = 0; - let mut registry_job_id = None; - let mut already_exists = false; - while let Some(batch) = reader.try_next().await? { - rows += batch.num_rows(); - if rows > 1 { - return Err(Error::Runtime { - message: "materialized-view submission must return exactly one status row" - .into(), - }); - } - if let Some(column) = batch.column_by_name("status") { - let values = column - .as_any() - .downcast_ref::() - .ok_or_else(|| Error::Runtime { - message: "materialized-view submission status is not UTF-8".into(), - })?; - already_exists = - values.len() == 1 && !values.is_null(0) && values.value(0) == "already_exists"; - } - if let Some(column) = batch.column_by_name("job_id") { - let values = column - .as_any() - .downcast_ref::() - .ok_or_else(|| Error::Runtime { - message: "materialized-view submission job_id is not UTF-8".into(), - })?; - if values.null_count() != 0 { - return Err(Error::Runtime { - message: "materialized-view submission contains a null job_id".into(), - }); - } - if values.is_empty() { - continue; - } - let value = values.value(0); - if !value.is_empty() { - registry_job_id = Some(value.to_string()); - } - } - } - if rows != 1 { - return Err(Error::Runtime { + let row = ReceiptRow::read(&submitted.query) + .await? + .ok_or_else(|| Error::Runtime { message: "materialized-view submission must return exactly one status row".into(), - }); + })?; + let already_exists = if let Some(column) = row.column("status") { + let status = column + .as_any() + .downcast_ref::() + .ok_or_else(|| Error::Runtime { + message: "materialized-view submission status is not UTF-8".into(), + })?; + !status.is_null(0) && status.value(0) == "already_exists" + } else { + false + }; + match row.job_id()? { + Some(id) => Ok(MaterializedViewJobSubmission::Registry { + job_id: id.to_owned(), + }), + None if already_exists => Ok(MaterializedViewJobSubmission::AlreadyExists), + None => Err(Error::Runtime { + message: + "server acknowledged an early materialized-view handle but returned no job_id" + .into(), + }), } - if already_exists && registry_job_id.is_none() { - return Ok(MaterializedViewJobSubmission::AlreadyExists); - } - let job_id = registry_job_id.ok_or_else(|| Error::Runtime { - message: "server acknowledged an early materialized-view handle but returned no job_id" - .into(), - })?; - Ok(MaterializedViewJobSubmission::Registry { job_id }) } pub(in crate::remote) async fn describe_materialized_view( diff --git a/rust/lancedb/src/remote/sql/receipt.rs b/rust/lancedb/src/remote/sql/receipt.rs new file mode 100644 index 000000000..4f45292d5 --- /dev/null +++ b/rust/lancedb/src/remote/sql/receipt.rs @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use arrow_array::{Array, ArrayRef, RecordBatch, StringArray}; +use futures::TryStreamExt; + +use crate::sql::Query; +use crate::{Error, Result}; + +/// The single row returned by a SQL job submission, after its stream completed successfully. +pub(in crate::remote) struct ReceiptRow(RecordBatch); + +impl ReceiptRow { + /// Empty batches carry no receipt data. Zero or multiple rows yield `None`. + pub(in crate::remote) async fn read(query: &Query) -> Result> { + let mut reader = query.reader().await?; + let mut receipt = None; + let mut rows = 0usize; + while let Some(batch) = reader.try_next().await? { + rows = rows.saturating_add(batch.num_rows()); + if rows == 1 && batch.num_rows() == 1 { + receipt = Some(Self(batch)); + } + } + Ok(receipt.filter(|_| rows == 1)) + } + + pub(in crate::remote) fn column(&self, name: &str) -> Option<&ArrayRef> { + self.0.column_by_name(name) + } + + /// An absent column or an empty string can represent a completed no-op. + /// Each command decides whether its receipt permits that outcome. + pub(in crate::remote) fn job_id(&self) -> Result> { + let Some(column) = self.column("job_id") else { + return Ok(None); + }; + let ids = column + .as_any() + .downcast_ref::() + .ok_or_else(|| Error::Runtime { + message: "SQL job receipt job_id is not UTF-8".into(), + })?; + if ids.is_null(0) { + return Err(Error::Runtime { + message: "SQL job receipt contains a null job_id".into(), + }); + } + let id = ids.value(0); + if id.is_empty() { + Ok(None) + } else if id.trim().is_empty() { + Err(Error::Runtime { + message: "SQL job receipt contains a blank job_id".into(), + }) + } else { + Ok(Some(id)) + } + } +} diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 78ca50c2a..277ec16ae 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -151,6 +151,7 @@ struct TestSqlService { exchange_drops: Arc, result: RecordBatch, result_tail: Vec>, + result_frames: Option>, large_result: RecordBatch, dictionary_result: RecordBatch, } @@ -332,6 +333,7 @@ impl Default for TestSqlService { exchange_drops: Arc::new(AtomicUsize::new(0)), result, result_tail: vec![], + result_frames: None, large_result, dictionary_result, } @@ -585,11 +587,14 @@ impl FlightService for TestSqlService { if large { encoder = encoder.with_max_flight_data_size(8 * 1024 * 1024); } - let stream = encoder.build(input).map_err(Status::from); + let stream = match &self.result_frames { + Some(frames) => futures::stream::iter(frames.clone()).map(Ok).boxed(), + None => encoder.build(input).map_err(Status::from).boxed(), + }; if let Some(initial) = initial { - Ok(self.adaptive_response(&initial.query, stream.boxed())) + Ok(self.adaptive_response(&initial.query, stream)) } else { - Ok(Response::new(stream.boxed())) + Ok(Response::new(stream)) } } @@ -1483,6 +1488,96 @@ async fn remote_create_if_not_exists_accepts_a_completed_noop_without_a_registry } } +#[rstest::rstest] +#[case::submitted("submitted", " job-1 ", Ok(Some(" job-1 ")), Ok(Some(" job-1 ")))] +#[case::blank_id("submitted", " \t ", Err("blank job_id"), Err("blank job_id"))] +#[case::missing_id("submitted", "", Err("returned no job_id"), Err("returned no job_id"))] +#[case::already_exists("already_exists", "", Ok(None), Err("create-only already_exists"))] +#[case::malformed_noop("already_exists", " \t ", Err("blank job_id"), Err("blank job_id"))] +#[tokio::test] +async fn remote_materialized_view_receipt_with_empty_batches( + #[case] status: &str, + #[case] job_id: &str, + #[case] expected_create: std::result::Result, &str>, + #[case] expected_refresh: std::result::Result, &str>, +) { + let row = RecordBatch::try_from_iter([ + ( + "status", + Arc::new(StringArray::from(vec![status])) as ArrayRef, + ), + ( + "job_id", + Arc::new(StringArray::from(vec![job_id])) as ArrayRef, + ), + ]) + .unwrap(); + let empty = row.slice(0, 0); + // FlightDataEncoderBuilder skips zero-row batches. Encode them explicitly on the wire. + let frames = + arrow_flight::utils::batches_to_flight_data(&row.schema(), vec![empty.clone(), row, empty]) + .unwrap(); + let service = TestSqlService { + adaptive: true, + defer: true, + materialized_view_job_handle_supported: true, + result_frames: Some(frames), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|r| -> http::Response { + panic!("unexpected HTTP request during create: {}", r.url()) + }) + .with_sql_client(sql.clone()); + let table = receipt_test_table(sql); + let create = db + .create_materialized_view_async(CreateMaterializedViewRequest { + name: "events".into(), + namespace_path: vec!["team".into()], + query: "SELECT * FROM people".into(), + exist_ok: true, + with_no_data: false, + auto_refresh_enabled: None, + auto_refresh_interval_seconds: None, + total_cpu_millis: None, + total_memory_bytes: None, + total_gpu_count: None, + gpu_class: None, + gpu_count: None, + }) + .await; + let refresh = table.refresh_materialized_view_async(None, false).await; + for (operation, actual, expected) in [ + ( + "CREATE", + create.as_ref().map(|job| job.id()), + expected_create, + ), + ( + "REFRESH", + refresh.as_ref().map(|job| job.id()), + expected_refresh, + ), + ] { + match expected { + Ok(id) => assert_eq!(actual.unwrap(), id, "{operation}"), + Err(message) => { + let err = actual.unwrap_err().to_string(); + assert!(err.contains(message), "{operation}: {err}"); + } + } + } + assert_eq!( + *statements.lock().unwrap(), + [ + r#"CREATE MATERIALIZED VIEW IF NOT EXISTS "events" AS SELECT * FROM people"#, + r#"REFRESH MATERIALIZED VIEW "events""#, + ] + ); + shutdown.send(()).unwrap(); +} + #[tokio::test] async fn remote_create_registry_handle_reopens_describes_and_cancels() { let service = TestSqlService { diff --git a/rust/lancedb/src/remote/table/receipt.rs b/rust/lancedb/src/remote/table/receipt.rs index a929668a3..818302cd7 100644 --- a/rust/lancedb/src/remote/table/receipt.rs +++ b/rust/lancedb/src/remote/table/receipt.rs @@ -1,14 +1,14 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -use arrow_array::{Array, StringArray, UInt64Array}; -use futures::TryStreamExt; +use arrow_array::{Array, UInt64Array}; use serde::de::DeserializeOwned; use super::{cleanup, optimize, prewarm}; use crate::job::Job; use crate::remote::client::{HttpSend, RestfulLanceDbClient}; use crate::remote::job::RemoteJob; +use crate::remote::sql::receipt::ReceiptRow; use crate::sql::Query; use crate::{Error, Result}; @@ -50,34 +50,22 @@ impl JobReceipt { Self::Cleanup => cleanup::map_error, }; let query = submission.map_err(map_error)?; - let mut reader = query.reader().await.map_err(map_error)?; - let mut receipt = None; - let mut rows = 0usize; - while let Some(batch) = reader.try_next().await.map_err(map_error)? { - rows = rows.saturating_add(batch.num_rows()); - if rows == 1 && batch.num_rows() == 1 { - receipt = Some(batch); - } - } - let batch = receipt - .filter(|_| rows == 1) - .ok_or_else(|| self.invalid())?; - let ids = batch - .column_by_name("job_id") - .and_then(|column| column.as_any().downcast_ref::()) - .filter(|ids| !ids.is_null(0) && !ids.value(0).trim().is_empty()) + let row = ReceiptRow::read(&query) + .await + .map_err(map_error)? .ok_or_else(|| self.invalid())?; + let Ok(Some(job_id)) = row.job_id() else { + return Err(self.invalid()); + }; if matches!(self, Self::Prewarm) { - batch - .column_by_name("table_version") + row.column("table_version") .and_then(|column| column.as_any().downcast_ref::()) .filter(|versions| !versions.is_null(0)) .ok_or_else(|| self.invalid())?; } - let job_id = ids.value(0).to_owned(); Ok(Job::new_typed(Box::new(RemoteJob::new( client.clone(), - job_id, + job_id.to_owned(), )))) } }