Skip to main content

duroxide_pg/
notifier.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4use anyhow::{ensure, Context, Result};
5use duroxide::providers::ProviderError;
6use sqlx::postgres::{types::Oid, PgListener, PgNotification};
7use sqlx::{pool::PoolConnection, Connection, PgPool, Postgres};
8use std::future::Future;
9use std::sync::Arc;
10use std::time::Duration;
11use tokio::sync::Notify;
12use tokio::task::JoinHandle;
13use tokio::time::{interval_at, sleep, sleep_until, timeout_at, Instant, MissedTickBehavior};
14use tracing::warn;
15
16use crate::provider::PostgresProvider;
17
18const MIN_RETRY_INTERVAL: Duration = Duration::from_millis(100);
19const DEGRADED_RETRY_INTERVAL: Duration = Duration::from_secs(1);
20const TIMER_REFRESH_BACKSTOP: Duration = Duration::from_secs(1);
21
22/// Optional LISTEN/NOTIFY-based waiting for orchestration and activity work.
23///
24/// Disabled by default. When enabled, one connection from the provider's pool
25/// is reserved for LISTEN, so the pool must allow at least two connections.
26///
27/// `ApplyAll` construction also activates notification triggers for the schema.
28/// `VerifyOnly` requires that a privileged `ApplyAll` provider has done this
29/// first. Turning this option off does not deactivate a schema's triggers.
30#[derive(Debug, Clone)]
31#[non_exhaustive]
32pub struct LongPollConfig {
33    /// Enable notification-driven waiting. Default: `false`.
34    pub enabled: bool,
35    /// Rescan future work and wake waiting fetches to recover missed
36    /// notifications. Must be nonzero when enabled. Default: 60 seconds.
37    pub notifier_poll_interval: Duration,
38    /// Delay added to future visibility timestamps to avoid waking early.
39    /// Default: 100 milliseconds.
40    pub timer_grace_period: Duration,
41}
42
43impl Default for LongPollConfig {
44    fn default() -> Self {
45        Self {
46            enabled: false,
47            notifier_poll_interval: Duration::from_secs(60),
48            timer_grace_period: Duration::from_millis(100),
49        }
50    }
51}
52
53impl LongPollConfig {
54    pub(crate) fn validate(&self, max_connections: u32) -> Result<()> {
55        if self.enabled {
56            ensure!(
57                max_connections >= 2,
58                "long-polling requires at least two pool connections: one is reserved for LISTEN"
59            );
60            ensure!(
61                !self.notifier_poll_interval.is_zero(),
62                "long-polling notifier_poll_interval must be nonzero"
63            );
64            deadline_after(self.notifier_poll_interval)?;
65            deadline_after(self.timer_grace_period)?;
66        }
67        Ok(())
68    }
69}
70
71pub(crate) struct LongPoller {
72    pub(crate) orch_notify: Arc<Notify>,
73    pub(crate) worker_notify: Arc<Notify>,
74    task: JoinHandle<()>,
75}
76
77impl LongPoller {
78    pub(crate) async fn start(
79        pool: PgPool,
80        schema: &str,
81        config: LongPollConfig,
82    ) -> Result<Option<Self>> {
83        if !config.enabled {
84            return Ok(None);
85        }
86
87        // Resolve the same unquoted identifiers used by provider SQL. Table OIDs
88        // avoid identifier folding/truncation and NOTIFY's channel-length limit.
89        let (orch_oid, worker_oid): (Oid, Oid) = sqlx::query_as(
90            "SELECT $1::pg_catalog.text::pg_catalog.regclass::pg_catalog.oid, \
91                    $2::pg_catalog.text::pg_catalog.regclass::pg_catalog.oid",
92        )
93        .bind(format!("{schema}.orchestrator_queue"))
94        .bind(format!("{schema}.worker_queue"))
95        .fetch_one(&pool)
96        .await?;
97        let channels = [
98            format!("duroxide_pg_{}", orch_oid.0),
99            format!("duroxide_pg_{}", worker_oid.0),
100        ];
101        let listener = subscribe(&pool, &channels).await?;
102        let orch_notify = Arc::new(Notify::new());
103        let worker_notify = Arc::new(Notify::new());
104        let notifications = [orch_notify.clone(), worker_notify.clone()];
105        let timer_query = format!(
106            "SELECT LEAST(\
107             (SELECT CEIL(EXTRACT(EPOCH FROM visible_at) * 1000)::BIGINT \
108              FROM {schema}.orchestrator_queue \
109              WHERE visible_at > TO_TIMESTAMP($1::BIGINT / 1000.0) \
110              ORDER BY visible_at LIMIT 1), \
111             (SELECT locked_until FROM {schema}.instance_locks \
112              WHERE locked_until > $1 ORDER BY locked_until LIMIT 1)), \
113             LEAST(\
114             (SELECT CEIL(EXTRACT(EPOCH FROM visible_at) * 1000)::BIGINT \
115              FROM {schema}.worker_queue \
116              WHERE visible_at > TO_TIMESTAMP($1::BIGINT / 1000.0) \
117              ORDER BY visible_at LIMIT 1), \
118             (SELECT MIN(locked_until) FROM {schema}.worker_queue \
119              WHERE lock_token IS NOT NULL AND locked_until > $1), \
120             (SELECT MIN(locked_until) FROM {schema}.sessions WHERE locked_until > $1))"
121        );
122        let task = tokio::spawn(run(
123            pool,
124            listener,
125            channels,
126            notifications,
127            timer_query,
128            config,
129        ));
130        Ok(Some(Self {
131            orch_notify,
132            worker_notify,
133            task,
134        }))
135    }
136
137    pub(crate) fn stop(&self) {
138        self.task.abort();
139    }
140}
141
142impl Drop for LongPoller {
143    fn drop(&mut self) {
144        self.stop();
145    }
146}
147
148async fn subscribe(pool: &PgPool, channels: &[String; 2]) -> Result<PgListener> {
149    let mut listener = PgListener::connect_with(pool).await?;
150    // Detect loss before SQLx silently reconnects, so timers and ready work can
151    // be recovered after resubscribing.
152    listener.eager_reconnect(false);
153    listener
154        .listen_all(channels.iter().map(String::as_str))
155        .await?;
156    // LISTEN must not consume the pool's only warm connection.
157    drop(
158        pool.acquire()
159            .await
160            .context("Warming a fetch connection after LISTEN")?,
161    );
162    Ok(listener)
163}
164
165async fn run(
166    pool: PgPool,
167    mut listener: PgListener,
168    channels: [String; 2],
169    notifications: [Arc<Notify>; 2],
170    timer_query: String,
171    config: LongPollConfig,
172) {
173    let mut refresh = TimerRefresh::default();
174    loop {
175        let result = run_connected(
176            &pool,
177            &mut listener,
178            &channels,
179            &notifications,
180            &timer_query,
181            &config,
182            &mut refresh,
183        )
184        .await;
185        for notify in &notifications {
186            notify.notify_waiters();
187        }
188        if pool.is_closed() {
189            return;
190        }
191        match result {
192            Ok(()) => warn!(
193                target: "duroxide::providers::postgres::notifier",
194                "LISTEN connection lost; reconnecting"
195            ),
196            Err(error) => warn!(
197                target: "duroxide::providers::postgres::notifier",
198                error = %error,
199                "Long-poll listener failed; reconnecting"
200            ),
201        }
202        drop(listener);
203        let reconnect = async {
204            loop {
205                sleep(DEGRADED_RETRY_INTERVAL).await;
206                match subscribe(&pool, &channels).await {
207                    Ok(listener) => break listener,
208                    Err(error) => warn!(
209                        target: "duroxide::providers::postgres::notifier",
210                        error = %error,
211                        "Long-poll reconnect failed; continuing one-second polling fallback"
212                    ),
213                }
214            }
215        };
216        tokio::pin!(reconnect);
217        let mut fallback = interval_at(
218            Instant::now() + DEGRADED_RETRY_INTERVAL,
219            DEGRADED_RETRY_INTERVAL,
220        );
221        fallback.set_missed_tick_behavior(MissedTickBehavior::Skip);
222        loop {
223            tokio::select! {
224                _ = pool.close_event() => {
225                    for notify in &notifications {
226                        notify.notify_waiters();
227                    }
228                    return;
229                }
230                _ = fallback.tick() => {
231                    for notify in &notifications {
232                        notify.notify_waiters();
233                    }
234                }
235                reconnected = &mut reconnect => {
236                    listener = reconnected;
237                    for notify in &notifications {
238                        notify.notify_waiters();
239                    }
240                    break;
241                }
242            }
243        }
244    }
245}
246
247type TimerDeadlines = (Option<i64>, Option<i64>);
248
249#[derive(Default)]
250struct TimerRefresh {
251    task: Option<JoinHandle<Result<TimerDeadlines>>>,
252}
253
254impl TimerRefresh {
255    fn start(&mut self, pool: &PgPool, query: &str) {
256        // Keep the same scan across listener reconnects and client watchdog wakes.
257        if self.task.is_none() {
258            let pool = pool.clone();
259            let query = query.to_string();
260            self.task = Some(tokio::spawn(
261                async move { refresh_timers(&pool, &query).await },
262            ));
263        }
264    }
265
266    async fn result(&mut self) -> Result<TimerDeadlines> {
267        let result = self.task.as_mut().expect("timer scan was started").await;
268        self.task.take();
269        result.context("Long-poll timer scan task failed")?
270    }
271}
272
273impl Drop for TimerRefresh {
274    fn drop(&mut self) {
275        if let Some(task) = &self.task {
276            task.abort();
277        }
278    }
279}
280
281struct RefreshConnection(Option<PoolConnection<Postgres>>);
282
283impl Drop for RefreshConnection {
284    fn drop(&mut self) {
285        // SQLx's normal pool return pings the connection, which can wait forever
286        // for a cancelled query. Discard only unfinished refresh connections.
287        if let Some(connection) = self.0.take() {
288            drop(connection.detach());
289        }
290    }
291}
292
293async fn refresh_timers(pool: &PgPool, query: &str) -> Result<TimerDeadlines> {
294    let mut connection = RefreshConnection(Some(pool.acquire().await?));
295    let mut tx = connection
296        .0
297        .as_mut()
298        .expect("refresh owns its connection")
299        .begin()
300        .await?;
301    let result: Result<_> = async {
302        sqlx::Executor::execute(
303            &mut *tx,
304            "SET TRANSACTION READ ONLY; \
305             SET LOCAL lock_timeout = '200ms'; SET LOCAL statement_timeout = '200ms'",
306        )
307        .await
308        .context("Setting long-poll timer scan timeouts")?;
309        sqlx::query_as(query)
310            .bind(PostgresProvider::now_millis())
311            .fetch_one(&mut *tx)
312            .await
313            .context("Reading long-poll timer deadlines")
314    }
315    .await;
316    match &result {
317        Ok(_) => tx
318            .commit()
319            .await
320            .context("Committing long-poll timer scan")?,
321        Err(error) => tx
322            .rollback()
323            .await
324            .with_context(|| format!("Rolling back long-poll timer scan after {error:#}"))?,
325    }
326    drop(connection.0.take());
327    result
328}
329
330async fn run_connected(
331    pool: &PgPool,
332    listener: &mut PgListener,
333    channels: &[String; 2],
334    notifications: &[Arc<Notify>; 2],
335    timer_query: &str,
336    config: &LongPollConfig,
337    refresh: &mut TimerRefresh,
338) -> Result<()> {
339    let mut timers: [Option<Instant>; 2] = [None, None];
340    let mut next_refresh = Instant::now();
341    let mut next_recovery = next_refresh;
342    let mut refresh_started = next_refresh;
343    // An adopted scan may have taken its snapshot before the new LISTEN.
344    let mut pending_catchup = [refresh.task.is_some(); 2];
345    refresh.start(pool, timer_query);
346    let mut refreshing = true;
347    let mut refresh_failed = false;
348    let mut refresh_stalled = false;
349    let mut next_backstop = refresh_started + TIMER_REFRESH_BACKSTOP;
350    // A paced scan must recheck work that matured since a queue's timer wake.
351    // Keep events during an in-flight scan pending for the following scan.
352    let mut refreshing_catchup = [false; 2];
353
354    loop {
355        let next_timer = timers.iter().flatten().copied().min();
356        tokio::select! {
357            _ = pool.close_event() => return Ok(()),
358            notification = listener.try_recv() => {
359                let Some(notification) = notification? else {
360                    return Ok(());
361                };
362                handle_notification(notification, channels, notifications, &mut timers, config);
363            }
364            result = refresh.result(), if refreshing => {
365                refreshing = false;
366                let recover = refresh_failed || Instant::now() >= next_recovery;
367                if recover {
368                    next_recovery = deadline_after(config.notifier_poll_interval)?;
369                }
370                next_refresh = next_recovery;
371                match result {
372                    Ok((orch, worker)) => {
373                        refresh_failed = false;
374                        for (index, timestamp) in [orch, worker].into_iter().enumerate() {
375                            // Recovery must also find ready work whose notification
376                            // was lost. Timer-only scans need not wake the other queue.
377                            if recover || refreshing_catchup[index] {
378                                notifications[index].notify_waiters();
379                            }
380                            if let Some(timestamp) = timestamp {
381                                pending_catchup[index] |= timestamp <= PostgresProvider::now_millis();
382                                schedule(timestamp, &notifications[index], &mut timers[index], config);
383                            }
384                        }
385                        if pending_catchup.iter().any(|pending| *pending) {
386                            next_refresh = next_refresh.min(
387                                (refresh_started + MIN_RETRY_INTERVAL).max(Instant::now())
388                            );
389                        }
390                    }
391                    Err(error) => {
392                        refresh_failed = true;
393                        next_refresh = (refresh_started + DEGRADED_RETRY_INTERVAL).max(Instant::now());
394                        for notify in notifications {
395                            notify.notify_waiters();
396                        }
397                        for (pending, attempted) in pending_catchup.iter_mut().zip(refreshing_catchup) {
398                            *pending |= attempted;
399                        }
400                        warn!(
401                            target: "duroxide::providers::postgres::notifier",
402                            error = %format_args!("{error:#}"),
403                            "Long-poll timer refresh failed; retrying with one-second polling fallback"
404                        );
405                    }
406                }
407            }
408            _ = sleep_until(next_backstop), if refreshing => {
409                if !refresh_stalled {
410                    warn!(
411                        target: "duroxide::providers::postgres::notifier",
412                        "Long-poll timer scan is still running; polling without cancelling or starting another scan"
413                    );
414                }
415                refresh_stalled = true;
416                refresh_failed = true;
417                for notify in notifications {
418                    notify.notify_waiters();
419                }
420                next_backstop = Instant::now() + DEGRADED_RETRY_INTERVAL;
421            }
422            _ = sleep_until(next_refresh), if !refreshing => {
423                refresh_started = Instant::now();
424                refreshing_catchup = std::mem::take(&mut pending_catchup);
425                refresh.start(pool, timer_query);
426                refreshing = true;
427                refresh_stalled = false;
428                next_backstop = refresh_started + TIMER_REFRESH_BACKSTOP;
429            }
430            _ = sleep_until(next_timer.unwrap_or(next_refresh)), if next_timer.is_some() => {
431                let now = Instant::now();
432                for (index, timer) in timers.iter_mut().enumerate() {
433                    if timer.is_some_and(|deadline| deadline <= now) {
434                        *timer = None;
435                        pending_catchup[index] = true;
436                        notifications[index].notify_waiters();
437                    }
438                }
439                // Only the earliest timer per queue is retained. Rescan after it
440                // fires to discover the next one without an unbounded timer heap.
441                next_refresh = next_refresh.min(
442                    (refresh_started + MIN_RETRY_INTERVAL).max(now)
443                );
444            }
445        }
446    }
447}
448
449fn handle_notification(
450    notification: PgNotification,
451    channels: &[String; 2],
452    notifications: &[Arc<Notify>; 2],
453    timers: &mut [Option<Instant>; 2],
454    config: &LongPollConfig,
455) {
456    let Some(index) = channels
457        .iter()
458        .position(|channel| channel == notification.channel())
459    else {
460        warn!(
461            target: "duroxide::providers::postgres::notifier",
462            "Ignoring a notification from an unexpected channel"
463        );
464        return;
465    };
466    match notification.payload().parse::<i64>() {
467        Ok(timestamp) => schedule(timestamp, &notifications[index], &mut timers[index], config),
468        Err(error) => {
469            warn!(
470                target: "duroxide::providers::postgres::notifier",
471                error = %error,
472                "Invalid long-poll timestamp; waking fetches to recheck the queue"
473            );
474            notifications[index].notify_waiters();
475        }
476    }
477}
478
479fn schedule(timestamp: i64, notify: &Notify, timer: &mut Option<Instant>, config: &LongPollConfig) {
480    let now = PostgresProvider::now_millis();
481    if timestamp <= now {
482        notify.notify_waiters();
483        return;
484    }
485    let delay = Duration::from_millis(timestamp.saturating_sub(now) as u64)
486        .checked_add(config.timer_grace_period);
487    let deadline = delay.and_then(|delay| Instant::now().checked_add(delay));
488    match deadline {
489        Some(deadline) => *timer = Some(timer.map_or(deadline, |current| current.min(deadline))),
490        None => warn!(
491            target: "duroxide::providers::postgres::notifier",
492            "Long-poll timer exceeds the clock range; relying on polling fallback"
493        ),
494    }
495}
496
497fn deadline_after(duration: Duration) -> Result<Instant> {
498    Instant::now()
499        .checked_add(duration)
500        .context("long-poll duration exceeds the supported clock range")
501}
502
503pub(crate) async fn fetch_with_poll<T, F, Fut>(
504    notify: Option<&Notify>,
505    poll_timeout: Duration,
506    operation: &'static str,
507    mut fetch: F,
508) -> Result<Option<T>, ProviderError>
509where
510    F: FnMut() -> Fut,
511    Fut: Future<Output = Result<Option<T>, ProviderError>>,
512{
513    let Some(notify) = notify.filter(|_| !poll_timeout.is_zero()) else {
514        return fetch().await;
515    };
516    let deadline = Instant::now().checked_add(poll_timeout).ok_or_else(|| {
517        ProviderError::permanent(operation, "poll_timeout exceeds the supported clock range")
518    })?;
519    let mut earliest_retry = Instant::now();
520    loop {
521        let notified = notify.notified();
522        tokio::pin!(notified);
523        // Register before reading the queue so a concurrent commit cannot be lost.
524        notified.as_mut().enable();
525        let result = fetch().await?;
526        if result.is_some() {
527            return Ok(result);
528        }
529        if Instant::now() >= deadline || timeout_at(deadline, notified).await.is_err() {
530            return Ok(None);
531        }
532        // The first wake is immediate; repeated unsuccessful wakes coalesce.
533        sleep_until(earliest_retry.min(deadline)).await;
534        if Instant::now() >= deadline {
535            return Ok(None);
536        }
537        earliest_retry = Instant::now() + MIN_RETRY_INTERVAL;
538    }
539}
540
541#[cfg(test)]
542mod tests {
543    use super::*;
544    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
545    use tokio::time::timeout;
546
547    #[derive(Default)]
548    struct ScanGate {
549        calls: AtomicUsize,
550        block_next: AtomicBool,
551        entered: Notify,
552        release: Notify,
553    }
554
555    async fn scan_pool(url: &str, max_connections: u32) -> (PgPool, Arc<ScanGate>) {
556        let gate = Arc::new(ScanGate::default());
557        let pool = sqlx::postgres::PgPoolOptions::new()
558            .min_connections(max_connections)
559            .max_connections(max_connections)
560            .before_acquire({
561                let gate = gate.clone();
562                move |_, _| {
563                    let gate = gate.clone();
564                    Box::pin(async move {
565                        gate.calls.fetch_add(1, Ordering::Relaxed);
566                        if gate.block_next.swap(false, Ordering::Relaxed) {
567                            let released = gate.release.notified();
568                            tokio::pin!(released);
569                            released.as_mut().enable();
570                            gate.entered.notify_one();
571                            released.await;
572                        }
573                        Ok(true)
574                    })
575                }
576            })
577            .connect(url)
578            .await
579            .unwrap();
580        (pool, gate)
581    }
582
583    // A session marker survives COMMIT but not a failed/rolled-back scan.
584    const MARK_COMPLETED_SCAN: &str = "pg_catalog.set_config(
585        'duroxide_test.completed_scans',
586        (COALESCE(NULLIF(current_setting('duroxide_test.completed_scans', true), ''), '0')::INT + 1)::TEXT,
587        false)";
588
589    #[test]
590    fn defaults_preserve_short_polling() {
591        let config = LongPollConfig::default();
592        assert!(!config.enabled);
593        assert_eq!(config.notifier_poll_interval, Duration::from_secs(60));
594        assert_eq!(config.timer_grace_period, Duration::from_millis(100));
595        config.validate(1).unwrap();
596    }
597
598    #[test]
599    fn enabled_configuration_requires_usable_pool_and_timers() {
600        let mut config = LongPollConfig {
601            enabled: true,
602            ..Default::default()
603        };
604        assert!(config.validate(1).unwrap_err().to_string().contains("two"));
605        config.validate(2).unwrap();
606        config.notifier_poll_interval = Duration::ZERO;
607        assert!(config.validate(2).is_err());
608        config.notifier_poll_interval = Duration::MAX;
609        assert!(config.validate(2).is_err());
610        config.notifier_poll_interval = Duration::from_secs(60);
611        config.timer_grace_period = Duration::MAX;
612        assert!(config.validate(2).is_err());
613    }
614
615    #[tokio::test]
616    async fn empty_long_poll_fetches_once_without_busy_polling() {
617        let notify = Notify::new();
618        let calls = AtomicUsize::new(0);
619        let start = Instant::now();
620        let result = fetch_with_poll(Some(&notify), Duration::from_millis(50), "test", || async {
621            calls.fetch_add(1, Ordering::Relaxed);
622            Ok(None::<()>)
623        })
624        .await
625        .unwrap();
626        assert!(result.is_none());
627        assert_eq!(calls.load(Ordering::Relaxed), 1);
628        assert!(start.elapsed() >= Duration::from_millis(50));
629    }
630
631    #[tokio::test]
632    async fn notification_between_empty_read_and_wait_is_not_lost() {
633        let notify = Notify::new();
634        let calls = AtomicUsize::new(0);
635        let result = fetch_with_poll(
636            Some(&notify),
637            Duration::from_millis(100),
638            "test",
639            || async {
640                if calls.fetch_add(1, Ordering::Relaxed) == 0 {
641                    notify.notify_waiters();
642                    Ok(None)
643                } else {
644                    Ok(Some(7))
645                }
646            },
647        )
648        .await
649        .unwrap();
650        assert_eq!(result, Some(7));
651        assert_eq!(calls.load(Ordering::Relaxed), 2);
652    }
653
654    #[tokio::test]
655    async fn repeated_unmatched_notifications_do_not_extend_deadline() {
656        let notify = Notify::new();
657        let calls = AtomicUsize::new(0);
658        let start = Instant::now();
659        let result = fetch_with_poll(Some(&notify), Duration::from_millis(30), "test", || async {
660            calls.fetch_add(1, Ordering::Relaxed);
661            notify.notify_waiters();
662            Ok(None::<()>)
663        })
664        .await
665        .unwrap();
666        assert!(result.is_none());
667        assert!(calls.load(Ordering::Relaxed) > 1);
668        assert!(start.elapsed() < Duration::from_millis(300));
669    }
670
671    #[tokio::test]
672    async fn repeated_empty_wakes_are_paced_but_the_first_wake_is_immediate() {
673        let notify = Notify::new();
674        let calls = std::sync::Mutex::new(Vec::new());
675        let result = fetch_with_poll(
676            Some(&notify),
677            Duration::from_millis(350),
678            "test",
679            || async {
680                calls.lock().unwrap().push(Instant::now());
681                notify.notify_waiters();
682                Ok(None::<()>)
683            },
684        )
685        .await
686        .unwrap();
687        assert!(result.is_none());
688        let calls = calls.lock().unwrap();
689        assert!(
690            (2..=5).contains(&calls.len()),
691            "fetch count: {}",
692            calls.len()
693        );
694        assert!(calls[1].duration_since(calls[0]) < MIN_RETRY_INTERVAL);
695        for pair in calls[1..].windows(2) {
696            assert!(pair[1].duration_since(pair[0]) >= MIN_RETRY_INTERVAL);
697        }
698    }
699
700    #[tokio::test]
701    async fn timer_scan_is_read_only_and_preserves_connection_defaults() {
702        dotenvy::dotenv().ok();
703        let Ok(url) = std::env::var("DATABASE_URL") else {
704            eprintln!("DATABASE_URL not set; skipping read-only timer database test");
705            return;
706        };
707        let pool = sqlx::postgres::PgPoolOptions::new()
708            .max_connections(1)
709            .connect(&url)
710            .await
711            .unwrap();
712        let schema = format!("readonly_scan_{}", uuid::Uuid::new_v4().simple());
713        sqlx::Executor::execute(
714            &pool,
715            format!(
716                "CREATE SCHEMA {schema}; CREATE TABLE {schema}.probe (id BIGINT);
717             INSERT INTO {schema}.probe VALUES (7)"
718            )
719            .as_str(),
720        )
721        .await
722        .unwrap();
723        let before: (i32, String) =
724            sqlx::query_as("SELECT pg_backend_pid(), current_setting('transaction_read_only')")
725                .fetch_one(&pool)
726                .await
727                .unwrap();
728        let read_only = refresh_timers(
729            &pool,
730            "SELECT (current_setting('transaction_read_only') = 'on')::INT::BIGINT, $1::BIGINT",
731        )
732        .await
733        .unwrap()
734        .0;
735        let write = refresh_timers(
736            &pool,
737            &format!(
738                "WITH inserted AS (INSERT INTO {schema}.probe VALUES ($1) RETURNING id)
739             SELECT id, NULL::BIGINT FROM inserted"
740            ),
741        )
742        .await;
743        let after: (i32, String) =
744            sqlx::query_as("SELECT pg_backend_pid(), current_setting('transaction_read_only')")
745                .fetch_one(&pool)
746                .await
747                .unwrap();
748        let rows: Vec<i64> =
749            sqlx::query_scalar(&format!("SELECT id FROM {schema}.probe ORDER BY id"))
750                .fetch_all(&pool)
751                .await
752                .unwrap();
753        sqlx::query(&format!("DROP SCHEMA {schema} CASCADE"))
754            .execute(&pool)
755            .await
756            .unwrap();
757        pool.close().await;
758        assert_eq!(read_only, Some(1), "the scan transaction must be READ ONLY");
759        let error = write.expect_err("the timer transaction must reject writes");
760        let code = error
761            .downcast_ref::<sqlx::Error>()
762            .and_then(sqlx::Error::as_database_error)
763            .and_then(|error| error.code());
764        assert_eq!(code.as_deref(), Some("25006"));
765        assert_eq!(rows, vec![7]);
766        assert_eq!(
767            after, before,
768            "rollback must preserve connection defaults and reuse"
769        );
770    }
771
772    #[tokio::test]
773    async fn reconnect_catches_up_after_a_scan_from_before_listen() {
774        dotenvy::dotenv().ok();
775        let Ok(url) = std::env::var("DATABASE_URL") else {
776            eprintln!("DATABASE_URL not set; skipping reconnect snapshot database test");
777            return;
778        };
779        let pool = sqlx::postgres::PgPoolOptions::new()
780            .max_connections(3)
781            .connect(&url)
782            .await
783            .unwrap();
784        let schema = format!("reconnect_snapshot_{}", uuid::Uuid::new_v4().simple());
785        sqlx::Executor::execute(
786            &pool,
787            format!(
788            "CREATE SCHEMA {schema}; CREATE TABLE {schema}.deadlines (queue INTEGER, due BIGINT)"
789        )
790            .as_str(),
791        )
792        .await
793        .unwrap();
794        let query = format!(
795            "SELECT min(due) FILTER (WHERE queue = 0), min(due) FILTER (WHERE queue = 1)
796             FROM {schema}.deadlines WHERE due > $1"
797        );
798        let channels = [format!("{schema}_orch"), format!("{schema}_worker")];
799        let mut listener = subscribe(&pool, &channels).await.unwrap();
800        let pid: i32 = sqlx::query_scalar(
801            "SELECT pid FROM pg_stat_activity WHERE query LIKE 'LISTEN%' AND strpos(query, $1) > 0",
802        )
803        .bind(&channels[0])
804        .fetch_one(&pool)
805        .await
806        .unwrap();
807        let notifications = [Arc::new(Notify::new()), Arc::new(Notify::new())];
808        let (snapshot_tx, snapshot_rx) = tokio::sync::oneshot::channel();
809        let (release_tx, release_rx) = tokio::sync::oneshot::channel();
810        let mut refresh = TimerRefresh {
811            task: Some(tokio::spawn({
812                let pool = pool.clone();
813                let query = query.clone();
814                async move {
815                    let result = refresh_timers(&pool, &query).await?;
816                    snapshot_tx.send(result).unwrap();
817                    release_rx.await.unwrap();
818                    Ok(result)
819                }
820            })),
821        };
822        let config = LongPollConfig {
823            enabled: true,
824            timer_grace_period: Duration::ZERO,
825            ..Default::default()
826        };
827        let disconnect = async {
828            assert_eq!(snapshot_rx.await.unwrap(), (None, None));
829            sqlx::query("SELECT pg_terminate_backend($1)")
830                .bind(pid)
831                .execute(&pool)
832                .await
833                .unwrap();
834        };
835        let (disconnected, ()) = timeout(Duration::from_secs(3), async {
836            tokio::join!(
837                run_connected(
838                    &pool,
839                    &mut listener,
840                    &channels,
841                    &notifications,
842                    &query,
843                    &config,
844                    &mut refresh
845                ),
846                disconnect,
847            )
848        })
849        .await
850        .unwrap();
851        assert!(
852            disconnected.is_ok()
853                || disconnected
854                    .unwrap_err()
855                    .downcast_ref::<sqlx::Error>()
856                    .is_some()
857        );
858        drop(listener);
859        // The successful snapshot is already old, but its result is still in flight.
860        let first = PostgresProvider::now_millis() + 1000;
861        let second = first + 200;
862        sqlx::query(&format!(
863            "INSERT INTO {schema}.deadlines VALUES (0, $1), (1, $2)"
864        ))
865        .bind(first)
866        .bind(second)
867        .execute(&pool)
868        .await
869        .unwrap();
870        let mut listener = subscribe(&pool, &channels).await.unwrap();
871        release_tx.send(()).unwrap();
872        let recovered = {
873            let connected = run_connected(
874                &pool,
875                &mut listener,
876                &channels,
877                &notifications,
878                &query,
879                &config,
880                &mut refresh,
881            );
882            tokio::pin!(connected);
883            let notifications = &notifications;
884            let wait = |index: usize, due: i64| async move {
885                fetch_with_poll(
886                    Some(notifications[index].as_ref()),
887                    Duration::from_secs(10),
888                    "test",
889                    || async move { Ok((PostgresProvider::now_millis() >= due).then_some(due)) },
890                )
891                .await
892                .unwrap()
893            };
894            timeout(Duration::from_secs(3), async {
895                tokio::select! {
896                    result = &mut connected => panic!("listener stopped unexpectedly: {result:?}"),
897                    deadlines = async { tokio::join!(wait(0, first), wait(1, second)) } => deadlines,
898                }
899            }).await
900        };
901        drop(refresh);
902        drop(listener);
903        let deadlines: Vec<i64> = sqlx::query_scalar(&format!(
904            "SELECT due FROM {schema}.deadlines ORDER BY queue"
905        ))
906        .fetch_all(&pool)
907        .await
908        .unwrap();
909        sqlx::query(&format!("DROP SCHEMA {schema} CASCADE"))
910            .execute(&pool)
911            .await
912            .unwrap();
913        pool.close().await;
914        assert_eq!(deadlines, vec![first, second]);
915        assert_eq!(
916            recovered.expect("both queues need fresh deadlines after resubscribing"),
917            (Some(first), Some(second))
918        );
919    }
920
921    #[tokio::test]
922    async fn timer_scan_timeouts_are_server_errors_and_reuse_the_connection() {
923        dotenvy::dotenv().ok();
924        let Ok(url) = std::env::var("DATABASE_URL") else {
925            eprintln!("DATABASE_URL not set; skipping timer-scan database test");
926            return;
927        };
928        let pool = sqlx::postgres::PgPoolOptions::new()
929            .max_connections(1)
930            .connect(&url)
931            .await
932            .unwrap();
933        let control = sqlx::postgres::PgPoolOptions::new()
934            .max_connections(2)
935            .connect(&url)
936            .await
937            .unwrap();
938        let schema = format!("bounded_scan_{}", uuid::Uuid::new_v4().simple());
939        sqlx::Executor::execute(
940            &control,
941            format!(
942                "CREATE SCHEMA {schema}; CREATE TABLE {schema}.probe (id INTEGER);
943             INSERT INTO {schema}.probe VALUES (1)"
944            )
945            .as_str(),
946        )
947        .await
948        .unwrap();
949        let before: (i32, String, String) = sqlx::query_as(
950            "SELECT pg_backend_pid(), current_setting('lock_timeout'), current_setting('statement_timeout')",
951        ).fetch_one(&pool).await.unwrap();
952        let valid = "SELECT $1::BIGINT, NULL::BIGINT";
953        assert!(refresh_timers(&pool, valid).await.unwrap().0.is_some());
954        let mut blocker = control.begin().await.unwrap();
955        sqlx::query(&format!(
956            "LOCK TABLE {schema}.probe IN ACCESS EXCLUSIVE MODE"
957        ))
958        .execute(&mut *blocker)
959        .await
960        .unwrap();
961        let mut outcomes = Vec::new();
962        for query in [
963            "SELECT $1::BIGINT, NULL::BIGINT FROM pg_sleep(2)".to_string(),
964            format!("SELECT $1::BIGINT, NULL::BIGINT FROM {schema}.probe"),
965        ] {
966            let error = timeout(Duration::from_secs(1), refresh_timers(&pool, &query))
967                .await
968                .expect("server timeout should beat the client backstop")
969                .unwrap_err();
970            let after: (i32, String, String) = sqlx::query_as(
971                "SELECT pg_backend_pid(), current_setting('lock_timeout'), current_setting('statement_timeout')",
972            ).fetch_one(&pool).await.unwrap();
973            outcomes.push((error, after));
974        }
975        blocker.rollback().await.unwrap();
976        let rows: i64 = sqlx::query_scalar(&format!("SELECT count(*) FROM {schema}.probe"))
977            .fetch_one(&control)
978            .await
979            .unwrap();
980        assert!(refresh_timers(&pool, valid).await.unwrap().0.is_some());
981        pool.close().await;
982        sqlx::query(&format!("DROP SCHEMA {schema} CASCADE"))
983            .execute(&control)
984            .await
985            .unwrap();
986        control.close().await;
987        assert_eq!(rows, 1, "failed scans must not change the durable state");
988        for (error, after) in outcomes {
989            let code = error
990                .downcast_ref::<sqlx::Error>()
991                .and_then(sqlx::Error::as_database_error)
992                .and_then(|error| error.code());
993            assert!(
994                matches!(code.as_deref(), Some("55P03" | "57014")),
995                "{error:#}"
996            );
997            assert_eq!(
998                after, before,
999                "timeouts must roll back and return the same healthy connection"
1000            );
1001        }
1002    }
1003
1004    #[tokio::test]
1005    async fn dense_overdue_refreshes_are_paced_and_do_not_wake_the_other_queue() {
1006        dotenvy::dotenv().ok();
1007        let Ok(url) = std::env::var("DATABASE_URL") else {
1008            eprintln!("DATABASE_URL not set; skipping timer-refresh database test");
1009            return;
1010        };
1011        let (pool, gate) = scan_pool(&url, 2).await;
1012        let schema = format!("timer_scan_{}", uuid::Uuid::new_v4().simple());
1013        let channels = [format!("{schema}_orch"), format!("{schema}_worker")];
1014        let mut listener = subscribe(&pool, &channels).await.unwrap();
1015        gate.calls.store(0, Ordering::Relaxed);
1016        let notifications = [Arc::new(Notify::new()), Arc::new(Notify::new())];
1017        let config = LongPollConfig {
1018            enabled: true,
1019            ..Default::default()
1020        };
1021        // A future timestamp matures during every query, as with dense timers
1022        // and nontrivial round-trip latency. Count scans without global resets.
1023        let query = "SELECT $1::BIGINT + 1, NULL::BIGINT FROM pg_catalog.pg_sleep(0.005)";
1024        let mut worker_wakes = 0;
1025        {
1026            let mut refresh = TimerRefresh::default();
1027            let run = run_connected(
1028                &pool,
1029                &mut listener,
1030                &channels,
1031                &notifications,
1032                query,
1033                &config,
1034                &mut refresh,
1035            );
1036            tokio::pin!(run);
1037            let duration = tokio::time::timeout(Duration::from_millis(350), async {
1038                loop {
1039                    tokio::select! {
1040                        result = &mut run => panic!("listener stopped unexpectedly: {result:?}"),
1041                        _ = notifications[1].notified() => worker_wakes += 1,
1042                    }
1043                }
1044            });
1045            assert!(duration.await.is_err());
1046        }
1047        let calls = gate.calls.load(Ordering::Relaxed);
1048        drop(listener);
1049        pool.close().await;
1050        assert!((2..=5).contains(&calls), "refreshes in 350ms: {calls}");
1051        assert_eq!(
1052            worker_wakes, 1,
1053            "only the initial recovery should wake the empty worker queue"
1054        );
1055    }
1056
1057    #[tokio::test]
1058    async fn paced_catchup_wakes_waiters_when_no_future_timestamp_remains() {
1059        dotenvy::dotenv().ok();
1060        let Ok(url) = std::env::var("DATABASE_URL") else {
1061            eprintln!("DATABASE_URL not set; skipping catch-up database test");
1062            return;
1063        };
1064        let (pool, gate) = scan_pool(&url, 2).await;
1065        let control = sqlx::postgres::PgPoolOptions::new()
1066            .max_connections(2)
1067            .connect(&url)
1068            .await
1069            .unwrap();
1070        let schema = format!("catchup_{}", uuid::Uuid::new_v4().simple());
1071        let channels = [format!("{schema}_orch"), format!("{schema}_worker")];
1072        let mut listener = subscribe(&pool, &channels).await.unwrap();
1073        let notifications = [Arc::new(Notify::new()), Arc::new(Notify::new())];
1074        let initial_scan = notifications[0].notified();
1075        tokio::pin!(initial_scan);
1076        initial_scan.as_mut().enable();
1077        let task = tokio::spawn({
1078            let pool = pool.clone();
1079            let notifications = notifications.clone();
1080            let channels = channels.clone();
1081            let query = format!(
1082                "SELECT NULL::BIGINT, NULL::BIGINT FROM {MARK_COMPLETED_SCAN} WHERE $1::BIGINT IS NOT NULL"
1083            );
1084            async move {
1085                let mut refresh = TimerRefresh::default();
1086                run_connected(
1087                    &pool,
1088                    &mut listener,
1089                    &channels,
1090                    &notifications,
1091                    &query,
1092                    &LongPollConfig {
1093                        enabled: true,
1094                        ..Default::default()
1095                    },
1096                    &mut refresh,
1097                )
1098                .await
1099            }
1100        });
1101        timeout(Duration::from_secs(3), initial_scan).await.unwrap();
1102        gate.block_next.store(true, Ordering::Relaxed);
1103        sqlx::query("SELECT pg_notify($1, $2)")
1104            .bind(&channels[0])
1105            .bind((PostgresProvider::now_millis() + 50).to_string())
1106            .execute(&control)
1107            .await
1108            .unwrap();
1109        timeout(Duration::from_secs(3), gate.entered.notified())
1110            .await
1111            .unwrap();
1112        // Register after the timer's wake but before its catch-up scan completes.
1113        let notified = notifications[0].notified();
1114        tokio::pin!(notified);
1115        notified.as_mut().enable();
1116        gate.release.notify_waiters();
1117        let wake = timeout(Duration::from_secs(1), notified).await;
1118        let completed: i32 =
1119            sqlx::query_scalar("SELECT current_setting('duroxide_test.completed_scans')::INT")
1120                .fetch_one(&pool)
1121                .await
1122                .unwrap();
1123        task.abort();
1124        assert!(task.await.unwrap_err().is_cancelled());
1125        pool.close().await;
1126        control.close().await;
1127        wake.expect("a catch-up scan must wake work that matured before its snapshot");
1128        assert_eq!(
1129            completed, 2,
1130            "both scans must have committed; idle alone is not success"
1131        );
1132    }
1133
1134    #[tokio::test]
1135    async fn timers_expiring_during_refresh_do_not_hide_the_next_timer() {
1136        dotenvy::dotenv().ok();
1137        let Ok(url) = std::env::var("DATABASE_URL") else {
1138            eprintln!("DATABASE_URL not set; skipping in-flight timer database test");
1139            return;
1140        };
1141        let (pool, gate) = scan_pool(&url, 2).await;
1142        let control = sqlx::postgres::PgPoolOptions::new()
1143            .max_connections(1)
1144            .connect(&url)
1145            .await
1146            .unwrap();
1147        let schema = format!("inflight_timer_{}", uuid::Uuid::new_v4().simple());
1148        sqlx::Executor::execute(
1149            &control,
1150            format!("CREATE SCHEMA {schema}; CREATE TABLE {schema}.deadlines (due BIGINT)")
1151                .as_str(),
1152        )
1153        .await
1154        .unwrap();
1155        let channels = [format!("{schema}_orch"), format!("{schema}_worker")];
1156        let listener = subscribe(&pool, &channels).await.unwrap();
1157        let notifications = [Arc::new(Notify::new()), Arc::new(Notify::new())];
1158        let initial_scan = notifications[0].notified();
1159        tokio::pin!(initial_scan);
1160        initial_scan.as_mut().enable();
1161        let task = tokio::spawn(run(
1162            pool.clone(),
1163            listener,
1164            channels.clone(),
1165            notifications.clone(),
1166            format!(
1167                "SELECT NULL::BIGINT, (SELECT min(due) FROM {schema}.deadlines WHERE due > $1)
1168                     FROM {MARK_COMPLETED_SCAN}"
1169            ),
1170            LongPollConfig {
1171                enabled: true,
1172                timer_grace_period: Duration::ZERO,
1173                ..Default::default()
1174            },
1175        ));
1176        timeout(Duration::from_secs(3), initial_scan).await.unwrap();
1177        gate.block_next.store(true, Ordering::Relaxed);
1178        sqlx::query("SELECT pg_notify($1, $2)")
1179            .bind(&channels[1])
1180            .bind((PostgresProvider::now_millis() + 50).to_string())
1181            .execute(&control)
1182            .await
1183            .unwrap();
1184        timeout(Duration::from_secs(3), gate.entered.notified())
1185            .await
1186            .unwrap();
1187
1188        // Stall acquisition, not a SQL statement subject to the 200ms timeout.
1189        let second = PostgresProvider::now_millis() + 50;
1190        let third = second + 500;
1191        sqlx::query(&format!("INSERT INTO {schema}.deadlines VALUES ($1), ($2)"))
1192            .bind(second)
1193            .bind(third)
1194            .execute(&control)
1195            .await
1196            .unwrap();
1197        sqlx::query("SELECT pg_notify($1, $2), pg_notify($1, $3)")
1198            .bind(&channels[1])
1199            .bind(second.to_string())
1200            .bind(third.to_string())
1201            .execute(&control)
1202            .await
1203            .unwrap();
1204        let wait = |due: i64| {
1205            fetch_with_poll(
1206                Some(notifications[1].as_ref()),
1207                Duration::from_secs(10),
1208                "test",
1209                move || async move { Ok((PostgresProvider::now_millis() >= due).then_some(due)) },
1210            )
1211        };
1212        assert_eq!(
1213            timeout(Duration::from_secs(3), wait(second))
1214                .await
1215                .unwrap()
1216                .unwrap(),
1217            Some(second)
1218        );
1219        gate.release.notify_waiters();
1220        assert!(
1221            PostgresProvider::now_millis() < third,
1222            "register before the final timer matures"
1223        );
1224        let result = timeout(Duration::from_secs(3), wait(third)).await;
1225        let completed: i32 =
1226            sqlx::query_scalar("SELECT current_setting('duroxide_test.completed_scans')::INT")
1227                .fetch_one(&pool)
1228                .await
1229                .unwrap();
1230        task.abort();
1231        assert!(task.await.unwrap_err().is_cancelled());
1232        pool.close().await;
1233        sqlx::query(&format!("DROP SCHEMA {schema} CASCADE"))
1234            .execute(&control)
1235            .await
1236            .unwrap();
1237        control.close().await;
1238        assert_eq!(
1239            result
1240                .expect("the next timer must beat the polling timeout")
1241                .unwrap(),
1242            Some(third)
1243        );
1244        assert!(
1245            completed >= 3,
1246            "the initial, gated, and catch-up scans must commit successfully"
1247        );
1248    }
1249
1250    #[tokio::test]
1251    async fn failed_refresh_retries_before_the_recovery_interval() {
1252        dotenvy::dotenv().ok();
1253        let Ok(url) = std::env::var("DATABASE_URL") else {
1254            eprintln!("DATABASE_URL not set; skipping timer-refresh database test");
1255            return;
1256        };
1257        let (pool, gate) = scan_pool(&url, 2).await;
1258        let schema = format!("failed_scan_{}", uuid::Uuid::new_v4().simple());
1259        let channels = [format!("{schema}_orch"), format!("{schema}_worker")];
1260        let mut listener = subscribe(&pool, &channels).await.unwrap();
1261        gate.calls.store(0, Ordering::Relaxed);
1262        let notifications = [Arc::new(Notify::new()), Arc::new(Notify::new())];
1263        let query = "SELECT $1::BIGINT / 0, NULL::BIGINT";
1264        let mut refresh = TimerRefresh::default();
1265        let result = tokio::time::timeout(
1266            Duration::from_millis(1500),
1267            run_connected(
1268                &pool,
1269                &mut listener,
1270                &channels,
1271                &notifications,
1272                query,
1273                &LongPollConfig {
1274                    enabled: true,
1275                    ..Default::default()
1276                },
1277                &mut refresh,
1278            ),
1279        )
1280        .await;
1281        drop(refresh);
1282        assert!(
1283            result.is_err(),
1284            "the listener should stay connected after a scan error"
1285        );
1286        let calls = gate.calls.load(Ordering::Relaxed);
1287        assert!(refresh_timers(&pool, "SELECT $1::BIGINT, NULL::BIGINT")
1288            .await
1289            .is_ok());
1290        drop(listener);
1291        pool.close().await;
1292        assert!(
1293            calls >= 2,
1294            "a failed scan waited for the 60-second recovery: {calls}"
1295        );
1296    }
1297
1298    #[tokio::test]
1299    async fn subscribing_keeps_a_warm_fetch_connection() {
1300        dotenvy::dotenv().ok();
1301        let Ok(url) = std::env::var("DATABASE_URL") else {
1302            eprintln!("DATABASE_URL not set; skipping listener database test");
1303            return;
1304        };
1305        let pool = sqlx::postgres::PgPoolOptions::new()
1306            .min_connections(1)
1307            .max_connections(2)
1308            .connect(&url)
1309            .await
1310            .unwrap();
1311        let channel = format!("warm_listener_{}", uuid::Uuid::new_v4().simple());
1312        let listener = subscribe(
1313            &pool,
1314            &[format!("{channel}_orch"), format!("{channel}_worker")],
1315        )
1316        .await
1317        .unwrap();
1318        let connections = pool.size();
1319        drop(listener);
1320        pool.close().await;
1321        assert_eq!(connections, 2, "LISTEN must leave another connection warm");
1322    }
1323
1324    #[tokio::test]
1325    async fn watchdog_and_reconnect_keep_the_same_pending_timer_scan() {
1326        dotenvy::dotenv().ok();
1327        let Ok(url) = std::env::var("DATABASE_URL") else {
1328            eprintln!("DATABASE_URL not set; skipping pending-scan database test");
1329            return;
1330        };
1331        let (pool, gate) = scan_pool(&url, 3).await;
1332        let control = sqlx::postgres::PgPoolOptions::new()
1333            .max_connections(2)
1334            .connect(&url)
1335            .await
1336            .unwrap();
1337        let schema = format!("pending_scan_{}", uuid::Uuid::new_v4().simple());
1338        let channels = [format!("{schema}_orch"), format!("{schema}_worker")];
1339        let listener = subscribe(&pool, &channels).await.unwrap();
1340        gate.calls.store(0, Ordering::Relaxed);
1341        let pid: i32 = sqlx::query_scalar(
1342            "SELECT pid FROM pg_stat_activity WHERE query LIKE 'LISTEN%' AND strpos(query, $1) > 0",
1343        )
1344        .bind(&channels[0])
1345        .fetch_one(&control)
1346        .await
1347        .unwrap();
1348        let notifications = [Arc::new(Notify::new()), Arc::new(Notify::new())];
1349        let initial_scan = notifications[0].notified();
1350        tokio::pin!(initial_scan);
1351        initial_scan.as_mut().enable();
1352        let task = tokio::spawn(run(
1353            pool.clone(),
1354            listener,
1355            channels.clone(),
1356            notifications.clone(),
1357            "SELECT NULL::BIGINT, NULL::BIGINT WHERE $1::BIGINT IS NOT NULL".to_string(),
1358            LongPollConfig {
1359                enabled: true,
1360                notifier_poll_interval: Duration::from_millis(50),
1361                ..Default::default()
1362            },
1363        ));
1364        timeout(Duration::from_secs(3), initial_scan).await.unwrap();
1365        gate.block_next.store(true, Ordering::Relaxed);
1366        timeout(Duration::from_secs(3), gate.entered.notified())
1367            .await
1368            .unwrap();
1369        for _ in 0..2 {
1370            timeout(Duration::from_millis(1500), notifications[0].notified())
1371                .await
1372                .expect("the watchdog must wake fetches while a scan is pending");
1373        }
1374        let before_reconnect = gate.calls.load(Ordering::Relaxed);
1375        sqlx::query("SELECT pg_terminate_backend($1)")
1376            .bind(pid)
1377            .execute(&control)
1378            .await
1379            .unwrap();
1380        timeout(Duration::from_secs(3), async {
1381            loop {
1382                let reconnected: bool = sqlx::query_scalar(
1383                    "SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE query LIKE 'LISTEN%' \
1384                     AND strpos(query, $1) > 0 AND pid <> $2)",
1385                )
1386                .bind(&channels[0])
1387                .bind(pid)
1388                .fetch_one(&control)
1389                .await
1390                .unwrap();
1391                if reconnected {
1392                    break;
1393                }
1394                sleep(Duration::from_millis(10)).await;
1395            }
1396        })
1397        .await
1398        .expect("listener must reconnect without replacing the pending scan");
1399        // LISTEN completing is not enough: let the re-entered loop process a
1400        // notification and a subsequent watchdog tick while the scan is gated.
1401        for _ in 0..2 {
1402            timeout(Duration::from_millis(1500), notifications[0].notified())
1403                .await
1404                .unwrap();
1405        }
1406        let after_reconnect = gate.calls.load(Ordering::Relaxed);
1407        gate.release.notify_waiters();
1408        timeout(Duration::from_secs(3), async {
1409            loop {
1410                if gate.calls.load(Ordering::Relaxed) >= 5 {
1411                    break;
1412                }
1413                sleep(Duration::from_millis(10)).await;
1414            }
1415        })
1416        .await
1417        .expect("the original scan must finish before starting the post-reconnect catch-up");
1418        task.abort();
1419        assert!(task.await.unwrap_err().is_cancelled());
1420        timeout(Duration::from_secs(3), pool.close()).await.unwrap();
1421        control.close().await;
1422        assert_eq!(
1423            before_reconnect, 2,
1424            "the watchdog must not replace the blocked scan"
1425        );
1426        assert_eq!(
1427            after_reconnect, 4,
1428            "reconnecting may acquire LISTEN and its warm connection, not another scan"
1429        );
1430    }
1431
1432    #[tokio::test]
1433    async fn fallback_wakes_fetches_while_reconnect_is_pending() {
1434        use std::sync::atomic::AtomicBool;
1435
1436        dotenvy::dotenv().ok();
1437        let Ok(url) = std::env::var("DATABASE_URL") else {
1438            eprintln!("DATABASE_URL not set; skipping reconnect database test");
1439            return;
1440        };
1441        let blocked = Arc::new(AtomicBool::new(false));
1442        let reconnecting = Arc::new(Notify::new());
1443        let release = Arc::new(Notify::new());
1444        let pool = sqlx::postgres::PgPoolOptions::new()
1445            .min_connections(2)
1446            .max_connections(2)
1447            .before_acquire({
1448                let blocked = blocked.clone();
1449                let reconnecting = reconnecting.clone();
1450                let release = release.clone();
1451                move |_, _| {
1452                    let blocked = blocked.clone();
1453                    let reconnecting = reconnecting.clone();
1454                    let release = release.clone();
1455                    Box::pin(async move {
1456                        if blocked.load(Ordering::Relaxed) {
1457                            let released = release.notified();
1458                            tokio::pin!(released);
1459                            released.as_mut().enable();
1460                            reconnecting.notify_one();
1461                            released.await;
1462                        }
1463                        Ok(true)
1464                    })
1465                }
1466            })
1467            .connect(&url)
1468            .await
1469            .unwrap();
1470        let control = sqlx::postgres::PgPoolOptions::new()
1471            .max_connections(1)
1472            .connect(&url)
1473            .await
1474            .unwrap();
1475        let channel = format!("pending_reconnect_{}", uuid::Uuid::new_v4().simple());
1476        let channels = [format!("{channel}_orch"), format!("{channel}_worker")];
1477        let listener = subscribe(&pool, &channels).await.unwrap();
1478        let pid: i32 = sqlx::query_scalar(
1479            "SELECT pid FROM pg_stat_activity WHERE query LIKE 'LISTEN%' AND strpos(query, $1) > 0",
1480        )
1481        .bind(&channels[0])
1482        .fetch_one(&control)
1483        .await
1484        .unwrap();
1485        let notifications = [Arc::new(Notify::new()), Arc::new(Notify::new())];
1486        let initial_scan = notifications[0].notified();
1487        tokio::pin!(initial_scan);
1488        initial_scan.as_mut().enable();
1489        let task = tokio::spawn(run(
1490            pool.clone(),
1491            listener,
1492            channels,
1493            notifications.clone(),
1494            "SELECT NULL::BIGINT, NULL::BIGINT WHERE $1::BIGINT IS NOT NULL".to_string(),
1495            LongPollConfig {
1496                enabled: true,
1497                ..Default::default()
1498            },
1499        ));
1500        tokio::time::timeout(Duration::from_secs(3), initial_scan)
1501            .await
1502            .expect("initial scan must finish");
1503        blocked.store(true, Ordering::Relaxed);
1504        sqlx::query("SELECT pg_terminate_backend($1)")
1505            .bind(pid)
1506            .execute(&control)
1507            .await
1508            .unwrap();
1509        tokio::time::timeout(Duration::from_secs(3), reconnecting.notified())
1510            .await
1511            .expect("reconnect must enter the blocked acquire hook");
1512        let result = tokio::time::timeout(Duration::from_millis(2500), async {
1513            for notify in &notifications {
1514                let calls = AtomicUsize::new(0);
1515                let item =
1516                    fetch_with_poll(Some(notify), Duration::from_secs(10), "test", || async {
1517                        Ok((calls.fetch_add(1, Ordering::Relaxed) != 0).then_some("ready"))
1518                    })
1519                    .await
1520                    .unwrap();
1521                assert_eq!(item, Some("ready"));
1522                assert_eq!(calls.load(Ordering::Relaxed), 2);
1523            }
1524        })
1525        .await;
1526        blocked.store(false, Ordering::Relaxed);
1527        release.notify_waiters();
1528        task.abort();
1529        assert!(task.await.unwrap_err().is_cancelled());
1530        tokio::time::timeout(Duration::from_secs(3), pool.close())
1531            .await
1532            .unwrap();
1533        control.close().await;
1534        result.expect("fallback wakes must continue independently of a pending reconnect");
1535    }
1536
1537    #[tokio::test]
1538    async fn zero_timeout_and_disabled_mode_fetch_once() {
1539        let notify = Notify::new();
1540        for (notify, timeout) in [
1541            (Some(&notify), Duration::ZERO),
1542            (None, Duration::from_secs(30)),
1543        ] {
1544            let result = tokio::time::timeout(
1545                Duration::from_millis(100),
1546                fetch_with_poll(notify, timeout, "test", || async { Ok(None::<()>) }),
1547            )
1548            .await
1549            .expect("short polling must not wait")
1550            .unwrap();
1551            assert!(result.is_none());
1552        }
1553    }
1554
1555    #[tokio::test]
1556    async fn a_claim_completing_after_the_wait_deadline_is_still_returned() {
1557        let notify = Notify::new();
1558        let result = fetch_with_poll(Some(&notify), Duration::from_millis(10), "test", || async {
1559            sleep(Duration::from_millis(30)).await;
1560            Ok(Some("claimed"))
1561        })
1562        .await
1563        .unwrap();
1564        assert_eq!(result, Some("claimed"));
1565    }
1566
1567    #[tokio::test]
1568    async fn fetch_errors_and_invalid_timeout_are_explicit() {
1569        let notify = Notify::new();
1570        let error = fetch_with_poll(Some(&notify), Duration::from_secs(30), "test", || async {
1571            Err::<Option<()>, _>(ProviderError::retryable("test", "unavailable"))
1572        })
1573        .await
1574        .unwrap_err();
1575        assert!(error.is_retryable());
1576        let error = fetch_with_poll(Some(&notify), Duration::MAX, "test", || async {
1577            Ok(None::<()>)
1578        })
1579        .await
1580        .unwrap_err();
1581        assert!(!error.is_retryable());
1582    }
1583}