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.
This commit is contained in:
Bruno Ramirez
2026-11-24 11:30:48 -08:00
committed by GitHub
parent f5d1cd67c7
commit 02eee69130
5 changed files with 198 additions and 82 deletions
+1
View File
@@ -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;
@@ -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::<StringArray>()
.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::<StringArray>()
.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::<StringArray>()
.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(
+60
View File
@@ -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<Option<Self>> {
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<Option<&str>> {
let Some(column) = self.column("job_id") else {
return Ok(None);
};
let ids = column
.as_any()
.downcast_ref::<StringArray>()
.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))
}
}
}
+98 -3
View File
@@ -151,6 +151,7 @@ struct TestSqlService {
exchange_drops: Arc<AtomicUsize>,
result: RecordBatch,
result_tail: Vec<std::result::Result<RecordBatch, Status>>,
result_frames: Option<Vec<FlightData>>,
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<Option<&str>, &str>,
#[case] expected_refresh: std::result::Result<Option<&str>, &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<String> {
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 {
+10 -22
View File
@@ -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::<StringArray>())
.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::<UInt64Array>())
.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(),
))))
}
}