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    /// Record (or replace) a prepared-statement binding under a server-side
213    /// statement name (S1D-005).
214    pub(crate) fn insert_prepared_binding(&self, name: String, binding: PreparedStatementBinding) {
215        self.prepared_names
216            .lock()
217            .unwrap_or_else(|error| error.into_inner())
218            .insert(name, binding.statement_id);
219        self.record
220            .lock()
221            .unwrap_or_else(|error| error.into_inner())
222            .prepared_statements
223            .insert(binding.statement_id, binding);
224    }
225
226    /// Drop a prepared-statement binding by server-side name (DEALLOCATE).
227    pub(crate) fn remove_prepared_binding(&self, name: &str) -> Option<StatementId> {
228        let statement_id = self
229            .prepared_names
230            .lock()
231            .unwrap_or_else(|error| error.into_inner())
232            .remove(name)?;
233        self.record
234            .lock()
235            .unwrap_or_else(|error| error.into_inner())
236            .prepared_statements
237            .remove(&statement_id);
238        Some(statement_id)
239    }
240
241    /// Number of registry-tracked prepared statements on this session.
242    #[cfg(test)]
243    pub(crate) fn prepared_statement_count(&self) -> usize {
244        self.record
245            .lock()
246            .map(|record| record.prepared_statements.len())
247            .unwrap_or(0)
248    }
249}
250
251/// Wall-clock microseconds since the Unix epoch — the same time base as the
252/// canonical model's `deadline_unix_micros` / `last_activity_unix_micros`.
253pub(crate) fn now_unix_micros() -> u64 {
254    SystemTime::now()
255        .duration_since(UNIX_EPOCH)
256        .unwrap_or_default()
257        .as_micros()
258        .min(u128::from(u64::MAX)) as u64
259}
260
261/// Token-keyed pool of live sessions. Threaded through `AppState` as
262/// `Arc<SessionStore>` so the idle reaper (a detached thread) shares the same
263/// map as request handlers.
264pub struct SessionStore {
265    sessions: std::sync::Mutex<HashMap<String, Arc<SessionEntry>>>,
266    max_sessions: usize,
267    idle_timeout: Duration,
268    /// Logical database the sessions of this store resolve against
269    /// (S1D-004). Process-local: sessions are in-memory and die with the
270    /// process, so the id is drawn at store construction. Catalog-allocated
271    /// cluster-wide database ids land with the distributed waves.
272    database_id: DatabaseId,
273}
274
275impl SessionStore {
276    /// New store allowing up to `max_sessions` concurrent sessions, each evicted
277    /// after `idle_timeout` of inactivity.
278    pub fn new(max_sessions: usize, idle_timeout: Duration) -> Self {
279        Self::new_with_database_id(max_sessions, idle_timeout, DatabaseId::new_random())
280    }
281
282    /// [`Self::new`] with an explicit logical database id stamped onto every
283    /// session record.
284    pub fn new_with_database_id(
285        max_sessions: usize,
286        idle_timeout: Duration,
287        database_id: DatabaseId,
288    ) -> Self {
289        Self {
290            sessions: std::sync::Mutex::new(HashMap::new()),
291            // Always allow at least one session so the feature is usable when
292            // a caller passes a zero/negative-feeling cap.
293            max_sessions: max_sessions.max(1),
294            idle_timeout,
295            database_id,
296        }
297    }
298
299    /// The logical database id stamped onto this store's session records.
300    pub fn database_id(&self) -> DatabaseId {
301        self.database_id
302    }
303
304    /// Register a new session under a fresh opaque token. Returns the token, or
305    /// `None` if the store is at capacity (caller maps this to HTTP 503).
306    ///
307    /// The session record carries [`AuthenticatedIdentity::Credentialless`];
308    /// authenticated daemons use [`Self::create_with_identity`].
309    pub fn create(&self, session: MongrelSession, owner: String) -> Option<String> {
310        self.create_with_identity(session, owner, AuthenticatedIdentity::Credentialless)
311    }
312
313    /// [`Self::create`] with the authenticated identity the session acts as
314    /// (S1D-004): fixed at session open and carried by the canonical record.
315    pub fn create_with_identity(
316        &self,
317        session: MongrelSession,
318        owner: String,
319        principal: AuthenticatedIdentity,
320    ) -> Option<String> {
321        let mut guard = self.sessions.lock().ok()?;
322        if guard.len() >= self.max_sessions {
323            return None;
324        }
325        let token = random_token()?;
326        // `random_token` emits exactly 32 lowercase hex digits, the canonical
327        // `SessionId` text form, so this parse cannot fail.
328        let session_id = SessionId::from_str(&token).unwrap_or(SessionId::ZERO);
329        let record = Session::new(session_id, principal, self.database_id, now_unix_micros());
330        guard.insert(
331            token.clone(),
332            Arc::new(SessionEntry {
333                session: std::sync::RwLock::new(Arc::new(session)),
334                owner,
335                last_used: std::sync::Mutex::new(Instant::now()),
336                lock: tokio::sync::Mutex::new(()),
337                closed: AtomicBool::new(false),
338                record: std::sync::Mutex::new(record),
339                prepared_names: std::sync::Mutex::new(BTreeMap::new()),
340            }),
341        );
342        Some(token)
343    }
344
345    /// Look up a session by token, verifying the caller owns it and the session
346    /// is not closed. Returns a cloned `Arc<SessionEntry>` (the store lock is
347    /// released immediately; the caller holds the entry's per-session lock for
348    /// the request duration, and must re-check `is_closed()` after locking).
349    /// Returns `None` for an unknown token, an ownership mismatch, or a closed
350    /// session.
351    pub fn get(&self, token: &str, owner: &str) -> Option<Arc<SessionEntry>> {
352        let guard = self.sessions.lock().ok()?;
353        let entry = guard.get(token)?;
354        if entry.owner != owner || entry.is_closed() {
355            return None;
356        }
357        Some(Arc::clone(entry))
358    }
359
360    /// Remove and drop a session, marking it closed first so any request that
361    /// already holds an `Arc` aborts after acquiring the lock. Returns whether a
362    /// session was removed. Rejects non-owners.
363    pub fn close(&self, token: &str, owner: &str) -> bool {
364        self.take_for_close(token, owner).is_some()
365    }
366
367    /// Mark closing and remove from new lookups while returning the live entry
368    /// so the caller can cancel its queries and wait a bounded grace period.
369    pub(crate) fn take_for_close(&self, token: &str, owner: &str) -> Option<Arc<SessionEntry>> {
370        if let Ok(mut guard) = self.sessions.lock() {
371            if let Some(entry) = guard.get(token) {
372                if entry.owner != owner {
373                    return None;
374                }
375                entry.mark_closed();
376            }
377            return guard.remove(token);
378        }
379        None
380    }
381
382    /// Evict every session idle for longer than the configured timeout, skipping
383    /// any session with an in-flight request (per-session lock held). Called
384    /// periodically by [`spawn_session_reaper`]. Returns the count evicted.
385    pub fn sweep_idle(&self) -> usize {
386        let Ok(mut guard) = self.sessions.lock() else {
387            return 0;
388        };
389        let timeout = self.idle_timeout;
390        // Collect tokens to evict: idle AND not currently in-flight (its
391        // per-session lock is acquirable). Holding the store lock prevents new
392        // lookups while we decide; try_lock fails exactly when a request holds
393        // or is acquiring the session lock.
394        let to_evict: Vec<String> = guard
395            .iter()
396            .filter_map(|(token, entry)| {
397                if entry.idle_for_at_least(timeout)
398                    && entry.session().query_registry().active_for_session(token) == 0
399                    && entry.lock.try_lock().is_ok()
400                {
401                    Some(token.clone())
402                } else {
403                    None
404                }
405            })
406            .collect();
407        let count = to_evict.len();
408        for token in &to_evict {
409            if let Some(entry) = guard.remove(token) {
410                entry.mark_closed();
411            }
412        }
413        count
414    }
415
416    /// Current number of live sessions (diagnostics / tests).
417    pub fn len(&self) -> usize {
418        self.sessions.lock().map(|g| g.len()).unwrap_or(0)
419    }
420
421    pub fn is_empty(&self) -> bool {
422        self.len() == 0
423    }
424
425    /// Mark every session closed and remove it from the pool during shutdown.
426    pub(crate) fn close_all(&self) {
427        if let Ok(mut guard) = self.sessions.lock() {
428            for entry in guard.values() {
429                entry.mark_closed();
430            }
431            guard.clear();
432        }
433    }
434}
435
436/// Background idle-session reaper. Sweeps every 30 s, evicting sessions whose
437/// `last_used` exceeds the configured timeout. Errors are logged and never
438/// abort the sweep. Mirrors `spawn_auto_compactor`'s pattern.
439pub fn spawn_session_reaper(store: Arc<SessionStore>) {
440    std::thread::Builder::new()
441        .name("mongreldb-session-reaper".into())
442        .spawn(move || loop {
443            std::thread::sleep(Duration::from_secs(30));
444            let evicted = store.sweep_idle();
445            if evicted > 0 {
446                eprintln!("[session-reaper] evicted {evicted} idle session(s)");
447            }
448        })
449        .expect("spawn session-reaper");
450}
451
452/// Generate an opaque, cryptographically-random session token. Reads 16 bytes
453/// from `/dev/urandom` (Linux/macOS) and hex-encodes them. Session tokens are
454/// bearer capabilities, so there is NO predictable fallback: if the OS RNG is
455/// unavailable, this returns `None` and the caller rejects session creation
456/// (HTTP 503) rather than handing out a guessable token.
457fn random_token() -> Option<String> {
458    let bytes = read_urandom(16)?;
459    let mut n = 0u128;
460    for &b in &bytes {
461        n = (n << 8) | b as u128;
462    }
463    Some(format!("{n:032x}"))
464}
465
466fn read_urandom(n: usize) -> Option<Vec<u8>> {
467    use std::io::Read;
468    let mut f = std::fs::File::open("/dev/urandom").ok()?;
469    let mut buf = vec![0u8; n];
470    f.read_exact(&mut buf).ok()?;
471    Some(buf)
472}
473
474#[cfg(test)]
475mod tests {
476    use super::*;
477    use mongreldb_core::Database;
478    use mongreldb_query::{RegisteredQueryGuard, SqlQueryOptions};
479    use tempfile::tempdir;
480
481    fn make_session() -> MongrelSession {
482        let dir = tempdir().unwrap();
483        let db = Arc::new(Database::create(dir.path()).unwrap());
484        // Keep the TempDir alive for the session's lifetime by leaking it; tests
485        // are short-lived and the OS reclaims on exit.
486        std::mem::forget(dir);
487        MongrelSession::open(db).unwrap()
488    }
489
490    #[test]
491    fn create_and_get_roundtrip() {
492        let store = SessionStore::new(8, Duration::from_secs(60));
493        let token = store.create(make_session(), "alice".into()).unwrap();
494        assert!(store.get(&token, "alice").is_some());
495        // Wrong owner → None (ownership enforced).
496        assert!(store.get(&token, "eve").is_none());
497        assert_eq!(store.len(), 1);
498    }
499
500    #[test]
501    fn close_removes_session() {
502        let store = SessionStore::new(8, Duration::from_secs(60));
503        let token = store.create(make_session(), "alice".into()).unwrap();
504        assert!(store.close(&token, "alice"));
505        assert!(store.get(&token, "alice").is_none());
506        assert!(store.is_empty());
507        // Non-owner cannot close.
508        let t2 = store.create(make_session(), "bob".into()).unwrap();
509        assert!(!store.close(&t2, "alice"));
510        assert_eq!(store.len(), 1);
511    }
512
513    #[test]
514    fn capacity_limit_rejects_new_sessions() {
515        let store = SessionStore::new(1, Duration::from_secs(60));
516        assert!(store.create(make_session(), "a".into()).is_some());
517        // At capacity → None.
518        assert!(store.create(make_session(), "b".into()).is_none());
519        assert_eq!(store.len(), 1);
520    }
521
522    #[test]
523    fn sweep_idle_evicts_stale_sessions() {
524        let store = SessionStore::new(8, Duration::from_millis(1));
525        let token = store.create(make_session(), "alice".into()).unwrap();
526        assert_eq!(store.len(), 1);
527        // Sleep past the idle timeout.
528        std::thread::sleep(Duration::from_millis(20));
529        let evicted = store.sweep_idle();
530        assert_eq!(evicted, 1);
531        assert!(store.get(&token, "alice").is_none());
532        assert!(store.is_empty());
533    }
534
535    #[test]
536    fn sweep_idle_keeps_active_queries() {
537        let store = SessionStore::new(8, Duration::from_millis(1));
538        let token = store.create(make_session(), "alice".into()).unwrap();
539        let entry = store.get(&token, "alice").unwrap();
540        let query = entry
541            .session()
542            .register_query(SqlQueryOptions {
543                session_id: Some(token.clone()),
544                ..SqlQueryOptions::default()
545            })
546            .unwrap();
547        let query = RegisteredQueryGuard::new(query);
548        std::thread::sleep(Duration::from_millis(20));
549
550        assert_eq!(store.sweep_idle(), 0);
551        assert!(store.get(&token, "alice").is_some());
552
553        drop(query);
554        assert_eq!(store.sweep_idle(), 1);
555        assert!(store.is_empty());
556    }
557
558    #[test]
559    fn protocol_record_carries_identity_database_and_session_id() {
560        let database_id = DatabaseId::new_random();
561        let store = SessionStore::new_with_database_id(8, Duration::from_secs(60), database_id);
562        let identity = AuthenticatedIdentity::CatalogUser {
563            username: "alice".to_owned(),
564            user_id: 42,
565            created_version: 7,
566        };
567        let token = store
568            .create_with_identity(make_session(), "alice".into(), identity.clone())
569            .unwrap();
570        let entry = store.get(&token, "alice").unwrap();
571        let record = entry.protocol_record();
572        assert_eq!(record.session_id, SessionId::from_str(&token).unwrap());
573        assert_eq!(record.principal, identity);
574        assert_eq!(record.current_database, database_id);
575        assert_eq!(record.transaction_state, TransactionState::Idle);
576        assert!(record.prepared_statements.is_empty());
577        assert!(record.settings.is_empty());
578        assert_eq!(record.read_your_writes_token, None);
579        assert!(record.last_activity_unix_micros > 0);
580        assert_eq!(store.database_id(), database_id);
581    }
582
583    #[test]
584    fn sync_record_tracks_commit_and_activity() {
585        let store = SessionStore::new(8, Duration::from_secs(60));
586        let token = store.create(make_session(), "alice".into()).unwrap();
587        let entry = store.get(&token, "alice").unwrap();
588        let before = entry.protocol_record().last_activity_unix_micros;
589        std::thread::sleep(Duration::from_millis(2));
590
591        let commit_ts = HlcTimestamp {
592            physical_micros: now_unix_micros().saturating_sub(1_000),
593            logical: 3,
594            node_tiebreaker: 0,
595        };
596        entry.sync_record_after_request(Some(commit_ts));
597        let record = entry.protocol_record();
598        assert!(record.last_activity_unix_micros >= before);
599        assert_eq!(
600            record.read_your_writes_token,
601            Some(commit_ts),
602            "a committed request must advance the read-your-writes token to the commit timestamp"
603        );
604
605        // Without a staged transaction the state stays Idle.
606        assert_eq!(record.transaction_state, TransactionState::Idle);
607
608        // A non-committed request never moves the token.
609        entry.sync_record_after_request(None);
610        assert_eq!(
611            entry.protocol_record().read_your_writes_token,
612            Some(commit_ts)
613        );
614    }
615
616    #[test]
617    fn prepared_bindings_are_tracked_by_name_and_id() {
618        let store = SessionStore::new(8, Duration::from_secs(60));
619        let token = store.create(make_session(), "alice".into()).unwrap();
620        let entry = store.get(&token, "alice").unwrap();
621
622        let first = entry.allocate_statement_id();
623        assert_eq!(first, StatementId::new(1));
624        let mut binding = PreparedStatementBinding {
625            statement_id: first,
626            sql: "SELECT 1".to_owned(),
627            parameter_types: vec![],
628            catalog_version: mongreldb_types::ids::MetadataVersion::new(3),
629            schema_versions: BTreeMap::new(),
630            feature_set: Default::default(),
631        };
632        entry.insert_prepared_binding("stmt_a".to_owned(), binding.clone());
633        assert_eq!(entry.prepared_statement_count(), 1);
634        assert_eq!(
635            entry.prepared_binding("stmt_a"),
636            Some((first, binding.clone()))
637        );
638
639        // Ids allocate monotonically from the greatest live id.
640        let second = entry.allocate_statement_id();
641        assert_eq!(second, StatementId::new(2));
642        binding.statement_id = second;
643        entry.insert_prepared_binding("stmt_b".to_owned(), binding);
644
645        assert_eq!(entry.remove_prepared_binding("stmt_a"), Some(first));
646        assert_eq!(entry.prepared_binding("stmt_a"), None);
647        assert_eq!(entry.prepared_statement_count(), 1);
648        assert_eq!(entry.protocol_record().prepared_statements.len(), 1);
649        // Removing an unknown name is a no-op.
650        assert_eq!(entry.remove_prepared_binding("stmt_a"), None);
651    }
652}