Skip to main content

halephant_core/connections/
server.rs

1//! Upstream PostgreSQL connection establishment.
2//!
3//! Owns the TCP dial + startup handshake that produces a fully
4//! authenticated [`ServerConn`]. Used by every path that opens a
5//! connection to an upstream PostgreSQL node — pool checkout, pool
6//! refill, topology probing, LISTEN/NOTIFY multiplex.
7//!
8//! The [`ServerConn`] data type and its per-connection prepared
9//! statement state [`PreparedStatements`] live here because they're
10//! "what `connect_server` returns" and travel together through
11//! every subsystem that holds an upstream connection.
12
13use std::collections::{HashSet, VecDeque};
14use std::time::{Duration, Instant};
15
16use anyhow::Context;
17use futures_util::{SinkExt, StreamExt};
18use tokio::net::TcpStream;
19use tokio_util::codec::Framed;
20
21use crate::auth;
22use crate::config::cluster::pool::user::UserParameters;
23use crate::o11y;
24use crate::proto::backend::BackendMessage;
25use crate::proto::codec::BackendCodec;
26use crate::proto::frontend::{FrontendMessage, ProtocolVersion, Startup};
27
28use super::options::escape;
29
30// ---------------------------------------------------------------------------
31// ServerConn — a fully initialized upstream connection
32// ---------------------------------------------------------------------------
33
34/// A server connection that has completed the PostgreSQL startup sequence and
35/// is ready for query forwarding.
36pub struct ServerConn {
37    pub framed: Framed<TcpStream, BackendCodec>,
38    pub params: Vec<(String, String)>,
39    pub backend_key: (i32, i32),
40    pub created_at: Instant,
41    /// Per-connection prepared-statement state: which canonical statements
42    /// are prepared on this backend, plus the bookkeeping to filter the
43    /// backend's `ParseComplete`/`CloseComplete` replies that answer
44    /// messages halephant injected on the client's behalf.
45    pub statements: PreparedStatements,
46    /// GUC variables SET by the client during this session. Only these are
47    /// RESET during connection reset, preserving startup parameters.
48    pub dirty_vars: HashSet<String>,
49    /// Last `ReadyForQuery` status seen on this connection. Updated by
50    /// the proxy forwarding loop so `reset_connection` knows whether a
51    /// `ROLLBACK` is needed. Starts as `Idle` (freshly connected).
52    pub last_tx_status: crate::proto::types::TransactionStatus,
53}
54
55// ---------------------------------------------------------------------------
56// PreparedStatements — per-connection prepared-statement state
57// ---------------------------------------------------------------------------
58
59/// Per-connection prepared-statement state for the proxy: which canonical
60/// statements are prepared on this backend (LRU-bounded), plus the
61/// bookkeeping to filter the backend's `ParseComplete`/`CloseComplete`
62/// replies that answer messages halephant injected on the client's
63/// behalf.
64///
65/// halephant proxies the extended query protocol with statement-name
66/// rewriting and transparent (re)preparation, so it emits `Parse`/`Close`
67/// messages the client never sent (re-prepares, LRU evictions) and
68/// absorbs others (client statement closes). The backend's reply stream
69/// therefore carries `ParseComplete`/`CloseComplete` messages that do not
70/// match what the client expects, and the proxy must filter them — in
71/// FIFO order, correct under pipelining, and rolled back if a `Parse` is
72/// rejected.
73///
74/// The cache and the reply bookkeeping are deliberately one type so the
75/// invariant between them — every optimistic insert pairs with a queued
76/// reply disposition, and the error path reverts both — is enforced
77/// inside these methods rather than by convention across call sites. The
78/// methods are pure and return intents; the async proxy layer executes
79/// the wire actions. See
80/// `docs/superpowers/specs/2026-06-30-halephant-prepared-statement-state-design.md`
81/// for the alternatives considered.
82///
83/// Lives next to [`ServerConn`] because it is state that follows a
84/// connection through its lifetime — created at `connect_server` time,
85/// travelling through checkout and checkin.
86///
87/// Construct only via [`PreparedStatements::new`] so the LRU cap is
88/// always explicit; there is no `Default` (which would silently mean an
89/// unbounded cache). Pass `max = 0` to opt into unlimited caching.
90pub struct PreparedStatements {
91    /// Canonical statements prepared on this backend, LRU-bounded.
92    cache: Lru,
93    /// One entry per `Parse` sent to the backend, in send order: the
94    /// canonical name (to roll back the optimistic insert on rejection)
95    /// and whether the matching `ParseComplete` is forwarded to the
96    /// client or suppressed.
97    parse_replies: VecDeque<ParseReply>,
98    /// One entry per `Close` sent to the backend, in send order: whether
99    /// the matching `CloseComplete` is forwarded (a client portal close)
100    /// or suppressed (a halephant eviction close).
101    close_replies: VecDeque<Reply>,
102}
103
104/// A `Parse` awaiting its backend reply.
105struct ParseReply {
106    reply: Reply,
107    canon: String,
108}
109
110/// What to do with a backend reply that answers a tracked `Parse`/`Close`.
111#[derive(Clone, Copy, PartialEq, Eq, Debug)]
112pub enum Reply {
113    /// Deliver the reply to the client.
114    Forward,
115    /// Swallow the reply; the client never sent the message it answers.
116    Suppress,
117}
118
119/// Outcome of a client `Parse`, returned by [`PreparedStatements::note_client_parse`].
120#[derive(Debug)]
121pub enum ClientParse {
122    /// Already prepared on this backend — answer the client with a
123    /// synthetic `ParseComplete` and do not forward the `Parse`.
124    Synthesize,
125    /// Forward the (rewritten) `Parse` to the backend. Send a statement
126    /// `Close` for `eviction` first when `Some`.
127    Forward { eviction: Option<String> },
128}
129
130/// Outcome of an internal re-prepare, returned by [`PreparedStatements::note_reprepare`].
131#[derive(Debug)]
132pub enum Reprepare {
133    /// Already prepared on this backend — nothing to do.
134    AlreadyPrepared,
135    /// Inject a `Parse`. Send a statement `Close` for `eviction` first
136    /// when `Some`.
137    Prepare { eviction: Option<String> },
138}
139
140impl PreparedStatements {
141    pub fn new(max: u32) -> Self {
142        Self {
143            cache: Lru::new(max),
144            parse_replies: VecDeque::new(),
145            close_replies: VecDeque::new(),
146        }
147    }
148
149    /// Handle a client `Parse` for `canon`. On a cache hit the statement
150    /// is already on the backend, so the caller answers synthetically; on
151    /// a miss the caller forwards the rewritten `Parse` and the backend's
152    /// real `ParseComplete` flows back to the client in order.
153    pub fn note_client_parse(&mut self, canon: &str) -> ClientParse {
154        if self.cache.contains(canon) {
155            self.cache.touch(canon);
156            ClientParse::Synthesize
157        } else {
158            let eviction = self.record_prepare(canon, Reply::Forward);
159            ClientParse::Forward { eviction }
160        }
161    }
162
163    /// Handle an internal re-prepare triggered by a `Bind`/`Describe`
164    /// whose statement the client never (re-)`Parse`d. The injected
165    /// `ParseComplete` is suppressed.
166    pub fn note_reprepare(&mut self, canon: &str) -> Reprepare {
167        if self.cache.contains(canon) {
168            self.cache.touch(canon);
169            Reprepare::AlreadyPrepared
170        } else {
171            let eviction = self.record_prepare(canon, Reply::Suppress);
172            Reprepare::Prepare { eviction }
173        }
174    }
175
176    /// Insert `canon` optimistically and queue the disposition of its
177    /// `ParseComplete`. When the cache is full, queue the eviction
178    /// `Close`'s `CloseComplete` for suppression and return the evicted
179    /// name. Caller must have confirmed `canon` is not already cached.
180    fn record_prepare(&mut self, canon: &str, reply: Reply) -> Option<String> {
181        let eviction = self.cache.insert(canon.to_owned());
182        if eviction.is_some() {
183            self.close_replies.push_back(Reply::Suppress);
184        }
185        self.parse_replies.push_back(ParseReply {
186            reply,
187            canon: canon.to_owned(),
188        });
189        eviction
190    }
191
192    /// Record that a client portal `Close` is being forwarded, so its
193    /// `CloseComplete` is delivered to the client.
194    pub fn note_portal_close(&mut self) {
195        self.close_replies.push_back(Reply::Forward);
196    }
197
198    /// Disposition of the next `ParseComplete` from the backend. Defaults
199    /// to forwarding when nothing is tracked, so an unexpected reply
200    /// surfaces to the client rather than being silently dropped.
201    pub fn next_parse_reply(&mut self) -> Reply {
202        self.parse_replies
203            .pop_front()
204            .map_or(Reply::Forward, |p| p.reply)
205    }
206
207    /// Disposition of the next `CloseComplete` from the backend.
208    pub fn next_close_reply(&mut self) -> Reply {
209        self.close_replies.pop_front().unwrap_or(Reply::Forward)
210    }
211
212    /// Reconcile after a backend `ErrorResponse` aborts the current
213    /// extended-protocol batch: every message after the error is skipped,
214    /// so the still-pending replies never arrive. Roll back the optimistic
215    /// inserts of the unconfirmed `Parse`s and drop the orphaned `Close`
216    /// bookkeeping.
217    pub fn roll_back_after_error(&mut self) {
218        self.close_replies.clear();
219        while let Some(pending) = self.parse_replies.pop_front() {
220            self.cache.remove(&pending.canon);
221        }
222    }
223
224    /// `DISCARD ALL` deallocated every prepared statement on the backend.
225    pub fn discard_all(&mut self) {
226        self.cache.clear();
227    }
228
229    /// Drop pending reply bookkeeping at a transaction or session
230    /// boundary. A client that disconnected mid-batch can leave a
231    /// disposition whose reply the backend skipped and will never send;
232    /// the cache itself persists across the boundary.
233    pub fn reset_pending(&mut self) {
234        self.parse_replies.clear();
235        self.close_replies.clear();
236    }
237}
238
239// ---------------------------------------------------------------------------
240// Lru — canonical prepared-statement cache with LRU eviction
241// ---------------------------------------------------------------------------
242
243/// Tracks which canonical prepared statements exist on a server
244/// connection, with LRU eviction when the configured limit is reached.
245/// A private component of [`PreparedStatements`]; constructed only via
246/// `Lru::new` so the cap is always explicit.
247struct Lru {
248    /// Set of canonical names currently prepared on this server.
249    prepared: HashSet<String>,
250    /// LRU order: front = oldest, back = most recently used.
251    order: VecDeque<String>,
252    /// Maximum statements to keep prepared per server connection.
253    max: u32,
254}
255
256impl Lru {
257    fn new(max: u32) -> Self {
258        Self {
259            prepared: HashSet::new(),
260            order: VecDeque::new(),
261            max,
262        }
263    }
264
265    /// Check whether the canonical statement is already prepared on this server.
266    fn contains(&self, canon: &str) -> bool {
267        self.prepared.contains(canon)
268    }
269
270    /// Mark a canonical statement as prepared on this server. Returns the name
271    /// of an evicted statement if the cache is full, which the caller must send
272    /// a `Close` for before preparing the new one.
273    fn insert(&mut self, canon: String) -> Option<String> {
274        if self.prepared.contains(&canon) {
275            // Move to back of LRU.
276            self.order.retain(|n| n != &canon);
277            self.order.push_back(canon);
278            return None;
279        }
280
281        let evicted = if self.max > 0 && self.prepared.len() as u32 >= self.max {
282            self.evict()
283        } else {
284            None
285        };
286
287        self.prepared.insert(canon.clone());
288        self.order.push_back(canon);
289        evicted
290    }
291
292    /// Touch a statement in the LRU (it was used).
293    fn touch(&mut self, canon: &str) {
294        self.order.retain(|n| n != canon);
295        self.order.push_back(canon.to_owned());
296    }
297
298    /// Evict the least recently used statement. Returns the canonical name of
299    /// the evicted statement.
300    fn evict(&mut self) -> Option<String> {
301        let name = self.order.pop_front()?;
302        self.prepared.remove(&name);
303        Some(name)
304    }
305
306    /// Clear all tracked statements (called after DISCARD ALL).
307    fn clear(&mut self) {
308        self.prepared.clear();
309        self.order.clear();
310    }
311
312    /// Remove a single canonical statement from the cache. Used to roll
313    /// back an optimistic insert when the backend rejects the `Parse`.
314    fn remove(&mut self, canon: &str) {
315        self.prepared.remove(canon);
316        self.order.retain(|n| n != canon);
317    }
318}
319
320// ---------------------------------------------------------------------------
321// TCP + startup handshake
322// ---------------------------------------------------------------------------
323
324/// Connect to a TCP address with a timeout, TCP_NODELAY, and TCP keepalive.
325/// Used for all upstream connections (pooled, listener, auth).
326pub(crate) async fn connect_tcp(addr: &str, timeout: Duration) -> anyhow::Result<TcpStream> {
327    let stream = tokio::time::timeout(timeout, TcpStream::connect(addr))
328        .await
329        .with_context(|| format!("connection to {addr} timed out"))?
330        .with_context(|| format!("failed to connect to {addr}"))?;
331    stream.set_nodelay(true)?;
332    let sock = socket2::SockRef::from(&stream);
333    let keepalive = socket2::TcpKeepalive::new()
334        .with_time(Duration::from_secs(30))
335        .with_interval(Duration::from_secs(10));
336    if let Err(e) = sock.set_tcp_keepalive(&keepalive) {
337        tracing::debug!(%e, "failed to set TCP keepalive (dead-peer detection degraded)");
338    }
339    Ok(stream)
340}
341
342/// Open a new TCP connection to `upstream_addr` and complete the PostgreSQL
343/// startup handshake, including password authentication if the server requests
344/// it.
345#[tracing::instrument(name = "pool.connect", skip_all, err(Display), fields(
346    otel.kind = "client",
347    db.system.name = "postgresql",
348    db.namespace = %database,
349    server.address = %upstream_addr,
350    user = %user,
351    otel.status_code,
352    otel.status_description,
353))]
354pub(crate) async fn connect_server(
355    upstream_addr: &str,
356    database: &str,
357    user: &str,
358    password: Option<&str>,
359    params: &UserParameters,
360    max_prepared: u32,
361    connect_timeout: Duration,
362) -> anyhow::Result<ServerConn> {
363    let connect_start = Instant::now();
364    async {
365        let stream = connect_tcp(upstream_addr, connect_timeout).await?;
366        let mut framed = Framed::new(stream, BackendCodec::new());
367
368        // Build startup parameters: user and database are required, then append
369        // application_name and GUC options from the config.
370        let mut startup_params = vec![
371            ("user".into(), user.into()),
372            ("database".into(), database.into()),
373        ];
374        if let Some(ref app_name) = params.application_name {
375            startup_params.push(("application_name".into(), app_name.clone()));
376        }
377        if !params.options.is_empty() {
378            let options: String = params
379                .options
380                .iter()
381                .map(|(k, v)| format!("-c {}={}", escape(k), escape(v)))
382                .collect::<Vec<_>>()
383                .join(" ");
384            startup_params.push(("options".into(), options));
385        }
386
387        // Send startup message.
388        framed
389            .send(FrontendMessage::Startup(Startup {
390                version: ProtocolVersion { major: 3, minor: 0 },
391                parameters: startup_params,
392            }))
393            .await?;
394
395        // Collect startup responses. Named `server_params` to avoid
396        // shadowing the `params: &UserParameters` function argument
397        // — these are the `ParameterStatus` values the server reports
398        // back, not the GUC settings the client sent in the startup
399        // message.
400        let mut server_params = Vec::new();
401        let mut backend_key = (0, 0);
402
403        loop {
404            match framed
405                .next()
406                .await
407                .transpose()
408                .context("reading startup response")?
409            {
410                Some(BackendMessage::AuthenticationOk) => {}
411                Some(BackendMessage::AuthenticationCleartextPassword) => {
412                    let pw = password.context(
413                        "upstream requires password auth but no password found in .pgpass",
414                    )?;
415                    framed
416                        .send(FrontendMessage::PasswordMessage(pw.as_bytes().to_vec()))
417                        .await?;
418                }
419                Some(BackendMessage::AuthenticationMd5Password { .. }) => {
420                    anyhow::bail!(
421                        "upstream {upstream_addr} requested MD5 auth — \
422                         use SCRAM-SHA-256 or trust instead"
423                    );
424                }
425                Some(BackendMessage::AuthenticationSasl { mechanisms }) => {
426                    if !mechanisms.iter().any(|m| m == "SCRAM-SHA-256") {
427                        anyhow::bail!(
428                            "upstream {upstream_addr} requires unsupported SASL mechanism: {mechanisms:?}"
429                        );
430                    }
431                    let pw = password.context(
432                        "upstream requires SCRAM auth but no password found in .pgpass",
433                    )?;
434                    auth::scram::client::authenticate(&mut framed, pw)
435                        .await
436                        .map_err(|e| anyhow::anyhow!("{e}"))?;
437                }
438                Some(BackendMessage::ParameterStatus { name, value }) => {
439                    server_params.push((name, value));
440                }
441                Some(BackendMessage::BackendKeyData {
442                    process_id,
443                    secret_key,
444                }) => {
445                    backend_key = (process_id, secret_key);
446                }
447                Some(BackendMessage::ReadyForQuery(_)) => break,
448                Some(BackendMessage::ErrorResponse(err)) => {
449                    anyhow::bail!(
450                        "upstream startup error: {}",
451                        err.message().unwrap_or("unknown")
452                    );
453                }
454                Some(other) => {
455                    anyhow::bail!("unexpected message during upstream startup: {other:?}");
456                }
457                None => anyhow::bail!("upstream closed during startup"),
458            }
459        }
460
461        Ok(ServerConn {
462            framed,
463            params: server_params,
464            backend_key,
465            created_at: Instant::now(),
466            statements: PreparedStatements::new(max_prepared),
467            dirty_vars: HashSet::new(),
468            last_tx_status: crate::proto::types::TransactionStatus::Idle,
469        })
470    }
471    .await
472    .inspect(|_| {
473        o11y::metrics::record_connect(connect_start, upstream_addr, database);
474        tracing::Span::current().record("otel.status_code", "OK");
475    })
476    .inspect_err(|_| {
477        o11y::metrics::record_error("connect_failed", upstream_addr);
478        let span = tracing::Span::current();
479        span.record("otel.status_code", "ERROR");
480        span.record("otel.status_description", "connect failed");
481    })
482}
483
484// ---------------------------------------------------------------------------
485// Tests
486// ---------------------------------------------------------------------------
487
488#[cfg(test)]
489mod tests {
490    use super::*;
491
492    // -- Lru cache --
493
494    #[test]
495    fn lru_insert_and_contains() {
496        let mut lru = Lru::new(10);
497        assert!(!lru.contains("stmt_a"));
498        lru.insert("stmt_a".into());
499        assert!(lru.contains("stmt_a"));
500    }
501
502    #[test]
503    fn lru_eviction() {
504        let mut lru = Lru::new(2);
505        lru.insert("a".into());
506        lru.insert("b".into());
507
508        // Cache is full, inserting c should evict a (oldest).
509        let evicted = lru.insert("c".into());
510        assert_eq!(evicted, Some("a".into()));
511        assert!(!lru.contains("a"));
512        assert!(lru.contains("b"));
513        assert!(lru.contains("c"));
514    }
515
516    #[test]
517    fn lru_touch_prevents_eviction() {
518        let mut lru = Lru::new(2);
519        lru.insert("a".into());
520        lru.insert("b".into());
521
522        // Touch a — now b is the oldest.
523        lru.touch("a");
524
525        let evicted = lru.insert("c".into());
526        assert_eq!(evicted, Some("b".into()));
527        assert!(lru.contains("a"));
528        assert!(lru.contains("c"));
529    }
530
531    #[test]
532    fn lru_insert_existing_moves_to_back() {
533        let mut lru = Lru::new(2);
534        lru.insert("a".into());
535        lru.insert("b".into());
536
537        // Re-insert a — should not evict, just move to back.
538        let evicted = lru.insert("a".into());
539        assert!(evicted.is_none());
540
541        // Now b is oldest — inserting c evicts b.
542        let evicted = lru.insert("c".into());
543        assert_eq!(evicted, Some("b".into()));
544    }
545
546    #[test]
547    fn lru_clear() {
548        let mut lru = Lru::new(10);
549        lru.insert("a".into());
550        lru.insert("b".into());
551        lru.clear();
552        assert!(!lru.contains("a"));
553        assert!(!lru.contains("b"));
554    }
555
556    #[test]
557    fn lru_remove_frees_the_slot() {
558        let mut lru = Lru::new(2);
559        lru.insert("a".into());
560        lru.insert("b".into());
561        lru.remove("a");
562        assert!(!lru.contains("a"));
563        assert!(lru.contains("b"));
564        // The slot "a" freed leaves room for "c" without evicting "b".
565        assert!(lru.insert("c".into()).is_none());
566        assert!(lru.contains("b"));
567        assert!(lru.contains("c"));
568    }
569
570    // -- PreparedStatements (cache + reply bookkeeping together) --
571
572    #[test]
573    fn parse_replies_are_fifo() {
574        let mut ps = PreparedStatements::new(0);
575        // A forwarded client Parse, then an injected re-prepare (distinct
576        // canonicals so the second is a cache miss).
577        assert!(matches!(
578            ps.note_client_parse("a"),
579            ClientParse::Forward { .. }
580        ));
581        assert!(matches!(ps.note_reprepare("b"), Reprepare::Prepare { .. }));
582        assert_eq!(ps.next_parse_reply(), Reply::Forward);
583        assert_eq!(ps.next_parse_reply(), Reply::Suppress);
584        // Nothing left — default to forwarding so a stray reply surfaces.
585        assert_eq!(ps.next_parse_reply(), Reply::Forward);
586    }
587
588    #[test]
589    fn cache_hit_synthesizes_without_recording() {
590        let mut ps = PreparedStatements::new(0);
591        ps.note_client_parse("a");
592        ps.next_parse_reply(); // confirm "a"
593        // Re-parsing "a" is a cache hit — answered synthetically, no reply queued.
594        assert!(matches!(ps.note_client_parse("a"), ClientParse::Synthesize));
595        assert!(matches!(ps.note_reprepare("a"), Reprepare::AlreadyPrepared));
596        assert_eq!(ps.next_parse_reply(), Reply::Forward); // queue empty
597    }
598
599    #[test]
600    fn eviction_returns_victim_and_suppresses_its_close() {
601        let mut ps = PreparedStatements::new(1);
602        assert!(matches!(
603            ps.note_client_parse("a"),
604            ClientParse::Forward { eviction: None }
605        ));
606        ps.next_parse_reply();
607        // Preparing "b" evicts "a".
608        assert!(matches!(
609            ps.note_client_parse("b"),
610            ClientParse::Forward { eviction: Some(v) } if v == "a"
611        ));
612        // The eviction Close's CloseComplete is suppressed.
613        assert_eq!(ps.next_close_reply(), Reply::Suppress);
614    }
615
616    #[test]
617    fn close_replies_disambiguate_portal_and_eviction() {
618        let mut ps = PreparedStatements::new(1);
619        ps.note_client_parse("a");
620        ps.next_parse_reply();
621        // A client portal Close (forward), then a Parse that evicts "a"
622        // (suppress) — both are CloseComplete on the wire, so order is all
623        // that tells them apart.
624        ps.note_portal_close();
625        ps.note_client_parse("b");
626        assert_eq!(ps.next_close_reply(), Reply::Forward);
627        assert_eq!(ps.next_close_reply(), Reply::Suppress);
628    }
629
630    #[test]
631    fn error_rolls_back_unconfirmed_parses_only() {
632        let mut ps = PreparedStatements::new(0);
633        // "a" prepared and confirmed by its ParseComplete.
634        ps.note_client_parse("a");
635        assert_eq!(ps.next_parse_reply(), Reply::Forward);
636        // "b" optimistically inserted, not yet confirmed.
637        ps.note_reprepare("b");
638        // The backend errors: "b" rolls back, "a" stays.
639        ps.roll_back_after_error();
640        assert!(
641            matches!(ps.note_client_parse("a"), ClientParse::Synthesize),
642            "confirmed statement should survive the rollback"
643        );
644        assert!(
645            matches!(ps.note_client_parse("b"), ClientParse::Forward { .. }),
646            "unconfirmed statement should be rolled back"
647        );
648    }
649
650    #[test]
651    fn discard_all_clears_the_cache() {
652        let mut ps = PreparedStatements::new(0);
653        ps.note_client_parse("a");
654        ps.next_parse_reply();
655        ps.discard_all();
656        assert!(
657            matches!(ps.note_client_parse("a"), ClientParse::Forward { .. }),
658            "DISCARD ALL should clear the cache"
659        );
660    }
661
662    #[test]
663    fn reset_pending_clears_dispositions_not_cache() {
664        let mut ps = PreparedStatements::new(1);
665        ps.note_reprepare("a"); // parse reply: Suppress
666        ps.note_reprepare("b"); // evicts "a": close reply Suppress; parse reply Suppress
667        ps.reset_pending();
668        // Pending dispositions cleared — both default back to Forward.
669        assert_eq!(ps.next_parse_reply(), Reply::Forward);
670        assert_eq!(ps.next_close_reply(), Reply::Forward);
671        // But the cache itself persists across the boundary.
672        assert!(matches!(ps.note_reprepare("b"), Reprepare::AlreadyPrepared));
673    }
674}