Skip to main content

google_cloud_spanner/
read_only_transaction.rs

1// Copyright 2026 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::channel_pool::{ChannelTarget, TransactionAffinity};
16use crate::database_client::DatabaseClient;
17use crate::error::{SpannerInternalError, aborted_due_to_failed_initial_statement, internal_error};
18use crate::model::transaction_options::{Mode, ReadOnly};
19use crate::model::transaction_selector::Selector;
20use crate::model::{
21    BeginTransactionRequest, Mutation, Transaction, TransactionOptions, TransactionSelector,
22};
23use crate::precommit::PrecommitTokenTracker;
24use crate::read::ReadRequest;
25use crate::result_set::{ResultSet, ResultSetParams, StreamOperation};
26use crate::retry_delay::extract_retry_delay_from_error;
27use crate::statement::Statement;
28use crate::timestamp_bound::TimestampBound;
29use crate::transaction_retry_policy::is_aborted_or_emulator_error;
30use crate::{Error, Result};
31use bytes::Bytes;
32use google_cloud_gax::backoff_policy::BackoffPolicyArg;
33use google_cloud_gax::error::rpc::Status;
34use google_cloud_gax::options::RequestOptions as GaxRequestOptions;
35use google_cloud_gax::options::internal::RequestOptionsExt as _;
36use google_cloud_gax::retry_policy::RetryPolicyArg;
37use http::HeaderMap;
38use std::error::Error as _;
39use std::mem::replace;
40use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
41use std::time::Duration;
42use tokio::sync::Notify;
43use tokio::sync::futures::OwnedNotified;
44
45/// A builder for [SingleUseReadOnlyTransaction].
46///
47/// # Example
48/// ```
49/// # use google_cloud_spanner::client::Spanner;
50/// # use google_cloud_spanner::transaction::TimestampBound;
51/// # async fn build_tx(spanner: Spanner) -> Result<(), google_cloud_spanner::Error> {
52/// let db_client = spanner.database_client("projects/p/instances/i/databases/d").build().await?;
53/// let read_only_tx = db_client.single_use()
54///     .set_timestamp_bound(TimestampBound::strong())
55///     .build();
56/// # Ok(())
57/// # }
58/// ```
59#[derive(Clone, Debug)]
60pub struct SingleUseReadOnlyTransactionBuilder {
61    client: DatabaseClient,
62    timestamp_bound: Option<TimestampBound>,
63}
64
65impl SingleUseReadOnlyTransactionBuilder {
66    pub(crate) fn new(client: DatabaseClient) -> Self {
67        Self {
68            client,
69            timestamp_bound: None,
70        }
71    }
72
73    /// Sets the timestamp bound for the read-only transaction.
74    ///
75    /// # Example
76    /// ```
77    /// # use google_cloud_spanner::client::Spanner;
78    /// # use google_cloud_spanner::transaction::TimestampBound;
79    /// # async fn set_bound(spanner: Spanner) -> Result<(), google_cloud_spanner::Error> {
80    /// let db_client = spanner.database_client("projects/p/instances/i/databases/d").build().await?;
81    /// let builder = db_client.single_use().set_timestamp_bound(TimestampBound::strong());
82    /// # Ok(())
83    /// # }
84    /// ```
85    /// When reading data in Spanner in a read-only transaction, you can set a timestamp bound,
86    /// which tells Spanner how to choose a timestamp at which to read the data.
87    ///
88    /// See <https://docs.cloud.google.com/spanner/docs/timestamp-bounds> for more information.
89    pub fn set_timestamp_bound(mut self, bound: TimestampBound) -> Self {
90        self.timestamp_bound = Some(bound);
91        self
92    }
93
94    /// Builds the [SingleUseReadOnlyTransaction].
95    ///
96    /// # Example
97    ///
98    /// ```
99    /// # use google_cloud_spanner::client::Spanner;
100    /// # async fn build(spanner: Spanner) -> Result<(), google_cloud_spanner::Error> {
101    /// let db_client = spanner.database_client("projects/p/instances/i/databases/d").build().await?;
102    /// let tx = db_client.single_use().build();
103    /// # Ok(())
104    /// # }
105    /// ```
106    pub fn build(self) -> SingleUseReadOnlyTransaction {
107        let read_only = match self.timestamp_bound {
108            Some(bound) => ReadOnly::default().set_timestamp_bound(bound.0),
109            None => ReadOnly::default().set_strong(true),
110        };
111        let transaction_selector = crate::model::TransactionSelector::default()
112            .set_single_use(TransactionOptions::default().set_read_only(read_only));
113
114        let session_name = self.client.session_name();
115        SingleUseReadOnlyTransaction {
116            context: ReadContext {
117                session_name,
118                client: self.client,
119                transaction_selector: ReadContextTransactionSelector::Fixed(
120                    transaction_selector,
121                    None,
122                ),
123                precommit_token_tracker: PrecommitTokenTracker::new_noop(),
124                transaction_tag: None,
125                begin_transaction_request_options: None,
126                affinity: None,
127                aborted_state: AbortedState::new_noop(),
128            },
129        }
130    }
131}
132
133/// A single-use read-only transaction. A single-use read-only transaction is the most
134/// efficient way to execute a single query or read operation.
135///
136/// # Example
137/// ```
138/// # use google_cloud_spanner::client::Spanner;
139/// # use google_cloud_spanner::statement::Statement;
140/// # async fn run(spanner: Spanner) -> Result<(), google_cloud_spanner::Error> {
141/// let db_client = spanner.database_client("projects/p/instances/i/databases/d").build().await?;
142/// let tx = db_client.single_use().build();
143/// let stmt = Statement::builder("SELECT * FROM users WHERE id = @id")
144///     .add_param("id", &42)
145///     .build();
146/// let rs = tx.execute_query(stmt).await?;
147/// # Ok(())
148/// # }
149/// ```
150#[derive(Debug)]
151pub struct SingleUseReadOnlyTransaction {
152    context: ReadContext,
153}
154
155impl SingleUseReadOnlyTransaction {
156    /// Executes a query.
157    ///
158    /// # Example
159    /// ```
160    /// # use google_cloud_spanner::client::Spanner;
161    /// # use google_cloud_spanner::statement::Statement;
162    /// # async fn run(spanner: Spanner) -> Result<(), google_cloud_spanner::Error> {
163    /// let db_client = spanner.database_client("projects/p/instances/i/databases/d").build().await?;
164    /// let tx = db_client.single_use().build();
165    /// let stmt = Statement::builder("SELECT * FROM users WHERE id = @id")
166    ///     .add_param("id", &42)
167    ///     .build();
168    /// let mut rs = tx.execute_query(stmt).await?;
169    /// while let Some(row) = rs.next().await {
170    ///     let _row = row?;
171    ///     // process row
172    /// }
173    /// # Ok(())
174    /// # }
175    /// ```
176    pub async fn execute_query(&self, statement: impl Into<Statement>) -> Result<ResultSet> {
177        self.context.execute_query(statement, None).await
178    }
179
180    /// Reads rows from the database using key lookups and scans, as a simple key/value style alternative to execute_query.
181    ///
182    /// # Example
183    /// ```
184    /// # use google_cloud_spanner::client::Spanner;
185    /// # use google_cloud_spanner::key::KeySet;
186    /// # use google_cloud_spanner::read::ReadRequest;
187    /// # use google_cloud_spanner::key;
188    /// # async fn run(spanner: Spanner) -> Result<(), google_cloud_spanner::Error> {
189    /// let db_client = spanner.database_client("projects/p/instances/i/databases/d").build().await?;
190    /// let transaction = db_client.single_use().build();
191    ///
192    /// // Read using the primary key
193    /// let read_by_pk = ReadRequest::builder("Users", vec!["Id", "Name"]).with_keys(KeySet::all()).build();
194    /// let mut result_set = transaction.execute_read(read_by_pk).await?;
195    /// while let Some(row) = result_set.next().await {
196    ///     let _row = row?;
197    ///     // process row
198    /// }
199    ///
200    /// // Read using a secondary index
201    /// let read_by_index = ReadRequest::builder("Users", vec!["Id", "Name"])
202    ///     .with_index("UsersByIndex", key![1_i64]).build();
203    /// let mut result_set = transaction.execute_read(read_by_index).await?;
204    /// while let Some(row) = result_set.next().await {
205    ///     let _row = row?;
206    ///     // process row
207    /// }
208    /// # Ok(())
209    /// # }
210    /// ```
211    pub async fn execute_read(&self, read: impl Into<ReadRequest>) -> Result<ResultSet> {
212        self.context.execute_read(read).await
213    }
214}
215
216/// Options for how to start a transaction.
217#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
218#[non_exhaustive]
219pub enum BeginTransactionOption {
220    /// The transaction will be started inlined with the first statement.
221    /// This reduces the number of round-trips to Spanner by one.
222    ///
223    /// If the first statement in the transaction fails, the transaction will not
224    /// be started and will be marked as permanently failed. Any subsequent statements
225    /// executed on that transaction will also fail. To allow a transaction to continue
226    /// executing subsequent statements after an initial statement failure, use
227    /// `BeginTransactionOption::ExplicitBegin`.
228    #[default]
229    InlineBegin,
230    /// The transaction will be started explicitly using a `BeginTransaction` RPC before
231    /// any statement is executed.
232    ///
233    /// Use this option when:
234    /// 1. Multiple queries are executed concurrently at the start of the transaction.
235    /// 2. The first statement in the transaction might fail and the application wants to
236    ///    catch the error and continue executing subsequent statements in the same transaction
237    ///    at the same snapshot read timestamp.
238    ExplicitBegin,
239}
240
241/// A builder for [MultiUseReadOnlyTransaction].
242///
243/// # Example
244/// ```
245/// # use google_cloud_spanner::client::Spanner;
246/// # use google_cloud_spanner::transaction::TimestampBound;
247/// # async fn build_tx(spanner: Spanner) -> Result<(), google_cloud_spanner::Error> {
248/// let db_client = spanner.database_client("projects/p/instances/i/databases/d").build().await?;
249/// let read_only_tx = db_client.read_only_transaction()
250///     .set_timestamp_bound(TimestampBound::strong())
251///     .build()
252///     .await?;
253/// # Ok(())
254/// # }
255/// ```
256#[derive(Clone, Debug)]
257pub struct MultiUseReadOnlyTransactionBuilder {
258    client: DatabaseClient,
259    timestamp_bound: Option<TimestampBound>,
260    begin_transaction_option: BeginTransactionOption,
261    begin_gax_options: Option<crate::RequestOptions>,
262    affinity: Option<Arc<TransactionAffinity>>,
263}
264
265impl MultiUseReadOnlyTransactionBuilder {
266    pub(crate) fn new(client: DatabaseClient) -> Self {
267        Self {
268            client,
269            timestamp_bound: None,
270            begin_transaction_option: BeginTransactionOption::InlineBegin,
271            begin_gax_options: None,
272            affinity: None,
273        }
274    }
275
276    /// Sets the option for how to start a transaction.
277    ///
278    /// # Example
279    /// ```
280    /// # use google_cloud_spanner::client::Spanner;
281    /// # use google_cloud_spanner::transaction::BeginTransactionOption;
282    /// # use google_cloud_spanner::statement::Statement;
283    /// # async fn set_begin_option(spanner: Spanner) -> Result<(), google_cloud_spanner::Error> {
284    /// let db_client = spanner.database_client("projects/p/instances/i/databases/d").build().await?;
285    /// let transaction = db_client.read_only_transaction().set_begin_transaction_option(BeginTransactionOption::ExplicitBegin).build().await?;
286    /// let statement = Statement::builder("SELECT * FROM users").build();
287    /// let result_set = transaction.execute_query(statement).await?;
288    /// # Ok(())
289    /// # }
290    /// ```
291    ///
292    /// By default, the Spanner client will inline the `BeginTransaction` call with the first query
293    /// in the transaction (`BeginTransactionOption::InlineBegin`). This reduces the number of round-trips
294    /// to Spanner that are needed for a transaction. Setting this option to `ExplicitBegin` can be
295    /// beneficial for specific transaction shapes:
296    ///
297    /// 1. When the transaction executes multiple parallel queries at the start of the transaction.
298    ///    Only one query can include a `BeginTransaction` option, and all other queries must wait for
299    ///    the first query to return the first result before they can proceed to execute. An explicit
300    ///    `BeginTransaction` RPC will quickly return a transaction ID and allow all queries to start
301    ///    execution in parallel once the transaction ID has been returned.
302    /// 2. When the first query in the transaction could fail, and the application wants to catch the error
303    ///    and continue executing subsequent queries in the same read-only transaction. With `InlineBegin`,
304    ///    if the initial statement fails, the transaction is marked as permanently failed and will not
305    ///    start; all subsequent queries on that transaction will also fail without starting a transaction
306    ///    that excludes the first statement. Using `ExplicitBegin` establishes the snapshot transaction
307    ///    upfront before any statements are executed, allowing subsequent statements to continue executing
308    ///    at the same snapshot read timestamp even if an earlier statement fails.
309    ///
310    /// # Example: Retrying an Initial Query with ExplicitBegin
311    ///
312    /// Applications that want the latency benefit of `InlineBegin` for the
313    /// initial query, but want to fall back to `ExplicitBegin` if the first
314    /// statement fails, can implement a retry loop:
315    ///
316    /// ```
317    /// # use google_cloud_spanner::client::DatabaseClient;
318    /// # use google_cloud_spanner::result::ResultSet;
319    /// # use google_cloud_spanner::statement::Statement;
320    /// # use google_cloud_spanner::transaction::{
321    /// #     BeginTransactionOption, MultiUseReadOnlyTransaction,
322    /// # };
323    /// # async fn execute_query_with_retry(
324    /// #     database_client: &DatabaseClient,
325    /// #     statement: &Statement,
326    /// # ) -> Result<(MultiUseReadOnlyTransaction, ResultSet), google_cloud_spanner::Error> {
327    /// // Note: For read-only transactions that execute queries in parallel at the start,
328    /// // the recommendation is to use ExplicitBegin directly, rather than a retry loop.
329    /// let mut last_error = None;
330    /// for option in [
331    ///     BeginTransactionOption::InlineBegin,
332    ///     BeginTransactionOption::ExplicitBegin,
333    /// ] {
334    ///     let transaction = database_client
335    ///         .read_only_transaction()
336    ///         .set_begin_transaction_option(option)
337    ///         .build()
338    ///         .await?;
339    ///
340    ///     match transaction.execute_query(statement.clone()).await {
341    ///         Ok(result_set) => return Ok((transaction, result_set)),
342    ///         Err(error) => last_error = Some(error),
343    ///     }
344    /// }
345    ///
346    /// Err(last_error.expect("at least one attempt failed"))
347    /// # }
348    /// ```
349    ///
350    /// Default is `BeginTransactionOption::InlineBegin`.
351    pub fn set_begin_transaction_option(mut self, option: BeginTransactionOption) -> Self {
352        self.begin_transaction_option = option;
353        self
354    }
355
356    /// Sets the per-attempt timeout for the BeginTransaction RPC.
357    ///
358    /// # Example
359    /// ```
360    /// # use google_cloud_spanner::client::Spanner;
361    /// # use std::time::Duration;
362    /// # async fn sample(spanner: Spanner) -> Result<(), google_cloud_spanner::Error> {
363    /// let db_client = spanner.database_client("projects/p/instances/i/databases/d").build().await?;
364    /// let transaction = db_client.read_only_transaction()
365    ///     .with_begin_attempt_timeout(Duration::from_secs(10))
366    ///     .build()
367    ///     .await?;
368    /// # Ok(())
369    /// # }
370    /// ```
371    ///
372    /// Note: This timeout is only used if the transaction uses the `ExplicitBegin` transaction option.
373    pub fn with_begin_attempt_timeout(mut self, timeout: Duration) -> Self {
374        self.begin_gax_options
375            .get_or_insert_with(crate::RequestOptions::default)
376            .set_attempt_timeout(timeout);
377        self
378    }
379
380    /// Sets the retry policy for the BeginTransaction RPC.
381    ///
382    /// # Example
383    /// ```
384    /// # use google_cloud_spanner::client::Spanner;
385    /// # use google_cloud_gax::retry_policy::NeverRetry;
386    /// # async fn sample(spanner: Spanner) -> Result<(), google_cloud_spanner::Error> {
387    /// let db_client = spanner.database_client("projects/p/instances/i/databases/d").build().await?;
388    /// let transaction = db_client.read_only_transaction()
389    ///     .with_begin_retry_policy(NeverRetry)
390    ///     .build()
391    ///     .await?;
392    /// # Ok(())
393    /// # }
394    /// ```
395    ///
396    /// Note: This policy is only used if the transaction uses the `ExplicitBegin` transaction option.
397    pub fn with_begin_retry_policy(mut self, policy: impl Into<RetryPolicyArg>) -> Self {
398        self.begin_gax_options
399            .get_or_insert_with(crate::RequestOptions::default)
400            .set_retry_policy(policy);
401        self
402    }
403
404    /// Sets the backoff policy for the BeginTransaction RPC.
405    ///
406    /// # Example
407    /// ```
408    /// # use google_cloud_spanner::client::Spanner;
409    /// # use google_cloud_gax::exponential_backoff::ExponentialBackoff;
410    /// # async fn sample(spanner: Spanner) -> Result<(), google_cloud_spanner::Error> {
411    /// let db_client = spanner.database_client("projects/p/instances/i/databases/d").build().await?;
412    /// let transaction = db_client.read_only_transaction()
413    ///     .with_begin_backoff_policy(ExponentialBackoff::default())
414    ///     .build()
415    ///     .await?;
416    /// # Ok(())
417    /// # }
418    /// ```
419    ///
420    /// Note: This policy is only used if the transaction uses the `ExplicitBegin` transaction option.
421    pub fn with_begin_backoff_policy(mut self, policy: impl Into<BackoffPolicyArg>) -> Self {
422        self.begin_gax_options
423            .get_or_insert_with(crate::RequestOptions::default)
424            .set_backoff_policy(policy);
425        self
426    }
427
428    /// Sets the timestamp bound for the read-only transaction.
429    ///
430    /// # Example
431    /// ```
432    /// # use google_cloud_spanner::client::Spanner;
433    /// # use google_cloud_spanner::transaction::TimestampBound;
434    /// # async fn set_bound(spanner: Spanner) -> Result<(), google_cloud_spanner::Error> {
435    /// let db_client = spanner.database_client("projects/p/instances/i/databases/d").build().await?;
436    /// let builder = db_client.read_only_transaction().set_timestamp_bound(TimestampBound::strong());
437    /// # Ok(())
438    /// # }
439    /// ```
440    pub fn set_timestamp_bound(mut self, bound: TimestampBound) -> Self {
441        self.timestamp_bound = Some(bound);
442        self
443    }
444
445    /// Builds the [MultiUseReadOnlyTransaction] and starts the transaction
446    /// by calling the `BeginTransaction` RPC.
447    ///
448    /// # Example
449    /// ```
450    /// # use google_cloud_spanner::client::Spanner;
451    /// # async fn build(spanner: Spanner) -> Result<(), google_cloud_spanner::Error> {
452    /// let db_client = spanner.database_client("projects/p/instances/i/databases/d").build().await?;
453    /// let tx = db_client.read_only_transaction().build().await?;
454    /// # Ok(())
455    /// # }
456    /// ```
457    pub async fn build(self) -> crate::Result<MultiUseReadOnlyTransaction> {
458        let read_only = ReadOnly::default().set_return_read_timestamp(true);
459        let read_only = match self.timestamp_bound {
460            Some(bound) => read_only.set_timestamp_bound(bound.0),
461            None => read_only.set_strong(true),
462        };
463        let options = TransactionOptions::default().set_read_only(read_only);
464
465        let session_name = self.client.session_name();
466        let affinity = Some(
467            self.affinity
468                .unwrap_or_else(|| Arc::new(TransactionAffinity::new_read_only())),
469        );
470        let selector = match self.begin_transaction_option {
471            BeginTransactionOption::ExplicitBegin => {
472                let response = execute_begin_transaction(
473                    &self.client,
474                    session_name.clone(),
475                    options,
476                    None,
477                    &affinity,
478                    self.begin_gax_options.clone().unwrap_or_default(),
479                    None,
480                )
481                .await?;
482
483                let transaction_selector =
484                    crate::model::TransactionSelector::default().set_id(response.id);
485
486                ReadContextTransactionSelector::Fixed(transaction_selector, response.read_timestamp)
487            }
488            BeginTransactionOption::InlineBegin => ReadContextTransactionSelector::Lazy(Arc::new(
489                Mutex::new(TransactionState::NotStarted(options)),
490            )),
491        };
492
493        Ok(MultiUseReadOnlyTransaction {
494            context: ReadContext {
495                session_name,
496                client: self.client,
497                transaction_selector: selector,
498                precommit_token_tracker: PrecommitTokenTracker::new_noop(),
499                transaction_tag: None,
500                begin_transaction_request_options: self.begin_gax_options,
501                affinity,
502                aborted_state: AbortedState::new_noop(),
503            },
504        })
505    }
506
507    #[allow(dead_code)]
508    pub(crate) fn with_affinity(mut self, affinity: Arc<TransactionAffinity>) -> Self {
509        self.affinity = Some(affinity);
510        self
511    }
512}
513
514/// A multi-use read-only transaction. This transaction can be used for multiple read queries
515/// ensuring consistency across all queries.
516///
517/// # Example
518/// ```
519/// # use google_cloud_spanner::client::Spanner;
520/// # use google_cloud_spanner::statement::Statement;
521/// # async fn run(spanner: Spanner) -> Result<(), google_cloud_spanner::Error> {
522/// let db_client = spanner.database_client("projects/p/instances/i/databases/d").build().await?;
523/// let tx = db_client.read_only_transaction().build().await?;
524/// let stmt1 = Statement::builder("SELECT * FROM users WHERE id = @id")
525///     .add_param("id", &42)
526///     .build();
527/// let mut rs1 = tx.execute_query(stmt1).await?;
528///
529/// let stmt2 = Statement::builder("SELECT * FROM other_table")
530///     .build();
531/// let mut rs2 = tx.execute_query(stmt2).await?;
532/// # Ok(())
533/// # }
534/// ```
535#[derive(Clone, Debug)]
536pub struct MultiUseReadOnlyTransaction {
537    pub(crate) context: ReadContext,
538}
539
540impl MultiUseReadOnlyTransaction {
541    /// Returns the read timestamp chosen for the transaction.
542    pub fn read_timestamp(&self) -> Option<wkt::Timestamp> {
543        self.context.transaction_selector.read_timestamp()
544    }
545
546    /// Executes a query using this transaction.
547    ///
548    /// # Example
549    /// ```
550    /// # use google_cloud_spanner::client::Spanner;
551    /// # use google_cloud_spanner::statement::Statement;
552    /// # async fn run(spanner: Spanner) -> Result<(), google_cloud_spanner::Error> {
553    /// let db_client = spanner.database_client("projects/p/instances/i/databases/d").build().await?;
554    /// let tx = db_client.read_only_transaction().build().await?;
555    /// let stmt = Statement::builder("SELECT * FROM users WHERE id = @id")
556    ///     .add_param("id", &42)
557    ///     .build();
558    /// let mut rs = tx.execute_query(stmt).await?;
559    /// while let Some(row) = rs.next().await {
560    ///     let _row = row?;
561    ///     // process row
562    /// }
563    /// # Ok(())
564    /// # }
565    /// ```
566    ///
567    /// # Note
568    /// If this transaction was configured with `BeginTransactionOption::InlineBegin` (the default)
569    /// and this is the first statement, an execution failure will prevent the transaction from starting and
570    /// mark it as permanently failed. All subsequent statements on this transaction will also fail. To allow a
571    /// read-only transaction to continue executing subsequent statements after an initial statement failure,
572    /// configure `BeginTransactionOption::ExplicitBegin` when building the transaction.
573    pub async fn execute_query(&self, statement: impl Into<Statement>) -> Result<ResultSet> {
574        self.context.execute_query(statement, None).await
575    }
576
577    /// Reads rows from the database using key lookups and scans, as a simple key/value style alternative to execute_query.
578    ///
579    /// # Example
580    /// ```
581    /// # use google_cloud_spanner::client::Spanner;
582    /// # use google_cloud_spanner::key::KeySet;
583    /// # use google_cloud_spanner::read::ReadRequest;
584    /// # use google_cloud_spanner::key;
585    /// # async fn run(spanner: Spanner) -> Result<(), google_cloud_spanner::Error> {
586    /// let db_client = spanner.database_client("projects/p/instances/i/databases/d").build().await?;
587    /// let transaction = db_client.read_only_transaction().build().await?;
588    ///
589    /// // Read using the primary key
590    /// let read_by_pk = ReadRequest::builder("Users", vec!["Id", "Name"]).with_keys(KeySet::all()).build();
591    /// let mut result_set = transaction.execute_read(read_by_pk).await?;
592    /// while let Some(row) = result_set.next().await {
593    ///     let _row = row?;
594    ///     // process row
595    /// }
596    ///
597    /// // Read using a secondary index
598    /// let read_by_index = ReadRequest::builder("Users", vec!["Id", "Name"])
599    ///     .with_index("UsersByIndex", key![1_i64]).build();
600    /// let mut result_set = transaction.execute_read(read_by_index).await?;
601    /// while let Some(row) = result_set.next().await {
602    ///     let _row = row?;
603    ///     // process row
604    /// }
605    /// # Ok(())
606    /// # }
607    /// ```
608    ///
609    /// # Note
610    /// If this transaction was configured with `BeginTransactionOption::InlineBegin` (the default)
611    /// and this is the first statement, an execution failure will prevent the transaction from starting and
612    /// mark it as permanently failed. All subsequent statements on this transaction will also fail. To allow a
613    /// read-only transaction to continue executing subsequent statements after an initial statement failure,
614    /// configure `BeginTransactionOption::ExplicitBegin` when building the transaction.
615    pub async fn execute_read(&self, read: impl Into<ReadRequest>) -> Result<ResultSet> {
616        self.context.execute_read(read).await
617    }
618
619    /// Returns a reference to the transaction channel affinity handle, if set.
620    #[allow(dead_code)]
621    pub(crate) fn affinity(&self) -> Option<&TransactionAffinity> {
622        self.context.affinity()
623    }
624}
625
626/// Executes an explicit `BeginTransaction` RPC on Spanner.
627pub(crate) async fn execute_begin_transaction<'a>(
628    client: &DatabaseClient,
629    session_name: String,
630    options: TransactionOptions,
631    transaction_tag: Option<String>,
632    channel_target: impl Into<ChannelTarget<'a>>,
633    request_options: GaxRequestOptions,
634    mutation_key: Option<Mutation>,
635) -> Result<Transaction> {
636    let mut request = BeginTransactionRequest::default()
637        .set_session(session_name)
638        .set_options(options)
639        .set_or_clear_mutation_key(mutation_key);
640    if let Some(tag) = transaction_tag {
641        request = request
642            .set_request_options(crate::model::RequestOptions::default().set_transaction_tag(tag));
643    }
644
645    let response = client
646        .begin_transaction(request, request_options, channel_target)
647        .await?;
648    if response.id.is_empty() {
649        return Err(internal_error("Transaction ID was not returned by Spanner"));
650    }
651    Ok(response)
652}
653
654#[derive(Clone, Debug)]
655pub(crate) enum ReadContextTransactionSelector {
656    Fixed(crate::model::TransactionSelector, Option<wkt::Timestamp>),
657    Lazy(Arc<Mutex<TransactionState>>),
658}
659
660#[derive(Clone, Debug)]
661pub(crate) enum TransactionState {
662    NotStarted(crate::model::TransactionOptions),
663    Starting(crate::model::TransactionOptions, Arc<Notify>),
664    Started(crate::model::TransactionSelector, Option<wkt::Timestamp>),
665    Failed(TransactionStartFailure),
666    FirstStatementFailed,
667}
668
669enum SelectorStatus {
670    Ready(crate::model::TransactionSelector),
671    Wait(OwnedNotified),
672}
673
674/// Represents the required action when preparing a transaction selector for commit.
675#[derive(Debug)]
676pub(crate) enum CommitAction {
677    /// The transaction has already started and has an established transaction ID.
678    Ready(Bytes),
679    /// An asynchronous statement is currently in flight starting the transaction.
680    Starting,
681    /// The transaction has not started yet. The caller has atomically transitioned
682    /// the state to `Starting` and must execute an explicit `BeginTransaction` RPC.
683    Begin(TransactionOptions, Arc<Notify>),
684}
685
686/// Represents the failure reason when a transaction fails to start.
687///
688/// Unlike [crate::Error], [TransactionStartFailure] implements [Clone] so it can be stored
689/// in the shared [TransactionState::Failed] state and cleanly broadcast to any concurrent
690/// followers or subsequent operations without loss of gRPC status, message, or AIP-193 error details.
691#[derive(Clone, Debug, PartialEq)]
692pub(crate) enum TransactionStartFailure {
693    /// A gRPC service error returned by Spanner (e.g. `NotFound`, `PermissionDenied`).
694    /// Preserves the exact status code, message, and all AIP-193 error details.
695    Service(Status),
696    /// An internal or client-side failure (e.g. Spanner failed to return a transaction ID).
697    Internal(String),
698}
699
700impl TransactionStartFailure {
701    pub(crate) fn from_error(err: &crate::Error) -> Self {
702        if let Some(status) = err.status() {
703            return Self::Service(status.clone());
704        }
705
706        if let Some(SpannerInternalError::UnexpectedData(message)) = err
707            .source()
708            .and_then(|source| source.downcast_ref::<SpannerInternalError>())
709        {
710            return Self::Internal(message.clone());
711        }
712
713        Self::Internal(err.to_string())
714    }
715
716    pub(crate) fn to_error(&self) -> crate::Error {
717        match self {
718            Self::Service(status) => {
719                let error_description = if status.message.is_empty() {
720                    format!("status code {}", status.code)
721                } else {
722                    status.message.clone()
723                };
724                let status = status.clone().set_message(format!(
725                    "Transaction cannot be used: initial statement failed with: {error_description}"
726                ));
727                crate::Error::service(status)
728            }
729            Self::Internal(message) => internal_error(format!(
730                "Transaction cannot be used: initial statement failed with: {message}"
731            )),
732        }
733    }
734}
735
736impl ReadContextTransactionSelector {
737    /// Acquires an exclusive mutex lock on the inner lazy transaction state, recovering from lock poisoning via `into_inner()`.
738    ///
739    /// Returns `None` if this is a `Fixed` transaction selector.
740    ///
741    /// # Poison Recovery Rationale
742    /// `lazy` protects the transaction lifecycle state (`TransactionState`). State transitions are
743    /// atomic enum assignments; the underlying data is always memory-safe and structurally sound
744    /// in Rust even if an earlier thread panicked. Recovering the guard via `into_inner()` ensures
745    /// that an isolated panic in an application query, streaming task, or fallback routine does not
746    /// permanently poison the selector lock and cascade into fatal panics across concurrent waiters,
747    /// subsequent statements, commit attempts, or cleanup routines.
748    fn lock_state(&self) -> Option<MutexGuard<'_, TransactionState>> {
749        match self {
750            Self::Lazy(lazy) => Some(lazy.lock().unwrap_or_else(PoisonError::into_inner)),
751            Self::Fixed(_, _) => None,
752        }
753    }
754
755    /// Returns whether this is a lazy transaction selector.
756    pub(crate) fn is_lazy(&self) -> bool {
757        matches!(self, Self::Lazy(_))
758    }
759
760    /// Returns whether the transaction has successfully started.
761    pub(crate) fn is_started(&self) -> bool {
762        if let Self::Fixed(selector, _) = self {
763            return matches!(selector.selector, Some(Selector::Id(_)));
764        }
765        if let Some(guard) = self.lock_state() {
766            return matches!(&*guard, TransactionState::Started(_, _));
767        }
768        false
769    }
770
771    pub(crate) async fn selector(&self) -> crate::Result<crate::model::TransactionSelector> {
772        match self {
773            Self::Fixed(selector, _) => Ok(selector.clone()),
774            Self::Lazy(_) => loop {
775                match self.poll_selector_status()? {
776                    SelectorStatus::Ready(selector) => return Ok(selector),
777                    SelectorStatus::Wait(notified) => notified.await,
778                }
779            },
780        }
781    }
782
783    /// Inspects the current lazy selector state returning whether it is ready,
784    /// failed, or needs to wait for the transaction to start.
785    fn poll_selector_status(&self) -> crate::Result<SelectorStatus> {
786        let Some(mut guard) = self.lock_state() else {
787            unreachable!("poll_selector_status called on non-Lazy selector");
788        };
789
790        // Fast path: Transaction is already started.
791        if let TransactionState::Started(selector, _) = &*guard {
792            return Ok(SelectorStatus::Ready(selector.clone()));
793        }
794
795        // If the transaction has not started, extract options and transition the state to Starting.
796        let pending_options = if let TransactionState::NotStarted(options) = &*guard {
797            Some(options.clone())
798        } else {
799            // The state is either Starting or Failed. Concurrent threads will yield None here
800            // and fall through to either wait for the leader or fail immediately.
801            None
802        };
803        if let Some(options) = pending_options {
804            // This thread becomes the "leader" and will start the transaction.
805            let notify = Arc::new(Notify::new());
806            *guard = TransactionState::Starting(options.clone(), Arc::clone(&notify));
807            return Ok(SelectorStatus::Ready(
808                crate::model::TransactionSelector::default().set_begin(options),
809            ));
810        }
811
812        // Handle other states: yield error or wait.
813        match &*guard {
814            // Note: Failed will be reached if either:
815            // 1. The transaction was configured with explicit BeginTransaction and the BeginTransaction RPC failed.
816            // 2. Or the initial statement with inlined begin failed, marking the transaction as failed.
817            TransactionState::Failed(failure) => Err(failure.to_error()),
818            // FirstStatementFailed is reached if the initial statement fails in a Read-Write transaction using inline-begin.
819            // When in this state, the transaction must first call an explicit BeginTransaction RPC.
820            // Any subsequent statements or commit attempts should fail fast.
821            // Returning Aborted signals the TransactionRunner to retry the transaction with an explicit BeginTransaction RPC.
822            TransactionState::FirstStatementFailed => {
823                Err(aborted_due_to_failed_initial_statement())
824            }
825            // Transaction is starting. Register the Notified future while holding the lock to prevent lost wakeups.
826            TransactionState::Starting(_, notify) => {
827                Ok(SelectorStatus::Wait(Arc::clone(notify).notified_owned()))
828            }
829            TransactionState::Started(_, _) | TransactionState::NotStarted(_) => unreachable!(),
830        }
831    }
832
833    /// Updates the transaction state to `Started` with the given transaction ID and optional
834    /// read timestamp.
835    ///
836    /// This method is called when a transaction has successfully been initiated (either via
837    /// an inline begin in a query or an explicit `BeginTransaction` RPC).
838    ///
839    /// If the previous state was `Starting`, it will notify all concurrent threads that were
840    /// waiting for the transaction to start.
841    pub(crate) fn update(
842        &self,
843        id: bytes::Bytes,
844        timestamp: Option<wkt::Timestamp>,
845    ) -> crate::Result<()> {
846        let Some(mut guard) = self.lock_state() else {
847            return Ok(());
848        };
849
850        if matches!(
851            &*guard,
852            TransactionState::NotStarted(_) | TransactionState::Starting(_, _)
853        ) {
854            // Atomically transition the state to Started and extract the previous state.
855            // We do this to take ownership of the Notify handle (if it was Starting)
856            // so we can notify waiters after dropping the lock.
857            let previous_state = replace(
858                &mut *guard,
859                TransactionState::Started(TransactionSelector::default().set_id(id), timestamp),
860            );
861            drop(guard);
862
863            // Notify all queries that are waiting for the transaction.
864            if let TransactionState::Starting(_, notify) = previous_state {
865                notify.notify_waiters();
866            }
867            Ok(())
868        } else if let TransactionState::Started(existing_selector, _) = &*guard {
869            // Spanner returns the transaction ID on all statements executed within that transaction
870            // when using multiplexed sessions.If the transaction has already started with the same ID,
871            // this is expected behavior and can be ignored.
872            if existing_selector.id() == Some(&id) {
873                Ok(())
874            } else {
875                Err(crate::error::internal_error(
876                    "got a transaction id for an already Started or Failed transaction",
877                ))
878            }
879        } else {
880            // This should never happen.
881            Err(crate::error::internal_error(
882                "got a transaction id for an already Started or Failed transaction",
883            ))
884        }
885    }
886
887    /// Returns the transaction ID if it is already available, without waiting.
888    ///
889    /// This method inspects the selector and returns the transaction ID if the
890    /// transaction has already started. It returns `None` if the transaction
891    /// has not yet started or is in a state without an ID.
892    pub(crate) fn get_id_no_wait(&self) -> crate::Result<Option<bytes::Bytes>> {
893        match self {
894            Self::Fixed(selector, _) => {
895                if let Some(Selector::Id(id)) = &selector.selector {
896                    return Ok(Some(id.clone()));
897                }
898            }
899            Self::Lazy(_) => {
900                if let Some(guard) = self.lock_state()
901                    && let TransactionState::Started(selector, _) = &*guard
902                    && let Some(Selector::Id(id)) = &selector.selector
903                {
904                    return Ok(Some(id.clone()));
905                }
906            }
907        }
908        Ok(None)
909    }
910
911    /// Atomically resolves the selector state for a commit operation.
912    ///
913    /// - If already started, returns the established transaction ID (`Ready`).
914    /// - If currently being started by an in-flight statement, returns `Starting` without waiting,
915    ///   allowing the commit caller to fail fast with an informative error.
916    /// - If the initial statement failed or was aborted, returns the failure error.
917    /// - If not started (e.g. mutation-only transaction), atomically transitions the state to `Starting`
918    ///   and returns `Begin`, electing the caller as leader to execute `BeginTransaction`.
919    pub(crate) fn prepare_for_commit(&self) -> Result<CommitAction> {
920        match self {
921            Self::Fixed(selector, _) => Self::prepare_fixed_for_commit(selector),
922            Self::Lazy(lazy) => Self::prepare_lazy_for_commit(lazy),
923        }
924    }
925
926    fn prepare_fixed_for_commit(selector: &TransactionSelector) -> Result<CommitAction> {
927        selector
928            .id()
929            .cloned()
930            .map(CommitAction::Ready)
931            .ok_or_else(|| internal_error("Transaction ID is missing"))
932    }
933
934    fn prepare_lazy_for_commit(lazy: &Arc<Mutex<TransactionState>>) -> Result<CommitAction> {
935        let mut guard = lazy.lock().unwrap_or_else(PoisonError::into_inner);
936        match &*guard {
937            TransactionState::Started(selector, _) => Self::prepare_fixed_for_commit(selector),
938            TransactionState::Starting(_, _) => Ok(CommitAction::Starting),
939            TransactionState::Failed(failure) => Err(failure.to_error()),
940            TransactionState::FirstStatementFailed => {
941                Err(aborted_due_to_failed_initial_statement())
942            }
943            TransactionState::NotStarted(options) => {
944                let options = options.clone();
945                let notify = Arc::new(Notify::new());
946                *guard = TransactionState::Starting(options.clone(), Arc::clone(&notify));
947                Ok(CommitAction::Begin(options, notify))
948            }
949        }
950    }
951
952    /// Handles the cancellation of an operation that was starting the transaction.
953    ///
954    /// If the transaction was in the `Starting` state, transitions the state appropriately
955    /// and wakes any waiting concurrent operations:
956    /// - For read-write transactions: transitions to `FirstStatementFailed`, so concurrent
957    ///   operations fail fast with `Aborted` and the runner retries with an explicit `BeginTransaction`.
958    /// - For read-only transactions: resets to `NotStarted`, allowing another query to attempt
959    ///   the inlined begin.
960    pub(crate) fn on_cancelled_starting(&self) {
961        let Some(mut guard) = self.lock_state() else {
962            return;
963        };
964
965        if let TransactionState::Starting(options, notify) = &*guard {
966            let notify = Arc::clone(notify);
967            let is_read_write = matches!(&options.mode, Some(Mode::ReadWrite(_)));
968            if is_read_write {
969                *guard = TransactionState::FirstStatementFailed;
970            } else {
971                *guard = TransactionState::NotStarted(options.clone());
972            }
973            drop(guard);
974            notify.notify_waiters();
975        }
976    }
977
978    /// Returns whether the initial statement failed for an inline-begin transaction.
979    pub(crate) fn is_first_statement_failed(&self) -> bool {
980        let Some(guard) = self.lock_state() else {
981            return false;
982        };
983        matches!(&*guard, TransactionState::FirstStatementFailed)
984    }
985
986    /// Returns the selector to use when restarting a streaming SQL query or streaming read.
987    ///
988    /// This method is called exclusively by [`ResultSet::restart_stream`] when retrying
989    /// after a transient stream failure. Unary RPCs (such as DML `ExecuteSql` or `ExecuteBatchDml`)
990    /// do not use this method because GAX automatically retries the cloned unary request.
991    ///
992    /// Unlike [`selector()`](Self::selector), which returns `Wait(notified)` when the transaction
993    /// is in the `Starting` state (which would cause a stream leader to self-deadlock waiting on itself),
994    /// this method inspects the state synchronously:
995    /// - If the transaction has already started (`Started`), returns the established selector.
996    /// - If the transaction is in the process of starting (`Starting`), returns a selector
997    ///   with the inlined begin options so the restart request can re-attempt the inlined begin.
998    /// - If the transaction reached a failure state (`Failed` or `FirstStatementFailed`),
999    ///   returns the corresponding error immediately.
1000    /// - A stream restart should never occur when the selector is `NotStarted`, as a stream
1001    ///   must have already been initiated to require a restart.
1002    pub(crate) fn selector_for_restart(&self) -> crate::Result<crate::model::TransactionSelector> {
1003        match self {
1004            Self::Fixed(selector, _) => Ok(selector.clone()),
1005            Self::Lazy(lazy) => {
1006                let guard = lazy.lock().unwrap_or_else(PoisonError::into_inner);
1007                match &*guard {
1008                    TransactionState::Started(selector, _) => Ok(selector.clone()),
1009                    TransactionState::Starting(options, _) => {
1010                        Ok(crate::model::TransactionSelector::default().set_begin(options.clone()))
1011                    }
1012                    TransactionState::NotStarted(_) => Err(internal_error(
1013                        "Cannot restart stream on a NotStarted transaction",
1014                    )),
1015                    TransactionState::Failed(failure) => Err(failure.to_error()),
1016                    TransactionState::FirstStatementFailed => {
1017                        Err(aborted_due_to_failed_initial_statement())
1018                    }
1019                }
1020            }
1021        }
1022    }
1023
1024    /// Transitions the transaction state to a failed state and wakes any concurrent
1025    /// operations parked waiting for an inlined begin to finish.
1026    ///
1027    /// # Rationale
1028    /// When an initial statement in a transaction includes an inlined `BeginTransaction`
1029    /// option and fails before receiving a transaction ID:
1030    /// - **Read-Write Transactions**: We must not automatically begin a transaction or
1031    ///   restart the stream. The error is returned directly to the application closure.
1032    ///   If the error is `Aborted` (or emulator error), the state transitions to `Failed`.
1033    ///   Parked followers wake up and fail fast with the leader's error without creating orphaned
1034    ///   transactions, while the runner retry loop retries with an inlined begin.
1035    ///   If non-retryable (e.g., `InvalidArgument`), the state transitions to
1036    ///   `FirstStatementFailed` and wakes any concurrent waiters. The runner will retry
1037    ///   with an explicit `BeginTransaction` RPC.
1038    /// - **Read-Only Transactions**: The state transitions to `Failed` and wakes any waiting
1039    ///   concurrent operations. The transaction fails fast; no fallback `BeginTransaction` RPC
1040    ///   is sent, and subsequent operations on the transaction will also fail. Applications
1041    ///   requiring resilience to initial statement failures should configure
1042    ///   `BeginTransactionOption::ExplicitBegin`.
1043    /// - **Already Started / Non-Lazy**: If the transaction is already established or is not
1044    ///   in the `Starting` state, this is a no-op.
1045    pub(crate) fn set_failed(&self, error: &Error, is_emulator: bool) {
1046        let Some(mut guard) = self.lock_state() else {
1047            return;
1048        };
1049        if let TransactionState::Starting(options, notify) = &*guard {
1050            let notify = Arc::clone(notify);
1051            let is_read_write = matches!(&options.mode, Some(Mode::ReadWrite(_)));
1052            if is_read_write {
1053                // If the initial statement in a ReadWrite transaction failed with a non-aborted error
1054                // (e.g. InvalidArgument or syntax error), Spanner never started a transaction.
1055                // Marking `FirstStatementFailed` ensures that if the application catches this error
1056                // and attempts subsequent statements, they fail fast with a synthetic Aborted error,
1057                // signaling TransactionRunner to retry with an explicit BeginTransaction RPC so that
1058                // subsequent operations can execute within an active transaction.
1059                //
1060                // If the initial statement failed with a genuine Aborted error (concurrency conflict),
1061                // retrying with InlineBegin is still preferred to preserve single-hop efficiency, so
1062                // we transition to `Failed` and let the runner perform a normal backoff retry.
1063                if !is_aborted_or_emulator_error(error, is_emulator) {
1064                    *guard = TransactionState::FirstStatementFailed;
1065                } else {
1066                    *guard = TransactionState::Failed(TransactionStartFailure::from_error(error));
1067                }
1068            } else {
1069                tracing::debug!(
1070                    "Initial statement in read-only transaction failed; marking transaction as permanently failed. \
1071                    All subsequent statements on this transaction will fail. \
1072                    Hint: If your application needs to handle errors on the first statement and continue \
1073                    using the read-only transaction, configure `BeginTransactionOption::ExplicitBegin`. \
1074                    Error: {error:?}"
1075                );
1076                *guard = TransactionState::Failed(TransactionStartFailure::from_error(error));
1077            }
1078            drop(guard);
1079            notify.notify_waiters();
1080        }
1081    }
1082
1083    /// Returns the read timestamp of the transaction, if available.
1084    ///
1085    /// For `Fixed` transactions, this returns the timestamp stored in the variant.
1086    /// For `Lazy` transactions, this returns the timestamp once the transaction has successfully started
1087    /// and yielded a timestamp. Returns `None` if the transaction has not started or did not yield a timestamp.
1088    pub(crate) fn read_timestamp(&self) -> Option<wkt::Timestamp> {
1089        match self {
1090            Self::Fixed(_, timestamp) => *timestamp,
1091            Self::Lazy(_) => match self.lock_state().as_deref() {
1092                Some(TransactionState::Started(_, timestamp)) => *timestamp,
1093                _ => None,
1094            },
1095        }
1096    }
1097}
1098
1099/// A guard that manages the `Starting` state of a transaction during an operation.
1100///
1101/// When an operation initiates an inlined `BeginTransaction`, it transitions the
1102/// transaction state to `Starting`. If that operation is cancelled (e.g. timeout,
1103/// cancellation of future before completion) without disarming this guard,
1104/// `on_cancelled_starting()` is called to safely transition the state and wake any
1105/// waiting concurrent operations.
1106pub(crate) struct LazyTransactionStartGuard {
1107    selector: Option<ReadContextTransactionSelector>,
1108}
1109
1110impl LazyTransactionStartGuard {
1111    pub(crate) fn new(selector: Option<ReadContextTransactionSelector>) -> Self {
1112        Self { selector }
1113    }
1114
1115    pub(crate) fn disarm(&mut self) {
1116        self.selector = None;
1117    }
1118}
1119
1120impl Drop for LazyTransactionStartGuard {
1121    fn drop(&mut self) {
1122        if let Some(selector) = self.selector.take() {
1123            selector.on_cancelled_starting();
1124        }
1125    }
1126}
1127
1128#[derive(Clone, Debug)]
1129pub(crate) struct AbortedInfo {
1130    pub(crate) status: Status,
1131    pub(crate) retry_delay: Option<Duration>,
1132}
1133
1134impl AbortedInfo {
1135    pub(crate) fn from_error(error: &Error) -> Option<Self> {
1136        let status = error.status()?.clone();
1137        let retry_delay = extract_retry_delay_from_error(error);
1138        Some(Self {
1139            status,
1140            retry_delay,
1141        })
1142    }
1143
1144    pub(crate) fn to_error(&self) -> Error {
1145        Error::service(self.status.clone())
1146    }
1147}
1148
1149#[derive(Clone, Debug)]
1150pub(crate) enum AbortedState {
1151    NoOp,
1152    Track(Arc<OnceLock<AbortedInfo>>),
1153}
1154
1155impl AbortedState {
1156    pub(crate) fn new() -> Self {
1157        Self::Track(Arc::new(OnceLock::new()))
1158    }
1159
1160    pub(crate) fn new_noop() -> Self {
1161        Self::NoOp
1162    }
1163
1164    pub(crate) fn record(&self, error: &Error, is_emulator: bool) {
1165        if let Self::Track(info_lock) = self {
1166            if info_lock.get().is_some() || !is_aborted_or_emulator_error(error, is_emulator) {
1167                return;
1168            }
1169            if let Some(info) = AbortedInfo::from_error(error) {
1170                let _ = info_lock.set(info);
1171            }
1172        }
1173    }
1174
1175    pub(crate) fn aborted_info(&self) -> Option<&AbortedInfo> {
1176        match self {
1177            Self::Track(info_lock) => info_lock.get(),
1178            Self::NoOp => None,
1179        }
1180    }
1181}
1182
1183impl Default for AbortedState {
1184    fn default() -> Self {
1185        Self::new()
1186    }
1187}
1188
1189#[derive(Clone, Debug)]
1190pub(crate) struct ReadContext {
1191    pub(crate) session_name: String,
1192    pub(crate) client: DatabaseClient,
1193    pub(crate) transaction_selector: ReadContextTransactionSelector,
1194    pub(crate) precommit_token_tracker: PrecommitTokenTracker,
1195    pub(crate) transaction_tag: Option<String>,
1196    pub(crate) begin_transaction_request_options: Option<GaxRequestOptions>,
1197    pub(crate) affinity: Option<Arc<TransactionAffinity>>,
1198    pub(crate) aborted_state: AbortedState,
1199}
1200
1201impl ReadContext {
1202    /// Amends the given request options with the transaction tag if present.
1203    ///
1204    /// This method returns the `RequestOptions` that should be used for the request.
1205    /// If no `transaction_tag` has been set, the given `RequestOptions` is returned unchanged.
1206    /// If a `transaction_tag` has been set, the given `RequestOptions` is modified to include the tag
1207    /// (or a new `RequestOptions` is created if `None` was passed in).
1208    pub(crate) fn amend_request_options(
1209        &self,
1210        mut options: Option<crate::model::RequestOptions>,
1211    ) -> Option<crate::model::RequestOptions> {
1212        if let Some(tag) = &self.transaction_tag {
1213            options
1214                .get_or_insert_with(crate::model::RequestOptions::default)
1215                .transaction_tag = tag.clone();
1216        }
1217        options
1218    }
1219
1220    /// Explicitly executes a `BeginTransaction` RPC for a transaction being committed.
1221    ///
1222    /// When using `BeginTransactionOption::InlineBegin` (the default), transactions normally inline
1223    /// the `BeginTransaction` request into the first read or query statement. However, a read-write
1224    /// transaction may consist entirely of buffered mutations without any preceding read or query statements.
1225    ///
1226    /// While Spanner's `CommitRequest` technically allows specifying a `single_use_transaction` option
1227    /// to begin and commit in a single round-trip (as used in `write_at_least_once`),
1228    /// doing so provides no replay protection—any network retry of the commit could re-execute
1229    /// non-idempotent mutations in a new transaction.
1230    ///
1231    /// To ensure full replay protection and idempotent retry semantics for `ReadWriteTransaction`,
1232    /// a transaction still in the `NotStarted` state at commit time must first explicitly acquire a concrete
1233    /// transaction ID via a standalone `BeginTransaction` RPC before sending the `CommitRequest`.
1234    ///
1235    /// The caller must have already transitioned the selector to `Starting` via
1236    /// [`prepare_for_commit`](ReadContextTransactionSelector::prepare_for_commit).
1237    pub(crate) async fn begin_explicitly_for_commit(
1238        &self,
1239        options: TransactionOptions,
1240        notify: Arc<Notify>,
1241        fallback_options: GaxRequestOptions,
1242        mutation_key: Option<Mutation>,
1243    ) -> Result<Bytes> {
1244        // Protect against cancellation or premature drop of the BeginTransaction future,
1245        // ensuring on_cancelled_starting safely transitions the state and notifies any waiters.
1246        let mut start_guard =
1247            LazyTransactionStartGuard::new(Some(self.transaction_selector.clone()));
1248
1249        // Merge any per-attempt options configured on the transaction builder with fallback options.
1250        let request_options = merge_request_options(
1251            fallback_options,
1252            self.begin_transaction_request_options.as_ref(),
1253        );
1254
1255        // Execute the BeginTransaction RPC. The mutation key (if any) provides a routing hint
1256        // so the RPC is directed to the optimal split/leader server.
1257        let response = match execute_begin_transaction(
1258            &self.client,
1259            self.session_name.clone(),
1260            options,
1261            self.transaction_tag.clone(),
1262            &self.affinity,
1263            request_options,
1264            mutation_key,
1265        )
1266        .await
1267        {
1268            Ok(response) => response,
1269            Err(error) => {
1270                self.handle_explicit_begin_commit_failure(&error, notify);
1271                start_guard.disarm();
1272                return Err(error);
1273            }
1274        };
1275
1276        // Record any precommit token returned by Spanner for subsequent commit retries.
1277        self.precommit_token_tracker
1278            .update(response.precommit_token);
1279
1280        // Atomically transition the selector to Started and wake any concurrent waiters.
1281        self.transaction_selector
1282            .update(response.id.clone(), response.read_timestamp)?;
1283        start_guard.disarm();
1284
1285        Ok(response.id)
1286    }
1287
1288    /// Handles failure of the explicit `BeginTransaction` RPC during commit.
1289    ///
1290    /// Transitions the state to `Failed`, wakes any waiters, and records the error if aborted.
1291    fn handle_explicit_begin_commit_failure(&self, error: &Error, notify: Arc<Notify>) {
1292        if let Some(mut guard) = self.transaction_selector.lock_state() {
1293            *guard = TransactionState::Failed(TransactionStartFailure::from_error(error));
1294        }
1295        notify.notify_waiters();
1296        self.record_if_aborted(error);
1297    }
1298
1299    /// Returns a reference to the transaction channel affinity handle, if set.
1300    #[allow(dead_code)]
1301    pub(crate) fn affinity(&self) -> Option<&TransactionAffinity> {
1302        self.affinity.as_deref()
1303    }
1304
1305    pub(crate) async fn selector(&self) -> Result<crate::model::TransactionSelector> {
1306        self.transaction_selector.selector().await
1307    }
1308
1309    pub(crate) fn record_if_aborted(&self, error: &Error) {
1310        self.aborted_state.record(error, self.client.is_emulator());
1311    }
1312
1313    pub(crate) fn aborted_info(&self) -> Option<&AbortedInfo> {
1314        self.aborted_state.aborted_info()
1315    }
1316}
1317
1318/// Merges the configured fields from a `source` `RequestOptions` into a `destination` `RequestOptions`.
1319/// Configured options in `source` will override those in `destination`.
1320pub(crate) fn merge_request_options(
1321    mut destination: GaxRequestOptions,
1322    source: Option<&GaxRequestOptions>,
1323) -> GaxRequestOptions {
1324    let Some(source) = source else {
1325        return destination;
1326    };
1327
1328    if let Some(timeout) = source.attempt_timeout() {
1329        destination.set_attempt_timeout(*timeout);
1330    }
1331    if let Some(retry) = source.retry_policy() {
1332        destination.set_retry_policy(retry.clone());
1333    }
1334    if let Some(backoff) = source.backoff_policy() {
1335        destination.set_backoff_policy(backoff.clone());
1336    }
1337    merge_request_headers(destination, source)
1338}
1339
1340fn merge_request_headers(
1341    mut destination: GaxRequestOptions,
1342    source: &GaxRequestOptions,
1343) -> GaxRequestOptions {
1344    let Some(source_headers) = source
1345        .get_extension::<HeaderMap>()
1346        .filter(|headers| !headers.is_empty())
1347    else {
1348        return destination;
1349    };
1350
1351    let Some(destination_headers) = destination.get_extension_mut::<HeaderMap>() else {
1352        return destination.insert_extension(source_headers.clone());
1353    };
1354
1355    merge_headers(destination_headers, source_headers);
1356    destination
1357}
1358
1359fn merge_headers(destination_headers: &mut HeaderMap, source_headers: &HeaderMap) {
1360    if destination_headers.is_empty() {
1361        *destination_headers = source_headers.clone();
1362        return;
1363    }
1364
1365    destination_headers.reserve(source_headers.len());
1366    for name in source_headers.keys() {
1367        let mut values = source_headers.get_all(name).iter();
1368        let Some(first_value) = values.next() else {
1369            continue;
1370        };
1371        destination_headers.insert(name.clone(), first_value.clone());
1372        for additional_value in values {
1373            destination_headers.append(name.clone(), additional_value.clone());
1374        }
1375    }
1376}
1377
1378/// Helper macro to execute a streaming SQL or streaming read RPC with lazy transaction start tracking.
1379macro_rules! execute_stream_with_retry {
1380    ($self:expr, $request:ident, $gax_options:ident, $operation_variant:path, $method_name:expr) => {{
1381        if let Some(info) = $self.aborted_info() {
1382            return Err(info.to_error());
1383        }
1384        let is_starting = matches!(
1385            $request
1386                .transaction
1387                .as_ref()
1388                .and_then(|t| t.selector.as_ref()),
1389            Some(crate::model::transaction_selector::Selector::Begin(_))
1390        );
1391        // RAII cancellation guard: If this future is dropped/cancelled at any .await point
1392        // before completion, the guard's Drop handler executes `on_cancelled_starting()`.
1393        // This wakes any concurrent followers parked waiting for this inlined begin to finish
1394        // and safely transitions the state (resetting to NotStarted for read-only, or marking
1395        // FirstStatementFailed for read-write), preventing permanent follower deadlocks.
1396        //
1397        // Because `Drop` serves as the abnormal exit / cancellation trigger, any path that
1398        // runs to normal completion (whether Ok or a handled Err) must explicitly call
1399        // `start_guard.disarm()` so the Drop handler does not treat deliberate completion
1400        // as an unexpected cancellation.
1401        let mut start_guard =
1402            LazyTransactionStartGuard::new(is_starting.then(|| $self.transaction_selector.clone()));
1403        let result = Box::pin(ResultSet::create(ResultSetParams {
1404            transaction_selector: Some($self.transaction_selector.clone()),
1405            precommit_token_tracker: $self.precommit_token_tracker.clone(),
1406            client: $self.client.clone(),
1407            operation: $operation_variant($request),
1408            gax_options: $gax_options,
1409            method_name: $method_name,
1410            affinity: $self.affinity.as_ref().map(Arc::clone),
1411            aborted_state: $self.aborted_state.clone(),
1412        }))
1413        .await;
1414
1415        if is_starting {
1416            if let Err(ref e) = result {
1417                $self.record_if_aborted(e);
1418                $self
1419                    .transaction_selector
1420                    .set_failed(e, $self.client.is_emulator());
1421            }
1422        }
1423        start_guard.disarm();
1424        result
1425    }};
1426}
1427
1428impl ReadContext {
1429    pub(crate) async fn execute_query(
1430        &self,
1431        statement: impl Into<Statement>,
1432        seqno: Option<i64>,
1433    ) -> Result<ResultSet> {
1434        if let Some(info) = self.aborted_info() {
1435            return Err(info.to_error());
1436        }
1437        let statement = statement.into();
1438        let gax_options = statement.gax_options().clone();
1439        let selector = self.selector().await?;
1440        let mut request = statement
1441            .into_request()
1442            .set_session(self.session_name.clone())
1443            .set_transaction(selector)
1444            .set_seqno(seqno.unwrap_or(0));
1445        request.request_options = self.amend_request_options(request.request_options);
1446
1447        execute_stream_with_retry!(
1448            self,
1449            request,
1450            gax_options,
1451            StreamOperation::Query,
1452            "ExecuteStreamingSql"
1453        )
1454    }
1455
1456    pub(crate) async fn execute_read(&self, read: impl Into<ReadRequest>) -> Result<ResultSet> {
1457        if let Some(info) = self.aborted_info() {
1458            return Err(info.to_error());
1459        }
1460        let read = read.into();
1461        let gax_options = read.gax_options.clone();
1462        let selector = self.selector().await?;
1463        let mut request = read
1464            .into_request()
1465            .set_session(self.session_name.clone())
1466            .set_transaction(selector);
1467        request.request_options = self.amend_request_options(request.request_options);
1468
1469        execute_stream_with_retry!(
1470            self,
1471            request,
1472            gax_options,
1473            StreamOperation::Read,
1474            "StreamingRead"
1475        )
1476    }
1477}
1478
1479#[cfg(test)]
1480pub(crate) mod tests {
1481    use super::*;
1482    use crate::RequestOptions;
1483    use crate::key::KeySet;
1484    use crate::model::ExecuteSqlRequest;
1485    use crate::model::transaction_selector::Selector as ModelSelector;
1486    use crate::read::ReadRequest;
1487    use crate::request_id_interceptor::REQUEST_ID_HEADER;
1488    use crate::result_set::tests::adapt;
1489    use crate::result_set::tests::string_val;
1490    use crate::retry_policy::SpannerRetryPolicy;
1491    use crate::statement::Statement;
1492    use crate::value::Value;
1493    use gaxi::grpc::tonic::{self, Code, Response, Status};
1494    use google_cloud_gax::backoff_policy::BackoffPolicy;
1495    use google_cloud_gax::error::rpc::Code as GaxCode;
1496    use google_cloud_gax::error::rpc::Status as GaxStatus;
1497    use google_cloud_gax::error::rpc::StatusDetails;
1498    use google_cloud_gax::exponential_backoff::{ExponentialBackoff, ExponentialBackoffBuilder};
1499    use google_cloud_gax::retry_policy::{NeverRetry, RetryPolicyExt};
1500    use google_cloud_gax::retry_state::RetryState;
1501    use google_cloud_rpc::model::RetryInfo;
1502    use google_cloud_test_macros::tokio_test_no_panics;
1503    use http::{HeaderMap, HeaderName, HeaderValue};
1504    use mock_v1::transaction_selector::Selector;
1505    use mockall::Sequence;
1506    use prost_types::Timestamp;
1507    use spanner_grpc_mock::MockSpanner;
1508    use spanner_grpc_mock::google::spanner::v1 as mock_v1;
1509    use std::sync::mpsc::channel as std_channel;
1510    use std::sync::{Arc, Mutex as StdMutex};
1511    use std::time::Duration;
1512    use tokio::sync::oneshot::channel as oneshot_channel;
1513    use tokio::sync::{Barrier, Mutex, Notify, mpsc};
1514    use tokio::task::{spawn, yield_now};
1515    use wkt::Duration as WktDuration;
1516
1517    mockall::mock! {
1518        #[derive(Debug)]
1519        BackoffPolicy {}
1520        impl BackoffPolicy for BackoffPolicy {
1521            fn on_failure(&self, state: &RetryState) -> Duration;
1522        }
1523    }
1524
1525    impl ReadContextTransactionSelector {
1526        pub(crate) fn is_starting(&self) -> bool {
1527            let Some(guard) = self.lock_state() else {
1528                return false;
1529            };
1530            matches!(&*guard, TransactionState::Starting(_, _))
1531        }
1532    }
1533
1534    #[test]
1535    fn auto_traits() {
1536        use std::fmt::Debug;
1537        static_assertions::assert_impl_all!(SingleUseReadOnlyTransactionBuilder: Debug, Send, Sync, Clone);
1538        static_assertions::assert_impl_all!(SingleUseReadOnlyTransaction: Debug, Send, Sync);
1539        static_assertions::assert_impl_all!(MultiUseReadOnlyTransactionBuilder: Debug, Send, Sync, Clone);
1540        static_assertions::assert_impl_all!(MultiUseReadOnlyTransaction: Debug, Send, Sync, Clone);
1541        static_assertions::assert_impl_all!(ReadContext: Debug, Send, Sync, Clone);
1542        static_assertions::assert_impl_all!(
1543            BeginTransactionOption: Send,
1544            Sync,
1545            Clone,
1546            Copy,
1547            Debug,
1548            Default,
1549            PartialEq,
1550            Eq
1551        );
1552    }
1553
1554    #[tokio_test_no_panics]
1555    async fn single_use_builder_clone() {
1556        let mock = create_session_mock();
1557        let (database_client, _server) = setup_db_client(mock).await;
1558
1559        let builder = database_client
1560            .single_use()
1561            .set_timestamp_bound(TimestampBound::strong());
1562        let cloned_builder = builder.clone();
1563        assert!(
1564            cloned_builder.timestamp_bound.is_some(),
1565            "cloned builder should retain timestamp bound"
1566        );
1567
1568        let transaction = cloned_builder.build();
1569        assert_eq!(
1570            transaction.context.session_name, "projects/p/instances/i/databases/d/sessions/123",
1571            "transaction built from cloned builder should retain session name"
1572        );
1573    }
1574
1575    #[tokio_test_no_panics]
1576    async fn multi_use_transaction_and_builder_clone() {
1577        let mock = create_session_mock();
1578        let (database_client, _server) = setup_db_client(mock).await;
1579
1580        let builder = database_client
1581            .read_only_transaction()
1582            .set_timestamp_bound(TimestampBound::strong())
1583            .set_begin_transaction_option(BeginTransactionOption::InlineBegin);
1584        let cloned_builder = builder.clone();
1585        assert!(
1586            cloned_builder.timestamp_bound.is_some(),
1587            "cloned builder should retain timestamp bound"
1588        );
1589        assert_eq!(
1590            cloned_builder.begin_transaction_option,
1591            BeginTransactionOption::InlineBegin,
1592            "cloned builder should retain begin transaction option"
1593        );
1594
1595        let transaction = builder
1596            .build()
1597            .await
1598            .expect("failed to build multi-use transaction");
1599        let cloned_transaction = transaction.clone();
1600        assert_eq!(
1601            cloned_transaction.context.session_name, transaction.context.session_name,
1602            "cloned transaction should retain session name"
1603        );
1604        if let (
1605            ReadContextTransactionSelector::Lazy(original_state),
1606            ReadContextTransactionSelector::Lazy(cloned_state),
1607        ) = (
1608            &transaction.context.transaction_selector,
1609            &cloned_transaction.context.transaction_selector,
1610        ) {
1611            assert!(
1612                Arc::ptr_eq(original_state, cloned_state),
1613                "cloned transaction must share the same underlying transaction state Arc"
1614            );
1615        } else {
1616            panic!("expected Lazy transaction selector variant");
1617        }
1618    }
1619
1620    pub(crate) fn create_session_mock() -> MockSpanner {
1621        let mut mock = MockSpanner::new();
1622        mock.expect_create_session().once().returning(|_| {
1623            Ok(Response::new(mock_v1::Session {
1624                name: "projects/p/instances/i/databases/d/sessions/123".to_string(),
1625                ..Default::default()
1626            }))
1627        });
1628        mock
1629    }
1630
1631    pub(crate) fn setup_select1() -> spanner_grpc_mock::google::spanner::v1::PartialResultSet {
1632        spanner_grpc_mock::google::spanner::v1::PartialResultSet {
1633            metadata: Some(spanner_grpc_mock::google::spanner::v1::ResultSetMetadata {
1634                row_type: Some(spanner_grpc_mock::google::spanner::v1::StructType {
1635                    fields: vec![Default::default()],
1636                }),
1637                ..Default::default()
1638            }),
1639            values: vec![prost_types::Value {
1640                kind: Some(prost_types::value::Kind::StringValue("1".to_string())),
1641            }],
1642            last: true,
1643            ..Default::default()
1644        }
1645    }
1646
1647    pub(crate) fn setup_select1_with_transaction_id(
1648        transaction_id: Vec<u8>,
1649    ) -> spanner_grpc_mock::google::spanner::v1::PartialResultSet {
1650        let mut result_set = setup_select1();
1651        result_set
1652            .metadata
1653            .as_mut()
1654            .expect("metadata present")
1655            .transaction = Some(spanner_grpc_mock::google::spanner::v1::Transaction {
1656            id: transaction_id,
1657            read_timestamp: Some(Timestamp {
1658                seconds: 1234567890,
1659                nanos: 0,
1660            }),
1661            ..Default::default()
1662        });
1663        result_set
1664    }
1665
1666    pub(crate) async fn setup_db_client(
1667        mock: spanner_grpc_mock::MockSpanner,
1668    ) -> (DatabaseClient, tokio::task::JoinHandle<()>) {
1669        use crate::client::Spanner;
1670        use google_cloud_auth::credentials::anonymous::Builder as Anonymous;
1671        let (address, server) = spanner_grpc_mock::start("0.0.0.0:0", mock)
1672            .await
1673            .expect("Failed to start mock server");
1674
1675        let spanner = Spanner::builder()
1676            .with_endpoint(address)
1677            .with_credentials(Anonymous::new().build())
1678            .build()
1679            .await
1680            .expect("Failed to build client");
1681
1682        let db_client = spanner
1683            .database_client("projects/p/instances/i/databases/d")
1684            .build()
1685            .await
1686            .expect("Failed to create DatabaseClient");
1687
1688        (db_client, server)
1689    }
1690
1691    #[tokio_test_no_panics]
1692    async fn single_use_builder() {
1693        let mock = create_session_mock();
1694
1695        let (db_client, _server) = setup_db_client(mock).await;
1696
1697        let tx = db_client.single_use().build();
1698        let selector = tx
1699            .context
1700            .transaction_selector
1701            .selector()
1702            .await
1703            .expect("Failed to get selector");
1704        let ro = selector
1705            .single_use()
1706            .expect("Expected SingleUse selector")
1707            .read_only()
1708            .expect("Expected ReadOnly mode");
1709        assert_eq!(
1710            ro.timestamp_bound,
1711            Some(crate::model::transaction_options::read_only::TimestampBound::Strong(true))
1712        );
1713
1714        let tx2 = db_client
1715            .single_use()
1716            .set_timestamp_bound(crate::timestamp_bound::TimestampBound::max_staleness(
1717                std::time::Duration::from_secs(10),
1718            ))
1719            .build();
1720        let selector = tx2
1721            .context
1722            .transaction_selector
1723            .selector()
1724            .await
1725            .expect("Failed to get selector");
1726        let ro2 = selector
1727            .single_use()
1728            .expect("Expected SingleUse selector")
1729            .read_only()
1730            .expect("Expected ReadOnly mode");
1731        assert_eq!(
1732            ro2.timestamp_bound,
1733            Some(
1734                crate::model::transaction_options::read_only::TimestampBound::MaxStaleness(
1735                    Box::new(wkt::Duration::new(10, 0).expect("failed to create Duration"))
1736                )
1737            )
1738        );
1739    }
1740
1741    #[tokio_test_no_panics]
1742    async fn execute_single_query() {
1743        use super::super::result_set::tests::string_val;
1744        use crate::statement::Statement;
1745        use crate::value::Value;
1746
1747        let mut mock = create_session_mock();
1748
1749        mock.expect_execute_streaming_sql().once().returning(|req| {
1750            let req = req.into_inner();
1751            assert_eq!(
1752                req.session,
1753                "projects/p/instances/i/databases/d/sessions/123"
1754            );
1755            assert_eq!(req.sql, "SELECT 1");
1756
1757            Ok(gaxi::grpc::tonic::Response::from(adapt([Ok(
1758                setup_select1(),
1759            )])))
1760        });
1761
1762        let (db_client, _server) = setup_db_client(mock).await;
1763
1764        let tx = db_client.single_use().build();
1765        let mut rs = tx
1766            .execute_query(Statement::builder("SELECT 1").build())
1767            .await
1768            .expect("Failed to execute query");
1769
1770        let row = rs.next().await.expect("has row").expect("has valid row");
1771        assert_eq!(row.raw_values(), [Value(string_val("1"))]);
1772        let result = rs.next().await;
1773        assert!(result.is_none(), "expected None, got {result:?}");
1774    }
1775
1776    #[tokio_test_no_panics]
1777    async fn execute_multi_query() {
1778        use super::super::result_set::tests::string_val;
1779        use crate::statement::Statement;
1780        use crate::value::Value;
1781        use spanner_grpc_mock::google::spanner::v1 as mock_v1;
1782
1783        let mut mock = create_session_mock();
1784
1785        mock.expect_begin_transaction().once().returning(|req| {
1786            let req = req.into_inner();
1787            assert_eq!(
1788                req.session,
1789                "projects/p/instances/i/databases/d/sessions/123"
1790            );
1791            Ok(tonic::Response::new(mock_v1::Transaction {
1792                id: vec![1, 2, 3],
1793                // prost_types::Timestamp fields need to be explicitly set because default is 0 for both
1794                read_timestamp: Some(prost_types::Timestamp {
1795                    seconds: 123456789,
1796                    nanos: 0,
1797                }),
1798                ..Default::default()
1799            }))
1800        });
1801
1802        mock.expect_execute_streaming_sql()
1803            .times(2)
1804            .returning(|req| {
1805                let req = req.into_inner();
1806                assert_eq!(
1807                    req.session,
1808                    "projects/p/instances/i/databases/d/sessions/123"
1809                );
1810                assert_eq!(
1811                    req.transaction
1812                        .expect("transaction should be present")
1813                        .selector
1814                        .expect("selector should be present"),
1815                    mock_v1::transaction_selector::Selector::Id(vec![1, 2, 3])
1816                );
1817
1818                Ok(gaxi::grpc::tonic::Response::from(adapt([Ok(
1819                    setup_select1(),
1820                )])))
1821            });
1822
1823        let (db_client, _server) = setup_db_client(mock).await;
1824
1825        let tx = db_client
1826            .read_only_transaction()
1827            .set_begin_transaction_option(BeginTransactionOption::ExplicitBegin)
1828            .build()
1829            .await
1830            .expect("Failed to start tx");
1831        assert_eq!(
1832            tx.read_timestamp()
1833                .expect("expected read timestamp")
1834                .seconds(),
1835            123456789
1836        );
1837
1838        for _ in 0..2 {
1839            let mut rs = tx
1840                .execute_query(Statement::builder("SELECT 1").build())
1841                .await
1842                .expect("Failed to execute query");
1843
1844            let row = rs.next().await.expect("has row").expect("has valid row");
1845            assert_eq!(row.raw_values(), [Value(string_val("1"))]);
1846
1847            let result = rs.next().await;
1848            assert!(result.is_none(), "expected None, got {result:?}");
1849        }
1850    }
1851
1852    #[tokio_test_no_panics]
1853    async fn execute_multi_query_inline_begin() -> anyhow::Result<()> {
1854        use super::super::result_set::tests::string_val;
1855        use crate::statement::Statement;
1856        use crate::value::Value;
1857        use spanner_grpc_mock::google::spanner::v1 as mock_v1;
1858
1859        let mut mock = create_session_mock();
1860
1861        // No explicit begin_transaction should be called.
1862        mock.expect_begin_transaction().never();
1863
1864        let mut seq = mockall::Sequence::new();
1865
1866        mock.expect_execute_streaming_sql()
1867            .times(1)
1868            .in_sequence(&mut seq)
1869            .returning(move |req| {
1870                let req = req.into_inner();
1871                assert_eq!(
1872                    req.session,
1873                    "projects/p/instances/i/databases/d/sessions/123"
1874                );
1875
1876                // First call: Should have Selector::Begin
1877                match req.transaction.unwrap().selector.unwrap() {
1878                    mock_v1::transaction_selector::Selector::Begin(_) => {}
1879                    _ => panic!("Expected Selector::Begin"),
1880                }
1881                let mut rs = setup_select1();
1882                rs.metadata.as_mut().unwrap().transaction = Some(mock_v1::Transaction {
1883                    id: vec![4, 5, 6],
1884                    read_timestamp: Some(prost_types::Timestamp {
1885                        seconds: 987654321,
1886                        nanos: 0,
1887                    }),
1888                    ..Default::default()
1889                });
1890                Ok(gaxi::grpc::tonic::Response::from(adapt([Ok(rs)])))
1891            });
1892
1893        mock.expect_execute_streaming_sql()
1894            .times(1)
1895            .in_sequence(&mut seq)
1896            .returning(move |req| {
1897                let req = req.into_inner();
1898                // Second call: Should have Selector::Id using the ID returned in the first call
1899                match req.transaction.unwrap().selector.unwrap() {
1900                    mock_v1::transaction_selector::Selector::Id(id) => {
1901                        assert_eq!(id, vec![4, 5, 6]);
1902                    }
1903                    _ => panic!("Expected Selector::Id"),
1904                }
1905                Ok(gaxi::grpc::tonic::Response::from(adapt([Ok(
1906                    setup_select1(),
1907                )])))
1908            });
1909
1910        let (db_client, _server) = setup_db_client(mock).await;
1911
1912        let tx = db_client
1913            .read_only_transaction()
1914            .set_begin_transaction_option(BeginTransactionOption::InlineBegin)
1915            .build()
1916            .await?;
1917
1918        // The read timestamp is not available until the first query is executed.
1919        assert!(tx.read_timestamp().is_none());
1920
1921        for i in 0..2 {
1922            let mut rs = tx
1923                .execute_query(Statement::builder("SELECT 1").build())
1924                .await?;
1925
1926            let row = rs.next().await.expect("Expected a row")?;
1927            assert_eq!(row.raw_values(), [Value(string_val("1"))]);
1928
1929            let result = rs.next().await;
1930            assert!(result.is_none(), "Expected None, got {result:?}");
1931
1932            if i == 0 {
1933                // Read timestamp becomes available.
1934                assert_eq!(
1935                    tx.read_timestamp()
1936                        .expect("Expected read timestamp")
1937                        .seconds(),
1938                    987654321
1939                );
1940            }
1941        }
1942
1943        Ok(())
1944    }
1945
1946    #[tokio_test_no_panics]
1947    async fn execute_single_read() {
1948        use super::super::result_set::tests::string_val;
1949        use crate::key::KeySet;
1950        use crate::read::ReadRequest;
1951        use crate::value::Value;
1952
1953        let mut mock = create_session_mock();
1954
1955        mock.expect_streaming_read().once().returning(|req| {
1956            let req = req.into_inner();
1957            assert_eq!(
1958                req.session,
1959                "projects/p/instances/i/databases/d/sessions/123"
1960            );
1961            assert_eq!(req.table, "Users");
1962            assert_eq!(req.columns, vec!["Id".to_string(), "Name".to_string()]);
1963
1964            Ok(gaxi::grpc::tonic::Response::from(adapt([Ok(
1965                setup_select1(),
1966            )])))
1967        });
1968
1969        let (db_client, _server) = setup_db_client(mock).await;
1970
1971        let tx = db_client.single_use().build();
1972        let read = ReadRequest::builder("Users", vec!["Id", "Name"])
1973            .with_keys(KeySet::all())
1974            .build();
1975        let mut rs = tx.execute_read(read).await.expect("Failed to execute read");
1976
1977        let row = rs.next().await.expect("has row").expect("has valid row");
1978        assert_eq!(row.raw_values(), [Value(string_val("1"))]);
1979        let result = rs.next().await;
1980        assert!(result.is_none(), "expected None, got {result:?}");
1981    }
1982
1983    #[tokio_test_no_panics]
1984    async fn execute_multi_read() -> anyhow::Result<()> {
1985        use super::super::result_set::tests::string_val;
1986        use crate::key::KeySet;
1987        use crate::read::ReadRequest;
1988        use crate::value::Value;
1989        use spanner_grpc_mock::google::spanner::v1 as mock_v1;
1990
1991        let mut mock = create_session_mock();
1992
1993        // No explicit begin_transaction should be called.
1994        mock.expect_begin_transaction().never();
1995
1996        let mut seq = mockall::Sequence::new();
1997
1998        mock.expect_streaming_read()
1999            .times(1)
2000            .in_sequence(&mut seq)
2001            .returning(move |req| {
2002                let req = req.into_inner();
2003                assert_eq!(
2004                    req.session,
2005                    "projects/p/instances/i/databases/d/sessions/123"
2006                );
2007
2008                // First call: Should have Selector::Begin
2009                match req.transaction.unwrap().selector.unwrap() {
2010                    mock_v1::transaction_selector::Selector::Begin(_) => {}
2011                    _ => panic!("Expected Selector::Begin"),
2012                }
2013                let mut rs = setup_select1();
2014                rs.metadata.as_mut().unwrap().transaction = Some(mock_v1::Transaction {
2015                    id: vec![4, 5, 6],
2016                    read_timestamp: Some(prost_types::Timestamp {
2017                        seconds: 987654321,
2018                        nanos: 0,
2019                    }),
2020                    ..Default::default()
2021                });
2022                Ok(gaxi::grpc::tonic::Response::from(adapt([Ok(rs)])))
2023            });
2024
2025        mock.expect_streaming_read()
2026            .times(1)
2027            .in_sequence(&mut seq)
2028            .returning(move |req| {
2029                let req = req.into_inner();
2030                // Second call: Should have Selector::Id using the ID returned in the first call
2031                match req.transaction.unwrap().selector.unwrap() {
2032                    mock_v1::transaction_selector::Selector::Id(id) => {
2033                        assert_eq!(id, vec![4, 5, 6]);
2034                    }
2035                    _ => panic!("Expected Selector::Id"),
2036                }
2037                Ok(gaxi::grpc::tonic::Response::from(adapt([Ok(
2038                    setup_select1(),
2039                )])))
2040            });
2041
2042        let (db_client, _server) = setup_db_client(mock).await;
2043
2044        let tx = db_client
2045            .read_only_transaction()
2046            .set_begin_transaction_option(BeginTransactionOption::InlineBegin)
2047            .build()
2048            .await?;
2049
2050        // The read timestamp is not available until the first query is executed.
2051        assert!(tx.read_timestamp().is_none());
2052
2053        for i in 0..2 {
2054            let read = ReadRequest::builder("Users", vec!["Id", "Name"])
2055                .with_keys(KeySet::all())
2056                .build();
2057            let mut rs = tx.execute_read(read).await?;
2058
2059            let row = rs.next().await.expect("Expected a row")?;
2060            assert_eq!(row.raw_values(), [Value(string_val("1"))]);
2061
2062            let result = rs.next().await;
2063            assert!(result.is_none(), "Expected None, got {result:?}");
2064
2065            if i == 0 {
2066                // Read timestamp becomes available.
2067                assert_eq!(
2068                    tx.read_timestamp()
2069                        .expect("Expected read timestamp")
2070                        .seconds(),
2071                    987654321
2072                );
2073            }
2074        }
2075
2076        Ok(())
2077    }
2078
2079    #[tokio_test_no_panics]
2080    async fn inline_begin_query_failure_fails_fast() -> anyhow::Result<()> {
2081        use gaxi::grpc::tonic::Status;
2082
2083        let mut mock = create_session_mock();
2084
2085        // 1. Initial query fails
2086        mock.expect_execute_streaming_sql()
2087            .times(1)
2088            .returning(|_| Err(Status::internal("Internal error on first statement")));
2089
2090        // 2. BeginTransaction must NEVER be called as a fallback
2091        mock.expect_begin_transaction().never();
2092
2093        let (db_client, _server) = setup_db_client(mock).await;
2094        let tx = db_client
2095            .read_only_transaction()
2096            .set_begin_transaction_option(BeginTransactionOption::InlineBegin)
2097            .build()
2098            .await?;
2099
2100        // First query fails fast with the initial error.
2101        let first_result = tx
2102            .execute_query(Statement::builder("SELECT 1").build())
2103            .await;
2104        assert!(
2105            first_result.is_err(),
2106            "Initial query must fail when execute_streaming_sql returns an error"
2107        );
2108        let error_message = first_result.expect_err("initial query failed").to_string();
2109        assert!(
2110            error_message.contains("Internal error on first statement"),
2111            "Error message should propagate: {error_message}"
2112        );
2113
2114        // Subsequent query on the same transaction must also fail immediately without any RPCs.
2115        let second_result = tx
2116            .execute_query(Statement::builder("SELECT 2").build())
2117            .await;
2118        assert!(
2119            second_result.is_err(),
2120            "Subsequent query must fail fast on a failed read-only transaction"
2121        );
2122        let second_error = second_result.expect_err("subsequent query failed");
2123        let status = second_error
2124            .status()
2125            .expect("Service status error must be preserved on subsequent query failure");
2126        assert_eq!(
2127            status.code,
2128            GaxCode::Internal,
2129            "Status code must match original failure"
2130        );
2131        assert_eq!(
2132            status.message,
2133            "Transaction cannot be used: initial statement failed with: Internal error on first statement",
2134            "Subsequent query error message must explicitly explain transaction cannot be used"
2135        );
2136
2137        Ok(())
2138    }
2139
2140    #[tokio_test_no_panics]
2141    async fn inline_begin_read_failure_fails_fast() -> anyhow::Result<()> {
2142        use crate::key::KeySet;
2143        use crate::read::ReadRequest;
2144        use gaxi::grpc::tonic::Status;
2145
2146        let mut mock = create_session_mock();
2147
2148        // 1. Initial read fails
2149        mock.expect_streaming_read()
2150            .times(1)
2151            .returning(|_| Err(Status::internal("Internal error on first read")));
2152
2153        // 2. BeginTransaction must NEVER be called as a fallback
2154        mock.expect_begin_transaction().never();
2155
2156        let (db_client, _server) = setup_db_client(mock).await;
2157        let tx = db_client
2158            .read_only_transaction()
2159            .set_begin_transaction_option(BeginTransactionOption::InlineBegin)
2160            .build()
2161            .await?;
2162
2163        let read = ReadRequest::builder("Users", vec!["Id", "Name"])
2164            .with_keys(KeySet::all())
2165            .build();
2166        let first_result = tx.execute_read(read).await;
2167        assert!(
2168            first_result.is_err(),
2169            "Initial read must fail when streaming_read returns an error"
2170        );
2171        let error_message = first_result.expect_err("initial read failed").to_string();
2172        assert!(
2173            error_message.contains("Internal error on first read"),
2174            "Error message should propagate: {error_message}"
2175        );
2176
2177        // Subsequent query on the same transaction must fail fast without any RPCs.
2178        let second_result = tx
2179            .execute_query(Statement::builder("SELECT 1").build())
2180            .await;
2181        assert!(
2182            second_result.is_err(),
2183            "Subsequent query must fail fast on a failed read-only transaction"
2184        );
2185        let second_error = second_result.expect_err("subsequent query failed");
2186        let status = second_error
2187            .status()
2188            .expect("Service status error must be preserved on subsequent query failure");
2189        assert_eq!(
2190            status.code,
2191            GaxCode::Internal,
2192            "Status code must match original failure"
2193        );
2194        assert_eq!(
2195            status.message,
2196            "Transaction cannot be used: initial statement failed with: Internal error on first read",
2197            "Subsequent query error message must explicitly explain transaction cannot be used"
2198        );
2199
2200        Ok(())
2201    }
2202
2203    #[tokio_test_no_panics]
2204    async fn inlined_begin_query_stream_fails_with_invalid_argument() -> anyhow::Result<()> {
2205        let mut mock = create_session_mock();
2206
2207        // 1. Initial query stream with inline begin fails with InvalidArgument.
2208        mock.expect_execute_streaming_sql()
2209            .times(1)
2210            .returning(|request| {
2211                let request = request.into_inner();
2212                match request
2213                    .transaction
2214                    .expect("transaction selector must be present")
2215                    .selector
2216                    .expect("selector kind must be present")
2217                {
2218                    Selector::Begin(_) => {}
2219                    _ => panic!("Expected Selector::Begin for first query"),
2220                }
2221                Ok(Response::from(adapt([Err(Status::invalid_argument(
2222                    "Table not found: invalid_table",
2223                ))])))
2224            });
2225
2226        // 2. BeginTransaction must NEVER be called as a fallback.
2227        mock.expect_begin_transaction().never();
2228
2229        let (database_client, _server) = setup_db_client(mock).await;
2230        let transaction = database_client
2231            .read_only_transaction()
2232            .set_begin_transaction_option(BeginTransactionOption::InlineBegin)
2233            .build()
2234            .await?;
2235
2236        let first_query_result = transaction
2237            .execute_query(Statement::builder("SELECT * FROM invalid_table").build())
2238            .await;
2239        assert!(
2240            first_query_result.is_err(),
2241            "Expected first query to fail with InvalidArgument"
2242        );
2243        let error_message = first_query_result
2244            .expect_err("first query failed")
2245            .to_string();
2246        assert!(
2247            error_message.contains("Table not found: invalid_table"),
2248            "Expected error message to propagate: {error_message}"
2249        );
2250
2251        // Transaction is permanently marked as Failed; subsequent query fails fast without RPC.
2252        let second_query_result = transaction
2253            .execute_query(Statement::builder("SELECT 1").build())
2254            .await;
2255        assert!(
2256            second_query_result.is_err(),
2257            "Expected second query to fail fast on a failed read-only transaction"
2258        );
2259        let second_error = second_query_result.expect_err("second query failed");
2260        let status = second_error
2261            .status()
2262            .expect("Service status error must be preserved on subsequent query failure");
2263        assert_eq!(
2264            status.code,
2265            GaxCode::InvalidArgument,
2266            "Status code must match original failure"
2267        );
2268        assert_eq!(
2269            status.message,
2270            "Transaction cannot be used: initial statement failed with: Table not found: invalid_table",
2271            "Subsequent query error message must explicitly explain transaction cannot be used"
2272        );
2273
2274        Ok(())
2275    }
2276
2277    #[tokio_test_no_panics]
2278    async fn inlined_begin_query_stream_chunk_failure_fails_fast() -> anyhow::Result<()> {
2279        let mut mock = create_session_mock();
2280
2281        // 1. Initial streaming query with inline begin fails on initial chunk with Unavailable.
2282        mock.expect_execute_streaming_sql()
2283            .times(1)
2284            .returning(|request| {
2285                let request = request.into_inner();
2286                match request
2287                    .transaction
2288                    .expect("transaction selector must be present")
2289                    .selector
2290                    .expect("selector kind must be present")
2291                {
2292                    Selector::Begin(_) => {}
2293                    _ => panic!("Expected Selector::Begin for first query"),
2294                }
2295                Ok(Response::from(adapt([Err(Status::unavailable(
2296                    "Transient initial stream failure",
2297                ))])))
2298            });
2299
2300        // 2. BeginTransaction must NEVER be called as a fallback.
2301        mock.expect_begin_transaction().never();
2302
2303        let (database_client, _server) = setup_db_client(mock).await;
2304        let transaction = database_client
2305            .read_only_transaction()
2306            .set_begin_transaction_option(BeginTransactionOption::InlineBegin)
2307            .build()
2308            .await?;
2309
2310        let statement = Statement::builder("SELECT 1")
2311            .with_retry_policy(NeverRetry)
2312            .build();
2313        let first_query_result = transaction.execute_query(statement).await;
2314        assert!(
2315            first_query_result.is_err(),
2316            "Expected initial query to fail fast on stream initialization error"
2317        );
2318        let error_message = first_query_result
2319            .expect_err("first query failed")
2320            .to_string();
2321        assert!(
2322            error_message.contains("Transient initial stream failure"),
2323            "Expected transient error message to propagate: {error_message}"
2324        );
2325
2326        // Subsequent query on the same transaction fails fast without any RPCs.
2327        let second_query_result = transaction
2328            .execute_query(Statement::builder("SELECT 1").build())
2329            .await;
2330        assert!(
2331            second_query_result.is_err(),
2332            "Subsequent query must fail fast on a failed read-only transaction"
2333        );
2334        let second_error = second_query_result.expect_err("second query failed");
2335        let status = second_error
2336            .status()
2337            .expect("Service status error must be preserved on subsequent query failure");
2338        assert_eq!(
2339            status.code,
2340            GaxCode::Unavailable,
2341            "Status code must match original failure"
2342        );
2343        assert_eq!(
2344            status.message,
2345            "Transaction cannot be used: initial statement failed with: Transient initial stream failure",
2346            "Subsequent query error message must explicitly explain transaction cannot be used"
2347        );
2348
2349        Ok(())
2350    }
2351
2352    #[tokio_test_no_panics]
2353    async fn inlined_begin_streaming_read_fails_with_invalid_argument() -> anyhow::Result<()> {
2354        let mut mock = create_session_mock();
2355
2356        // 1. Initial streaming read with inline begin fails with InvalidArgument.
2357        mock.expect_streaming_read().times(1).returning(|request| {
2358            let request = request.into_inner();
2359            match request
2360                .transaction
2361                .expect("transaction selector must be present")
2362                .selector
2363                .expect("selector kind must be present")
2364            {
2365                Selector::Begin(_) => {}
2366                _ => panic!("Expected Selector::Begin for first read"),
2367            }
2368            Ok(Response::from(adapt([Err(Status::invalid_argument(
2369                "Table not found: invalid_table",
2370            ))])))
2371        });
2372
2373        // 2. BeginTransaction must NEVER be called as a fallback.
2374        mock.expect_begin_transaction().never();
2375
2376        let (database_client, _server) = setup_db_client(mock).await;
2377        let transaction = database_client
2378            .read_only_transaction()
2379            .set_begin_transaction_option(BeginTransactionOption::InlineBegin)
2380            .build()
2381            .await?;
2382
2383        let read_request = ReadRequest::builder("invalid_table", vec!["Id"])
2384            .with_keys(KeySet::all())
2385            .build();
2386        let first_read_result = transaction.execute_read(read_request).await;
2387        assert!(
2388            first_read_result.is_err(),
2389            "Expected first read to fail with InvalidArgument"
2390        );
2391        let error_message = first_read_result
2392            .expect_err("first read failed")
2393            .to_string();
2394        assert!(
2395            error_message.contains("Table not found: invalid_table"),
2396            "Expected error message to propagate: {error_message}"
2397        );
2398
2399        // Subsequent query on the same transaction fails fast without any RPCs.
2400        let second_query_result = transaction
2401            .execute_query(Statement::builder("SELECT 1").build())
2402            .await;
2403        assert!(
2404            second_query_result.is_err(),
2405            "Subsequent query must fail fast on a failed read-only transaction"
2406        );
2407        let second_error = second_query_result.expect_err("second query failed");
2408        let status = second_error
2409            .status()
2410            .expect("Service status error must be preserved on subsequent query failure");
2411        assert_eq!(
2412            status.code,
2413            GaxCode::InvalidArgument,
2414            "Status code must match original failure"
2415        );
2416        assert_eq!(
2417            status.message,
2418            "Transaction cannot be used: initial statement failed with: Table not found: invalid_table",
2419            "Subsequent query error message must explicitly explain transaction cannot be used"
2420        );
2421
2422        Ok(())
2423    }
2424
2425    #[tokio_test_no_panics]
2426    async fn explicit_begin_allows_subsequent_statements_after_first_fails() -> anyhow::Result<()> {
2427        let mut mock = create_session_mock();
2428        let mut sequence = Sequence::new();
2429
2430        // 1. Explicit begin transaction succeeds at build() time.
2431        mock.expect_begin_transaction()
2432            .times(1)
2433            .in_sequence(&mut sequence)
2434            .returning(|request| {
2435                let request = request.into_inner();
2436                assert_eq!(
2437                    request.session, "projects/p/instances/i/databases/d/sessions/123",
2438                    "Session name matches expected session"
2439                );
2440                Ok(Response::new(mock_v1::Transaction {
2441                    id: vec![7, 8, 9],
2442                    read_timestamp: Some(Timestamp {
2443                        seconds: 123456789,
2444                        nanos: 0,
2445                    }),
2446                    ..Default::default()
2447                }))
2448            });
2449
2450        // 2. First query with established transaction ID fails with InvalidArgument (e.g. invalid table).
2451        mock.expect_execute_streaming_sql()
2452            .times(1)
2453            .in_sequence(&mut sequence)
2454            .returning(|request| {
2455                let request = request.into_inner();
2456                match request
2457                    .transaction
2458                    .expect("transaction selector must be present")
2459                    .selector
2460                    .expect("selector kind must be present")
2461                {
2462                    Selector::Id(transaction_id) => {
2463                        assert_eq!(
2464                            transaction_id,
2465                            vec![7, 8, 9],
2466                            "Expected first query to use established transaction ID"
2467                        );
2468                    }
2469                    _ => panic!("Expected Selector::Id on query with explicit begin"),
2470                }
2471                Ok(Response::from(adapt([Err(Status::invalid_argument(
2472                    "Table not found: invalid_table",
2473                ))])))
2474            });
2475
2476        // 3. Second query with same established transaction ID succeeds.
2477        mock.expect_execute_streaming_sql()
2478            .times(1)
2479            .in_sequence(&mut sequence)
2480            .returning(|request| {
2481                let request = request.into_inner();
2482                match request
2483                    .transaction
2484                    .expect("transaction selector must be present")
2485                    .selector
2486                    .expect("selector kind must be present")
2487                {
2488                    Selector::Id(transaction_id) => {
2489                        assert_eq!(
2490                            transaction_id,
2491                            vec![7, 8, 9],
2492                            "Expected second query to use established transaction ID"
2493                        );
2494                    }
2495                    _ => panic!("Expected Selector::Id on second query"),
2496                }
2497                Ok(Response::from(adapt([Ok(setup_select1())])))
2498            });
2499
2500        let (database_client, _server) = setup_db_client(mock).await;
2501        let transaction = database_client
2502            .read_only_transaction()
2503            .set_begin_transaction_option(BeginTransactionOption::ExplicitBegin)
2504            .build()
2505            .await?;
2506
2507        // First query fails with InvalidArgument.
2508        let first_query_result = transaction
2509            .execute_query(Statement::builder("SELECT * FROM invalid_table").build())
2510            .await;
2511        assert!(
2512            first_query_result.is_err(),
2513            "Expected first query to fail with InvalidArgument"
2514        );
2515
2516        // Because ExplicitBegin was used, the transaction remains valid with its established snapshot.
2517        let mut second_result_set = transaction
2518            .execute_query(Statement::builder("SELECT 1").build())
2519            .await?;
2520        let row = second_result_set
2521            .next()
2522            .await
2523            .expect("Expected row result from second query")?;
2524        assert_eq!(
2525            row.raw_values(),
2526            [Value(string_val("1"))],
2527            "Second query successfully executed within established transaction"
2528        );
2529        assert_eq!(
2530            transaction
2531                .read_timestamp()
2532                .expect("Expected read timestamp to be set")
2533                .seconds(),
2534            123456789,
2535            "Read timestamp should match explicit begin timestamp"
2536        );
2537
2538        Ok(())
2539    }
2540
2541    #[tokio_test_no_panics]
2542    async fn inlined_begin_subsequent_statement_succeeds_after_second_statement_fails()
2543    -> anyhow::Result<()> {
2544        let mut mock = create_session_mock();
2545        let mut sequence = Sequence::new();
2546
2547        // 1. Initial query with inline begin succeeds, returning metadata with transaction ID.
2548        mock.expect_execute_streaming_sql()
2549            .times(1)
2550            .in_sequence(&mut sequence)
2551            .returning(|request| {
2552                let request = request.into_inner();
2553                match request
2554                    .transaction
2555                    .expect("transaction selector must be present")
2556                    .selector
2557                    .expect("selector kind must be present")
2558                {
2559                    Selector::Begin(_) => {}
2560                    _ => panic!("Expected Selector::Begin for first query"),
2561                }
2562                let mut result_set_partial = setup_select1();
2563                result_set_partial
2564                    .metadata
2565                    .as_mut()
2566                    .expect("metadata should be present")
2567                    .transaction = Some(mock_v1::Transaction {
2568                    id: vec![7, 8, 9],
2569                    read_timestamp: Some(Timestamp {
2570                        seconds: 123456789,
2571                        nanos: 0,
2572                    }),
2573                    ..Default::default()
2574                });
2575                Ok(Response::from(adapt([Ok(result_set_partial)])))
2576            });
2577
2578        // 2. Second query using established transaction ID fails with InvalidArgument (e.g. invalid table).
2579        mock.expect_execute_streaming_sql()
2580            .times(1)
2581            .in_sequence(&mut sequence)
2582            .returning(|request| {
2583                let request = request.into_inner();
2584                match request
2585                    .transaction
2586                    .expect("transaction selector must be present")
2587                    .selector
2588                    .expect("selector kind must be present")
2589                {
2590                    Selector::Id(transaction_id) => {
2591                        assert_eq!(
2592                            transaction_id,
2593                            vec![7, 8, 9],
2594                            "Expected second query to use established transaction ID"
2595                        );
2596                    }
2597                    _ => panic!("Expected Selector::Id on second query"),
2598                }
2599                Ok(Response::from(adapt([Err(Status::invalid_argument(
2600                    "Table not found: invalid_table",
2601                ))])))
2602            });
2603
2604        // 3. Third query using established transaction ID succeeds.
2605        mock.expect_execute_streaming_sql()
2606            .times(1)
2607            .in_sequence(&mut sequence)
2608            .returning(|request| {
2609                let request = request.into_inner();
2610                match request
2611                    .transaction
2612                    .expect("transaction selector must be present")
2613                    .selector
2614                    .expect("selector kind must be present")
2615                {
2616                    Selector::Id(transaction_id) => {
2617                        assert_eq!(
2618                            transaction_id,
2619                            vec![7, 8, 9],
2620                            "Expected third query to use established transaction ID"
2621                        );
2622                    }
2623                    _ => panic!("Expected Selector::Id on third query"),
2624                }
2625                Ok(Response::from(adapt([Ok(setup_select1())])))
2626            });
2627
2628        let (database_client, _server) = setup_db_client(mock).await;
2629        let transaction = database_client
2630            .read_only_transaction()
2631            .set_begin_transaction_option(BeginTransactionOption::InlineBegin)
2632            .build()
2633            .await?;
2634
2635        // 1. First query succeeds and establishes the transaction.
2636        let mut first_result_set = transaction
2637            .execute_query(Statement::builder("SELECT 1").build())
2638            .await?;
2639        let first_row = first_result_set.next().await.expect("row expected")?;
2640        assert_eq!(
2641            first_row.raw_values(),
2642            [Value(string_val("1"))],
2643            "First query result matches expected value"
2644        );
2645        assert_eq!(
2646            transaction
2647                .read_timestamp()
2648                .expect("Expected read timestamp to be set")
2649                .seconds(),
2650            123456789,
2651            "Read timestamp matches inlined begin timestamp"
2652        );
2653
2654        // 2. Second query fails with InvalidArgument.
2655        let second_result = transaction
2656            .execute_query(Statement::builder("SELECT * FROM invalid_table").build())
2657            .await;
2658        assert!(
2659            second_result.is_err(),
2660            "Expected second query to fail with InvalidArgument"
2661        );
2662
2663        // 3. Third query continues to execute successfully on the existing transaction snapshot.
2664        let mut third_result_set = transaction
2665            .execute_query(Statement::builder("SELECT 1").build())
2666            .await?;
2667        let third_row = third_result_set
2668            .next()
2669            .await
2670            .expect("row expected from third query")?;
2671        assert_eq!(
2672            third_row.raw_values(),
2673            [Value(string_val("1"))],
2674            "Third query result matches expected value"
2675        );
2676
2677        Ok(())
2678    }
2679
2680    #[tokio_test_no_panics]
2681    async fn inlined_begin_streaming_read_chunk_failure_fails_fast() -> anyhow::Result<()> {
2682        let mut mock = create_session_mock();
2683
2684        // 1. Initial streaming read with inline begin fails on chunk with Unavailable.
2685        mock.expect_streaming_read().times(1).returning(|request| {
2686            let request = request.into_inner();
2687            match request
2688                .transaction
2689                .expect("transaction selector must be present")
2690                .selector
2691                .expect("selector kind must be present")
2692            {
2693                Selector::Begin(_) => {}
2694                _ => panic!("Expected Selector::Begin for first read"),
2695            }
2696            Ok(Response::from(adapt([Err(Status::unavailable(
2697                "Transient initial read chunk failure",
2698            ))])))
2699        });
2700
2701        // 2. BeginTransaction must NEVER be called as a fallback.
2702        mock.expect_begin_transaction().never();
2703
2704        let (database_client, _server) = setup_db_client(mock).await;
2705        let transaction = database_client
2706            .read_only_transaction()
2707            .set_begin_transaction_option(BeginTransactionOption::InlineBegin)
2708            .build()
2709            .await?;
2710
2711        let read_request = ReadRequest::builder("Users", vec!["Id", "Name"])
2712            .with_keys(KeySet::all())
2713            .with_retry_policy(NeverRetry)
2714            .build();
2715        let first_read_result = transaction.execute_read(read_request).await;
2716        assert!(
2717            first_read_result.is_err(),
2718            "Expected initial read to fail fast on stream initialization chunk error"
2719        );
2720        let error_message = first_read_result
2721            .expect_err("first read failed")
2722            .to_string();
2723        assert!(
2724            error_message.contains("Transient initial read chunk failure"),
2725            "Expected transient read error message to propagate: {error_message}"
2726        );
2727
2728        // Subsequent query on the same transaction fails fast without any RPCs.
2729        let second_query_result = transaction
2730            .execute_query(Statement::builder("SELECT 1").build())
2731            .await;
2732        assert!(
2733            second_query_result.is_err(),
2734            "Subsequent query must fail fast on a failed read-only transaction"
2735        );
2736        let second_error = second_query_result.expect_err("second query failed");
2737        let status = second_error
2738            .status()
2739            .expect("Service status error must be preserved on subsequent query failure");
2740        assert_eq!(
2741            status.code,
2742            GaxCode::Unavailable,
2743            "Status code must match original failure"
2744        );
2745        assert_eq!(
2746            status.message,
2747            "Transaction cannot be used: initial statement failed with: Transient initial read chunk failure",
2748            "Subsequent query error message must explicitly explain transaction cannot be used"
2749        );
2750
2751        Ok(())
2752    }
2753
2754    #[tokio_test_no_panics]
2755    async fn single_use_query_send_error_returns_immediately() -> anyhow::Result<()> {
2756        use crate::statement::Statement;
2757        use gaxi::grpc::tonic::Status;
2758
2759        let mut mock = create_session_mock();
2760
2761        mock.expect_execute_streaming_sql()
2762            .times(1)
2763            .returning(|_| Err(Status::internal("Internal error single use query")));
2764
2765        mock.expect_begin_transaction().never();
2766
2767        let (db_client, _server) = setup_db_client(mock).await;
2768        // single_use creates a Fixed selector
2769        let tx = db_client.single_use().build();
2770
2771        let rs_result = tx
2772            .execute_query(Statement::builder("SELECT 1").build())
2773            .await;
2774
2775        assert!(rs_result.is_err());
2776        let err_str = rs_result.unwrap_err().to_string();
2777        assert!(err_str.contains("Internal error single use query"));
2778
2779        Ok(())
2780    }
2781
2782    #[tokio_test_no_panics]
2783    async fn inline_begin_already_started_query_send_error_returns_immediately()
2784    -> anyhow::Result<()> {
2785        use crate::statement::Statement;
2786        use gaxi::grpc::tonic::Status;
2787        use spanner_grpc_mock::google::spanner::v1 as mock_v1;
2788
2789        let mut mock = create_session_mock();
2790        let mut seq = mockall::Sequence::new();
2791
2792        mock.expect_begin_transaction().never();
2793
2794        // 1. First query executes successfully and implicitly starts the transaction.
2795        mock.expect_execute_streaming_sql()
2796            .times(1)
2797            .in_sequence(&mut seq)
2798            .returning(move |_req| {
2799                let mut rs = setup_select1();
2800                rs.metadata.as_mut().unwrap().transaction = Some(mock_v1::Transaction {
2801                    id: vec![4, 5, 6],
2802                    read_timestamp: None,
2803                    ..Default::default()
2804                });
2805                Ok(gaxi::grpc::tonic::Response::from(adapt([Ok(rs)])))
2806            });
2807
2808        // 2. Second query fails immediately upon send()
2809        mock.expect_execute_streaming_sql()
2810            .times(1)
2811            .in_sequence(&mut seq)
2812            .returning(|_| Err(Status::internal("Internal error second query")));
2813
2814        let (db_client, _server) = setup_db_client(mock).await;
2815
2816        let tx = db_client
2817            .read_only_transaction()
2818            .set_begin_transaction_option(BeginTransactionOption::InlineBegin)
2819            .build()
2820            .await?;
2821
2822        // Run first query (starts tx)
2823        let mut rs = tx
2824            .execute_query(Statement::builder("SELECT 1").build())
2825            .await?;
2826        let _ = rs.next().await.expect("has row")?;
2827
2828        // Run second query (fails)
2829        let rs_result = tx
2830            .execute_query(Statement::builder("SELECT 2").build())
2831            .await;
2832
2833        assert!(rs_result.is_err());
2834        let err_str = rs_result.unwrap_err().to_string();
2835        assert!(err_str.contains("Internal error second query"));
2836
2837        Ok(())
2838    }
2839
2840    #[tokio_test_no_panics]
2841    async fn execute_concurrent_queries_inline_begin() -> anyhow::Result<()> {
2842        let mut mock = create_session_mock();
2843        mock.expect_begin_transaction().never();
2844
2845        let mut seq = mockall::Sequence::new();
2846        let (tx_sender, rx_receiver) = mpsc::channel(1);
2847        let rx_receiver = Arc::new(Mutex::new(Some(rx_receiver)));
2848
2849        let task1_ready = Arc::new(Notify::new());
2850        let task1_ready_clone = Arc::clone(&task1_ready);
2851        let tasks_started = Arc::new(Barrier::new(3));
2852
2853        // 1. First query: should include Selector::Begin
2854        mock.expect_execute_streaming_sql()
2855            .times(1)
2856            .in_sequence(&mut seq)
2857            .returning(move |req| {
2858                task1_ready_clone.notify_one();
2859                let req = req.into_inner();
2860                match req
2861                    .transaction
2862                    .expect("transaction selector must be present")
2863                    .selector
2864                    .expect("selector kind must be present")
2865                {
2866                    Selector::Begin(_) => {}
2867                    _ => panic!("Expected Selector::Begin for first query"),
2868                }
2869                let rx = rx_receiver
2870                    .try_lock()
2871                    .expect("mutex poisoned")
2872                    .take()
2873                    .expect("rx receiver must be present");
2874                Ok(Response::from(rx))
2875            });
2876
2877        // 2. The other queries: should include populated Selector::Id
2878        mock.expect_execute_streaming_sql()
2879            .times(2)
2880            .in_sequence(&mut seq)
2881            .returning(move |req| {
2882                let req = req.into_inner();
2883                match req
2884                    .transaction
2885                    .expect("transaction selector must be present")
2886                    .selector
2887                    .expect("selector kind must be present")
2888                {
2889                    Selector::Id(id) => {
2890                        assert_eq!(id, vec![4, 5, 6]);
2891                    }
2892                    _ => panic!("Expected Selector::Id for other queries"),
2893                }
2894
2895                let (tx, rx) = mpsc::channel(1);
2896                tx.try_send(Ok(setup_select1()))
2897                    .expect("send should succeed");
2898                Ok(Response::from(rx))
2899            });
2900
2901        let (db_client, _server) = setup_db_client(mock).await;
2902        let tx = db_client
2903            .read_only_transaction()
2904            .set_begin_transaction_option(BeginTransactionOption::InlineBegin)
2905            .build()
2906            .await?;
2907        let tx = Arc::new(tx);
2908
2909        // Spawn 3 concurrent queries.
2910        // Task 1 launches first and executes the first query.
2911        let tx1 = Arc::clone(&tx);
2912        let handle1 = tokio::spawn(async move {
2913            let mut rs = tx1
2914                .execute_query(Statement::builder("SELECT 1").build())
2915                .await?;
2916            // Read the first result to get the transaction ID.
2917            let _ = rs.next().await;
2918            Ok::<_, crate::Error>(rs)
2919        });
2920
2921        // Wait for Task 1 to reach the mock server.
2922        task1_ready.notified().await;
2923
2924        let tx2 = Arc::clone(&tx);
2925        let tasks_started2 = Arc::clone(&tasks_started);
2926        let handle2 = tokio::spawn(async move {
2927            tasks_started2.wait().await;
2928            tx2.execute_query(Statement::builder("SELECT 1").build())
2929                .await
2930        });
2931
2932        let tx3 = Arc::clone(&tx);
2933        let tasks_started3 = Arc::clone(&tasks_started);
2934        let handle3 = tokio::spawn(async move {
2935            tasks_started3.wait().await;
2936            tx3.execute_query(Statement::builder("SELECT 1").build())
2937                .await
2938        });
2939
2940        // Ensure both Tasks 2 and 3 have reached the barrier before proceeding.
2941        tasks_started.wait().await;
2942
2943        // Flush the scheduler on this single-threaded executor.
2944        // This guarantees that Tasks 2 & 3 run until they both hit the internal
2945        // selector Notify latch and become suspended.
2946        tokio::task::yield_now().await;
2947
2948        // Provide the first result (including the transaction ID) to Task 1.
2949        // This transitions the selector to 'Started' and unblocks Tasks 2 and 3.
2950        let mut rs = setup_select1();
2951        rs.metadata
2952            .as_mut()
2953            .expect("metadata should be present")
2954            .transaction = Some(mock_v1::Transaction {
2955            id: vec![4, 5, 6],
2956            read_timestamp: Some(prost_types::Timestamp {
2957                seconds: 987654321,
2958                nanos: 0,
2959            }),
2960            ..Default::default()
2961        });
2962        tx_sender.send(Ok(rs)).await.expect("channel broken");
2963        drop(tx_sender);
2964
2965        // Collect all results
2966        let mut rs1 = handle1.await??;
2967        let mut rs2 = handle2.await??;
2968        let mut rs3 = handle3.await??;
2969
2970        // Verify the query results
2971        assert!(rs1.next().await.is_none());
2972
2973        let row2 = rs2.next().await.expect("Expected a row")?;
2974        assert_eq!(row2.raw_values(), [Value(string_val("1"))]);
2975        assert!(rs2.next().await.is_none());
2976
2977        let row3 = rs3.next().await.expect("Expected a row")?;
2978        assert_eq!(row3.raw_values(), [Value(string_val("1"))]);
2979        assert!(rs3.next().await.is_none());
2980
2981        // Verify that the read timestamp was populated
2982        assert_eq!(
2983            tx.read_timestamp()
2984                .expect("read timestamp should be populated")
2985                .seconds(),
2986            987654321
2987        );
2988
2989        Ok(())
2990    }
2991
2992    #[tokio_test_no_panics]
2993    async fn execute_concurrent_queries_inline_begin_failed_cascade() -> anyhow::Result<()> {
2994        let mut mock = create_session_mock();
2995        let mut seq = mockall::Sequence::new();
2996
2997        let (tx_sender, rx_receiver) = mpsc::channel(1);
2998        let rx_receiver = Arc::new(Mutex::new(Some(rx_receiver)));
2999
3000        let task1_ready = Arc::new(Notify::new());
3001        let task1_ready_clone = Arc::clone(&task1_ready);
3002        let tasks_started = Arc::new(Barrier::new(3));
3003
3004        // 1. Return a stream connected to tx_sender.
3005        // We will use tx_sender later in the test to inject a failed first chunk.
3006        mock.expect_execute_streaming_sql()
3007            .times(1)
3008            .in_sequence(&mut seq)
3009            .returning(move |_req| {
3010                task1_ready_clone.notify_one();
3011                let rx = rx_receiver
3012                    .try_lock()
3013                    .expect("mutex poisoned")
3014                    .take()
3015                    .expect("receiver should be present");
3016                Ok(tonic::Response::from(rx))
3017            });
3018
3019        // 2. BeginTransaction must NEVER be called as a fallback.
3020        mock.expect_begin_transaction().never();
3021
3022        // The other queries will never be executed.
3023        mock.expect_execute_streaming_sql().times(0).returning(|_| {
3024            panic!("Other queries should not launch after failure to start the transaction")
3025        });
3026
3027        let (db_client, _server) = setup_db_client(mock).await;
3028        let tx = db_client
3029            .read_only_transaction()
3030            .set_begin_transaction_option(BeginTransactionOption::InlineBegin)
3031            .build()
3032            .await?;
3033        let tx = Arc::new(tx);
3034
3035        // Spawn 3 concurrent queries.
3036        let tx1 = Arc::clone(&tx);
3037        let handle1 = tokio::spawn(async move {
3038            let mut rs = tx1
3039                .execute_query(Statement::builder("SELECT 1").build())
3040                .await?;
3041            rs.next().await.ok_or_else(|| {
3042                crate::error::internal_error("stream exhausted (this should never happen)")
3043            })??;
3044            Ok::<_, crate::Error>(rs)
3045        });
3046
3047        // Wait for Task 1 to reach the mock and transition the selector to Starting.
3048        task1_ready.notified().await;
3049
3050        let tx2 = Arc::clone(&tx);
3051        let tasks_started2 = Arc::clone(&tasks_started);
3052        let handle2 = tokio::spawn(async move {
3053            tasks_started2.wait().await;
3054            tx2.execute_query(Statement::builder("SELECT 1").build())
3055                .await
3056        });
3057
3058        let tx3 = Arc::clone(&tx);
3059        let tasks_started3 = Arc::clone(&tasks_started);
3060        let handle3 = tokio::spawn(async move {
3061            tasks_started3.wait().await;
3062            tx3.execute_query(Statement::builder("SELECT 1").build())
3063                .await
3064        });
3065
3066        // Ensure both Tasks 2 and 3 have reached the barrier before proceeding.
3067        tasks_started.wait().await;
3068
3069        // Flush the scheduler on this single-threaded executor.
3070        // This guarantees that Tasks 2 & 3 run until they both hit the internal
3071        // selector Notify latch and become suspended.
3072        tokio::task::yield_now().await;
3073
3074        // Push error to channel failing first query stream!
3075        tx_sender
3076            .send(Err(gaxi::grpc::tonic::Status::internal(
3077                "Mocked boot failed",
3078            )))
3079            .await
3080            .expect("channel broken");
3081        drop(tx_sender);
3082
3083        // Collect all results - all should fail with identical cached error!
3084        let err1 = handle1
3085            .await?
3086            .expect_err("task 1 should have failed")
3087            .to_string();
3088        let err2 = handle2
3089            .await?
3090            .expect_err("task 2 should have failed")
3091            .to_string();
3092        let err3 = handle3
3093            .await?
3094            .expect_err("task 3 should have failed")
3095            .to_string();
3096
3097        assert!(err1.contains("Mocked boot failed"), "err1: {}", err1);
3098        assert!(
3099            err2.contains(
3100                "Transaction cannot be used: initial statement failed with: Mocked boot failed"
3101            ),
3102            "err2: {}",
3103            err2
3104        );
3105        assert!(
3106            err3.contains(
3107                "Transaction cannot be used: initial statement failed with: Mocked boot failed"
3108            ),
3109            "err3: {}",
3110            err3
3111        );
3112
3113        Ok(())
3114    }
3115
3116    #[tokio_test_no_panics]
3117    async fn execute_concurrent_queries_inline_begin_stream_restart_deadlock_prevention()
3118    -> crate::Result<()> {
3119        let mut mock = create_session_mock();
3120        mock.expect_begin_transaction().never();
3121
3122        let mut seq = mockall::Sequence::new();
3123
3124        let (tx_sender, rx_receiver) = mpsc::channel(1);
3125        let rx_receiver = Arc::new(Mutex::new(Some(rx_receiver)));
3126
3127        let task1_ready = Arc::new(Notify::new());
3128        let task1_ready_clone = Arc::clone(&task1_ready);
3129        let tasks_started = Arc::new(Barrier::new(3));
3130
3131        // 1. Task 1 initial query: Return a stream connected to tx_sender for error injection.
3132        mock.expect_execute_streaming_sql()
3133            .times(1)
3134            .in_sequence(&mut seq)
3135            .returning(move |req| {
3136                let req = req.into_inner();
3137                // Return a stream connected to tx_sender.
3138                // We will use tx_sender later in the test to inject a transient error.
3139                task1_ready_clone.notify_one();
3140                match req
3141                    .transaction
3142                    .expect("transaction should be present")
3143                    .selector
3144                    .expect("selector should be present")
3145                {
3146                    Selector::Begin(_) => {}
3147                    _ => panic!("Expected Selector::Begin for first query"),
3148                }
3149                let rx = rx_receiver
3150                    .try_lock()
3151                    .expect("mutex poisoned")
3152                    .take()
3153                    .expect("receiver should be present");
3154                Ok(Response::from(rx))
3155            });
3156
3157        // 2. Task 1 restart query: should include Selector::Begin, since
3158        // it failed with a transient error.
3159        mock.expect_execute_streaming_sql()
3160            .times(1)
3161            .in_sequence(&mut seq)
3162            .returning(move |req| {
3163                let req = req.into_inner();
3164                match req
3165                    .transaction
3166                    .expect("transaction should be present")
3167                    .selector
3168                    .expect("selector should be present")
3169                {
3170                    Selector::Begin(_) => {
3171                        let mut rs = setup_select1();
3172                        rs.metadata
3173                            .as_mut()
3174                            .expect("metadata should be present")
3175                            .transaction = Some(mock_v1::Transaction {
3176                            id: vec![4, 5, 6],
3177                            ..Default::default()
3178                        });
3179                        let (tx, rx) = mpsc::channel(1);
3180                        tx.try_send(Ok(rs)).expect("send should succeed");
3181                        Ok(Response::from(rx))
3182                    }
3183                    _ => panic!("Expected Selector::Begin for stream restart query"),
3184                }
3185            });
3186
3187        // 3. Tasks 2 & 3: should include populated Selector::Id
3188        mock.expect_execute_streaming_sql()
3189            .times(2)
3190            .in_sequence(&mut seq)
3191            .returning(move |req| {
3192                let req = req.into_inner();
3193                match req
3194                    .transaction
3195                    .expect("transaction should be present")
3196                    .selector
3197                    .expect("selector should be present")
3198                {
3199                    Selector::Id(id) => {
3200                        assert_eq!(id, vec![4, 5, 6]);
3201                        let (tx, rx) = mpsc::channel(1);
3202                        tx.try_send(Ok(setup_select1()))
3203                            .expect("send should succeed");
3204                        Ok(Response::from(rx))
3205                    }
3206                    _ => panic!("Expected Selector::Id for concurrent queries"),
3207                }
3208            });
3209
3210        let (db_client, _server) = setup_db_client(mock).await;
3211        let tx = db_client
3212            .read_only_transaction()
3213            .set_begin_transaction_option(BeginTransactionOption::InlineBegin)
3214            .build()
3215            .await?;
3216        let tx = Arc::new(tx);
3217
3218        let handle1_tx = Arc::clone(&tx);
3219        let handle1 = tokio::spawn(async move {
3220            let statement = Statement::builder("SELECT 1")
3221                .with_backoff_policy(
3222                    ExponentialBackoffBuilder::new()
3223                        .with_initial_delay(Duration::from_nanos(1))
3224                        .clamp(),
3225                )
3226                .build();
3227            let mut rs = handle1_tx.execute_query(statement).await?;
3228            let _ = rs.next().await.ok_or_else(|| {
3229                crate::error::internal_error("stream exhausted (this should never happen)")
3230            })??;
3231            Ok::<_, crate::Error>(rs)
3232        });
3233
3234        // Wait for Task 1 to reach the mock and transition the selector to Starting.
3235        task1_ready.notified().await;
3236
3237        let handle2_tx = Arc::clone(&tx);
3238        let tasks_started2 = Arc::clone(&tasks_started);
3239        let handle2 = tokio::spawn(async move {
3240            tasks_started2.wait().await;
3241            let mut rs = handle2_tx
3242                .execute_query(Statement::builder("SELECT 1").build())
3243                .await?;
3244            let _ = rs.next().await.ok_or_else(|| {
3245                crate::error::internal_error("stream exhausted (this should never happen)")
3246            })??;
3247            Ok::<_, crate::Error>(rs)
3248        });
3249
3250        let handle3_tx = Arc::clone(&tx);
3251        let tasks_started3 = Arc::clone(&tasks_started);
3252        let handle3 = tokio::spawn(async move {
3253            tasks_started3.wait().await;
3254            let mut rs = handle3_tx
3255                .execute_query(Statement::builder("SELECT 1").build())
3256                .await?;
3257            let _ = rs.next().await.ok_or_else(|| {
3258                crate::error::internal_error("stream exhausted (this should never happen)")
3259            })??;
3260            Ok::<_, crate::Error>(rs)
3261        });
3262
3263        // Ensure both Tasks 2 and 3 have reached the barrier before proceeding.
3264        tasks_started.wait().await;
3265
3266        // Flush the scheduler on this single-threaded executor.
3267        // This guarantees that Tasks 2 & 3 run until they both hit the internal
3268        // selector Notify latch and become suspended.
3269        tokio::task::yield_now().await;
3270
3271        let grpc_status = Status::new(gaxi::grpc::tonic::Code::Unavailable, "transient error");
3272        tx_sender.send(Err(grpc_status)).await.expect("send failed");
3273        drop(tx_sender);
3274
3275        // Collect and verify all results.
3276        // handle.await returns Result<Result<ResultSet, Error>, JoinError>.
3277        // The first ? handles the potential JoinError (panic in the task),
3278        // and the second ? handles the Spanner error.
3279        let mut rs1 = handle1.await.expect("Task 1 panicked")?;
3280        let mut rs2 = handle2.await.expect("Task 2 panicked")?;
3281        let mut rs3 = handle3.await.expect("Task 3 panicked")?;
3282
3283        // Verify that all results have been exhausted.
3284        // (The tasks themselves already successfully read the first row).
3285        assert!(rs1.next().await.is_none(), "Stream 1 should be exhausted");
3286        assert!(rs2.next().await.is_none(), "Stream 2 should be exhausted");
3287        assert!(rs3.next().await.is_none(), "Stream 3 should be exhausted");
3288
3289        Ok(())
3290    }
3291
3292    #[tokio_test_no_panics]
3293    async fn execute_concurrent_queries_late_arrival_failure() -> anyhow::Result<()> {
3294        let mut mock = create_session_mock();
3295        let mut seq = mockall::Sequence::new();
3296
3297        // 1. Initial query fails.
3298        mock.expect_execute_streaming_sql()
3299            .times(1)
3300            .in_sequence(&mut seq)
3301            .returning(|req| {
3302                let req = req.into_inner();
3303                match req
3304                    .transaction
3305                    .expect("transaction should be present")
3306                    .selector
3307                    .expect("selector should be present")
3308                {
3309                    Selector::Begin(_) => {}
3310                    _ => panic!("Expected Selector::Begin for first query"),
3311                }
3312                Err(Status::internal("Initial inline-begin failed"))
3313            });
3314
3315        // 2. BeginTransaction must NEVER be called as a fallback.
3316        mock.expect_begin_transaction().never();
3317
3318        // Any further attempts would panic because we haven't mocked them.
3319        mock.expect_execute_streaming_sql().never();
3320
3321        let (db_client, _server) = setup_db_client(mock).await;
3322        let tx = db_client
3323            .read_only_transaction()
3324            .set_begin_transaction_option(BeginTransactionOption::InlineBegin)
3325            .build()
3326            .await?;
3327
3328        // First query: triggers the failure and transitions the state to Failed.
3329        let err1 = tx
3330            .execute_query(Statement::builder("SELECT 1").build())
3331            .await
3332            .expect_err("First query should fail");
3333        assert!(err1.to_string().contains("Initial inline-begin failed"));
3334
3335        // Second query: starts AFTER the failure is already cached.
3336        // It should immediately return the same error without invoking the mock server.
3337        let err2 = tx
3338            .execute_query(Statement::builder("SELECT 1").build())
3339            .await
3340            .expect_err("Late query should fail immediately");
3341        assert!(
3342            err2.to_string().contains(
3343                "Transaction cannot be used: initial statement failed with: Initial inline-begin failed"
3344            ),
3345            "err2: {err2}"
3346        );
3347
3348        Ok(())
3349    }
3350
3351    #[tokio_test_no_panics]
3352    async fn execute_concurrent_reads_inline_begin() -> anyhow::Result<()> {
3353        use crate::key::KeySet;
3354        use crate::read::ReadRequest;
3355        let mut mock = create_session_mock();
3356        mock.expect_begin_transaction().never();
3357
3358        let mut seq = mockall::Sequence::new();
3359        let (tx_sender, rx_receiver) = mpsc::channel(1);
3360        let rx_receiver = Arc::new(Mutex::new(Some(rx_receiver)));
3361
3362        let task1_ready = Arc::new(Notify::new());
3363        let task1_ready_clone = Arc::clone(&task1_ready);
3364        let tasks_started = Arc::new(Barrier::new(3));
3365
3366        // 1. First read: should include Selector::Begin
3367        mock.expect_streaming_read()
3368            .times(1)
3369            .in_sequence(&mut seq)
3370            .returning(move |req| {
3371                task1_ready_clone.notify_one();
3372                let req = req.into_inner();
3373                match req
3374                    .transaction
3375                    .expect("transaction should be present")
3376                    .selector
3377                    .expect("selector should be present")
3378                {
3379                    mock_v1::transaction_selector::Selector::Begin(_) => {}
3380                    _ => panic!("Expected Selector::Begin for first read"),
3381                }
3382
3383                let rx = rx_receiver
3384                    .try_lock()
3385                    .expect("mutex poisoned")
3386                    .take()
3387                    .expect("receiver should be present");
3388                Ok(Response::from(rx))
3389            });
3390
3391        // 2. The other reads: should include populated Selector::Id
3392        mock.expect_streaming_read()
3393            .times(2)
3394            .in_sequence(&mut seq)
3395            .returning(move |req| {
3396                let req = req.into_inner();
3397                match req
3398                    .transaction
3399                    .expect("transaction should be present")
3400                    .selector
3401                    .expect("selector should be present")
3402                {
3403                    mock_v1::transaction_selector::Selector::Id(id) => {
3404                        assert_eq!(id, vec![4, 5, 6]);
3405                    }
3406                    _ => panic!("Expected Selector::Id for other reads"),
3407                }
3408
3409                let (tx, rx) = mpsc::channel(1);
3410                tx.try_send(Ok(setup_select1()))
3411                    .expect("send should succeed");
3412                Ok(Response::from(rx))
3413            });
3414
3415        let (db_client, _server) = setup_db_client(mock).await;
3416        let tx = db_client
3417            .read_only_transaction()
3418            .set_begin_transaction_option(BeginTransactionOption::InlineBegin)
3419            .build()
3420            .await?;
3421        let tx = Arc::new(tx);
3422
3423        let read_req = ReadRequest::builder("Table", vec!["Col"])
3424            .with_keys(KeySet::all())
3425            .build();
3426
3427        // Spawn 3 concurrent reads.
3428        let tx1 = Arc::clone(&tx);
3429        let read1 = read_req.clone();
3430        let handle1 = tokio::spawn(async move {
3431            let mut rs = tx1.execute_read(read1).await?;
3432            let _ = rs.next().await;
3433            Ok::<_, crate::Error>(rs)
3434        });
3435
3436        task1_ready.notified().await;
3437
3438        let tx2 = Arc::clone(&tx);
3439        let read2 = read_req.clone();
3440        let tasks_started2 = Arc::clone(&tasks_started);
3441        let handle2 = tokio::spawn(async move {
3442            tasks_started2.wait().await;
3443            let mut rs = tx2.execute_read(read2).await?;
3444            let _ = rs.next().await;
3445            Ok::<_, crate::Error>(rs)
3446        });
3447
3448        let tx3 = Arc::clone(&tx);
3449        let read3 = read_req.clone();
3450        let tasks_started3 = Arc::clone(&tasks_started);
3451        let handle3 = tokio::spawn(async move {
3452            tasks_started3.wait().await;
3453            let mut rs = tx3.execute_read(read3).await?;
3454            let _ = rs.next().await;
3455            Ok::<_, crate::Error>(rs)
3456        });
3457
3458        tasks_started.wait().await;
3459        tokio::task::yield_now().await;
3460
3461        // Provide the transaction ID.
3462        let mut rs = setup_select1();
3463        rs.metadata
3464            .as_mut()
3465            .expect("metadata should be present")
3466            .transaction = Some(mock_v1::Transaction {
3467            id: vec![4, 5, 6],
3468            ..Default::default()
3469        });
3470        tx_sender.send(Ok(rs)).await.expect("send failed");
3471        drop(tx_sender);
3472
3473        let mut rs1 = handle1.await.expect("Task 1 panicked")?;
3474        let mut rs2 = handle2.await.expect("Task 2 panicked")?;
3475        let mut rs3 = handle3.await.expect("Task 3 panicked")?;
3476
3477        assert!(rs1.next().await.is_none());
3478        assert!(rs2.next().await.is_none());
3479        assert!(rs3.next().await.is_none());
3480
3481        Ok(())
3482    }
3483
3484    #[tokio_test_no_panics]
3485    async fn execute_inline_begin_idempotent_update() -> anyhow::Result<()> {
3486        let (db_client, _server) = setup_db_client(create_session_mock()).await;
3487        // Access internal state for unit testing.
3488        let tx = db_client
3489            .read_only_transaction()
3490            .set_begin_transaction_option(BeginTransactionOption::InlineBegin)
3491            .build()
3492            .await?;
3493
3494        let id1 = bytes::Bytes::from_static(b"tx1");
3495        let id2 = bytes::Bytes::from_static(b"tx2");
3496
3497        // 1. Initial update.
3498        tx.context.transaction_selector.update(id1.clone(), None)?;
3499        assert_eq!(
3500            tx.context
3501                .transaction_selector
3502                .selector()
3503                .await?
3504                .id()
3505                .expect("ID should be present"),
3506            &id1
3507        );
3508
3509        // 2. Redundant update with same ID should succeed, as Spanner returns the
3510        // transaction ID on all statements executed within that transaction when
3511        // using multiplexed sessions.
3512        tx.context.transaction_selector.update(id1.clone(), None)?;
3513
3514        // 3. Update with DIFFERENT ID after already Started should fail.
3515        let err2 = tx
3516            .context
3517            .transaction_selector
3518            .update(id2, None)
3519            .expect_err("Update after Started should fail");
3520        assert!(err2.to_string().contains("already Started or Failed"));
3521
3522        Ok(())
3523    }
3524
3525    #[tokio_test_no_panics]
3526    async fn execute_inline_begin_with_transient_failure() -> anyhow::Result<()> {
3527        let mut mock = create_session_mock();
3528        let mut sequence = Sequence::new();
3529
3530        // 1. First attempt fails transiently.
3531        mock.expect_execute_streaming_sql()
3532            .times(1)
3533            .in_sequence(&mut sequence)
3534            .returning(|_| Err(Status::new(Code::Unavailable, "Transient 1")));
3535
3536        // 2. The retry of the query statement retains the inline-begin selector and succeeds.
3537        mock.expect_execute_streaming_sql()
3538            .times(1)
3539            .in_sequence(&mut sequence)
3540            .returning(|request| {
3541                let request = request.into_inner();
3542                let selector = request
3543                    .transaction
3544                    .expect("transaction selector must be present")
3545                    .selector
3546                    .expect("selector kind must be present");
3547                assert!(
3548                    matches!(selector, Selector::Begin(_)),
3549                    "Expected Selector::Begin for retried query with inline begin"
3550                );
3551                let mut result_set_partial = setup_select1();
3552                result_set_partial
3553                    .metadata
3554                    .as_mut()
3555                    .expect("metadata should be present")
3556                    .transaction = Some(mock_v1::Transaction {
3557                    id: vec![1, 2, 3],
3558                    ..Default::default()
3559                });
3560                let (tx, rx) = mpsc::channel(1);
3561                tx.try_send(Ok(result_set_partial))
3562                    .expect("send should succeed");
3563                Ok(Response::from(rx))
3564            });
3565
3566        let (db_client, _server) = setup_db_client(mock).await;
3567        let transaction = db_client
3568            .read_only_transaction()
3569            .set_begin_transaction_option(BeginTransactionOption::InlineBegin)
3570            .build()
3571            .await?;
3572
3573        let mut mock_backoff = MockBackoffPolicy::new();
3574        mock_backoff
3575            .expect_on_failure()
3576            .times(1)
3577            .returning(|_| Duration::from_nanos(1));
3578
3579        let mut result_set = transaction
3580            .execute_query(
3581                Statement::builder("SELECT 1")
3582                    .with_backoff_policy(mock_backoff)
3583                    .build(),
3584            )
3585            .await?;
3586        assert!(
3587            result_set.next().await.is_some(),
3588            "expected first row to be present"
3589        );
3590        assert!(
3591            result_set.next().await.is_none(),
3592            "stream should be exhausted"
3593        );
3594
3595        Ok(())
3596    }
3597
3598    #[tokio_test_no_panics]
3599    async fn execute_inline_begin_fails_fast_when_retries_exhaust() -> anyhow::Result<()> {
3600        let mut mock = create_session_mock();
3601        let mut sequence = Sequence::new();
3602
3603        // 1. Initial attempt fails transiently.
3604        mock.expect_execute_streaming_sql()
3605            .times(1)
3606            .in_sequence(&mut sequence)
3607            .returning(|_| Err(Status::new(Code::Unavailable, "Transient 1")));
3608
3609        // 2. Retry attempt fails transiently, exhausting the retry limit (2 attempts).
3610        mock.expect_execute_streaming_sql()
3611            .times(1)
3612            .in_sequence(&mut sequence)
3613            .returning(|_| Err(Status::new(Code::Unavailable, "Transient 2")));
3614
3615        // 3. BeginTransaction must NEVER be called as a fallback.
3616        mock.expect_begin_transaction().never();
3617
3618        let (db_client, _server) = setup_db_client(mock).await;
3619        let transaction = db_client
3620            .read_only_transaction()
3621            .set_begin_transaction_option(BeginTransactionOption::InlineBegin)
3622            .build()
3623            .await?;
3624
3625        let mut mock_backoff = MockBackoffPolicy::new();
3626        mock_backoff
3627            .expect_on_failure()
3628            .times(1)
3629            .returning(|_| Duration::from_nanos(1));
3630
3631        let first_result = transaction
3632            .execute_query(
3633                Statement::builder("SELECT 1")
3634                    .with_backoff_policy(mock_backoff)
3635                    .with_retry_policy(SpannerRetryPolicy::new().with_attempt_limit(2))
3636                    .build(),
3637            )
3638            .await;
3639        assert!(
3640            first_result.is_err(),
3641            "Expected first query to fail with Unavailable after retries exhaust"
3642        );
3643        let first_error = first_result.expect_err("first query should fail");
3644        assert_eq!(
3645            first_error.status().expect("status").code,
3646            GaxCode::Unavailable,
3647            "Expected Unavailable status code on first query failure"
3648        );
3649
3650        // Subsequent query fails fast without any RPCs.
3651        let second_result = transaction
3652            .execute_query(Statement::builder("SELECT 1").build())
3653            .await;
3654        assert!(
3655            second_result.is_err(),
3656            "Expected second query to fail fast on a failed read-only transaction"
3657        );
3658        let second_error = second_result.expect_err("second query should fail fast");
3659        assert_eq!(
3660            second_error.status().expect("status").code,
3661            GaxCode::Unavailable,
3662            "Subsequent query error status code should match initial error"
3663        );
3664
3665        Ok(())
3666    }
3667
3668    #[tokio_test_no_panics]
3669    async fn leader_aware_routing_query_in_read_only() -> anyhow::Result<()> {
3670        let mut mock = create_session_mock();
3671        mock.expect_execute_streaming_sql().once().returning(|req| {
3672            assert!(
3673                req.metadata()
3674                    .get("x-goog-spanner-route-to-leader")
3675                    .is_none()
3676            );
3677            let stream = adapt([Ok(mock_v1::PartialResultSet {
3678                metadata: Some(mock_v1::ResultSetMetadata {
3679                    row_type: Some(mock_v1::StructType { fields: vec![] }),
3680                    ..Default::default()
3681                }),
3682                ..Default::default()
3683            })]);
3684            Ok(tonic::Response::from(stream))
3685        });
3686
3687        let (db_client, _server) = setup_db_client(mock).await;
3688        let tx = db_client.single_use().build();
3689        let _rs = tx
3690            .execute_query(Statement::builder("SELECT 1").build())
3691            .await?;
3692        Ok(())
3693    }
3694
3695    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3696    async fn execute_concurrent_begin_explicitly_redundancy_prevention() -> anyhow::Result<()> {
3697        let (tx_rpc, rx_rpc) = std_channel();
3698        let (tx_started, rx_started) = oneshot_channel();
3699        let tx_started_mutex = StdMutex::new(Some(tx_started));
3700
3701        let mut mock = create_session_mock();
3702        let mut seq = mockall::Sequence::new();
3703
3704        // Task 1 (leader) fires the initial query inline.
3705        mock.expect_execute_streaming_sql()
3706            .once()
3707            .in_sequence(&mut seq)
3708            .returning(move |_req| {
3709                if let Some(tx) = tx_started_mutex.lock().expect("mutex poisoned").take() {
3710                    let _ = tx.send(());
3711                }
3712                rx_rpc.recv().expect("channel broken");
3713                let (tx, rx) = mpsc::channel(1);
3714                let metadata = mock_v1::ResultSetMetadata {
3715                    transaction: Some(mock_v1::Transaction {
3716                        id: vec![42],
3717                        ..Default::default()
3718                    }),
3719                    ..Default::default()
3720                };
3721                let prs = mock_v1::PartialResultSet {
3722                    metadata: Some(metadata),
3723                    ..Default::default()
3724                };
3725                tx.try_send(Ok(prs)).expect("send should succeed");
3726                Ok(tonic::Response::new(rx))
3727            });
3728
3729        // Task 2 (follower) arrives while Task 1 is in flight, suspends until Task 1 completes,
3730        // and then successfully fires its query using the newly extracted transaction ID (vec![42]).
3731        mock.expect_execute_streaming_sql()
3732            .once()
3733            .in_sequence(&mut seq)
3734            .returning(move |req| {
3735                let req = req.into_inner();
3736                assert_eq!(
3737                    req.transaction,
3738                    Some(mock_v1::TransactionSelector {
3739                        selector: Some(mock_v1::transaction_selector::Selector::Id(vec![42])),
3740                    })
3741                );
3742                let (tx, rx) = mpsc::channel(1);
3743                let metadata = mock_v1::ResultSetMetadata {
3744                    row_type: Some(mock_v1::StructType { fields: vec![] }),
3745                    ..Default::default()
3746                };
3747                let prs = mock_v1::PartialResultSet {
3748                    metadata: Some(metadata),
3749                    ..Default::default()
3750                };
3751                tx.try_send(Ok(prs)).expect("send should succeed");
3752                Ok(tonic::Response::new(rx))
3753            });
3754
3755        let (db_client, _server) = setup_db_client(mock).await;
3756
3757        let tx = Arc::new(
3758            db_client
3759                .read_only_transaction()
3760                .set_begin_transaction_option(BeginTransactionOption::InlineBegin)
3761                .build()
3762                .await?,
3763        );
3764
3765        let tx_leader = Arc::clone(&tx);
3766        let handle_leader = tokio::spawn(async move {
3767            let mut rs = tx_leader
3768                .execute_query(Statement::builder("SELECT 1").build())
3769                .await?;
3770            let _ = rs.next().await;
3771            Ok::<_, crate::Error>(())
3772        });
3773
3774        rx_started.await.expect("oneshot broken");
3775
3776        // Now the state is Starting and the leader is blocked inside execute_streaming_sql.
3777        // Task 2 executes a concurrent query, which must wait for the leader rather than firing a redundant RPC.
3778        let tx_follower = Arc::clone(&tx);
3779        let handle_follower = tokio::spawn(async move {
3780            let mut rs = tx_follower
3781                .execute_query(Statement::builder("SELECT 2").build())
3782                .await?;
3783            let _ = rs.next().await;
3784            Ok::<_, crate::Error>(())
3785        });
3786
3787        // Unblock the leader
3788        tx_rpc.send(()).expect("send failed");
3789
3790        handle_leader.await.expect("Task 1 panicked")?;
3791        handle_follower.await.expect("Task 2 panicked")?;
3792
3793        Ok(())
3794    }
3795
3796    #[tokio_test_no_panics]
3797    async fn execute_multi_query_redundant_transaction_id_explicit() -> anyhow::Result<()> {
3798        run_execute_multi_query_redundant_transaction_id(BeginTransactionOption::ExplicitBegin)
3799            .await
3800    }
3801
3802    #[tokio_test_no_panics]
3803    async fn execute_multi_query_redundant_transaction_id_inline() -> anyhow::Result<()> {
3804        run_execute_multi_query_redundant_transaction_id(BeginTransactionOption::InlineBegin).await
3805    }
3806
3807    async fn run_execute_multi_query_redundant_transaction_id(
3808        option: BeginTransactionOption,
3809    ) -> anyhow::Result<()> {
3810        let mut mock = create_session_mock();
3811        let mut sequence = mockall::Sequence::new();
3812
3813        if option == BeginTransactionOption::ExplicitBegin {
3814            mock.expect_begin_transaction()
3815                .once()
3816                .in_sequence(&mut sequence)
3817                .returning(|req| {
3818                    let req = req.into_inner();
3819                    assert_eq!(
3820                        req.session,
3821                        "projects/p/instances/i/databases/d/sessions/123"
3822                    );
3823                    Ok(tonic::Response::new(mock_v1::Transaction {
3824                        id: vec![4, 5, 6],
3825                        read_timestamp: Some(prost_types::Timestamp {
3826                            seconds: 123456789,
3827                            nanos: 0,
3828                        }),
3829                        ..Default::default()
3830                    }))
3831                });
3832
3833            mock.expect_execute_streaming_sql()
3834                .times(2)
3835                .returning(|req| {
3836                    let req = req.into_inner();
3837                    assert_eq!(
3838                        req.transaction
3839                            .expect("transaction should be present")
3840                            .selector
3841                            .expect("selector should be present"),
3842                        mock_v1::transaction_selector::Selector::Id(vec![4, 5, 6])
3843                    );
3844
3845                    let mut result_set_partial = setup_select1();
3846                    result_set_partial
3847                        .metadata
3848                        .as_mut()
3849                        .expect("metadata should be present")
3850                        .transaction = Some(mock_v1::Transaction {
3851                        id: vec![4, 5, 6],
3852                        read_timestamp: Some(prost_types::Timestamp {
3853                            seconds: 123456789,
3854                            nanos: 0,
3855                        }),
3856                        ..Default::default()
3857                    });
3858                    Ok(gaxi::grpc::tonic::Response::from(adapt([Ok(
3859                        result_set_partial,
3860                    )])))
3861                });
3862        } else {
3863            mock.expect_begin_transaction().never();
3864
3865            mock.expect_execute_streaming_sql()
3866                .times(1)
3867                .in_sequence(&mut sequence)
3868                .returning(|req| {
3869                    let req = req.into_inner();
3870                    assert_eq!(
3871                        req.session,
3872                        "projects/p/instances/i/databases/d/sessions/123"
3873                    );
3874
3875                    match req
3876                        .transaction
3877                        .expect("transaction should be present")
3878                        .selector
3879                        .expect("selector should be present")
3880                    {
3881                        mock_v1::transaction_selector::Selector::Begin(_) => {}
3882                        _ => panic!("Expected Selector::Begin"),
3883                    }
3884                    let mut result_set_partial = setup_select1();
3885                    result_set_partial
3886                        .metadata
3887                        .as_mut()
3888                        .expect("metadata should be present")
3889                        .transaction = Some(mock_v1::Transaction {
3890                        id: vec![4, 5, 6],
3891                        read_timestamp: Some(prost_types::Timestamp {
3892                            seconds: 987654321,
3893                            nanos: 0,
3894                        }),
3895                        ..Default::default()
3896                    });
3897                    Ok(gaxi::grpc::tonic::Response::from(adapt([Ok(
3898                        result_set_partial,
3899                    )])))
3900                });
3901
3902            mock.expect_execute_streaming_sql()
3903                .times(1)
3904                .in_sequence(&mut sequence)
3905                .returning(|req| {
3906                    let req = req.into_inner();
3907                    match req
3908                        .transaction
3909                        .expect("transaction should be present")
3910                        .selector
3911                        .expect("selector should be present")
3912                    {
3913                        mock_v1::transaction_selector::Selector::Id(id) => {
3914                            assert_eq!(id, vec![4, 5, 6]);
3915                        }
3916                        _ => panic!("Expected Selector::Id"),
3917                    }
3918                    let mut result_set_partial = setup_select1();
3919                    result_set_partial
3920                        .metadata
3921                        .as_mut()
3922                        .expect("metadata should be present")
3923                        .transaction = Some(mock_v1::Transaction {
3924                        id: vec![4, 5, 6],
3925                        read_timestamp: Some(prost_types::Timestamp {
3926                            seconds: 987654321,
3927                            nanos: 0,
3928                        }),
3929                        ..Default::default()
3930                    });
3931                    Ok(gaxi::grpc::tonic::Response::from(adapt([Ok(
3932                        result_set_partial,
3933                    )])))
3934                });
3935        }
3936
3937        let (db_client, _server) = setup_db_client(mock).await;
3938
3939        let transaction = db_client
3940            .read_only_transaction()
3941            .set_begin_transaction_option(option)
3942            .build()
3943            .await
3944            .expect("Failed to start transaction");
3945
3946        for _ in 0..2 {
3947            let mut result_set = transaction
3948                .execute_query(Statement::builder("SELECT 1").build())
3949                .await
3950                .expect("Failed to execute query");
3951
3952            let row = result_set
3953                .next()
3954                .await
3955                .expect("has row")
3956                .expect("has valid row");
3957            assert_eq!(row.raw_values(), [Value(string_val("1"))]);
3958
3959            let next_result = result_set.next().await;
3960            assert!(next_result.is_none(), "expected None, got {next_result:?}");
3961        }
3962
3963        Ok(())
3964    }
3965
3966    #[tokio_test_no_panics]
3967    async fn read_only_transaction_begin_with_never_retry() -> anyhow::Result<()> {
3968        let mut mock = MockSpanner::new();
3969        let mut sequence = mockall::Sequence::new();
3970
3971        mock.expect_begin_transaction()
3972            .once()
3973            .in_sequence(&mut sequence)
3974            .returning(|_| Err(tonic::Status::unavailable("transient error")));
3975
3976        mock.expect_create_session().returning(|_| {
3977            Ok(Response::new(mock_v1::Session {
3978                name: "session".to_string(),
3979                multiplexed: true,
3980                ..Default::default()
3981            }))
3982        });
3983
3984        let (db_client, _server) = setup_db_client(mock).await;
3985
3986        let res = db_client
3987            .read_only_transaction()
3988            .set_begin_transaction_option(BeginTransactionOption::ExplicitBegin)
3989            .with_begin_retry_policy(NeverRetry)
3990            .build()
3991            .await;
3992
3993        assert!(res.is_err(), "should fail immediately without retry");
3994        let err = res.unwrap_err();
3995        assert_eq!(err.status().expect("status").code, GaxCode::Unavailable);
3996
3997        Ok(())
3998    }
3999
4000    #[tokio_test_no_panics]
4001    async fn read_only_transaction_begin_with_attempt_timeout() -> anyhow::Result<()> {
4002        let mut mock = MockSpanner::new();
4003        let mut sequence = mockall::Sequence::new();
4004
4005        mock.expect_begin_transaction()
4006            .once()
4007            .in_sequence(&mut sequence)
4008            .withf(|req| {
4009                let timeout_header = req.metadata().get("grpc-timeout");
4010                assert!(
4011                    timeout_header.is_some(),
4012                    "grpc-timeout header should be present"
4013                );
4014                let val = timeout_header.unwrap().to_str().unwrap();
4015                assert!(
4016                    val.contains("5000") || val.contains("5"),
4017                    "timeout header value '{}' should represent 5 seconds",
4018                    val
4019                );
4020                true
4021            })
4022            .returning(|_| {
4023                Ok(Response::new(mock_v1::Transaction {
4024                    id: vec![42],
4025                    ..Default::default()
4026                }))
4027            });
4028
4029        mock.expect_create_session().returning(|_| {
4030            Ok(Response::new(mock_v1::Session {
4031                name: "session".to_string(),
4032                multiplexed: true,
4033                ..Default::default()
4034            }))
4035        });
4036
4037        let (db_client, _server) = setup_db_client(mock).await;
4038
4039        let _transaction = db_client
4040            .read_only_transaction()
4041            .set_begin_transaction_option(BeginTransactionOption::ExplicitBegin)
4042            .with_begin_attempt_timeout(std::time::Duration::from_secs(5))
4043            .build()
4044            .await?;
4045
4046        Ok(())
4047    }
4048
4049    #[tokio_test_no_panics]
4050    async fn read_only_transaction_builder_sets_gax_options() -> anyhow::Result<()> {
4051        let mut mock = MockSpanner::new();
4052        mock.expect_create_session().returning(|_| {
4053            Ok(Response::new(mock_v1::Session {
4054                name: "session".to_string(),
4055                multiplexed: true,
4056                ..Default::default()
4057            }))
4058        });
4059        let (db_client, _server) = setup_db_client(mock).await;
4060
4061        let builder = db_client
4062            .read_only_transaction()
4063            .with_begin_attempt_timeout(Duration::from_secs(5))
4064            .with_begin_retry_policy(NeverRetry)
4065            .with_begin_backoff_policy(ExponentialBackoff::default());
4066
4067        let gax = builder
4068            .begin_gax_options
4069            .as_ref()
4070            .expect("begin_gax_options missing");
4071        assert_eq!(*gax.attempt_timeout(), Some(Duration::from_secs(5)));
4072        assert!(gax.retry_policy().is_some());
4073        assert!(gax.backoff_policy().is_some());
4074
4075        Ok(())
4076    }
4077
4078    #[test]
4079    fn test_merge_request_options() {
4080        // Case 1: Destination has values, source is empty (Destination preserved)
4081        let mut dest = crate::RequestOptions::default();
4082        dest.set_attempt_timeout(Duration::from_secs(2));
4083        dest.set_retry_policy(NeverRetry);
4084
4085        // Source is None (Destination preserved)
4086        let merged = merge_request_options(dest, None);
4087
4088        assert_eq!(*merged.attempt_timeout(), Some(Duration::from_secs(2)));
4089        assert!(merged.retry_policy().is_some());
4090
4091        // Case 2: Source has overriding values, destination is empty (Source overrides)
4092        let dest = crate::RequestOptions::default();
4093
4094        let mut source = crate::RequestOptions::default();
4095        source.set_attempt_timeout(Duration::from_secs(5));
4096        source.set_retry_policy(NeverRetry);
4097
4098        let merged = merge_request_options(dest, Some(&source));
4099
4100        assert_eq!(*merged.attempt_timeout(), Some(Duration::from_secs(5)));
4101        assert!(merged.retry_policy().is_some());
4102
4103        // Case 3: Both have distinct custom headers (Headers must merge/combine)
4104        let mut dest = crate::RequestOptions::default();
4105        let mut dest_headers = HeaderMap::new();
4106        dest_headers.insert(
4107            HeaderName::from_static("x-goog-spanner-route-to-leader"),
4108            HeaderValue::from_static("true"),
4109        );
4110        dest = dest.insert_extension(dest_headers);
4111
4112        let mut source = crate::RequestOptions::default();
4113        let mut src_headers = HeaderMap::new();
4114        src_headers.insert(
4115            HeaderName::from_static("x-custom-header"),
4116            HeaderValue::from_static("custom-value"),
4117        );
4118        source = source.insert_extension(src_headers);
4119
4120        let merged = merge_request_options(dest, Some(&source));
4121        let merged_headers = merged
4122            .get_extension::<HeaderMap>()
4123            .expect("HeaderMap missing");
4124
4125        assert_eq!(
4126            merged_headers
4127                .get("x-goog-spanner-route-to-leader")
4128                .expect("route to leader header should be present")
4129                .to_str()
4130                .expect("header value should be valid string"),
4131            "true"
4132        );
4133        assert_eq!(
4134            merged_headers
4135                .get("x-custom-header")
4136                .expect("custom header should be present")
4137                .to_str()
4138                .expect("header value should be valid string"),
4139            "custom-value"
4140        );
4141        assert_eq!(
4142            merged_headers
4143                .get_all("x-goog-spanner-route-to-leader")
4144                .iter()
4145                .count(),
4146            1,
4147            "route to leader header should only appear once"
4148        );
4149        assert_eq!(
4150            merged_headers.get_all("x-custom-header").iter().count(),
4151            1,
4152            "custom header should only appear once"
4153        );
4154
4155        // Case 4: Overwriting existing header replaces value without duplicating key
4156        let mut dest = crate::RequestOptions::default();
4157        let mut dest_headers = HeaderMap::new();
4158        dest_headers.insert(
4159            HeaderName::from_static("x-custom-header"),
4160            HeaderValue::from_static("original-value"),
4161        );
4162        dest = dest.insert_extension(dest_headers);
4163
4164        let mut source = crate::RequestOptions::default();
4165        let mut src_headers = HeaderMap::new();
4166        src_headers.insert(
4167            HeaderName::from_static("x-custom-header"),
4168            HeaderValue::from_static("overridden-value"),
4169        );
4170        source = source.insert_extension(src_headers);
4171
4172        let merged = merge_request_options(dest, Some(&source));
4173        let merged_headers = merged
4174            .get_extension::<HeaderMap>()
4175            .expect("HeaderMap missing");
4176
4177        assert_eq!(
4178            merged_headers.get_all("x-custom-header").iter().count(),
4179            1,
4180            "Overwritten header must only be present once"
4181        );
4182        assert_eq!(
4183            merged_headers
4184                .get("x-custom-header")
4185                .expect("custom header present")
4186                .to_str()
4187                .expect("valid ascii"),
4188            "overridden-value"
4189        );
4190
4191        // Case 5: Source options is completely untouched (isolation)
4192        let source_headers = source
4193            .get_extension::<HeaderMap>()
4194            .expect("source HeaderMap present");
4195        assert_eq!(
4196            source_headers
4197                .get("x-custom-header")
4198                .expect("source custom header present")
4199                .to_str()
4200                .expect("valid ascii"),
4201            "overridden-value"
4202        );
4203        assert_eq!(
4204            source_headers.len(),
4205            1,
4206            "source HeaderMap must remain isolated and unmodified"
4207        );
4208
4209        // Case 6: Pure merge_request_options preserves all headers intact, including request ID header
4210        let mut destination = RequestOptions::default();
4211        let mut destination_headers = HeaderMap::new();
4212        destination_headers.insert(
4213            REQUEST_ID_HEADER.clone(),
4214            HeaderValue::from_static("12345.1"),
4215        );
4216        destination_headers.insert(
4217            HeaderName::from_static("x-goog-spanner-route-to-leader"),
4218            HeaderValue::from_static("true"),
4219        );
4220        destination = destination.insert_extension(destination_headers);
4221
4222        let merged = merge_request_options(destination, None);
4223        let merged_headers = merged
4224            .get_extension::<HeaderMap>()
4225            .expect("merged HeaderMap should be present");
4226        assert_eq!(
4227            merged_headers
4228                .get(&REQUEST_ID_HEADER)
4229                .expect("REQUEST_ID_HEADER should be preserved by pure merge_request_options")
4230                .to_str()
4231                .expect("valid ascii"),
4232            "12345.1"
4233        );
4234        assert_eq!(
4235            merged_headers
4236                .get("x-goog-spanner-route-to-leader")
4237                .expect("route to leader header should be preserved")
4238                .to_str()
4239                .expect("valid ascii"),
4240            "true"
4241        );
4242    }
4243
4244    #[test]
4245    fn merge_request_options_copies_source_headers_when_destination_has_no_headers() {
4246        let destination = RequestOptions::default();
4247        let mut source = RequestOptions::default();
4248        let mut source_headers = HeaderMap::new();
4249        source_headers.insert(
4250            HeaderName::from_static("x-custom-header"),
4251            HeaderValue::from_static("custom-value"),
4252        );
4253        source = source.insert_extension(source_headers);
4254
4255        let merged = merge_request_options(destination, Some(&source));
4256        let merged_headers = merged
4257            .get_extension::<HeaderMap>()
4258            .expect("merged HeaderMap should be present");
4259        assert_eq!(
4260            merged_headers.get("x-custom-header"),
4261            Some(&HeaderValue::from_static("custom-value")),
4262            "custom header must be copied to empty destination options"
4263        );
4264    }
4265
4266    #[test]
4267    fn merge_request_options_destination_empty_map_clones_bulk() {
4268        let mut destination = RequestOptions::default();
4269        destination = destination.insert_extension(HeaderMap::new());
4270
4271        let mut source = RequestOptions::default();
4272        let mut source_headers = HeaderMap::new();
4273        source_headers.insert(
4274            HeaderName::from_static("x-custom-header"),
4275            HeaderValue::from_static("custom-value"),
4276        );
4277        source = source.insert_extension(source_headers);
4278
4279        let merged = merge_request_options(destination, Some(&source));
4280        let merged_headers = merged
4281            .get_extension::<HeaderMap>()
4282            .expect("merged HeaderMap should be present");
4283        assert_eq!(
4284            merged_headers.get("x-custom-header"),
4285            Some(&HeaderValue::from_static("custom-value")),
4286            "source headers should be cloned into empty destination map"
4287        );
4288    }
4289
4290    #[test]
4291    fn merge_request_options_empty_source_headers_does_not_insert_extension() {
4292        let destination = RequestOptions::default();
4293        let mut source = RequestOptions::default();
4294        let empty_headers = HeaderMap::new();
4295        source = source.insert_extension(empty_headers);
4296
4297        let merged = merge_request_options(destination, Some(&source));
4298        assert!(
4299            merged.get_extension::<HeaderMap>().is_none(),
4300            "empty source headers must not insert a redundant HeaderMap extension"
4301        );
4302    }
4303
4304    #[test]
4305    fn merge_request_options_multi_valued_headers_preserved_consistently() {
4306        let multi_header = HeaderName::from_static("x-multi-value");
4307        let first_value = HeaderValue::from_static("first-value");
4308        let second_value = HeaderValue::from_static("second-value");
4309
4310        let mut source_headers = HeaderMap::new();
4311        source_headers.append(multi_header.clone(), first_value.clone());
4312        source_headers.append(multi_header.clone(), second_value.clone());
4313        let source = RequestOptions::default().insert_extension(source_headers);
4314
4315        // Case A: Destination has no initial headers.
4316        let destination_empty = RequestOptions::default();
4317        let merged_a = merge_request_options(destination_empty, Some(&source));
4318        let headers_a = merged_a
4319            .get_extension::<HeaderMap>()
4320            .expect("headers should be present");
4321        let values_a: Vec<_> = headers_a.get_all(&multi_header).iter().collect();
4322        assert_eq!(
4323            values_a,
4324            vec![&first_value, &second_value],
4325            "multi-valued headers must be preserved when destination was empty"
4326        );
4327
4328        // Case B: Destination already has existing headers and an older value for the same key.
4329        let mut destination_headers = HeaderMap::new();
4330        destination_headers.insert(
4331            HeaderName::from_static("x-existing-header"),
4332            HeaderValue::from_static("existing-value"),
4333        );
4334        destination_headers.insert(
4335            multi_header.clone(),
4336            HeaderValue::from_static("old-stale-value"),
4337        );
4338        let destination_with_headers =
4339            RequestOptions::default().insert_extension(destination_headers);
4340
4341        let merged_b = merge_request_options(destination_with_headers, Some(&source));
4342        let headers_b = merged_b
4343            .get_extension::<HeaderMap>()
4344            .expect("headers should be present");
4345        let values_b: Vec<_> = headers_b.get_all(&multi_header).iter().collect();
4346        assert_eq!(
4347            values_b,
4348            vec![&first_value, &second_value],
4349            "multi-valued headers must replace existing key values and preserve all items"
4350        );
4351        assert_eq!(
4352            headers_b.get("x-existing-header"),
4353            Some(&HeaderValue::from_static("existing-value")),
4354            "existing headers on destination must be preserved"
4355        );
4356    }
4357
4358    #[test]
4359    fn merge_request_options_multi_valued_destination_replaced_by_single_valued_source() {
4360        let multi_header = HeaderName::from_static("x-replaced-header");
4361        let mut destination_headers = HeaderMap::new();
4362        destination_headers.append(
4363            multi_header.clone(),
4364            HeaderValue::from_static("initial-val-1"),
4365        );
4366        destination_headers.append(
4367            multi_header.clone(),
4368            HeaderValue::from_static("initial-val-2"),
4369        );
4370        let destination = RequestOptions::default().insert_extension(destination_headers);
4371
4372        let mut source_headers = HeaderMap::new();
4373        source_headers.insert(
4374            multi_header.clone(),
4375            HeaderValue::from_static("replacement-val"),
4376        );
4377        let source = RequestOptions::default().insert_extension(source_headers);
4378
4379        let merged = merge_request_options(destination, Some(&source));
4380        let merged_headers = merged
4381            .get_extension::<HeaderMap>()
4382            .expect("merged HeaderMap should be present");
4383        let values: Vec<_> = merged_headers.get_all(&multi_header).iter().collect();
4384        assert_eq!(
4385            values,
4386            vec![&HeaderValue::from_static("replacement-val")],
4387            "all prior multi-values on destination must be replaced by single source value"
4388        );
4389    }
4390
4391    #[test]
4392    fn transaction_selector_failed_state_propagates_error() {
4393        let options = TransactionOptions {
4394            mode: Some(Mode::ReadWrite(Default::default())),
4395            ..Default::default()
4396        };
4397        let selector = ReadContextTransactionSelector::Lazy(Arc::new(StdMutex::new(
4398            TransactionState::Starting(options, Arc::new(Notify::new())),
4399        )));
4400
4401        let initial_err = crate::error::internal_error("initial statement error");
4402        selector.set_failed(&initial_err, false);
4403
4404        assert!(
4405            selector.is_first_statement_failed(),
4406            "selector must be in FirstStatementFailed state"
4407        );
4408
4409        let res = selector.prepare_for_commit();
4410        assert!(
4411            res.is_err(),
4412            "selector.prepare_for_commit must return an error"
4413        );
4414        let err = res.expect_err("res must be err");
4415        assert!(
4416            err.to_string()
4417                .contains("Aborted due to failed initial statement"),
4418            "error message must contain expected text"
4419        );
4420    }
4421
4422    #[tokio_test_no_panics]
4423    async fn test_subsequent_query_failure_does_not_lock_mutex() -> anyhow::Result<()> {
4424        let mut mock = create_session_mock();
4425
4426        // The query fails with a transient error
4427        mock.expect_execute_streaming_sql()
4428            .once()
4429            .returning(|_| Err(tonic::Status::new(tonic::Code::Internal, "query failed")));
4430
4431        let (db_client, _server) = setup_db_client(mock).await;
4432
4433        // Construct a lazy read-only transaction context
4434        let mut transaction_selector = crate::model::TransactionSelector::default();
4435        transaction_selector.selector = Some(crate::model::transaction_selector::Selector::Id(
4436            bytes::Bytes::copy_from_slice(&[1, 2, 3]),
4437        ));
4438
4439        let state = Arc::new(StdMutex::new(TransactionState::Started(
4440            transaction_selector.clone(),
4441            None,
4442        )));
4443        let selector = ReadContextTransactionSelector::Lazy(state.clone());
4444
4445        let context = ReadContext {
4446            session_name: "projects/p/instances/i/databases/d/sessions/123".to_string(),
4447            client: db_client,
4448            transaction_selector: selector,
4449            precommit_token_tracker: crate::read_only_transaction::PrecommitTokenTracker::new(),
4450            transaction_tag: None,
4451            begin_transaction_request_options: None,
4452            affinity: None,
4453            aborted_state: AbortedState::new_noop(),
4454        };
4455
4456        // Poison the mutex
4457        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4458            let _guard = state.lock().expect("mutex should lock");
4459            panic!("poisoning the mutex intentionally");
4460        }));
4461
4462        // Execute a subsequent query (request uses Selector::Id, meaning it's a subsequent query)
4463        let statement = Statement::builder("SELECT 1").build();
4464        let request = statement
4465            .into_request()
4466            .set_session(context.session_name.clone())
4467            .set_transaction(transaction_selector);
4468
4469        let gax_options = RequestOptions::default();
4470
4471        async fn run_macro(
4472            context: &ReadContext,
4473            request: ExecuteSqlRequest,
4474            gax_options: RequestOptions,
4475        ) -> crate::Result<ResultSet> {
4476            execute_stream_with_retry!(
4477                context,
4478                request,
4479                gax_options,
4480                StreamOperation::Query,
4481                "ExecuteStreamingSql"
4482            )
4483        }
4484
4485        let res = run_macro(&context, request, gax_options).await;
4486
4487        // Assert that we get the query failed error rather than a panic from the poisoned mutex
4488        assert!(
4489            res.is_err(),
4490            "expected query to fail rather than panic on poisoned mutex"
4491        );
4492        let err = res.expect_err("expected query to fail");
4493        assert_eq!(err.status().map(|s| s.code), Some(GaxCode::Internal));
4494        assert_eq!(
4495            err.status().map(|s| s.message.as_str()),
4496            Some("query failed")
4497        );
4498
4499        Ok(())
4500    }
4501
4502    #[tokio_test_no_panics]
4503    async fn concurrent_queries_shared_statement_with_custom_headers_isolation()
4504    -> anyhow::Result<()> {
4505        let mut mock = create_session_mock();
4506
4507        mock.expect_execute_streaming_sql()
4508            .times(10)
4509            .returning(|req| {
4510                let metadata = req.metadata();
4511                // 1. Verify custom header is present, has the expected value, and is present only ONCE
4512                let custom_val = metadata
4513                    .get("x-custom-header")
4514                    .expect("x-custom-header must be present");
4515                assert_eq!(
4516                    custom_val.to_str().expect("valid ascii"),
4517                    "custom-shared-value"
4518                );
4519                assert_eq!(
4520                    metadata.get_all("x-custom-header").iter().count(),
4521                    1,
4522                    "x-custom-header must only be present once"
4523                );
4524
4525                // 2. Verify request ID header is present and is present only ONCE
4526                assert!(
4527                    metadata.get("x-goog-spanner-request-id").is_some(),
4528                    "request ID must be present"
4529                );
4530                assert_eq!(
4531                    metadata.get_all("x-goog-spanner-request-id").iter().count(),
4532                    1,
4533                    "request ID header must only be present once"
4534                );
4535
4536                Ok(gaxi::grpc::tonic::Response::from(adapt([Ok(
4537                    setup_select1(),
4538                )])))
4539            });
4540
4541        let (db_client, _server) = setup_db_client(mock).await;
4542
4543        let mut custom_headers = HeaderMap::new();
4544        custom_headers.insert(
4545            HeaderName::from_static("x-custom-header"),
4546            HeaderValue::from_static("custom-shared-value"),
4547        );
4548
4549        let shared_stmt = Statement::builder("SELECT 1")
4550            .build()
4551            .with_gax_options(crate::RequestOptions::default().insert_extension(custom_headers));
4552
4553        let mut handles = Vec::new();
4554        for _ in 0..10 {
4555            let client = db_client.clone();
4556            let stmt = shared_stmt.clone();
4557            handles.push(tokio::spawn(async move {
4558                let mut rs = client
4559                    .single_use()
4560                    .build()
4561                    .execute_query(stmt)
4562                    .await
4563                    .expect("Failed to execute query");
4564                let row = rs.next().await.expect("has row").expect("has valid row");
4565                assert_eq!(row.raw_values(), [Value(string_val("1"))]);
4566            }));
4567        }
4568
4569        for handle in handles {
4570            handle.await.expect("task panicked");
4571        }
4572
4573        // Verify the original shared statement's gax_options remained intact and isolated
4574        let stmt_headers = shared_stmt
4575            .gax_options()
4576            .get_extension::<HeaderMap>()
4577            .expect("shared statement HeaderMap intact");
4578        assert_eq!(
4579            stmt_headers
4580                .get("x-custom-header")
4581                .expect("custom header present")
4582                .to_str()
4583                .expect("valid ascii"),
4584            "custom-shared-value"
4585        );
4586        assert_eq!(
4587            stmt_headers.get_all("x-custom-header").iter().count(),
4588            1,
4589            "Shared statement custom header must only be present once"
4590        );
4591        assert!(
4592            stmt_headers.get("x-goog-spanner-request-id").is_none(),
4593            "Shared statement must NOT have been contaminated with request ID"
4594        );
4595
4596        Ok(())
4597    }
4598
4599    #[tokio_test_no_panics]
4600    async fn multi_use_read_only_transaction_affinity_preserved() -> crate::Result<()> {
4601        use crate::statement::Statement;
4602        use gaxi::grpc::tonic::Response;
4603
4604        let mut mock = create_session_mock();
4605        mock.expect_execute_streaming_sql().once().returning(|_| {
4606            Ok(Response::from(adapt([Ok(
4607                setup_select1_with_transaction_id(vec![1, 2, 3]),
4608            )])))
4609        });
4610        let (db_client, _server) = setup_db_client(mock).await;
4611
4612        let affinity = Arc::new(TransactionAffinity::new_read_only());
4613        let builder = db_client
4614            .read_only_transaction()
4615            .with_affinity(Arc::clone(&affinity));
4616
4617        let transaction = builder.build().await?;
4618        assert!(
4619            transaction
4620                .affinity()
4621                .expect("affinity present")
4622                .is_read_only(),
4623            "MultiUseReadOnlyTransaction affinity must be ReadOnly"
4624        );
4625        assert_eq!(
4626            transaction
4627                .affinity()
4628                .expect("affinity present")
4629                .pinned_entry_id(),
4630            None,
4631            "Initial pinned entry ID should be None"
4632        );
4633
4634        transaction
4635            .affinity()
4636            .expect("affinity present")
4637            .compare_and_set_entry_id(0, 1)
4638            .expect("pin entry");
4639        assert_eq!(
4640            affinity.pinned_entry_id(),
4641            Some(1),
4642            "Affinity handle passed to builder must observe the pinned channel ID"
4643        );
4644
4645        let result_set = transaction
4646            .execute_query(Statement::builder("SELECT 1").build())
4647            .await?;
4648        assert_eq!(
4649            result_set.affinity().pinned_entry_id(),
4650            Some(1),
4651            "ResultSet generated from MultiUse transaction must share the same pinned affinity"
4652        );
4653
4654        Ok(())
4655    }
4656
4657    #[tokio_test_no_panics]
4658    async fn multi_use_read_only_transaction_default_affinity_created() -> crate::Result<()> {
4659        let mock = create_session_mock();
4660        let (db_client, _server) = setup_db_client(mock).await;
4661
4662        let builder = db_client.read_only_transaction();
4663        let transaction = builder.build().await?;
4664        assert!(
4665            transaction
4666                .affinity()
4667                .expect("affinity present")
4668                .is_read_only(),
4669            "Default MultiUseReadOnlyTransaction affinity must be ReadOnly"
4670        );
4671        assert_eq!(
4672            transaction
4673                .affinity()
4674                .expect("affinity present")
4675                .pinned_entry_id(),
4676            None,
4677            "Default affinity should start unpinned"
4678        );
4679
4680        Ok(())
4681    }
4682
4683    #[tokio_test_no_panics]
4684    async fn single_use_read_only_transaction_affinity_present() -> crate::Result<()> {
4685        use crate::statement::Statement;
4686        use gaxi::grpc::tonic::Response;
4687
4688        let mut mock = create_session_mock();
4689        mock.expect_execute_streaming_sql()
4690            .once()
4691            .returning(|_| Ok(Response::from(adapt([Ok(setup_select1())]))));
4692
4693        let (db_client, _server) = setup_db_client(mock).await;
4694
4695        let transaction = db_client.single_use().build();
4696        let result_set = transaction
4697            .execute_query(Statement::builder("SELECT 1").build())
4698            .await?;
4699
4700        let affinity = result_set.affinity();
4701        assert!(
4702            affinity.is_read_only(),
4703            "SingleUse query ResultSet affinity must be ReadOnly"
4704        );
4705        assert_eq!(
4706            affinity.pinned_entry_id(),
4707            None,
4708            "Initial pinned entry ID should be None"
4709        );
4710
4711        affinity
4712            .compare_and_set_entry_id(0, 505)
4713            .expect("pin entry");
4714        assert_eq!(
4715            result_set.affinity().pinned_entry_id(),
4716            Some(505),
4717            "Pinned channel ID must be retained on the ResultSet for stream resumption"
4718        );
4719
4720        Ok(())
4721    }
4722
4723    #[tokio_test_no_panics]
4724    async fn multi_use_read_only_transaction_does_not_record_location_router_affinity() -> Result<()>
4725    {
4726        use crate::client::Spanner;
4727        use crate::client::SpannerBuilderExt;
4728        use crate::omni::InstanceType;
4729        use google_cloud_auth::credentials::anonymous::Builder as Anonymous;
4730        use spanner_grpc_mock::start;
4731        use tokio::sync::mpsc::channel as mpsc_channel;
4732
4733        let mut mock = create_session_mock();
4734        let transaction_id = vec![1, 2, 3];
4735        let transaction_id_clone = transaction_id.clone();
4736
4737        mock.expect_fetch_cache_update().returning(|_| {
4738            let (_sender, receiver) = mpsc_channel(1);
4739            Ok(tonic::Response::from(receiver))
4740        });
4741
4742        mock.expect_execute_streaming_sql()
4743            .times(2)
4744            .returning(move |request| {
4745                let request = request.into_inner();
4746                let result_set = if request
4747                    .transaction
4748                    .as_ref()
4749                    .and_then(|transaction| transaction.selector.as_ref())
4750                    .is_some_and(|selector| matches!(selector, Selector::Begin(_)))
4751                {
4752                    setup_select1_with_transaction_id(transaction_id_clone.clone())
4753                } else {
4754                    setup_select1()
4755                };
4756                let (sender, receiver) = mpsc_channel(1);
4757                sender
4758                    .try_send(Ok(result_set))
4759                    .expect("send should succeed");
4760                Ok(Response::from(receiver))
4761            });
4762
4763        let (address, _server) = start("127.0.0.1:0", mock)
4764            .await
4765            .expect("Failed to start mock server");
4766
4767        let spanner = Spanner::builder()
4768            .with_endpoint(address)
4769            .with_instance_type(InstanceType::Omni)
4770            .with_credentials(Anonymous::new().build())
4771            .build()
4772            .await
4773            .expect("Failed to build client");
4774
4775        let database_client = spanner
4776            .database_client(
4777                "projects/test-project/instances/test-instance/databases/test-database",
4778            )
4779            .with_location_aware_routing(true)
4780            .build()
4781            .await
4782            .expect("Failed to create DatabaseClient");
4783
4784        let router = database_client
4785            .location_router()
4786            .expect("location router must be present for Omni");
4787
4788        let transaction = database_client
4789            .read_only_transaction()
4790            .set_begin_transaction_option(BeginTransactionOption::InlineBegin)
4791            .build()
4792            .await
4793            .expect("Failed to build read only transaction");
4794
4795        // Execute first query (inline begin)
4796        let mut result_set = transaction
4797            .execute_query(Statement::builder("SELECT 1").build())
4798            .await
4799            .expect("first query should succeed");
4800        let _ = result_set.next().await;
4801
4802        // Execute second query (dispatched with Selector::Id)
4803        let mut second_result_set = transaction
4804            .execute_query(Statement::builder("SELECT 2").build())
4805            .await
4806            .expect("second query should succeed");
4807        let _ = second_result_set.next().await;
4808
4809        assert_eq!(
4810            router.affinity_count(),
4811            0,
4812            "MultiUseReadOnlyTransaction must not record affinity in LocationRouter"
4813        );
4814        assert_eq!(
4815            router.get_transaction_affinity(&transaction_id),
4816            None,
4817            "Transaction ID must not have recorded affinity in LocationRouter"
4818        );
4819
4820        Ok(())
4821    }
4822
4823    #[tokio_test_no_panics]
4824    async fn inlined_begin_query_metadata_missing_transaction_fails_subsequent_statement_receives_error()
4825    -> anyhow::Result<()> {
4826        use crate::statement::Statement;
4827        use gaxi::grpc::tonic::Response;
4828
4829        let mut mock = create_session_mock();
4830        let mut sequence = Sequence::new();
4831
4832        // 1. Initial query stream returns metadata without transaction entity.
4833        mock.expect_execute_streaming_sql()
4834            .times(1)
4835            .in_sequence(&mut sequence)
4836            .returning(|_| {
4837                Ok(Response::from(adapt([Ok(setup_select1())]))) // setup_select1 has metadata but no transaction ID
4838            });
4839
4840        let (database_client, _server) = setup_db_client(mock).await;
4841        let transaction = database_client
4842            .read_only_transaction()
4843            .set_begin_transaction_option(BeginTransactionOption::InlineBegin)
4844            .build()
4845            .await?;
4846
4847        // First statement fails because metadata is missing transaction ID.
4848        let first_result = transaction
4849            .execute_query(Statement::builder("SELECT 1").build())
4850            .await;
4851        assert!(
4852            first_result.is_err(),
4853            "Expected first query to fail with missing transaction ID error"
4854        );
4855        let first_error = first_result.expect_err("first query failed").to_string();
4856        assert!(
4857            first_error.contains("failed to return a transaction ID"),
4858            "Expected missing transaction ID error: {first_error}"
4859        );
4860
4861        // Subsequent statement on the same read-only transaction must fail with the start failure,
4862        // and must NOT return Aborted (read-only transactions are never aborted).
4863        let second_result = transaction
4864            .execute_query(Statement::builder("SELECT 2").build())
4865            .await;
4866        assert!(
4867            second_result.is_err(),
4868            "Expected subsequent query on failed read-only transaction to fail"
4869        );
4870        let second_error = second_result.expect_err("second query failed").to_string();
4871        assert_eq!(
4872            second_error,
4873            "cannot deserialize the response unexpected data received from Spanner: Transaction cannot be used: initial statement failed with: Spanner failed to return a transaction ID for a query that included a BeginTransaction option",
4874            "Expected exact cleanly wrapped error message on subsequent query without duplicate prefixes"
4875        );
4876        assert!(
4877            !second_error.contains("Aborted"),
4878            "Read-only transactions should never return Aborted error: {second_error}"
4879        );
4880
4881        Ok(())
4882    }
4883
4884    #[tokio_test_no_panics]
4885    async fn inlined_begin_query_stream_empty_fails_fast() -> anyhow::Result<()> {
4886        let mut mock = create_session_mock();
4887
4888        // 1. Initial query stream returns an empty stream (no metadata, no chunks).
4889        mock.expect_execute_streaming_sql()
4890            .times(1)
4891            .returning(|request| {
4892                let request = request.into_inner();
4893                let transaction = request
4894                    .transaction
4895                    .as_ref()
4896                    .expect("transaction options required for inline begin");
4897                let selector = transaction.selector.as_ref().expect("selector required");
4898                assert!(
4899                    matches!(selector, Selector::Begin(_)),
4900                    "Expected Selector::Begin on initial query"
4901                );
4902                Ok(Response::from(adapt([])))
4903            });
4904
4905        // 2. BeginTransaction must NEVER be called as a fallback.
4906        mock.expect_begin_transaction().never();
4907
4908        let (database_client, _server) = setup_db_client(mock).await;
4909        let transaction = database_client
4910            .read_only_transaction()
4911            .set_begin_transaction_option(BeginTransactionOption::InlineBegin)
4912            .build()
4913            .await?;
4914
4915        // First query fails fast because the stream ended without metadata.
4916        let first_result = transaction
4917            .execute_query(Statement::builder("SELECT 1").build())
4918            .await;
4919        assert!(
4920            first_result.is_err(),
4921            "Initial query must fail when stream ends without metadata"
4922        );
4923
4924        // Subsequent query on the same transaction fails fast without any RPCs.
4925        let second_result = transaction
4926            .execute_query(Statement::builder("SELECT 2").build())
4927            .await;
4928        assert!(
4929            second_result.is_err(),
4930            "Subsequent query must fail fast on a failed read-only transaction"
4931        );
4932        let second_error = second_result.expect_err("second query failed");
4933        assert!(
4934            second_error.to_string().contains(
4935                "Transaction cannot be used: initial statement failed with: Query stream ended without metadata or error"
4936            ),
4937            "Expected formatted failure message, got: {second_error}"
4938        );
4939
4940        Ok(())
4941    }
4942
4943    #[test]
4944    fn selector_for_restart_state_machine_arms() {
4945        let options = TransactionOptions::default();
4946        let notify = Arc::new(Notify::new());
4947
4948        // 1. NotStarted returns Internal error
4949        let selector = ReadContextTransactionSelector::Lazy(Arc::new(StdMutex::new(
4950            TransactionState::NotStarted(options.clone()),
4951        )));
4952        let result = selector.selector_for_restart();
4953        assert!(result.is_err(), "NotStarted must return error");
4954        let error = result.expect_err("NotStarted returns error");
4955        assert!(
4956            error
4957                .to_string()
4958                .contains("Cannot restart stream on a NotStarted transaction"),
4959            "Expected cannot restart message, got: {error}"
4960        );
4961
4962        // 2. Starting returns Begin selector
4963        let selector = ReadContextTransactionSelector::Lazy(Arc::new(StdMutex::new(
4964            TransactionState::Starting(options.clone(), notify),
4965        )));
4966        let result = selector.selector_for_restart();
4967        assert!(result.is_ok(), "Starting must return Begin selector");
4968        assert!(
4969            matches!(
4970                result.expect("selector is ok").selector,
4971                Some(ModelSelector::Begin(_))
4972            ),
4973            "Expected Begin selector"
4974        );
4975
4976        // 3. Started returns Id selector
4977        let started_selector = TransactionSelector::default().set_id(vec![1, 2, 3]);
4978        let selector = ReadContextTransactionSelector::Lazy(Arc::new(StdMutex::new(
4979            TransactionState::Started(started_selector.clone(), None),
4980        )));
4981        let result = selector.selector_for_restart();
4982        assert!(result.is_ok(), "Started must return Id selector");
4983        assert_eq!(
4984            result.expect("selector is ok"),
4985            started_selector,
4986            "Expected Id selector"
4987        );
4988
4989        // 4. Failed returns failure.to_error() (preserving service error or wrapping internal error)
4990        let status = GaxStatus::default()
4991            .set_code(GaxCode::InvalidArgument)
4992            .set_message("Original failure");
4993        let selector = ReadContextTransactionSelector::Lazy(Arc::new(StdMutex::new(
4994            TransactionState::Failed(TransactionStartFailure::Service(status)),
4995        )));
4996        let result = selector.selector_for_restart();
4997        assert!(result.is_err(), "Failed must return error");
4998        let error = result.expect_err("Failed returns error");
4999        assert_eq!(
5000            error.status().map(|status| status.code),
5001            Some(GaxCode::InvalidArgument),
5002            "Expected InvalidArgument status code"
5003        );
5004        assert_eq!(
5005            error.status().map(|status| status.message.as_str()),
5006            Some("Transaction cannot be used: initial statement failed with: Original failure"),
5007            "Expected formatted error message preserving service error"
5008        );
5009
5010        let selector = ReadContextTransactionSelector::Lazy(Arc::new(StdMutex::new(
5011            TransactionState::Failed(TransactionStartFailure::Internal(
5012                "Missing transaction ID".to_string(),
5013            )),
5014        )));
5015        let result = selector.selector_for_restart();
5016        assert!(result.is_err(), "Failed must return error");
5017        let error = result.expect_err("Failed returns error");
5018        assert!(
5019            error
5020                .to_string()
5021                .contains("Transaction cannot be used: initial statement failed with:")
5022                && error.to_string().contains("Missing transaction ID"),
5023            "Expected start failure message, got: {error}"
5024        );
5025
5026        // 5. FirstStatementFailed returns synthetic Aborted
5027        let selector = ReadContextTransactionSelector::Lazy(Arc::new(StdMutex::new(
5028            TransactionState::FirstStatementFailed,
5029        )));
5030        let result = selector.selector_for_restart();
5031        assert!(result.is_err(), "FirstStatementFailed must return error");
5032        let error = result.expect_err("FirstStatementFailed returns error");
5033        assert!(
5034            error
5035                .to_string()
5036                .contains("Aborted due to failed initial statement"),
5037            "Expected aborted error, got: {error}"
5038        );
5039
5040        // 6. Fixed returns the fixed selector
5041        let fixed_selector = TransactionSelector::default().set_id(vec![4, 5, 6]);
5042        let selector = ReadContextTransactionSelector::Fixed(fixed_selector.clone(), None);
5043        let result = selector.selector_for_restart();
5044        assert!(result.is_ok(), "Fixed must return fixed selector");
5045        assert_eq!(
5046            result.expect("selector is ok"),
5047            fixed_selector,
5048            "Expected fixed selector"
5049        );
5050    }
5051
5052    #[test]
5053    fn transaction_start_failure_preserves_error_details() {
5054        use google_cloud_rpc::model::RetryInfo;
5055        use wkt::Duration;
5056
5057        let retry_info = RetryInfo::default().set_retry_delay(Duration::clamp(5, 0));
5058        let status = GaxStatus::default()
5059            .set_code(GaxCode::ResourceExhausted)
5060            .set_message("Quota exceeded")
5061            .set_details(vec![StatusDetails::RetryInfo(retry_info)]);
5062
5063        let failure = TransactionStartFailure::Service(status);
5064        let error = failure.to_error();
5065
5066        let error_status = error.status().expect("status should be preserved");
5067        assert_eq!(
5068            error_status.code,
5069            GaxCode::ResourceExhausted,
5070            "status code must match"
5071        );
5072        assert_eq!(
5073            error_status.message,
5074            "Transaction cannot be used: initial statement failed with: Quota exceeded",
5075            "status message must match"
5076        );
5077        assert_eq!(
5078            error_status.details.len(),
5079            1,
5080            "status details must be preserved"
5081        );
5082        match &error_status.details[0] {
5083            StatusDetails::RetryInfo(info) => {
5084                assert_eq!(
5085                    info.retry_delay,
5086                    Some(Duration::clamp(5, 0)),
5087                    "retry_delay in details must match"
5088                );
5089            }
5090            other => panic!("Expected RetryInfo details, got: {other:?}"),
5091        }
5092    }
5093
5094    #[test]
5095    fn on_cancelled_starting_state_machine_transitions() {
5096        use crate::generated::gapic_dataplane::model::TransactionOptions;
5097        use crate::generated::gapic_dataplane::model::transaction_options::Mode;
5098
5099        let rw_options =
5100            TransactionOptions::default().set_mode(Mode::ReadWrite(Default::default()));
5101
5102        // 1. ReadWrite mode: Starting -> FirstStatementFailed (simulating drop without disarm)
5103        let notify = Arc::new(Notify::new());
5104        let selector = ReadContextTransactionSelector::Lazy(Arc::new(StdMutex::new(
5105            TransactionState::Starting(rw_options.clone(), notify),
5106        )));
5107        selector.on_cancelled_starting();
5108        assert!(
5109            selector.is_first_statement_failed(),
5110            "on_cancelled_starting in ReadWrite mode must transition state to FirstStatementFailed"
5111        );
5112
5113        // 2. ReadOnly mode: Starting -> NotStarted (resets so next attempt can restart)
5114        let ro_options = TransactionOptions::default().set_mode(Mode::ReadOnly(Default::default()));
5115        let notify = Arc::new(Notify::new());
5116        let selector = ReadContextTransactionSelector::Lazy(Arc::new(StdMutex::new(
5117            TransactionState::Starting(ro_options.clone(), notify),
5118        )));
5119        selector.on_cancelled_starting();
5120        assert!(
5121            matches!(
5122                selector.poll_selector_status(),
5123                Ok(SelectorStatus::Wait(_)) | Err(_)
5124            ) || selector.get_id_no_wait().is_ok(),
5125            "on_cancelled_starting in ReadOnly mode must reset to NotStarted"
5126        );
5127
5128        // 3. LazyTransactionStartGuard drop without disarm -> transitions to FirstStatementFailed
5129        let notify = Arc::new(Notify::new());
5130        let selector = ReadContextTransactionSelector::Lazy(Arc::new(StdMutex::new(
5131            TransactionState::Starting(rw_options.clone(), notify),
5132        )));
5133        {
5134            let _guard = LazyTransactionStartGuard::new(Some(selector.clone()));
5135            // guard dropped here without disarm()
5136        }
5137        assert!(
5138            selector.is_first_statement_failed(),
5139            "Guard dropped without disarm must transition state to FirstStatementFailed"
5140        );
5141
5142        // 4. LazyTransactionStartGuard with disarm() -> does not trigger cancellation
5143        let notify = Arc::new(Notify::new());
5144        let selector = ReadContextTransactionSelector::Lazy(Arc::new(StdMutex::new(
5145            TransactionState::Starting(rw_options.clone(), notify),
5146        )));
5147        {
5148            let mut guard = LazyTransactionStartGuard::new(Some(selector.clone()));
5149            guard.disarm();
5150        }
5151        assert!(
5152            !selector.is_first_statement_failed(),
5153            "Disarmed guard must not transition state on drop"
5154        );
5155    }
5156
5157    #[tokio_test_no_panics]
5158    async fn streaming_query_empty_transaction_id_fails_and_wakes_waiters() -> crate::Result<()> {
5159        let mut mock = create_session_mock();
5160        mock.expect_execute_streaming_sql().once().returning(|_| {
5161            Ok(Response::from(adapt([Ok(
5162                setup_select1_with_transaction_id(vec![]),
5163            )])))
5164        });
5165        let (db_client, _server) = setup_db_client(mock).await;
5166        let transaction = db_client
5167            .read_only_transaction()
5168            .set_timestamp_bound(TimestampBound::strong())
5169            .build()
5170            .await?;
5171
5172        let query = Statement::builder("SELECT 1").build();
5173        let result = transaction.execute_query(query).await;
5174        assert!(
5175            result.is_err(),
5176            "execute_query must fail when Spanner returns an empty transaction ID"
5177        );
5178        let error = result.expect_err("expected error");
5179        assert!(
5180            error
5181                .to_string()
5182                .contains("Spanner failed to return a transaction ID"),
5183            "Expected missing transaction ID error message, got: {error}"
5184        );
5185
5186        Ok(())
5187    }
5188
5189    #[test]
5190    fn transaction_selector_recovers_from_poisoned_lock_on_start() -> crate::Result<()> {
5191        use bytes::Bytes;
5192        use std::panic::catch_unwind;
5193
5194        let inner_state = Arc::new(StdMutex::new(TransactionState::NotStarted(
5195            TransactionOptions::default().set_read_only(ReadOnly::default()),
5196        )));
5197        let selector = ReadContextTransactionSelector::Lazy(Arc::clone(&inner_state));
5198
5199        // Deliberately poison the mutex.
5200        let inner_state_clone = Arc::clone(&inner_state);
5201        let _ = catch_unwind(move || {
5202            let _guard = inner_state_clone
5203                .lock()
5204                .expect("lock must succeed before poison");
5205            panic!("deliberate panic to poison mutex");
5206        });
5207        assert!(
5208            inner_state.is_poisoned(),
5209            "transaction state mutex must be poisoned"
5210        );
5211
5212        // Verify query methods recover under poison.
5213        assert!(
5214            selector.is_lazy(),
5215            "selector must be identified as lazy even if poisoned"
5216        );
5217        assert!(
5218            !selector.is_started(),
5219            "selector must not be started initially"
5220        );
5221        assert!(
5222            !selector.is_starting(),
5223            "selector must not be starting initially"
5224        );
5225
5226        // Verify poll_selector_status successfully transitions under poison.
5227        let status = selector.poll_selector_status()?;
5228        match status {
5229            SelectorStatus::Ready(transaction_selector) => {
5230                assert!(
5231                    transaction_selector.begin().is_some(),
5232                    "expected begin options in ready status"
5233                );
5234            }
5235            SelectorStatus::Wait(_) => {
5236                panic!("first poller should become leader, not waiter");
5237            }
5238        }
5239        assert!(
5240            selector.is_starting(),
5241            "selector must be starting after poll_selector_status"
5242        );
5243
5244        // Verify update succeeds and transitions to Started under poison.
5245        let timestamp = wkt::Timestamp::clamp(12345, 6789);
5246        selector.update(Bytes::from_static(b"test-tx-id"), Some(timestamp))?;
5247
5248        assert!(
5249            selector.is_started(),
5250            "selector must be started after update"
5251        );
5252        assert_eq!(
5253            selector.get_id_no_wait()?,
5254            Some(Bytes::from_static(b"test-tx-id")),
5255            "expected transaction ID"
5256        );
5257        assert_eq!(
5258            selector.read_timestamp(),
5259            Some(timestamp),
5260            "expected read timestamp"
5261        );
5262
5263        Ok(())
5264    }
5265
5266    #[test]
5267    fn transaction_selector_recovers_from_poisoned_lock_on_failure() -> crate::Result<()> {
5268        use std::panic::catch_unwind;
5269
5270        let notify = Arc::new(Notify::new());
5271        let options = TransactionOptions::default().set_read_only(ReadOnly::default());
5272        let inner_state = Arc::new(StdMutex::new(TransactionState::Starting(
5273            options,
5274            Arc::clone(&notify),
5275        )));
5276        let selector = ReadContextTransactionSelector::Lazy(Arc::clone(&inner_state));
5277
5278        // Deliberately poison the mutex.
5279        let inner_state_clone = Arc::clone(&inner_state);
5280        let _ = catch_unwind(move || {
5281            let _guard = inner_state_clone
5282                .lock()
5283                .expect("lock must succeed before poison");
5284            panic!("deliberate panic to poison mutex");
5285        });
5286        assert!(
5287            inner_state.is_poisoned(),
5288            "transaction state mutex must be poisoned"
5289        );
5290
5291        // For read-only, set_failed transitions directly to Failed (fail-fast).
5292        let test_error = internal_error("transient stream error");
5293        // set_failed marks the selector as Failed despite lock poisoning.
5294        selector.set_failed(&test_error, false);
5295
5296        let prepare_result = selector.prepare_for_commit();
5297        assert!(
5298            prepare_result.is_err(),
5299            "prepare_for_commit must return error after set_failed on poisoned lock"
5300        );
5301
5302        let restart_result = selector.selector_for_restart();
5303        assert!(
5304            restart_result.is_err(),
5305            "selector_for_restart must return error for Failed transaction on poisoned lock"
5306        );
5307
5308        Ok(())
5309    }
5310
5311    #[test]
5312    fn transaction_selector_on_cancelled_starting_recovers_from_poisoned_lock() -> crate::Result<()>
5313    {
5314        use std::panic::catch_unwind;
5315
5316        // Test read-write cancellation transitions to FirstStatementFailed.
5317        {
5318            use crate::model::transaction_options::ReadWrite;
5319            let notify = Arc::new(Notify::new());
5320            let read_write_options =
5321                TransactionOptions::default().set_read_write(ReadWrite::default());
5322            let inner_state = Arc::new(StdMutex::new(TransactionState::Starting(
5323                read_write_options,
5324                Arc::clone(&notify),
5325            )));
5326            let selector = ReadContextTransactionSelector::Lazy(Arc::clone(&inner_state));
5327
5328            let inner_state_clone = Arc::clone(&inner_state);
5329            let _ = catch_unwind(move || {
5330                let _guard = inner_state_clone
5331                    .lock()
5332                    .expect("lock must succeed before poison");
5333                panic!("deliberate panic to poison mutex");
5334            });
5335            assert!(
5336                inner_state.is_poisoned(),
5337                "read-write transaction mutex must be poisoned"
5338            );
5339
5340            selector.on_cancelled_starting();
5341            assert!(
5342                selector.is_first_statement_failed(),
5343                "read-write selector must transition to FirstStatementFailed on cancellation"
5344            );
5345        }
5346
5347        // Test read-only cancellation transitions back to NotStarted.
5348        {
5349            let notify = Arc::new(Notify::new());
5350            let read_only_options =
5351                TransactionOptions::default().set_read_only(ReadOnly::default());
5352            let inner_state = Arc::new(StdMutex::new(TransactionState::Starting(
5353                read_only_options,
5354                Arc::clone(&notify),
5355            )));
5356            let selector = ReadContextTransactionSelector::Lazy(Arc::clone(&inner_state));
5357
5358            let inner_state_clone = Arc::clone(&inner_state);
5359            let _ = catch_unwind(move || {
5360                let _guard = inner_state_clone
5361                    .lock()
5362                    .expect("lock must succeed before poison");
5363                panic!("deliberate panic to poison mutex");
5364            });
5365            assert!(
5366                inner_state.is_poisoned(),
5367                "read-only transaction mutex must be poisoned"
5368            );
5369
5370            selector.on_cancelled_starting();
5371            assert!(
5372                !selector.is_starting(),
5373                "read-only selector must reset from Starting back to NotStarted on cancellation"
5374            );
5375        }
5376
5377        Ok(())
5378    }
5379
5380    #[test]
5381    fn aborted_state_record_and_get() {
5382        let state = AbortedState::default();
5383        assert!(
5384            state.aborted_info().is_none(),
5385            "initially aborted_info must be None"
5386        );
5387
5388        let retry_info = RetryInfo::default().set_retry_delay(WktDuration::clamp(5, 42_000_000));
5389        let status = GaxStatus::default()
5390            .set_code(GaxCode::Aborted)
5391            .set_message("transaction was aborted")
5392            .set_details(vec![StatusDetails::RetryInfo(retry_info)]);
5393        let error = Error::service(status);
5394
5395        state.record(&error, false);
5396        let info = state
5397            .aborted_info()
5398            .expect("aborted_info must be present after recording abort");
5399        assert_eq!(
5400            info.status.code,
5401            GaxCode::Aborted,
5402            "status code must be Aborted"
5403        );
5404        assert_eq!(
5405            info.status.message, "transaction was aborted",
5406            "status message must match"
5407        );
5408        assert_eq!(
5409            info.retry_delay,
5410            Some(Duration::new(5, 42_000_000)),
5411            "retry delay must be extracted from RetryInfo"
5412        );
5413
5414        let reconstructed = info.to_error();
5415        assert_eq!(
5416            reconstructed.status().map(|status| status.code),
5417            Some(GaxCode::Aborted),
5418            "reconstructed error must have Aborted code"
5419        );
5420        assert_eq!(
5421            reconstructed.status().map(|status| status.message.as_str()),
5422            Some("transaction was aborted"),
5423            "reconstructed error must preserve message"
5424        );
5425    }
5426
5427    #[test]
5428    fn aborted_state_first_abort_wins() {
5429        let state = AbortedState::default();
5430
5431        let status1 = GaxStatus::default()
5432            .set_code(GaxCode::Aborted)
5433            .set_message("first abort");
5434        let error1 = Error::service(status1);
5435
5436        let status2 = GaxStatus::default()
5437            .set_code(GaxCode::Aborted)
5438            .set_message("second abort");
5439        let error2 = Error::service(status2);
5440
5441        state.record(&error1, false);
5442        state.record(&error2, false);
5443
5444        let info = state
5445            .aborted_info()
5446            .expect("aborted_info must be present after recording abort");
5447        assert_eq!(
5448            info.status.message, "first abort",
5449            "first abort message must be preserved"
5450        );
5451    }
5452
5453    #[test]
5454    fn aborted_state_ignores_non_aborted_errors() {
5455        let state = AbortedState::default();
5456
5457        let status = GaxStatus::default()
5458            .set_code(GaxCode::NotFound)
5459            .set_message("not found");
5460        let error = Error::service(status);
5461
5462        state.record(&error, false);
5463        assert!(
5464            state.aborted_info().is_none(),
5465            "non-aborted error must not be recorded"
5466        );
5467    }
5468
5469    #[test]
5470    fn aborted_state_emulator_internal_error_handling() {
5471        let state = AbortedState::default();
5472
5473        let status = GaxStatus::default()
5474            .set_code(GaxCode::Internal)
5475            .set_message("Schema generation error: was not registered with the Action Manager");
5476        let error = Error::service(status);
5477
5478        // When not in emulator mode, Internal error is NOT treated as aborted.
5479        state.record(&error, false);
5480        assert!(
5481            state.aborted_info().is_none(),
5482            "emulator internal error must not be recorded when is_emulator is false"
5483        );
5484
5485        // When in emulator mode, it IS treated as aborted.
5486        state.record(&error, true);
5487        let info = state
5488            .aborted_info()
5489            .expect("emulator internal error must be recorded when is_emulator is true");
5490        assert_eq!(
5491            info.status.code,
5492            GaxCode::Internal,
5493            "recorded status must be Internal"
5494        );
5495    }
5496
5497    #[test]
5498    fn aborted_state_noop_ignores_all_errors() {
5499        let state = AbortedState::new_noop();
5500        let status = GaxStatus::default().set_code(GaxCode::Aborted);
5501        let error = Error::service(status);
5502        state.record(&error, false);
5503        state.record(&error, true);
5504        assert!(
5505            state.aborted_info().is_none(),
5506            "noop state must ignore all errors"
5507        );
5508    }
5509
5510    #[test]
5511    fn prepare_for_commit_state_transitions() -> Result<()> {
5512        // 1. Fixed selector with transaction ID -> CommitAction::Ready
5513        let fixed_selector = TransactionSelector::default().set_id(Bytes::from_static(&[1, 2, 3]));
5514        let selector = ReadContextTransactionSelector::Fixed(fixed_selector, None);
5515        let action = selector.prepare_for_commit()?;
5516        match action {
5517            CommitAction::Ready(id) => {
5518                assert_eq!(
5519                    id,
5520                    Bytes::from_static(&[1, 2, 3]),
5521                    "fixed selector with ID must return Ready with matching ID"
5522                );
5523            }
5524            other => panic!("expected CommitAction::Ready, got {other:?}"),
5525        }
5526
5527        // 2. Fixed selector without ID -> Err
5528        let empty_fixed = TransactionSelector::default();
5529        let selector = ReadContextTransactionSelector::Fixed(empty_fixed, None);
5530        assert!(
5531            selector.prepare_for_commit().is_err(),
5532            "fixed selector without ID must fail prepare_for_commit"
5533        );
5534
5535        // 3. Lazy selector in Started state with ID -> CommitAction::Ready
5536        let started_selector =
5537            TransactionSelector::default().set_id(Bytes::from_static(&[4, 5, 6]));
5538        let lazy_state = Arc::new(StdMutex::new(TransactionState::Started(
5539            started_selector,
5540            None,
5541        )));
5542        let selector = ReadContextTransactionSelector::Lazy(Arc::clone(&lazy_state));
5543        let action = selector.prepare_for_commit()?;
5544        match action {
5545            CommitAction::Ready(id) => {
5546                assert_eq!(
5547                    id,
5548                    Bytes::from_static(&[4, 5, 6]),
5549                    "started lazy selector must return Ready with matching ID"
5550                );
5551            }
5552            other => panic!("expected CommitAction::Ready, got {other:?}"),
5553        }
5554
5555        // 4. Lazy selector in Started state without ID -> Err
5556        let empty_started = TransactionSelector::default();
5557        let lazy_state = Arc::new(StdMutex::new(TransactionState::Started(
5558            empty_started,
5559            None,
5560        )));
5561        let selector = ReadContextTransactionSelector::Lazy(Arc::clone(&lazy_state));
5562        assert!(
5563            selector.prepare_for_commit().is_err(),
5564            "started lazy selector without ID must fail prepare_for_commit"
5565        );
5566
5567        // 5. Lazy selector in Starting state -> CommitAction::Starting
5568        let lazy_state = Arc::new(StdMutex::new(TransactionState::Starting(
5569            TransactionOptions::default(),
5570            Arc::new(Notify::new()),
5571        )));
5572        let selector = ReadContextTransactionSelector::Lazy(Arc::clone(&lazy_state));
5573        let action = selector.prepare_for_commit()?;
5574        assert!(
5575            matches!(action, CommitAction::Starting),
5576            "starting lazy selector must return Starting"
5577        );
5578
5579        // 6. Lazy selector in Failed state -> Err
5580        let lazy_state = Arc::new(StdMutex::new(TransactionState::Failed(
5581            TransactionStartFailure::Internal("test failure".to_string()),
5582        )));
5583        let selector = ReadContextTransactionSelector::Lazy(Arc::clone(&lazy_state));
5584        let failure_result = selector.prepare_for_commit();
5585        assert!(
5586            failure_result.is_err(),
5587            "failed lazy selector must return Err from prepare_for_commit"
5588        );
5589
5590        // 7. Lazy selector in FirstStatementFailed state -> Err (synthetic Aborted)
5591        let lazy_state = Arc::new(StdMutex::new(TransactionState::FirstStatementFailed));
5592        let selector = ReadContextTransactionSelector::Lazy(Arc::clone(&lazy_state));
5593        let first_statement_result = selector.prepare_for_commit();
5594        assert!(
5595            first_statement_result.is_err(),
5596            "FirstStatementFailed must return synthetic Aborted from prepare_for_commit"
5597        );
5598
5599        // 8. Lazy selector in NotStarted state -> atomically transitions to Starting and returns CommitAction::Begin
5600        let lazy_state = Arc::new(StdMutex::new(TransactionState::NotStarted(
5601            TransactionOptions::default(),
5602        )));
5603        let selector = ReadContextTransactionSelector::Lazy(Arc::clone(&lazy_state));
5604        let action = selector.prepare_for_commit()?;
5605        match action {
5606            CommitAction::Begin(options, notify) => {
5607                assert!(
5608                    options.mode.is_none(),
5609                    "options must match default NotStarted options"
5610                );
5611                assert!(
5612                    selector.is_starting(),
5613                    "selector must transition to Starting state under lock"
5614                );
5615                notify.notify_waiters();
5616            }
5617            other => panic!("expected CommitAction::Begin, got {other:?}"),
5618        }
5619
5620        Ok(())
5621    }
5622
5623    #[tokio_test_no_panics]
5624    async fn handle_explicit_begin_commit_failure_wakes_concurrent_selector_waiter()
5625    -> crate::Result<()> {
5626        let mock = create_session_mock();
5627        let (database_client, _server) = setup_db_client(mock).await;
5628        let transaction = database_client
5629            .read_only_transaction()
5630            .set_timestamp_bound(TimestampBound::strong())
5631            .build()
5632            .await?;
5633
5634        // Prepare selector for commit, transitioning it to Starting
5635        let action = transaction
5636            .context
5637            .transaction_selector
5638            .prepare_for_commit()?;
5639        let notify = match action {
5640            CommitAction::Begin(_, notify) => notify,
5641            other => panic!("expected CommitAction::Begin, got {other:?}"),
5642        };
5643
5644        // Spawn a follower task calling selector().await while state is Starting.
5645        // It should register on notify and park waiting for the leader.
5646        let context_follower = transaction.context.clone();
5647        let follower_handle = spawn(async move { context_follower.selector().await });
5648
5649        // Wait until the follower has entered selector() and registered on notify (bumping strong_count to 3)
5650        while Arc::strong_count(&notify) < 3 {
5651            yield_now().await;
5652        }
5653
5654        // Leader encounters explicit begin failure during commit
5655        let error = crate::error::internal_error("explicit begin commit failure");
5656        transaction
5657            .context
5658            .handle_explicit_begin_commit_failure(&error, notify);
5659
5660        // Follower MUST NOT hang; it should be woken up promptly and receive the failure
5661        let follower_outcome = follower_handle.await.expect("follower task must not panic");
5662        assert!(
5663            follower_outcome.is_err(),
5664            "follower selector must return error when explicit begin fails"
5665        );
5666        let follower_error = follower_outcome.expect_err("follower outcome must be Err");
5667        assert!(
5668            follower_error
5669                .to_string()
5670                .contains("explicit begin commit failure"),
5671            "follower error must match failure reason, got: {follower_error}"
5672        );
5673
5674        Ok(())
5675    }
5676}