Skip to main content

uqa_execution/row_locks/
changes.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Row-change observation, resolution, and publication.
8
9use super::{
10    cross_process, mutation_strength, normalize_pending_row_changes, remove_inactive_versions,
11    resolve_local_change_target, row_has_waiter, table_hash, Arc, CrossAttachment, DocId,
12    LockStrength, RowLockKey, RowLockManager, SQLError,
13};
14
15#[derive(Clone, Default)]
16pub struct RowChangeBaseline {
17    pub epoch: u64,
18    pub cross_sequence: u64,
19    pub(super) _retention: Option<Arc<cross_process::JournalReadLease>>,
20    pub(super) _manager: Option<Arc<RowLockManager>>,
21}
22
23impl std::fmt::Debug for RowChangeBaseline {
24    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25        formatter
26            .debug_struct("RowChangeBaseline")
27            .field("epoch", &self.epoch)
28            .field("cross_sequence", &self.cross_sequence)
29            .finish_non_exhaustive()
30    }
31}
32
33impl PartialEq for RowChangeBaseline {
34    fn eq(&self, other: &Self) -> bool {
35        self.epoch == other.epoch && self.cross_sequence == other.cross_sequence
36    }
37}
38impl Eq for RowChangeBaseline {}
39
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub struct PendingRowChange {
42    pub key: RowLockKey,
43    pub kind: PendingRowChangeKind,
44}
45
46#[derive(Clone, Copy, Debug, PartialEq, Eq)]
47pub enum PendingRowChangeKind {
48    Insert,
49    Update,
50    Delete,
51    Rewrite(RowLockKey),
52}
53
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55pub enum RowChangeTarget {
56    Unchanged,
57    Present(DocId),
58    Deleted,
59}
60
61#[derive(Clone, Copy, Debug)]
62pub(super) struct CommittedRowChange {
63    pub(super) epoch: u64,
64    pub(super) key: RowLockKey,
65    pub(super) kind: CommittedRowChangeKind,
66    pub(super) strength: LockStrength,
67}
68
69#[derive(Clone, Copy, Debug)]
70pub(super) enum CommittedRowChangeKind {
71    Update,
72    Delete,
73    Rewrite(RowLockKey),
74}
75
76pub struct RowChangeObservation {
77    manager: Arc<RowLockManager>,
78}
79
80impl Drop for RowChangeObservation {
81    fn drop(&mut self) {
82        self.manager.end_change_observation();
83    }
84}
85
86impl RowLockManager {
87    pub fn begin_change_observation(self: &Arc<Self>) -> RowChangeObservation {
88        self.state.lock().active_change_observers += 1;
89        RowChangeObservation {
90            manager: Arc::clone(self),
91        }
92    }
93
94    fn end_change_observation(&self) {
95        let mut state = self.state.lock();
96        state.active_change_observers = state.active_change_observers.saturating_sub(1);
97        remove_inactive_versions(&mut state);
98    }
99
100    pub fn current_change_epoch(&self) -> u64 {
101        self.state.lock().change_epoch
102    }
103
104    #[cfg(test)]
105    pub fn current_row_version(&self, table: &str, doc_id: DocId) -> u64 {
106        let key = RowLockKey {
107            table: self.table_key(table),
108            doc_id,
109        };
110        self.state
111            .lock()
112            .changes
113            .iter()
114            .rev()
115            .find(|change| change.key == key)
116            .map_or(0, |change| change.epoch)
117    }
118
119    pub fn conflicting_change_target_after(
120        &self,
121        table: &str,
122        doc_id: DocId,
123        baseline: &RowChangeBaseline,
124        wanted: LockStrength,
125    ) -> Result<RowChangeTarget, SQLError> {
126        let key = RowLockKey {
127            table: self.table_key(table),
128            doc_id,
129        };
130        if let Some(CrossAttachment::Active(coordinator)) = self.cross.as_ref() {
131            return coordinator
132                .change_target_after(
133                    table_hash(table.as_bytes()),
134                    doc_id,
135                    baseline.cross_sequence,
136                    wanted,
137                )
138                .map_err(SQLError::Internal);
139        }
140        Ok(resolve_local_change_target(
141            &self.state.lock().changes,
142            key,
143            baseline.epoch,
144            wanted,
145        ))
146    }
147
148    /// Follow committed primary-key rewrites from `doc_id` to the final identity, considering only rewrites newer than the statement snapshot. This prevents an old update chain from attaching to a later row that reused the same primary key.
149    pub fn row_successor_after(
150        &self,
151        table: &str,
152        doc_id: DocId,
153        baseline: &RowChangeBaseline,
154    ) -> Result<RowChangeTarget, SQLError> {
155        let key = RowLockKey {
156            table: self.table_key(table),
157            doc_id,
158        };
159        if let Some(CrossAttachment::Active(coordinator)) = self.cross.as_ref() {
160            return coordinator
161                .change_target_after(
162                    table_hash(table.as_bytes()),
163                    doc_id,
164                    baseline.cross_sequence,
165                    LockStrength::ForUpdate,
166                )
167                .map_err(SQLError::Internal);
168        }
169        Ok(resolve_local_change_target(
170            &self.state.lock().changes,
171            key,
172            baseline.epoch,
173            LockStrength::ForUpdate,
174        ))
175    }
176
177    pub fn publish_row_changes(
178        &self,
179        session_id: u64,
180        changes: impl IntoIterator<Item = PendingRowChange>,
181    ) -> Result<(), SQLError> {
182        let changes = normalize_pending_row_changes(changes);
183        if changes.is_empty() {
184            return Ok(());
185        }
186        let mut state = self.state.lock();
187        state.change_epoch = state.change_epoch.wrapping_add(1);
188        let change_epoch = state.change_epoch;
189        let committed = changes
190            .into_iter()
191            .filter_map(|change| {
192                let kind = match change.kind {
193                    PendingRowChangeKind::Insert => return None,
194                    PendingRowChangeKind::Update => CommittedRowChangeKind::Update,
195                    PendingRowChangeKind::Delete => CommittedRowChangeKind::Delete,
196                    PendingRowChangeKind::Rewrite(successor) => {
197                        CommittedRowChangeKind::Rewrite(successor)
198                    }
199                };
200                let strength = match kind {
201                    CommittedRowChangeKind::Rewrite(_) | CommittedRowChangeKind::Delete => {
202                        LockStrength::ForUpdate
203                    }
204                    CommittedRowChangeKind::Update => {
205                        mutation_strength(&state, session_id, change.key)
206                    }
207                };
208                Some(CommittedRowChange {
209                    epoch: change_epoch,
210                    key: change.key,
211                    kind,
212                    strength,
213                })
214            })
215            .collect::<Vec<_>>();
216        let publication_result = if let Some(CrossAttachment::Active(coordinator)) =
217            self.cross.as_ref()
218        {
219            let published = committed
220                .iter()
221                .map(|change| cross_process::PublishedRowChange {
222                    table_hash: table_hash(&self.relation_bytes(change.key.table)),
223                    doc_id: change.key.doc_id,
224                    kind: match change.kind {
225                        CommittedRowChangeKind::Update => {
226                            cross_process::PublishedRowChangeKind::Update
227                        }
228                        CommittedRowChangeKind::Delete => {
229                            cross_process::PublishedRowChangeKind::Delete
230                        }
231                        CommittedRowChangeKind::Rewrite(successor) => {
232                            cross_process::PublishedRowChangeKind::Rewrite(
233                                cross_process::PublishedRowIdentity {
234                                    table_hash: table_hash(&self.relation_bytes(successor.table)),
235                                    doc_id: successor.doc_id,
236                                },
237                            )
238                        }
239                    },
240                    strength: change.strength,
241                })
242                .collect::<Vec<_>>();
243            coordinator
244                .publish_changes(&published)
245                .map_err(SQLError::Internal)
246        } else {
247            Ok(())
248        };
249        for change in committed {
250            let key = change.key;
251            if state.active_change_observers != 0
252                || state.rows.contains_key(&key)
253                || row_has_waiter(&state, key)
254            {
255                state.changes.push(change);
256            }
257        }
258        publication_result
259    }
260}