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    scheduled: Arc<ScheduledTerminations>,
27}
28
29#[derive(Default)]
30struct ScheduledTerminations {
31    idle: Mutex<Option<ScheduledAction>>,
32    /// The termination scheduled for the open transaction, with the start of the transaction it belongs to.
33    transaction: Mutex<Option<(i64, ScheduledAction)>>,
34}
35
36impl SessionTerminations {
37    pub(crate) fn new(tracks_idle: bool) -> Self {
38        Self {
39            tracks_idle,
40            gate_depth: AtomicUsize::new(0),
41            busy_epoch: Arc::new(AtomicU64::new(0)),
42            scheduled: Arc::new(ScheduledTerminations::default()),
43        }
44    }
45
46    /// The termination worker retires the owning session's timers without tracking another idle period.
47    fn for_termination(&self) -> Self {
48        Self {
49            tracks_idle: false,
50            gate_depth: AtomicUsize::new(0),
51            busy_epoch: Arc::clone(&self.busy_epoch),
52            scheduled: Arc::clone(&self.scheduled),
53        }
54    }
55
56    /// Note one more hold of the statement gate; `true` when it is the outermost, which begins a busy period.
57    pub(crate) fn enter_gate(&self) -> bool {
58        self.tracks_idle && self.gate_depth.fetch_add(1, Ordering::AcqRel) == 0
59    }
60
61    /// Note the release of a hold of the statement gate; `true` when it was the outermost, which begins an idle period.
62    pub(crate) fn leave_gate(&self) -> bool {
63        self.tracks_idle && self.gate_depth.fetch_sub(1, Ordering::AcqRel) == 1
64    }
65
66    /// Whether no operation holds the statement gate, so that the session is idle.
67    pub(crate) fn is_idle(&self) -> bool {
68        self.gate_depth.load(Ordering::Acquire) == 0
69    }
70
71    /// Cancel every scheduled termination, as closing the session does.
72    pub(crate) fn disarm(&self) {
73        *self.scheduled.idle.lock() = None;
74        *self.scheduled.transaction.lock() = None;
75    }
76}
77
78/// What a scheduled termination must still find when its time comes for it to apply.
79enum TerminationScope {
80    /// The idle period it was scheduled for, which ends when the session is busy again.
81    IdlePeriod {
82        epoch: Arc<AtomicU64>,
83        expected: u64,
84    },
85    /// 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.
86    Transaction { started: i64, explicit: bool },
87}
88
89/// A timeout of the session in milliseconds, or `None` for `0`.
90fn timeout(engine: &Engine, name: &str) -> Option<Duration> {
91    let milliseconds = engine.session.setting(name).parse::<u64>().ok()?;
92    (milliseconds != 0).then(|| Duration::from_millis(milliseconds))
93}
94
95impl Engine {
96    /// A busy period begins: the idle termination no longer applies, and a statement outside a transaction block starts the transaction that `transaction_timeout` limits.
97    pub(crate) fn session_became_busy(&self) {
98        if !self.session.closure.is_open() {
99            return;
100        }
101        let terminations = &self.runtime.terminations;
102        terminations.busy_epoch.fetch_add(1, Ordering::AcqRel);
103        *terminations.scheduled.idle.lock() = None;
104        if self.transaction_depth() == 0 {
105            self.schedule_transaction_termination(uqa_sql::expr::clock_timestamp_micros());
106        }
107    }
108
109    /// An idle period begins: a terminated session finishes its termination, and otherwise the idle and transaction terminations that apply to it are scheduled.
110    pub(crate) fn session_became_idle(&self) {
111        if !self.session.closure.is_open() {
112            return;
113        }
114        if self.runtime.cancellation.termination().is_some() {
115            self.session_terminator_engine()
116                .finish_session_termination();
117            return;
118        }
119        let transaction_start = self
120            .session
121            .transactions
122            .lock()
123            .first()
124            .map(|frame| frame.started_at_micros);
125        let (name, reason) = if let Some(started) = transaction_start {
126            self.schedule_transaction_termination(started);
127            (
128                "idle_in_transaction_session_timeout",
129                CancellationReason::IdleInTransactionSessionTimeout,
130            )
131        } else {
132            *self.runtime.terminations.scheduled.transaction.lock() = None;
133            (
134                "idle_session_timeout",
135                CancellationReason::IdleSessionTimeout,
136            )
137        };
138        let Some(after) = timeout(self, name) else {
139            return;
140        };
141        let epoch = Arc::clone(&self.runtime.terminations.busy_epoch);
142        let expected = epoch.load(Ordering::Acquire);
143        let action =
144            self.termination_action(reason, TerminationScope::IdlePeriod { epoch, expected });
145        *self.runtime.terminations.scheduled.idle.lock() =
146            Some(self.runtime.cancellation.schedule(after, action));
147    }
148
149    /// 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.
150    fn schedule_transaction_termination(&self, started: i64) {
151        let mut scheduled = self.runtime.terminations.scheduled.transaction.lock();
152        if scheduled
153            .as_ref()
154            .is_some_and(|(start, _)| *start == started)
155        {
156            return;
157        }
158        *scheduled = None;
159        let Some(limit) = timeout(self, "transaction_timeout") else {
160            return;
161        };
162        let elapsed = uqa_sql::expr::clock_timestamp_micros().saturating_sub(started);
163        let elapsed = Duration::from_micros(u64::try_from(elapsed).unwrap_or(0));
164        let explicit = self.transaction_depth() != 0;
165        let action = self.termination_action(
166            CancellationReason::TransactionTimeout,
167            TerminationScope::Transaction { started, explicit },
168        );
169        *scheduled = Some((
170            started,
171            self.runtime
172                .cancellation
173                .schedule(limit.saturating_sub(elapsed), action),
174        ));
175    }
176
177    /// 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.
178    fn termination_action(
179        &self,
180        reason: CancellationReason,
181        scope: TerminationScope,
182    ) -> impl FnOnce() + Send + 'static {
183        let token = self.runtime.cancellation.clone();
184        let terminator = self.session_terminator_engine();
185        move || {
186            if !terminator.session.closure.is_open() {
187                return;
188            }
189            let applies = match &scope {
190                TerminationScope::IdlePeriod { epoch, expected } => {
191                    epoch.load(Ordering::Acquire) == *expected
192                }
193                TerminationScope::Transaction { started, explicit } => {
194                    !*explicit
195                        || terminator
196                            .session
197                            .transactions
198                            .lock()
199                            .first()
200                            .is_some_and(|frame| frame.started_at_micros == *started)
201                }
202            };
203            if !applies {
204                return;
205            }
206            token.cancel_with(reason);
207            // Without a thread of its own the termination still holds: the session finishes it when its owner next uses it.
208            let _ = std::thread::Builder::new()
209                .name("uqa-session-termination".into())
210                .spawn(move || terminator.terminate_idle_session());
211        }
212    }
213
214    /// Roll back the transaction of a terminated session that is idle; a session that is busy finishes its own termination when its statement ends.
215    fn terminate_idle_session(&self) {
216        let Some(_statement) = self.runtime.statement_gate.try_lock() else {
217            return;
218        };
219        self.finish_session_termination();
220    }
221
222    /// Roll back every transaction frame of the terminated session and drop what it holds, once, as the backend's exit does.
223    fn finish_session_termination(&self) {
224        let _ = self.close_terminated_session();
225    }
226
227    /// Finalize the same session on another thread, retaining its transaction, catalog epochs, cancellation signal and scheduled timers. Cleanup defers cancellation only while it holds the statement gate and tracks no idle periods.
228    fn session_terminator_engine(&self) -> Engine {
229        let mut runtime = crate::QueryRuntime::with_cancellation(
230            self.sql_function_depth_limit(),
231            self.runtime.cancellation.clone(),
232            self.session.state.client_level(),
233            self.session.state.io_timing(),
234        );
235        runtime.function_context = std::sync::Arc::clone(&self.runtime.function_context);
236        runtime.diagnostics = self.runtime.diagnostics.fork();
237        runtime.statement_gate = Arc::clone(&self.runtime.statement_gate);
238        runtime.notices = Arc::clone(&self.runtime.notices);
239        runtime.notifications = Arc::clone(&self.runtime.notifications);
240        runtime.notification_wake = Arc::clone(&self.runtime.notification_wake);
241        runtime.terminations = self.runtime.terminations.for_termination();
242        Engine {
243            storage: crate::StorageContext::shared_from(&self.storage),
244            durable: Arc::clone(&self.durable),
245            session: Arc::clone(&self.session),
246            extensions: crate::RuntimeExtensions::shared_from(&self.extensions),
247            epochs: Arc::clone(&self.epochs),
248            runtime,
249            row_locks: Arc::clone(&self.row_locks),
250            statistics: Arc::clone(&self.statistics),
251            notification_hub: Arc::clone(&self.notification_hub),
252            session_id: self.session_id,
253            owns_session_registration: false,
254            query_table_snapshots: None,
255            query_view_snapshots: None,
256            query_sql_function_snapshots: None,
257            query_catalog_snapshot: None,
258            query_transaction_overlay: None,
259            query_transaction_origin: None,
260        }
261    }
262
263    /// 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`.
264    pub fn session_termination(&self) -> Option<uqa_sql::SQLError> {
265        self.runtime
266            .cancellation
267            .termination()
268            .map(|reason| uqa_core::QueryCancelled::new(reason).into())
269    }
270}