Skip to main content

uqa_execution/row_locks/
grants.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! In-process row grant table and tuple-lock conflict rules.
8
9use super::{
10    AtomicU64, ByteClaim, CommittedRowChange, HashMap, LockStrength, Ordering, RelationLockGrant,
11    RelationLockMode, RowLockKey,
12};
13
14#[derive(Clone, Debug)]
15pub(super) struct LockGrant {
16    pub(super) session_id: u64,
17    pub(super) identity: Option<super::KeyReservationIdentity>,
18    pub(super) acquisitions: Vec<MarkedStrength>,
19}
20
21#[derive(Clone, Copy, Debug)]
22pub(super) struct MarkedStrength {
23    pub(super) acquisition_id: u64,
24    pub(super) strength: LockStrength,
25    pub(super) mark: u32,
26}
27
28impl LockGrant {
29    pub(super) fn effective_strength(&self) -> LockStrength {
30        self.acquisitions
31            .iter()
32            .map(|acquisition| acquisition.strength)
33            .max()
34            .expect("row-lock grant must retain an acquisition")
35    }
36}
37
38pub(super) struct LockTable {
39    pub(super) rows: HashMap<RowLockKey, Vec<LockGrant>>,
40    pub(super) waiting: HashMap<u64, HashMap<RowLockKey, LockStrength>>,
41    pub(super) relations: HashMap<u64, Vec<RelationLockGrant>>,
42    pub(super) waiting_relations: HashMap<u64, HashMap<u64, RelationLockMode>>,
43    /// The sidecar byte each local session is currently blocked on, whether its immediate holder is local or foreign. Publishing local edges lets another process walk mixed local/cross-process deadlock cycles.
44    pub(super) advertised_waits: HashMap<u64, ByteClaim>,
45    pub(super) changes: Vec<CommittedRowChange>,
46    pub(super) change_epoch: u64,
47    pub(super) active_change_observers: usize,
48}
49
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51pub enum LockAcquire {
52    Granted {
53        waited: bool,
54        /// Whether this acquisition waited for a conflicting holder in another OS process. Cross-process commits are invisible to the in-process change epochs, so the lock consumer rechecks such candidates against the latest committed row images.
55        foreign_waited: bool,
56        acquisition: Option<RowLockAcquisition>,
57    },
58    Skipped,
59}
60
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62pub struct RowLockAcquisition {
63    pub(super) session_id: u64,
64    pub(super) key: RowLockKey,
65    pub(super) acquisition_id: u64,
66}
67
68pub(super) enum GrantAttempt {
69    Conflict,
70    Granted(Option<RowLockAcquisition>),
71}
72
73pub struct LockRequest<'a> {
74    pub session_id: u64,
75    pub key: RowLockKey,
76    pub strength: LockStrength,
77    pub mark: u32,
78    pub wait: uqa_sql::ast::LockWait,
79    pub cancel: &'a uqa_core::CancellationToken,
80    pub relation: &'a str,
81}
82
83/// Undo one just-granted row acquisition whose cross-process claim failed.
84pub(super) fn rollback_grant(state: &mut LockTable, acquisition: RowLockAcquisition) {
85    if let Some(grants) = state.rows.get_mut(&acquisition.key) {
86        grants.retain_mut(|grant| {
87            if grant.session_id == acquisition.session_id {
88                grant
89                    .acquisitions
90                    .retain(|marked| marked.acquisition_id != acquisition.acquisition_id);
91            }
92            !grant.acquisitions.is_empty()
93        });
94        if grants.is_empty() {
95            state.rows.remove(&acquisition.key);
96        }
97    }
98}
99
100pub(super) fn try_grant(
101    state: &mut LockTable,
102    request: &LockRequest<'_>,
103    next_acquisition: &AtomicU64,
104    identity: Option<&super::KeyReservationIdentity>,
105) -> GrantAttempt {
106    let LockRequest {
107        session_id,
108        key,
109        strength,
110        mark,
111        ..
112    } = *request;
113    let grants = state.rows.entry(key).or_default();
114    if grants.iter().any(|grant| {
115        grant.session_id != session_id
116            && lock_strengths_conflict(grant.effective_strength(), strength)
117    }) {
118        return GrantAttempt::Conflict;
119    }
120    if let Some(existing) = grants
121        .iter_mut()
122        .find(|grant| grant.session_id == session_id)
123    {
124        if strength <= existing.effective_strength() {
125            return GrantAttempt::Granted(None);
126        }
127        let acquisition_id = next_acquisition.fetch_add(1, Ordering::Relaxed);
128        existing.acquisitions.push(MarkedStrength {
129            acquisition_id,
130            strength,
131            mark,
132        });
133        return GrantAttempt::Granted(Some(RowLockAcquisition {
134            session_id,
135            key,
136            acquisition_id,
137        }));
138    }
139    let acquisition_id = next_acquisition.fetch_add(1, Ordering::Relaxed);
140    grants.push(LockGrant {
141        session_id,
142        identity: identity.cloned(),
143        acquisitions: vec![MarkedStrength {
144            acquisition_id,
145            strength,
146            mark,
147        }],
148    });
149    GrantAttempt::Granted(Some(RowLockAcquisition {
150        session_id,
151        key,
152        acquisition_id,
153    }))
154}
155
156pub fn lock_strengths_conflict(left: LockStrength, right: LockStrength) -> bool {
157    if left == LockStrength::ForUpdate || right == LockStrength::ForUpdate {
158        return true;
159    }
160    if left == LockStrength::ForKeyShare || right == LockStrength::ForKeyShare {
161        return false;
162    }
163    matches!(
164        (left, right),
165        (
166            LockStrength::ForShare | LockStrength::ForNoKeyUpdate,
167            LockStrength::ForNoKeyUpdate
168        ) | (LockStrength::ForNoKeyUpdate, LockStrength::ForShare)
169    )
170}