Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/reader/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,35 @@ impl ResultReader for ErrorReader {
}
}

/// Prevents repeated reader errors from masking a lost buffered error.
pub struct ErrorThenEndReader {
pub schema: SchemaRef,
pub error_pending: bool,
}

#[async_trait]
impl ResultReader for ErrorThenEndReader {
async fn schema(&self) -> Result<SchemaRef> {
Ok(self.schema.clone())
}

async fn next_batch(&mut self) -> Result<Option<RecordBatch>> {
if std::mem::take(&mut self.error_pending) {
Err(Error::io().message("simulated one-shot read error"))
} else {
Ok(None)
}
}

fn try_next_batch(&mut self) -> Result<crate::reader::TryNextBatch> {
if std::mem::take(&mut self.error_pending) {
Err(Error::io().message("simulated one-shot read error"))
} else {
Ok(crate::reader::TryNextBatch::End)
}
}
}

/// A reader that yields one successful batch, then errors on the
/// next `next_batch()` call. Used to exercise iterator
/// implementations' error-after-data path (i.e. that `Some(Err(...))`
Expand Down
102 changes: 75 additions & 27 deletions src/result_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,8 @@ pub enum TryNextBatch<'a> {
End,
}

type Prefetched<T> = Option<std::result::Result<T, Box<Error>>>;

