feat(spanner): add multiplexed session support
Problem
The Spanner v1 protocol has a multiplexed session shape (Session.multiplexed = true) — one long-lived session shared by many concurrent ops, no per-session pooling, no expiry. Spanner Omni deployments only accept multiplexed sessions for read-write transactions; vanilla Cloud Spanner accepts them for read workloads. The Rust client previously had no support for this, so any user pointed at Omni couldn't use the crate at all.
This PR adds end-to-end support, with the multiplexed code path auto-enabled when SPANNER_OMNI_ENDPOINT is set in the environment.
Session management
SessionManagerholds the long-lived multiplexed handle in aparking_lot::RwLockso concurrentget()callers can clone it in parallel; only recreation needs the write lock.NotFoundon any clone flips a shared invalid flag; the nextget()recreates the master under an async lock that double-checks the flag. A monotonicmultiplexed_generationcounter, snapshotted onto each clone, prevents stale clones (whose master has already been rotated) from re-flagging a freshly-recreated master and triggering redundantCreateSessionRPCs.get()andrecreate_multiplexed_session()honour the manager'sCancellationToken, returningFailedToCreateSessionafterclose()so a closed manager can't be silently resurrected.close()drops the multiplexed master withoutDeleteSession— per the v1 proto, multiplexed sessions can't be deleted via the API and are reclaimed by server-side TTL.- Acquire / release / latency metrics fire on the multiplexed path the same way they do on the pool path, so OTel dashboards remain accurate after migration.
Read-write transactions (inline begin)
- Multiplexed RW transactions use inline begin: the transaction is started implicitly on the first query/DML, with the server-assigned
tx_idcaptured from response metadata into a slot shared with the parent transaction.PartitionedDmlis excluded — it continues to use explicitBeginTransaction, since inline begin withPartitionedDmlis rejected by the server. - Streaming retries upgrade the cached request's selector to
Id(tx_id)once captured (newReader::update_transaction_selectortrait method, with a no-op default body so external impls don't break — SemVer-compatible). Without this, a resumed stream withBegin(...)+resume_tokencould start a second server-side transaction the client never tracks. RowIteratoronly pre-fetches the first frame on the very first op of a transaction (when the inline-begin slot is still unpopulated); subsequent ops on the same transaction behave like non-multiplexed iterators.- Mutations-only commits go through an explicit
BeginTransactionwithmutation_keyset to a randomly-selected buffered mutation (per proto guidance for partition-lookup load distribution), capturing bothtx_idand the responseprecommit_token. The lifetimetransaction_tagis used for the begin RPC. commit()returns a synthetic emptyCommitResponseif the transaction reaches commit with no operations and no buffered mutations — mirrorsrollback()'s no-op guard, so an empty multiplexed tx doesn't shipTransactionId(\"\")to the server (which is rejected).
Precommit token handling
- Multiplexed-session precommit tokens are kept by highest
seq_numper proto contract, not last-write-wins. A shared helper enforces this at every capture site (DML, batch DML, streaming reads, mutations-onlyBeginTransaction). - The captured token is forwarded on
CommitRequest.precommit_token.
Apply path
Client::apply_at_least_onceroutes through the regular RW transaction path on multiplexed sessions, sinceSingleUseTransactioncommits with mutations are not supported on multiplexed sessions (no place to attachmutation_key/precommit_token; server returns UNIMPLEMENTED).
Tests
Unit tests:
update_precommit_token: empty slot, strictly-greaterseq_num, lowerseq_num, equalseq_num.Reader::update_transaction_selectorfor bothStatementReaderandTableReader:Begin(...)replaced withId(tx_id),resume_tokenuntouched.- Compile-time canary: an external-style
Readerimpl that omitsupdate_transaction_selectorstill compiles (default body present). SessionManager::getafterclosereturnsFailedToCreateSession.- Multiplexed master is recreated when the invalid flag is flipped (server-assigned session name changes after invalidation).
- Stale multiplexed clone (older generation) does NOT re-flag the invalid bit; current-generation clone does.
Integration tests against the Cloud Spanner emulator (recent images participate in the multiplexed protocol — accept multiplexed:true, return precommitToken on BeginTransaction with mutation_key, and reject buggy request shapes with NOT_FOUND / UNIMPLEMENTED):
- inline-begin: query then commit captures
tx_id. - mutations-only commit drives
begin_for_mutations_only. - empty transaction commits cleanly without shipping
TransactionId(\"\"). - multi-op transaction reuses the captured
tx_idacross ops. apply_at_least_onceon a multiplexed session (server rejects theSingleUseTransaction-with-mutations shape used by the non-multiplexed path).partitioned_updateon a multiplexed session (server rejects the inline-beginPartitionedDmlshape).- DML followed by buffered mutations in the same RW transaction.
Not exercised end-to-end (would need either a gRPC mock harness or a stricter Spanner endpoint): streaming-retry selector upgrade in production, strict precommit_token / seq_num enforcement (the emulator participates but doesn't reject mismatches), and the lock-contention contract of the RwLock-protected multiplexed clone.
Test plan
- [x] CI: full Spanner emulator suite passes (
cargo test -p gcloud-spanner --lib --test client_test --test transaction_rw_test --test transaction_ro_test --test multiplexed_test). - [x] Manual smoke against a Spanner Omni endpoint with
SPANNER_OMNI_ENDPOINTset: verify RW transactions, mutations-only commits, and concurrent ops succeed.