Skip to main content

uqa_engine/session/
terminations.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Terminating a session after `idle_in_transaction_session_timeout`, `idle_session_timeout` or `transaction_timeout`, as `PostgreSQL` terminates the backend: the session's cancellation token reports the termination to every later check, and the transaction of a session that is idle when its time comes is rolled back at once, which releases its locks.
8
9use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
10use std::sync::Arc;
11use std::time::Duration;
12
13use parking_lot::Mutex;
14use uqa_core::{CancellationReason, ScheduledAction};
15
16use super::Engine;
17
18/// The terminations a session has scheduled for its idle period and its transaction.
19pub(crate) struct SessionTerminations {
20    /// Whether this engine owns the session's idle periods; engines forked to work for a session do not.
21    tracks_idle: bool,
22    /// How many nested holds of the statement gate this engine has.
23    gate_depth: AtomicUsize,
24    /// Counts the session's busy periods, so that a termination scheduled for an idle period that has ended does nothing.
25    busy_epoch: Arc<AtomicU64>,
26    idle: Mutex<Option<ScheduledAction>>,
27    /// The termination scheduled for the open transaction, with the start of the transaction it belongs to.
28    transaction: Mutex<Option<(i64, ScheduledAction)>>,
29}
30
31impl SessionTerminations {
32    pub(crate) fn new(tracks_idle: bool) -> Self {
33        Self {
34            tracks_idle,
35            gate_depth: AtomicUsize::new(0),
36            busy_epoch: Arc::new(AtomicU64::new(0)),
37            idle: Mutex::new(None),
38            transaction: Mutex::new(None),
39        }
40    }
41
42    /// Note one more hold of the statement gate; `true` when it is the outermost, which begins a busy period.
43    pub(crate) fn enter_gate(&self) -> bool {
44        self.tracks_idle && self.gate_depth.fetch_add(1, Ordering::AcqRel) == 0
45    }
46
47    /// Note the release of a hold of the statement gate; `true` when it was the outermost, which begins an idle period.
48    pub(crate) fn leave_gate(&self) -> bool {
49        self.tracks_idle && self.gate_depth.fetch_sub(1, Ordering::AcqRel) == 1
50    }
51
52    /// Whether no operation holds the statement gate, so that the session is idle.
53    pub(crate) fn is_idle(&self) -> bool {
54        self.gate_depth.load(Ordering::Acquire) == 0
55    }
56
57    /// Cancel every scheduled termination, as closing the session does.
58    pub(crate) fn disarm(&self) {
59        *self.idle.lock() = None;
60        *self.transaction.lock() = None;
61    }
62}
63
64/// What a scheduled termination must still find when its time comes for it to apply.
65enum TerminationScope {
66    /// The idle period it was scheduled for, which ends when the session is busy again.
67    IdlePeriod {
68        epoch: Arc<AtomicU64>,
69        expected: u64,
70    },
71    /// The transaction that began at this time (microseconds since the epoch), as long as it stays the session's outermost transaction; a statement outside a transaction block has none, and its termination is canceled when it ends.
72    Transaction { started: i64, explicit: bool },
73}
74
75/// A timeout of the session in milliseconds, or `None` for `0`.
76fn timeout(engine: &Engine, name: &str) -> Option<Duration> {
77    let milliseconds = engine.session.setting(name).parse::<u64>().ok()?;
78    (milliseconds != 0).then(|| Duration::from_millis(milliseconds))
79}
80
81impl Engine {
82    /// A busy period begins: the idle termination no longer applies, and a statement outside a transaction block starts the transaction that `transaction_timeout` limits.
83    pub(crate) fn session_became_busy(&self) {
84        let terminations = &self.runtime.terminations;
85        terminations.busy_epoch.fetch_add(1, Ordering::AcqRel);
86        *terminations.idle.lock() = None;
87        if self.transaction_depth() == 0 {
88            self.schedule_transaction_termination(uqa_sql::expr::clock_timestamp_micros());
89        }
90    }
91
92    /// An idle period begins: a terminated session finishes its termination, and otherwise the idle and transaction terminations that apply to it are scheduled.
93    pub(crate) fn session_became_idle(&self) {
94        if self.runtime.cancellation.termination().is_some() {
95            self.session_terminator_engine()
96                .finish_session_termination();
97            return;
98        }
99        let transaction_start = self
100            .session
101            .transactions
102            .lock()
103            .first()
104            .map(|frame| frame.started_at_micros);
105        let (name, reason) = if let Some(started) = transaction_start {
106            self.schedule_transaction_termination(started);
107            (
108                "idle_in_transaction_session_timeout",
109                CancellationReason::IdleInTransactionSessionTimeout,
110            )
111        } else {
112            *self.runtime.terminations.transaction.lock() = None;
113            (
114                "idle_session_timeout",
115                CancellationReason::IdleSessionTimeout,
116            )
117        };
118        let Some(after) = timeout(self, name) else {
119            return;
120        };
121        let epoch = Arc::clone(&self.runtime.terminations.busy_epoch);
122        let expected = epoch.load(Ordering::Acquire);
123        let action =
124            self.termination_action(reason, TerminationScope::IdlePeriod { epoch, expected });
125        *self.runtime.terminations.idle.lock() = Some(uqa_core::cancel::schedule(after, action));
126    }
127
128    /// Schedule the termination of the transaction that began at `started` (microseconds since the epoch) once it outlasts `transaction_timeout`, unless one is already scheduled for it.
129    fn schedule_transaction_termination(&self, started: i64) {
130        let mut scheduled = self.runtime.terminations.transaction.lock();
131        if scheduled
132            .as_ref()
133            .is_some_and(|(start, _)| *start == started)
134        {
135            return;
136        }
137        *scheduled = None;
138        let Some(limit) = timeout(self, "transaction_timeout") else {
139            return;
140        };
141        let elapsed = uqa_sql::expr::clock_timestamp_micros().saturating_sub(started);
142        let elapsed = Duration::from_micros(u64::try_from(elapsed).unwrap_or(0));
143        let explicit = self.transaction_depth() != 0;
144        let action = self.termination_action(
145            CancellationReason::TransactionTimeout,
146            TerminationScope::Transaction { started, explicit },
147        );
148        *scheduled = Some((
149            started,
150            uqa_core::cancel::schedule(limit.saturating_sub(elapsed), action),
151        ));
152    }
153
154    /// The action that terminates the session for `reason`: it terminates the session's token, which ends a running statement, and rolls back the transaction of a session that is idle on a thread of its own. It does nothing once `scope` has ended.
155    fn termination_action(
156        &self,
157        reason: CancellationReason,
158        scope: TerminationScope,
159    ) -> impl FnOnce() + Send + 'static {
160        let token = self.runtime.cancellation.clone();
161        let terminator = self.session_terminator_engine();
162        move || {
163            let applies = match &scope {
164                TerminationScope::IdlePeriod { epoch, expected } => {
165                    epoch.load(Ordering::Acquire) == *expected
166                }
167                TerminationScope::Transaction { started, explicit } => {
168                    !*explicit
169                        || terminator
170                            .session
171                            .transactions
172                            .lock()
173                            .first()
174                            .is_some_and(|frame| frame.started_at_micros == *started)
175                }
176            };
177            if !applies {
178                return;
179            }
180            token.cancel_with(reason);
181            // Without a thread of its own the termination still holds: the session finishes it when its owner next uses it.
182            let _ = std::thread::Builder::new()
183                .name("uqa-session-termination".into())
184                .spawn(move || terminator.terminate_idle_session());
185        }
186    }
187
188    /// Roll back the transaction of a terminated session that is idle; a session that is busy finishes its own termination when its statement ends.
189    fn terminate_idle_session(&self) {
190        let Some(_statement) = self.runtime.statement_gate.try_lock() else {
191            return;
192        };
193        self.finish_session_termination();
194    }
195
196    /// Roll back every transaction frame of the terminated session and drop what it holds, once, as the backend's exit does.
197    fn finish_session_termination(&self) {
198        if self
199            .session
200            .termination_finished
201            .swap(true, Ordering::AcqRel)
202        {
203            return;
204        }
205        while self.transaction_depth() != 0 {
206            if self.rollback().is_err() {
207                break;
208            }
209        }
210        let _ = self.clear_notification_listener_without_transaction();
211        self.release_automatic_statistics_client();
212    }
213
214    /// An engine that works for this session on another thread: it shares the session, its storage, its locks and its statement gate, holds a token of its own, and tracks no idle periods.
215    fn session_terminator_engine(&self) -> Engine {
216        let mut epochs = crate::EpochCoordinator::new();
217        epochs.share_published_from(&self.epochs);
218        let mut runtime = crate::QueryRuntime::new(
219            self.sql_function_depth_limit(),
220            self.session.state.client_level(),
221        );
222        runtime.diagnostics = self.runtime.diagnostics.fork();
223        runtime.statement_gate = Arc::clone(&self.runtime.statement_gate);
224        runtime.notices = Arc::clone(&self.runtime.notices);
225        runtime.notifications = Arc::clone(&self.runtime.notifications);
226        runtime.terminations = SessionTerminations::new(false);
227        Engine {
228            storage: crate::StorageContext::shared_from(&self.storage),
229            durable: Arc::clone(&self.durable),
230            session: Arc::clone(&self.session),
231            extensions: crate::RuntimeExtensions::shared_from(&self.extensions),
232            epochs,
233            runtime,
234            row_locks: Arc::clone(&self.row_locks),
235            statistics: Arc::clone(&self.statistics),
236            notification_hub: Arc::clone(&self.notification_hub),
237            session_id: self.session_id,
238            owns_session_registration: false,
239            query_table_snapshots: None,
240            query_view_snapshots: None,
241            query_sql_function_snapshots: None,
242            query_catalog_snapshot: None,
243            query_transaction_overlay: None,
244            query_transaction_origin: None,
245        }
246    }
247
248    /// The error that terminated this session, if a session timeout did; every later statement reports it, and a server closes the connection after sending it at `FATAL`.
249    pub fn session_termination(&self) -> Option<uqa_sql::SQLError> {
250        self.runtime
251            .cancellation
252            .termination()
253            .map(|reason| uqa_core::QueryCancelled::new(reason).into())
254    }
255}