// `ResultBatch::into_arrow()` was deliberately removed: the
// `#[non_exhaustive]` envelope is the right escape hatch already.
// Wrappers `match` directly on `ResultBatch::Arrow(rb)` and choose
Expand Down Expand Up @@ -464,14 +466,8 @@ pub struct ResultStream {
/// until the next call to `next_batch` replaces it.
current: Option<ResultBatch>,

/// A single batch pulled early by [`peek_first_batch`](Self::peek_first_batch)
/// and buffered for replay so the peek is **non-consuming**: the next
/// [`next_batch`](Self::next_batch) returns this batch instead of
/// re-entering the reader. Lets the statement layer read a DML
/// row-count result (which SEA delivers as the result set) without
/// stealing it from the caller's fetch — keeping result rows at parity
/// with the Thrift path. `None` once drained or when never peeked.
prefetched: Option<ResultBatch>,
/// A peek must preserve both data and read errors for the caller's fetch.
prefetched: Prefetched<ResultBatch>,

/// Row cursor inside [`current`](Self::current). Reset to `0`
/// every time `next_batch` populates a fresh batch.
Expand Down Expand Up @@ -718,7 +714,7 @@ impl ResultStream {
// A batch buffered by `peek_first_batch` is replayed here first,
// so a non-consuming peek doesn't steal it from the caller.
if let Some(batch) = self.prefetched.take() {
self.set_current_batch(batch);
self.set_current_batch(batch.map_err(|error| *error)?);
return Ok(self.current.as_ref());
}
if self.exhausted {
Expand Down Expand Up @@ -752,7 +748,7 @@ impl ResultStream {
/// network or background-prefetch progress.
pub fn try_next_batch(&mut self) -> Result<TryNextBatch<'_>> {
if let Some(batch) = self.prefetched.take() {
self.set_current_batch(batch);
self.set_current_batch(batch.map_err(|error| *error)?);
return Ok(TryNextBatch::Ready(
self.current.as_ref().expect("batch was just installed"),
));
Expand Down Expand Up @@ -790,9 +786,8 @@ impl ResultStream {

/// Non-consuming peek at the **first** batch of the stream.
///
/// Pulls one batch from the reader exactly once and buffers it so a
/// subsequent [`next_batch`](Self::next_batch) still returns it — the
/// peek does not advance consumption. Returns `None` for an empty
/// Buffers the first batch or error so the caller's next read observes
/// the same outcome. Returns `None` for an empty
/// stream. Only valid before any `next_batch`/`peek_first_batch` has
/// run (it no-ops if a batch is already current or buffered), which is
/// the only context it's used in: deriving a DML row-count off the
Expand All @@ -805,7 +800,7 @@ impl ResultStream {
.expect("ResultStream reader is present until into_owned_batches consumes it");
match reader.next_batch().await {
Ok(Some(rb)) => {
self.prefetched = Some(ResultBatch::Arrow(rb));
self.prefetched = Some(Ok(ResultBatch::Arrow(rb)));
// Stamp first-batch (result-set-ready) latency at fetch
// time, not when the caller later consumes the prefetched
// batch via `next_batch`. `record_result_batch` is
Expand All @@ -814,7 +809,7 @@ impl ResultStream {
// `result_set_ready_latency_millis` reflecting when the
// result set became ready rather than the caller's
// think-time before the first `next_batch` pull.
if let (Some(telemetry), Some(batch)) =
if let (Some(telemetry), Some(Ok(batch))) =
(&self.telemetry, self.prefetched.as_ref())
{
telemetry.record_batch(batch);
Expand All @@ -823,11 +818,16 @@ impl ResultStream {
Ok(None) => self.exhausted = true,
Err(e) => {
self.finalize_telemetry(Some(&e));
self.prefetched = Some(Err(Box::new(e.clone())));
Comment thread
aakash-saravanan-db marked this conversation as resolved.
Resolved
return Err(e);
}
}
}
Ok(self.prefetched.as_ref())
match self.prefetched.as_ref() {
Some(Ok(batch)) => Ok(Some(batch)),
Some(Err(error)) => Err((**error).clone()),
None => Ok(None),
}
}

/// The batch most recently buffered by
Expand Down Expand Up @@ -919,7 +919,10 @@ impl ResultStream {
// Preserve a peeked-but-not-yet-consumed first batch: it was
// pulled from the reader, so it must be yielded ahead of the
// reader's remaining batches or it would be silently dropped.
let prefetched = self.prefetched.take().map(|ResultBatch::Arrow(rb)| rb);
let prefetched = self
.prefetched
.take()
.map(|outcome| outcome.map(|ResultBatch::Arrow(rb)| rb));
OwnedBatchIter {
reader: self
.reader
Expand Down Expand Up @@ -954,10 +957,7 @@ impl Drop for ResultStream {
/// reader's natural end-of-stream the same way.
pub struct OwnedBatchIter {
reader: Box<dyn ResultReader>,
/// A batch peeked off the stream before conversion (see
/// [`ResultStream::peek_first_batch`]); yielded before the reader's
/// own batches so it isn't lost.
prefetched: Option<RecordBatch>,
prefetched: Prefetched<RecordBatch>,
telemetry: Option<ResultStreamTelemetry>,
done: bool,
}
Expand All @@ -969,11 +969,19 @@ impl Iterator for OwnedBatchIter {
if self.done {
return None;
}
if let Some(batch) = self.prefetched.take() {
if let Some(telemetry) = &self.telemetry {
telemetry.record_result_batch();
}
return Some(Ok(batch));
if let Some(outcome) = self.prefetched.take() {
return match outcome {
Ok(batch) => {
if let Some(telemetry) = &self.telemetry {
telemetry.record_result_batch();
}
Some(Ok(batch))
}
Err(error) => {
self.done = true;
Some(Err(*error))
}
};
}
// Runtime-aware blocking poll: uses block_in_place + the
// current Handle when there's a tokio runtime on this thread
Expand Down Expand Up @@ -1027,6 +1035,7 @@ impl Drop for OwnedBatchIter {
mod tests {
use super::*;
use crate::kernel_error::ErrorCode;
use crate::reader::test_utils::ErrorThenEndReader;
use crate::reader::InMemoryReader;
use arrow_array::{
ArrayRef, BinaryArray, BooleanArray, Date32Array, Decimal128Array, Decimal256Array,
Expand All @@ -1048,6 +1057,16 @@ mod tests {
.expect("from_reader")
}

async fn stream_with_one_shot_error() -> ResultStream {
let schema = schema_for(vec![Field::new("a", DataType::Int32, false)]);
ResultStream::from_reader(Box::new(ErrorThenEndReader {
schema,
error_pending: true,
}))
.await
.expect("from_reader")
}

async fn advance_to_first_row(stream: &mut ResultStream) {
let _ = stream
.next_batch()
Expand Down Expand Up @@ -1346,6 +1365,34 @@ mod tests {
assert!(stream.next_batch().await.unwrap().is_none());
}

#[tokio::test]
async fn next_batch_replays_peek_error() {
for nonblocking in [false, true] {
let mut stream = stream_with_one_shot_error().await;
assert!(stream.peek_first_batch().await.is_err());
let error = if nonblocking {
stream.try_next_batch().unwrap_err()
} else {
stream.next_batch().await.unwrap_err()
};
assert_eq!(error.message, "simulated one-shot read error");
assert!(stream.next_batch().await.unwrap().is_none());
}
}

#[tokio::test]
async fn into_owned_batches_replays_peek_error() {
let mut stream = stream_with_one_shot_error().await;
assert!(stream.peek_first_batch().await.is_err());

let mut iter = stream.into_owned_batches();
assert_eq!(
iter.next().unwrap().unwrap_err().message,
"simulated one-shot read error"
);
assert!(iter.next().is_none());
}

#[tokio::test]
async fn into_owned_batches_yields_then_terminates() {
// Stream construction is async (schema pulled via async fn);
Expand All @@ -1356,7 +1403,8 @@ mod tests {
.unwrap();
let b2 = RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![3]))]).unwrap();
let reader = InMemoryReader::new(b1.schema(), vec![b1.clone(), b2.clone()]);
let stream = ResultStream::from_reader(Box::new(reader)).await.unwrap();
let mut stream = ResultStream::from_reader(Box::new(reader)).await.unwrap();
assert!(stream.peek_first_batch().await.unwrap().is_some());

let mut iter = stream.into_owned_batches();
let first = iter.next().unwrap().unwrap();
Expand Down
12 changes: 11 additions & 1 deletion src/statement/mutable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -646,13 +646,23 @@ impl Statement {
self.last_closed = Some(Arc::clone(&closed));
let mut result_stream = ResultStream::from_reader(result.reader).await?;
result_stream.attach_telemetry(telemetry_for_body.clone());
let mut status = result.status;
if status.num_modified_rows.is_none() {
// Optional count reads must not turn a successful write into an execute error.
if let Ok(count) =
crate::statement::dml_count::read_dml_affected_rows(&mut result_stream)
.await
{
status.num_modified_rows = count;
}
}
let executed = ExecutedStatement::new(
Arc::clone(&self.session),
result.statement_id,
valid,
result_stream,
closed,
result.status,
status,
);
Ok(DirectStatement::Completed(executed))
}
Expand Down
80 changes: 79 additions & 1 deletion tests/v0_execute_wiremock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use arrow_ipc::writer::StreamWriter;
use arrow_schema::{DataType, Field, Fields, Schema};
use base64::{engine::general_purpose::STANDARD, Engine};
use databricks_sql_kernel::{
AuthConfig, ConnectionConfig, ErrorCode, ExecutedStatementHandle,
AuthConfig, ConnectionConfig, DirectStatement, ErrorCode, ExecutedStatementHandle,
GeospatialResultRepresentation, HttpConfig, ResultBatch, ResultConfig, Session, TryNextBatch,
TypedValue, MAX_CLIENT_QUERY_TIMEOUT,
};
Expand Down Expand Up @@ -2389,6 +2389,84 @@ async fn polling_path_carries_terminal_status_not_initial() {
exec.close().await.expect("close");
}

#[tokio::test]
async fn execute_direct_populates_count_without_consuming_result() {
for (count, server_count, state) in [
(2, None, "CLOSED"),
(0, None, "SUCCEEDED"),
(2, Some(11), "SUCCEEDED"),
] {
let server = MockServer::start().await;
mount_create_session(&server).await;
mount_delete_session(&server).await;
mount_close_any_statement(&server).await;
let batch = int64_batch("num_affected_rows", vec![count]);
let mut body: serde_json::Value =
serde_json::from_str(&succeeded_inline_body("stmt-direct-count", &batch)).unwrap();
body["status"]["state"] = json!(state);
if let Some(value) = server_count {
body["status"]["num_modified_rows"] = json!(value);
}
mount_execute(&server, body.to_string()).await;

let session = open_session(&server).await;
let mut stmt = session.statement();
stmt.spec().sql("UPDATE t SET x = x + 1");
let DirectStatement::Completed(mut exec) = stmt.execute_direct().await.unwrap() else {
panic!("inline result must return a completed statement");
};
let expected = server_count.unwrap_or(count);
assert_eq!(exec.num_modified_rows(), Some(expected));
let batches = drain(exec.result_stream_mut()).await;
assert_eq!(batches.len(), 1);
assert_eq!(batches[0].columns(), batch.columns());
assert_eq!(exec.num_modified_rows(), Some(expected));
exec.close().await.expect("close");
}
}

#[tokio::test]
async fn execute_direct_defers_dml_count_inference_error_to_fetch() {
let server = MockServer::start().await;
mount_create_session(&server).await;
mount_delete_session(&server).await;

let chunk_path = "/api/2.0/sql/statements/stmt-direct-count-error/result/chunks/1";
let batch = int64_batch("num_affected_rows", vec![1]);
let mut body: serde_json::Value =
serde_json::from_str(&closed_inline_body("stmt-direct-count-error", &batch)).unwrap();
let empty_chunk = arrow_schema_ipc_bytes(&batch.schema());
body["manifest"]["total_chunk_count"] = json!(2);
body["result"]["attachment"] = json!(STANDARD.encode(&empty_chunk));
body["result"]["byte_count"] = json!(empty_chunk.len());
body["result"]["row_count"] = json!(0);
body["result"]["next_chunk_index"] = json!(1);
mount_execute(&server, body.to_string()).await;
Mock::given(method("GET"))
.and(path(chunk_path))
.respond_with(ResponseTemplate::new(404))
.expect(1)
.mount(&server)
.await;

let session = open_session(&server).await;
let mut stmt = session.statement();
stmt.spec().sql("UPDATE t SET value = 1");
let DirectStatement::Completed(mut exec) = stmt.execute_direct().await.expect("execute direct")
else {
panic!("terminal response must return a completed statement");
};

assert_eq!(exec.num_modified_rows(), None);
let error = exec
.result_stream_mut()
.next_batch()
.await
.expect_err("fetch must replay the inference error");
assert_eq!(error.code, ErrorCode::NotFound);
exec.close().await.expect("close");
}

#[tokio::test]
async fn polling_path_materializes_dml_count_after_terminal_state() {
// The synchronous poll loop deliberately reads raw status responses. DML
Expand Down
Loading