Skip to main content

mongreldb_server/
sessions.rs

1//! Server-side session store enabling cross-request interactive transactions
2//! over the daemon (PLAN.md Phase 6 #10), aligned with the canonical session
3//! model of `mongreldb-protocol` (spec section 10.4, S1D-004).
4//!
5//! Each session holds a long-lived [`MongrelSession`] whose `sql_txn` staging
6//! survives across `run()` calls. Because `BEGIN`/`COMMIT` only stage ops
7//! logically (the core `Transaction` is opened at `COMMIT`, not `BEGIN`), an
8//! idle session with an open transaction does **not** pin an MVCC epoch — so
9//! abandoned sessions cost only the staged-ops memory until the idle reaper
10//! evicts them.
11//!
12//! ## Canonical session record (S1D-004)
13//!
14//! Every entry also carries the protocol crate's [`Session`] record: principal
15//! identity, current database, transaction state, prepared statements,
16//! session settings, read-your-writes token, and last activity. The record is
17//! data only — sessions stay lightweight and own no storage; the
18//! [`MongrelSession`] remains the execution handle the record keys off. The
19//! record is updated best-effort by request handlers
20//! ([`SessionEntry::sync_record_after_request`]) and read back for
21//! diagnostics/tests via [`SessionEntry::protocol_record`].
22//!
23//! ## Safety rails
24//! - **Auth-bound ownership**: a session is owned by the principal that created
25//!   it; lookups by a different principal return `None` (treated as 404 to
26//!   avoid confirming a session's existence to a non-owner).
27//! - **Per-session serialization**: a `tokio::sync::Mutex` guards each session
28//!   so two concurrent requests on the same token cannot interleave a
29//!   `BEGIN`/`INSERT`/`COMMIT` sequence.
30//! - **Bounded capacity**: `max_sessions` rejects new sessions with 503 once
31//!   full.
32//! - **Idle reaper**: [`SessionStore::sweep_idle`] drops sessions whose
33//!   `last_used` exceeds the configured timeout, discarding any staged
34//!   transaction (effective rollback).
35
36use std::collections::{BTreeMap, HashMap};
37use std::str::FromStr;
38use std::sync::atomic::{AtomicBool, Ordering};
39use std::sync::Arc;
40use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
41
42use mongreldb_protocol::prepared::{PreparedStatementBinding, StatementId};
43use mongreldb_protocol::request::{AuthenticatedIdentity, IsolationLevel, SessionId};
44use mongreldb_protocol::session::{Session, TransactionState};
45use mongreldb_query::MongrelSession;
46use mongreldb_types::hlc::HlcTimestamp;
47use mongreldb_types::ids::{DatabaseId, TransactionId};
48
49/// One pooled session plus its ownership and liveness metadata.
50pub struct SessionEntry {
51    /// The live query session — reused across requests via `X-Session-ID`.
52    /// Behind a lock so the S1D-005 replan path can swap in a freshly opened
53    /// session (current catalog registrations) while a request holds the
54    /// per-session lock.
55    session: std::sync::RwLock<Arc<MongrelSession>>,
56    /// Principal that created the session (`username`, `"token"`, or
57    /// `"anonymous"`). Requests from any other principal are rejected.
58    pub owner: String,
59    last_used: std::sync::Mutex<Instant>,
60    /// Held for the duration of a request to serialize per-session access.
61    pub lock: tokio::sync::Mutex<()>,
62    /// Set when the session is closed/evicted. `get()` rejects closed entries,
63    /// and request handlers re-check it after acquiring the lock so an in-flight
64    /// request that obtained an `Arc` just before eviction aborts rather than
65    /// committing into a closed session.
66    closed: AtomicBool,
67    /// The canonical S1D-004 session record: protocol-facing identity,
68    /// transaction state, prepared-statement bindings, settings,
69    /// read-your-writes token, and last-activity timestamp. Data only — the
70    /// execution handle above remains the owner of execution state.
71    record: std::sync::Mutex<Session>,
72    /// Server-side prepared-statement name → protocol statement id. The plan
73    /// itself lives in the `MongrelSession`; the binding record it is
74    /// validated against lives in `record.prepared_statements` (S1D-005).
75    prepared_names: std::sync::Mutex<BTreeMap<String, StatementId>>,
76}
77
78impl SessionEntry {
79    /// The live query session handle, cloned per use. Callers that must
80    /// observe a replan-driven session swap re-read it through this accessor.
81    pub fn session(&self) -> Arc<MongrelSession> {
82        self.session
83            .read()
84            .unwrap_or_else(|error| error.into_inner())
85            .clone()
86    }
87
88    /// Swap in a freshly opened query session (S1D-005): the old session's
89    /// DataFusion registrations snapshot the catalog at open, so replanning a
90    /// prepared statement after a cross-session catalog change requires a
91    /// session built against the current catalog. Callers hold the
92    /// per-session lock, so no request is mid-flight on the old session, and
93    /// must only swap when no transaction is staged on the old one.
94    pub(crate) fn replace_session(&self, session: MongrelSession) {
95        *self
96            .session
97            .write()
98            .unwrap_or_else(|error| error.into_inner()) = Arc::new(session);
99    }
100
101    pub(crate) fn touch(&self) {
102        if let Ok(mut t) = self.last_used.lock() {
103            *t = Instant::now();
104        }
105        if let Ok(mut record) = self.record.lock() {
106            record.last_activity_unix_micros = now_unix_micros();
107        }
108    }
109
110    /// Whether this entry has been closed/evicted and must reject new work.
111    pub(crate) fn is_closed(&self) -> bool {
112        self.closed.load(Ordering::Acquire)
113    }
114
115    fn mark_closed(&self) {
116        self.closed.store(true, Ordering::Release);
117    }
118
119    fn idle_for_at_least(&self, timeout: Duration) -> bool {
120        self.last_used
121            .lock()
122            .map(|t| t.elapsed() >= timeout)
123            .unwrap_or(false)
124    }
125
126    /// A consistent copy of the canonical S1D-004 session record
127    /// (diagnostics and tests).
128    pub fn protocol_record(&self) -> Session {
129        self.record
130            .lock()
131            .map(|record| record.clone())
132            .unwrap_or_else(|error| error.into_inner().clone())
133    }
134
135    /// Refresh the canonical record after a request completed on this
136    /// session: last activity, transaction state (derived from the session's
137    /// staged-ops staging), and the read-your-writes token when the request
138    /// durably committed. Callers hold the per-session lock, so the record
139    /// cannot race another request on this session.
140    ///
141    /// `commit` is `Some` exactly when the request committed. The token is
142    /// the literal HLC commit-timestamp lineage of the write when one is
143    /// known: the core commit log's `CommitReceipt.commit_ts` recorded for an
144    /// idempotent commit (the S1B-005 idempotency path), else the exact
145    /// commit timestamp the query layer sourced into the durable outcome,
146    /// else the per-open epoch→commit-ts ledger
147    /// (`Database::commit_ts_for_epoch`). When none of those resolve it is
148    /// the node's HLC timestamp captured at a fresh `begin` after the commit
149    /// became visible — the single HLC authority orders it after the write's
150    /// commit timestamp (spec §8.2), so any later read at this token observes
151    /// the session's own write.
152    pub(crate) fn sync_record_after_request(&self, commit: Option<HlcTimestamp>) {
153        let Ok(mut record) = self.record.lock() else {
154            return;
155        };
156        record.last_activity_unix_micros = now_unix_micros();
157        let staging = self.session().staged_sql_operation_count().is_some();
158        match (&record.transaction_state, staging) {
159            (TransactionState::Idle, true) => {
160                record.transaction_state = TransactionState::Active {
161                    transaction_id: TransactionId::new_random(),
162                    isolation: IsolationLevel::Snapshot,
163                };
164            }
165            (TransactionState::Active { .. }, false) => {
166                record.transaction_state = TransactionState::Idle;
167            }
168            _ => {}
169        }
170        if let Some(commit_ts) = commit {
171            record.read_your_writes_token = Some(commit_ts);
172        }
173    }
174
175    /// Allocate the next session-scoped prepared-statement id. Callers hold
176    /// the per-session lock, so id allocation cannot race.
177    pub(crate) fn allocate_statement_id(&self) -> StatementId {
178        let record = self
179            .record
180            .lock()
181            .unwrap_or_else(|error| error.into_inner());
182        let next = record
183            .prepared_statements
184            .keys()
185            .next_back()
186            .map_or(1, |id| id.get().saturating_add(1));
187        StatementId::new(next)
188    }
189
190    /// The binding recorded for a server-side statement name, if the name was
191    /// prepared through the registry-tracked prepare endpoint.
192    pub(crate) fn prepared_binding(
193        &self,
194        name: &str,
195    ) -> Option<(StatementId, PreparedStatementBinding)> {
196        let names = self
197            .prepared_names
198            .lock()
199            .unwrap_or_else(|error| error.into_inner());
200        let statement_id = names.get(name).copied()?;
201        let record = self
202            .record
203            .lock()
204            .unwrap_or_else(|error| error.into_inner());
205        record
206            .prepared_statements
207            .get(&statement_id)
208            .cloned()
209            .map(|binding| (statement_id, binding))
210    }
211
212    pub(crate) fn prepared_binding_by_id(
213        &self,
214        statement_id: u64,
215    ) -> Option<(String, PreparedStatementBinding)> {
216        let statement_id = StatementId::new(statement_id);
217        let name = self
218            .prepared_names
219            .lock()
220            .unwrap_or_else(|error| error.into_inner())
221            .iter()
222            .find_map(|(name, id)| (*id == statement_id).then(|| name.clone()))?;
223        let binding = self
224            .record
225            .lock()
226            .unwrap_or_else(|error| error.into_inner())
227            .prepared_statements
228            .get(&statement_id)
229            .cloned()?;
230        Some((name, binding))
231    }
232
233    /// Record (or replace) a prepared-statement binding under a server-side
234    /// statement name (S1D-005).
235    pub(crate) fn insert_prepared_binding(&self, name: String, binding: PreparedStatementBinding) {
236        self.prepared_names
237            .lock()
238            .unwrap_or_else(|error| error.into_inner())
239            .insert(name, binding.statement_id);
240        self.record
241            .lock()
242            .unwrap_or_else(|error| error.into_inner())
243            .prepared_statements
244            .insert(binding.statement_id, binding);
245    }
246
247    /// Drop a prepared-statement binding by server-side name (DEALLOCATE).
248    pub(crate) fn remove_prepared_binding(&self, name: &str) -> Option<StatementId> {
249        let statement_id = self
250            .prepared_names
251            .lock()
252            .unwrap_or_else(|error| error.into_inner())
253            .remove(name)?;
254        self.record
255            .lock()
256            .unwrap_or_else(|error| error.into_inner())
257            .prepared_statements
258            .remove(&statement_id);
259        Some(statement_id)
260    }
261
262    /// Number of registry-tracked prepared statements on this session.
263    #[cfg(test)]
264    pub(crate) fn prepared_statement_count(&self) -> usize {
265        self.record
266            .lock()
267            .map(|record| record.prepared_statements.len())
268            .unwrap_or(0)
269    }
270}
271
272/// Wall-clock microseconds since the Unix epoch — the same time base as the
273/// canonical model's `deadline_unix_micros` / `last_activity_unix_micros`.
274pub(crate) fn now_unix_micros() -> u64 {
275    SystemTime::now()
276        .duration_since(UNIX_EPOCH)
277        .unwrap_or_default()
278        .as_micros()
279        .min(u128::from(u64::MAX)) as u64
280}
281
282/// Token-keyed pool of live sessions. Threaded through `AppState` as
283/// `Arc<SessionStore>` so the idle reaper (a detached thread) shares the same
284/// map as request handlers.
285pub struct SessionStore {
286    sessions: std::sync::Mutex<HashMap<String, Arc<SessionEntry>>>,
287    max_sessions: usize,
288    idle_timeout: Duration,
289    /// Logical database the sessions of this store resolve against
290    /// (S1D-004). Process-local: sessions are in-memory and die with the
291    /// process, so the id is drawn at store construction. Catalog-allocated
292    /// cluster-wide database ids land with the distributed waves.
293    database_id: DatabaseId,
294}
295
296impl SessionStore {
297    /// New store allowing up to `max_sessions` concurrent sessions, each evicted
298    /// after `idle_timeout` of inactivity.
299    pub fn new(max_sessions: usize, idle_timeout: Duration) -> Self {
300        Self::new_with_database_id(max_sessions, idle_timeout, DatabaseId::new_random())
301    }
302
303    /// [`Self::new`] with an explicit logical database id stamped onto every
304    /// session record.
305    pub fn new_with_database_id(
306        max_sessions: usize,
307        idle_timeout: Duration,
308        database_id: DatabaseId,
309    ) -> Self {
310        Self {
311            sessions: std::sync::Mutex::new(HashMap::new()),
312            // Always allow at least one session so the feature is usable when
313            // a caller passes a zero/negative-feeling cap.
314            max_sessions: max_sessions.max(1),
315            idle_timeout,
316            database_id,
317        }
318    }
319
320    /// The logical database id stamped onto this store's session records.
321    pub fn database_id(&self) -> DatabaseId {
322        self.database_id
323    }
324
325    /// Register a new session under a fresh opaque token. Returns the token, or
326    /// `None` if the store is at capacity (caller maps this to HTTP 503).
327    ///
328    /// The session record carries [`AuthenticatedIdentity::Credentialless`];
329    /// authenticated daemons use [`Self::create_with_identity`].
330    pub fn create(&self, session: MongrelSession, owner: String) -> Option<String> {
331        self.create_with_identity(session, owner, AuthenticatedIdentity::Credentialless)
332    }
333
334    /// [`Self::create`] with the authenticated identity the session acts as
335    /// (S1D-004): fixed at session open and carried by the canonical record.
336    pub fn create_with_identity(
337        &self,
338        session: MongrelSession,
339        owner: String,
340        principal: AuthenticatedIdentity,
341    ) -> Option<String> {
342        let mut guard = self.sessions.lock().ok()?;
343        if guard.len() >= self.max_sessions {
344            return None;
345        }
346        let token = random_token()?;
347        // `random_token` emits exactly 32 lowercase hex digits, the canonical
348        // `SessionId` text form, so this parse cannot fail.
349        let session_id = SessionId::from_str(&token).unwrap_or(SessionId::ZERO);
350        let record = Session::new(session_id, principal, self.database_id, now_unix_micros());
351        guard.insert(
352            token.clone(),
353            Arc::new(SessionEntry {
354                session: std::sync::RwLock::new(Arc::new(session)),
355                owner,
356                last_used: std::sync::Mutex::new(Instant::now()),
357                lock: tokio::sync::Mutex::new(()),
358                closed: AtomicBool::new(false),
359                record: std::sync::Mutex::new(record),
360                prepared_names: std::sync::Mutex::new(BTreeMap::new()),
361            }),
362        );
363        Some(token)
364    }
365
366    /// Look up a session by token, verifying the caller owns it and the session
367    /// is not closed. Returns a cloned `Arc<SessionEntry>` (the store lock is
368    /// released immediately; the caller holds the entry's per-session lock for
369    /// the request duration, and must re-check `is_closed()` after locking).
370    /// Returns `None` for an unknown token, an ownership mismatch, or a closed
371    /// session.
372    pub fn get(&self, token: &str, owner: &str) -> Option<Arc<SessionEntry>> {
373        let guard = self.sessions.lock().ok()?;
374        let entry = guard.get(token)?;
375        if entry.owner != owner || entry.is_closed() {
376            return None;
377        }
378        Some(Arc::clone(entry))
379    }
380
381    /// Native RPC session ids are bearer capabilities delivered only over
382    /// TLS. The authenticated identity was fixed when the session was
383    /// created, so native requests do not accept a caller-supplied owner.
384    pub(crate) fn get_by_token(&self, token: &str) -> Option<Arc<SessionEntry>> {
385        let guard = self.sessions.lock().ok()?;
386        let entry = guard.get(token)?;
387        (!entry.is_closed()).then(|| Arc::clone(entry))
388    }
389
390    pub(crate) fn close_by_token(&self, token: &str) -> bool {
391        let Ok(mut guard) = self.sessions.lock() else {
392            return false;
393        };
394        if let Some(entry) = guard.remove(token) {
395            entry.mark_closed();
396            true
397        } else {
398            false
399        }
400    }
401
402    /// Remove and drop a session, marking it closed first so any request that
403    /// already holds an `Arc` aborts after acquiring the lock. Returns whether a
404    /// session was removed. Rejects non-owners.
405    pub fn close(&self, token: &str, owner: &str) -> bool {
406        self.take_for_close(token, owner).is_some()
407    }
408
409    /// Mark closing and remove from new lookups while returning the live entry
410    /// so the caller can cancel its queries and wait a bounded grace period.
411    pub(crate) fn take_for_close(&self, token: &str, owner: &str) -> Option<Arc<SessionEntry>> {
412        if let Ok(mut guard) = self.sessions.lock() {
413            if let Some(entry) = guard.get(token) {
414                if entry.owner != owner {
415                    return None;
416                }
417                entry.mark_closed();
418            }
419            return guard.remove(token);
420        }
421        None
422    }
423
424    /// Evict every session idle for longer than the configured timeout, skipping
425    /// any session with an in-flight request (per-session lock held). Called
426    /// periodically by [`spawn_session_reaper`]. Returns the count evicted.
427    pub fn sweep_idle(&self) -> usize {
428        let Ok(mut guard) = self.sessions.lock() else {
429            return 0;
430        };
431        let timeout = self.idle_timeout;
432        // Collect tokens to evict: idle AND not currently in-flight (its
433        // per-session lock is acquirable). Holding the store lock prevents new
434        // lookups while we decide; try_lock fails exactly when a request holds
435        // or is acquiring the session lock.
436        let to_evict: Vec<String> = guard
437            .iter()
438            .filter_map(|(token, entry)| {
439                if entry.idle_for_at_least(timeout)
440                    && entry.session().query_registry().active_for_session(token) == 0
441                    && entry.lock.try_lock().is_ok()
442                {
443                    Some(token.clone())
444                } else {
445                    None
446                }
447            })
448            .collect();
449        let count = to_evict.len();
450        for token in &to_evict {
451            if let Some(entry) = guard.remove(token) {
452                entry.mark_closed();
453            }
454        }
455        count
456    }
457
458    /// Current number of live sessions (diagnostics / tests).
459    pub fn len(&self) -> usize {
460        self.sessions.lock().map(|g| g.len()).unwrap_or(0)
461    }
462
463    pub fn is_empty(&self) -> bool {
464        self.len() == 0
465    }
466
467    /// Mark every session closed and remove it from the pool during shutdown.
468    pub(crate) fn close_all(&self) {
469        if let Ok(mut guard) = self.sessions.lock() {
470            for entry in guard.values() {
471                entry.mark_closed();
472            }
473            guard.clear();
474        }
475    }
476}
477
478/// Background idle-session reaper. Sweeps every 30 s, evicting sessions whose
479/// `last_used` exceeds the configured timeout. Errors are logged and never
480/// abort the sweep. Mirrors `spawn_auto_compactor`'s pattern.
481pub fn spawn_session_reaper(store: Arc<SessionStore>) {
482    std::thread::Builder::new()
483        .name("mongreldb-session-reaper".into())
484        .spawn(move || loop {
485            std::thread::sleep(Duration::from_secs(30));
486            let evicted = store.sweep_idle();
487            if evicted > 0 {
488                eprintln!("[session-reaper] evicted {evicted} idle session(s)");
489            }
490        })
491        .expect("spawn session-reaper");
492}
493
494/// Generate an opaque, cryptographically-random session token. Reads 16 bytes
495/// from `/dev/urandom` (Linux/macOS) and hex-encodes them. Session tokens are
496/// bearer capabilities, so there is NO predictable fallback: if the OS RNG is
497/// unavailable, this returns `None` and the caller rejects session creation
498/// (HTTP 503) rather than handing out a guessable token.
499fn random_token() -> Option<String> {
500    let bytes = read_urandom(16)?;
501    let mut n = 0u128;
502    for &b in &bytes {
503        n = (n << 8) | b as u128;
504    }
505    Some(format!("{n:032x}"))
506}
507
508fn read_urandom(n: usize) -> Option<Vec<u8>> {
509    use std::io::Read;
510    let mut f = std::fs::File::open("/dev/urandom").ok()?;
511    let mut buf = vec![0u8; n];
512    f.read_exact(&mut buf).ok()?;
513    Some(buf)
514}
515
516#[cfg(test)]
517mod tests {
518    use super::*;
519    use mongreldb_core::Database;
520    use mongreldb_query::{RegisteredQueryGuard, SqlQueryOptions};
521    use tempfile::tempdir;
522
523    fn make_session() -> MongrelSession {
524        let dir = tempdir().unwrap();
525        let db = Arc::new(Database::create(dir.path()).unwrap());
526        // Keep the TempDir alive for the session's lifetime by leaking it; tests
527        // are short-lived and the OS reclaims on exit.
528        std::mem::forget(dir);
529        MongrelSession::open(db).unwrap()
530    }
531
532    #[test]
533    fn create_and_get_roundtrip() {
534        let store = SessionStore::new(8, Duration::from_secs(60));
535        let token = store.create(make_session(), "alice".into()).unwrap();
536        assert!(store.get(&token, "alice").is_some());
537        // Wrong owner → None (ownership enforced).
538        assert!(store.get(&token, "eve").is_none());
539        assert_eq!(store.len(), 1);
540    }
541
542    #[test]
543    fn close_removes_session() {
544        let store = SessionStore::new(8, Duration::from_secs(60));
545        let token = store.create(make_session(), "alice".into()).unwrap();
546        assert!(store.close(&token, "alice"));
547        assert!(store.get(&token, "alice").is_none());
548        assert!(store.is_empty());
549        // Non-owner cannot close.
550        let t2 = store.create(make_session(), "bob".into()).unwrap();
551        assert!(!store.close(&t2, "alice"));
552        assert_eq!(store.len(), 1);
553    }
554
555    #[test]
556    fn capacity_limit_rejects_new_sessions() {
557        let store = SessionStore::new(1, Duration::from_secs(60));
558        assert!(store.create(make_session(), "a".into()).is_some());
559        // At capacity → None.
560        assert!(store.create(make_session(), "b".into()).is_none());
561        assert_eq!(store.len(), 1);
562    }
563
564    #[test]
565    fn sweep_idle_evicts_stale_sessions() {
566        let store = SessionStore::new(8, Duration::from_millis(1));
567        let token = store.create(make_session(), "alice".into()).unwrap();
568        assert_eq!(store.len(), 1);
569        // Sleep past the idle timeout.
570        std::thread::sleep(Duration::from_millis(20));
571        let evicted = store.sweep_idle();
572        assert_eq!(evicted, 1);
573        assert!(store.get(&token, "alice").is_none());
574        assert!(store.is_empty());
575    }
576
577    #[test]
578    fn sweep_idle_keeps_active_queries() {
579        let store = SessionStore::new(8, Duration::from_millis(1));
580        let token = store.create(make_session(), "alice".into()).unwrap();
581        let entry = store.get(&token, "alice").unwrap();
582        let query = entry
583            .session()
584            .register_query(SqlQueryOptions {
585                session_id: Some(token.clone()),
586                ..SqlQueryOptions::default()
587            })
588            .unwrap();
589        let query = RegisteredQueryGuard::new(query);
590        std::thread::sleep(Duration::from_millis(20));
591
592        assert_eq!(store.sweep_idle(), 0);
593        assert!(store.get(&token, "alice").is_some());
594
595        drop(query);
596        assert_eq!(store.sweep_idle(), 1);
597        assert!(store.is_empty());
598    }
599
600    #[test]
601    fn protocol_record_carries_identity_database_and_session_id() {
602        let database_id = DatabaseId::new_random();
603        let store = SessionStore::new_with_database_id(8, Duration::from_secs(60), database_id);
604        let identity = AuthenticatedIdentity::CatalogUser {
605            username: "alice".to_owned(),
606            user_id: 42,
607            created_version: 7,
608        };
609        let token = store
610            .create_with_identity(make_session(), "alice".into(), identity.clone())
611            .unwrap();
612        let entry = store.get(&token, "alice").unwrap();
613        let record = entry.protocol_record();
614        assert_eq!(record.session_id, SessionId::from_str(&token).unwrap());
615        assert_eq!(record.principal, identity);
616        assert_eq!(record.current_database, database_id);
617        assert_eq!(record.transaction_state, TransactionState::Idle);
618        assert!(record.prepared_statements.is_empty());
619        assert!(record.settings.is_empty());
620        assert_eq!(record.read_your_writes_token, None);
621        assert!(record.last_activity_unix_micros > 0);
622        assert_eq!(store.database_id(), database_id);
623    }
624
625    #[test]
626    fn sync_record_tracks_commit_and_activity() {
627        let store = SessionStore::new(8, Duration::from_secs(60));
628        let token = store.create(make_session(), "alice".into()).unwrap();
629        let entry = store.get(&token, "alice").unwrap();
630        let before = entry.protocol_record().last_activity_unix_micros;
631        std::thread::sleep(Duration::from_millis(2));
632
633        let commit_ts = HlcTimestamp {
634            physical_micros: now_unix_micros().saturating_sub(1_000),
635            logical: 3,
636            node_tiebreaker: 0,
637        };
638        entry.sync_record_after_request(Some(commit_ts));
639        let record = entry.protocol_record();
640        assert!(record.last_activity_unix_micros >= before);
641        assert_eq!(
642            record.read_your_writes_token,
643            Some(commit_ts),
644            "a committed request must advance the read-your-writes token to the commit timestamp"
645        );
646
647        // Without a staged transaction the state stays Idle.
648        assert_eq!(record.transaction_state, TransactionState::Idle);
649
650        // A non-committed request never moves the token.
651        entry.sync_record_after_request(None);
652        assert_eq!(
653            entry.protocol_record().read_your_writes_token,
654            Some(commit_ts)
655        );
656    }
657
658    #[test]
659    fn prepared_bindings_are_tracked_by_name_and_id() {
660        let store = SessionStore::new(8, Duration::from_secs(60));
661        let token = store.create(make_session(), "alice".into()).unwrap();
662        let entry = store.get(&token, "alice").unwrap();
663
664        let first = entry.allocate_statement_id();
665        assert_eq!(first, StatementId::new(1));
666        let mut binding = PreparedStatementBinding {
667            statement_id: first,
668            sql: "SELECT 1".to_owned(),
669            parameter_types: vec![],
670            catalog_version: mongreldb_types::ids::MetadataVersion::new(3),
671            schema_versions: BTreeMap::new(),
672            feature_set: Default::default(),
673        };
674        entry.insert_prepared_binding("stmt_a".to_owned(), binding.clone());
675        assert_eq!(entry.prepared_statement_count(), 1);
676        assert_eq!(
677            entry.prepared_binding("stmt_a"),
678            Some((first, binding.clone()))
679        );
680
681        // Ids allocate monotonically from the greatest live id.
682        let second = entry.allocate_statement_id();
683        assert_eq!(second, StatementId::new(2));
684        binding.statement_id = second;
685        entry.insert_prepared_binding("stmt_b".to_owned(), binding);
686
687        assert_eq!(entry.remove_prepared_binding("stmt_a"), Some(first));
688        assert_eq!(entry.prepared_binding("stmt_a"), None);
689        assert_eq!(entry.prepared_statement_count(), 1);
690        assert_eq!(entry.protocol_record().prepared_statements.len(), 1);
691        // Removing an unknown name is a no-op.
692        assert_eq!(entry.remove_prepared_binding("stmt_a"), None);
693    }
694}