kovan_stm/transaction.rs
1use super::node::StmNode;
2use super::var::TVarInner;
3use super::{Stm, StmError, TVar};
4use alloc::boxed::Box;
5use kovan::{Guard, Shared, alloc_node, retire_node};
6use std::any::Any;
7use std::collections::BTreeMap;
8use std::sync::Arc;
9use std::sync::atomic::Ordering;
10
11// See `var.rs`: must resolve to the identical concrete type as
12// `TVarInner::version_lock`, since `lock_atomic` below is a raw pointer to
13// that same field.
14#[cfg(feature = "shuttle")]
15use shuttle::sync::atomic::AtomicU64;
16#[cfg(not(feature = "shuttle"))]
17use std::sync::atomic::AtomicU64;
18
19/// Unique ID for a TVar (memory address) to sort locks.
20type TVarId = usize;
21
22/// Internal entry for the Read Set.
23#[derive(Clone)]
24struct ReadEntry {
25 /// The version of the TVar observed when reading.
26 version: u64,
27 /// Store the pointer to the `AtomicU64` directly
28 lock_atomic: *const AtomicU64,
29 // NOTE: back in times I used OCC style, then switched to locking.
30 // Maybe I will just use that over all `*Entry` types later.
31 /// An `Arc` clone that keeps the `TVarInner` (and thus
32 /// `version_lock`) alive for the entire lifetime of this read entry.
33 _keep_alive: Arc<dyn Any + Send + Sync>,
34}
35
36/// A value a transaction stores in one variable, published at commit.
37///
38/// Type erasure lets one write set hold the writes of variables of different types. The
39/// entry owns the value until commit moves it into the node it publishes, or until the
40/// transaction rolls back and drops it: either way the value is dropped exactly once.
41trait PendingWrite: Send {
42 /// The value, for the transaction's own reads of the variable.
43 fn value(&self) -> &dyn Any;
44 /// The variable's version lock.
45 fn lock(&self) -> &AtomicU64;
46 /// Publishes the value in a new node, retires the node it replaces, and releases the
47 /// variable's lock with `version`.
48 fn commit(self: Box<Self>, version: u64);
49}
50
51/// The [`PendingWrite`] of a variable of `T`. Holding the variable's `Arc` keeps its
52/// `version_lock` and `data` alive until the commit, even if every `TVar` handle is gone.
53struct Write<T: Send + Sync + 'static> {
54 var: Arc<TVarInner<T>>,
55 value: T,
56}
57
58impl<T: Any + Send + Sync + 'static> PendingWrite for Write<T> {
59 fn value(&self) -> &dyn Any {
60 &self.value
61 }
62
63 fn lock(&self) -> &AtomicU64 {
64 &self.var.version_lock
65 }
66
67 fn commit(self: Box<Self>, version: u64) {
68 let Write { var, value } = *self;
69 let node = alloc_node(StmNode::new(value));
70 let guard = kovan::pin();
71 // SAFETY: a fresh node, published here once.
72 let old = var
73 .data
74 .swap(unsafe { Shared::from_raw(node) }, Ordering::AcqRel, &guard);
75 if !old.is_null() {
76 // SAFETY: unlinked by the swap, which only this committer (holding the
77 // variable's lock) makes; every node of `data` comes from `alloc_node`, and
78 // `StmNode` is #[repr(C)] with its RetiredNode at offset 0.
79 unsafe { retire_node(old.as_raw()) };
80 }
81 // Release: a reader that sees the new version sees the new node.
82 var.version_lock.store(version, Ordering::Release);
83 }
84}
85
86type WriteEntry = Box<dyn PendingWrite>;
87
88/// Clear the lock bit of every entry an aborting commit locked, leaving each version as it was.
89fn unlock<'e>(locked: impl Iterator<Item = &'e WriteEntry>) {
90 for entry in locked {
91 entry.lock().fetch_and(!1, Ordering::Release);
92 }
93}
94
95/// Representation of a transaction in STM.
96pub struct Transaction<'a> {
97 stm: &'a Stm,
98 guard: &'a Guard,
99 /// Timestamp at the start of the transaction.
100 read_version: u64,
101 /// Map of TVar address -> Read Record.
102 read_set: BTreeMap<TVarId, ReadEntry>,
103 /// Map of TVar address -> Write Record.
104 write_set: BTreeMap<TVarId, WriteEntry>, // BTreeMap for deterministic locking order
105 /// Side effects to run only after a successful commit.
106 post_commit_hooks: Vec<Box<dyn FnOnce() + Send>>,
107 /// Side effects to run only if the transaction aborts/rolls back.
108 post_rollback_hooks: Vec<Box<dyn FnOnce() + Send>>,
109 /// Tracks if the transaction committed successfully to prevent rollback hooks in Drop.
110 committed: bool,
111}
112
113impl<'a> Drop for Transaction<'a> {
114 fn drop(&mut self) {
115 if !self.committed {
116 // Transaction is being dropped without a successful commit.
117 // Run rollback hooks.
118 let hooks = std::mem::take(&mut self.post_rollback_hooks);
119 for hook in hooks {
120 hook();
121 }
122 }
123 }
124}
125
126impl<'a> Transaction<'a> {
127 pub(crate) fn new(stm: &'a Stm, guard: &'a Guard) -> Self {
128 Self {
129 stm,
130 guard,
131 read_version: stm.global_clock.load(Ordering::Acquire),
132 read_set: BTreeMap::new(),
133 write_set: BTreeMap::new(),
134 post_commit_hooks: Vec::new(),
135 post_rollback_hooks: Vec::new(),
136 committed: false,
137 }
138 }
139
140 /// Schedule a side-effect (I/O) to run ONLY if the transaction commits successfully.
141 ///
142 /// This closure will run *after* all locks are released.
143 pub fn on_commit<F>(&mut self, f: F)
144 where
145 F: FnOnce() + Send + 'static,
146 {
147 self.post_commit_hooks.push(Box::new(f));
148 }
149
150 /// Schedule a side-effect to run ONLY if the transaction aborts or fails.
151 ///
152 /// This is useful for cleaning up temporary resources or logging failures.
153 /// It runs when the transaction is dropped without committing.
154 ///
155 /// # Example
156 /// ```text
157 /// let tmp_file = create_temp_file();
158 /// tx.on_rollback(move || remove_file(tmp_file));
159 /// ```
160 pub fn on_rollback<F>(&mut self, f: F)
161 where
162 F: FnOnce() + Send + 'static,
163 {
164 self.post_rollback_hooks.push(Box::new(f));
165 }
166
167 /// Read a TVar.
168 ///
169 /// The `TVar` wrapper contains an `Arc<TVarInner<T>>`. This method clones the Arc
170 /// into the read entry (`_keep_alive`), so the `version_lock` pointer stored in
171 /// `ReadEntry.lock_atomic` remains valid even if the `TVar` handle is dropped before
172 /// `commit()` runs. The stable identity key is `Arc::as_ptr(&tvar.0)` - the address
173 /// of the heap-allocated `TVarInner`, which is invariant across `TVar` clones.
174 pub fn load<T: Any + Send + Sync + Clone>(&mut self, tvar: &TVar<T>) -> Result<T, StmError> {
175 // Use the address of the heap-allocated TVarInner as the stable id,
176 // not the address of the TVar wrapper (which may live on the stack).
177 let id = Arc::as_ptr(&tvar.0) as usize;
178
179 // 1. Check Write Set (Read-Your-Own-Writes)
180 // The id is the address of this variable's `TVarInner<T>`, which the entry keeps
181 // alive, so an entry under it is a `Write<T>` and holds a `T`.
182 if let Some(value) = self
183 .write_set
184 .get(&id)
185 .and_then(|e| e.value().downcast_ref::<T>())
186 {
187 return Ok(value.clone());
188 }
189
190 // 2. A validated read, a repeated one too: a commit may have replaced the value since
191 // the first read, and a transaction that read both would see two values of it.
192 let (locked, version) = tvar.0.load_version_lock();
193
194 // If locked by someone else, or version is newer than our start time, abort
195 if locked || version > self.read_version {
196 return Err(StmError::Retry);
197 }
198
199 // Load data from Kovan Atomic
200 let shared = tvar.0.data.load(Ordering::Acquire, self.guard);
201
202 // Post-validate: check lock again to ensure consistent snapshot
203 let (locked_after, version_after) = tvar.0.load_version_lock();
204 if locked_after || version_after != version {
205 return Err(StmError::Retry);
206 }
207
208 // Record in Read Set, or find the version the first read recorded.
209 match self.read_set.get(&id) {
210 Some(first) if first.version != version => return Err(StmError::Retry),
211 Some(_) => {}
212 None => {
213 let inner_arc = Arc::clone(&tvar.0);
214 let keep_alive: Arc<dyn Any + Send + Sync> = inner_arc;
215 self.read_set.insert(
216 id,
217 ReadEntry {
218 version,
219 lock_atomic: &tvar.0.version_lock as *const _,
220 _keep_alive: keep_alive,
221 },
222 );
223 }
224 }
225
226 // SAFETY: Guard is active, pointer is valid.
227 unsafe {
228 let val = shared.as_ref().ok_or(StmError::Retry)?;
229 Ok(val.data.clone())
230 }
231 }
232
233 /// Write to a TVar.
234 ///
235 /// This method clones the `Arc<TVarInner<T>>` from the `TVar` wrapper and moves it
236 /// into the `committer` closure. The committer is invoked during `commit()`, which
237 /// may run after the `TVar` handle is dropped. The Arc clone ensures the
238 /// `TVarInner` (and thus `version_lock` and `data`) remains alive until the
239 /// commit closure executes.
240 pub fn store<T: Any + Send + Sync + 'static>(
241 &mut self,
242 tvar: &TVar<T>,
243 val: T,
244 ) -> Result<(), StmError> {
245 // Use the address of the heap-allocated TVarInner as the stable id.
246 let id = Arc::as_ptr(&tvar.0) as usize;
247
248 // A second store to the variable replaces (and drops) the first one's value.
249 let entry: WriteEntry = Box::new(Write {
250 var: Arc::clone(&tvar.0),
251 value: val,
252 });
253 self.write_set.insert(id, entry);
254 Ok(())
255 }
256
257 /// Commit the transaction.
258 /// Returns true if successful, false if conflict (caller should retry).
259 pub(crate) fn commit(mut self) -> bool {
260 // Because we implement Drop, we cannot move fields out of self directly.
261 // We use std::mem::take to ownership of the sets.
262 let write_set = std::mem::take(&mut self.write_set);
263 let post_commit_hooks = std::mem::take(&mut self.post_commit_hooks);
264
265 // 0. Read-only optimization
266 if write_set.is_empty() {
267 // Mark committed so Drop doesn't run rollback hooks
268 self.committed = true;
269 for hook in post_commit_hooks {
270 hook();
271 }
272 return true;
273 }
274
275 // 1. Acquire Locks
276 for (id, entry) in &write_set {
277 let lock_atomic = entry.lock();
278 let mut current = lock_atomic.load(Ordering::Acquire);
279 loop {
280 if current & 1 == 1 {
281 // Locked by another committer: abort, releasing the locks already taken.
282 // One kept is never released, and no transaction touching it could commit.
283 // self is dropped here, committed is false -> rollback hooks run
284 unlock(write_set.range(..*id).map(|(_, e)| e));
285 return false;
286 }
287 match lock_atomic.compare_exchange_weak(
288 current,
289 current | 1,
290 Ordering::Acquire,
291 Ordering::Relaxed,
292 ) {
293 Ok(_) => break, // Locked
294 Err(x) => current = x, // Retry CAS
295 }
296 }
297
298 // Check if we read this variable. If so, validate version.
299 if let Some(read_entry) = self.read_set.get(id) {
300 // current is the value before we set bit 0
301 if current > read_entry.version {
302 // Version changed since we read it: abort, releasing this lock and
303 // every one taken before it.
304 unlock(write_set.range(..=*id).map(|(_, e)| e));
305 return false;
306 }
307 }
308 }
309
310 // 2. Increment Global Clock
311 // We increment by 2 to keep the clock even (odd numbers indicate locks).
312 //
313 // Clock is advanced HERE, *before* read-set validation.
314 // If validation subsequently fails and the transaction aborts, this
315 // increment is NOT rolled back - the global clock advances permanently.
316 // Under heavy contention this creates a feedback loop: aborts push the
317 // clock forward, causing other concurrent transactions to see version
318 // mismatches and also abort. This is a performance degradation, not a
319 // correctness issue.
320 // TLII is still safe (stale reads are caught by validation), but throughput suffers.
321 // TODO(vclq): A correct alternative is to increment the clock *after* validation succeeds,
322 // while holding all write locks.
323 let global_ver = self.stm.global_clock.fetch_add(2, Ordering::AcqRel);
324 let write_version = global_ver + 2;
325
326 // 3. Validate Read Set
327 //
328 // `ReadEntry` stores `lock_atomic: *const AtomicU64` - a direct pointer
329 // to the `version_lock` field captured at read time. We load the atomic directly,
330 // decode the (locked, version) pair, and validate without any TVar pointer cast.
331 let mut valid = true;
332 for (id, entry) in &self.read_set {
333 // If writing to this var, we have lock, no need to check
334 if write_set.contains_key(id) {
335 continue;
336 }
337
338 let (locked, ver) = unsafe {
339 let lock = &*entry.lock_atomic;
340 let val = lock.load(std::sync::atomic::Ordering::Acquire);
341 (val & 1 == 1, val & !1)
342 };
343 if locked || ver > entry.version {
344 valid = false;
345 break;
346 }
347 }
348
349 if !valid {
350 // Release locks and abort
351 unlock(write_set.values());
352 // self dropped here -> rollback hooks run
353 return false;
354 }
355
356 // 4. Commit Writes
357 for (_, entry) in write_set {
358 entry.commit(write_version);
359 }
360
361 // 5. Success
362 self.committed = true; // Disable rollback hooks in Drop
363
364 // Run post-commit hooks
365 for hook in post_commit_hooks {
366 hook();
367 }
368
369 true
370 }
371}
372
373#[cfg(test)]
374mod tests {
375 use crate::Stm;
376
377 /// Verify that TVars defined outside the `atomically` closure work correctly
378 /// with the documented lifetime invariant.
379 ///
380 /// The `atomically` closure uses a higher-rank trait bound, which makes it impossible
381 /// to enforce `'v: 'a` without also updating `Stm::atomically`'s signature. The
382 /// architectural invariant (TVars must outlive the transaction) is documented on
383 /// `load` and `store` and must be upheld by callers. This test demonstrates correct
384 /// usage with TVars whose lifetimes clearly exceed the transaction.
385 #[test]
386 fn test_tvar_lifetime_valid_usage() {
387 let stm = Stm::new();
388 let var = stm.tvar(10i32);
389
390 let result = stm.atomically(|tx| {
391 let val = tx.load(&var)?;
392 tx.store(&var, val + 1)?;
393 Ok(val)
394 });
395
396 assert_eq!(result, 10);
397
398 let val = stm.atomically(|tx| tx.load(&var));
399 assert_eq!(val, 11);
400 }
401
402 /// Verify that the read-set validation using a direct `*const AtomicU64`
403 /// pointer (instead of a type-erased TVar cast) works correctly.
404 ///
405 /// This test confirms that read-set validation correctly reads the current version
406 /// without non comforming layout cast that we had before...
407 #[test]
408 fn test_read_set_validation_correct_type() {
409 // Tests that the read set validation works correctly
410 // by verifying that concurrent read validation detects version changes
411 let stm = Stm::new();
412 let var = stm.tvar(42i32);
413
414 let result = stm.atomically(|tx| tx.load(&var));
415 assert_eq!(result, 42);
416 }
417
418 /// A commit that meets a write-set variable locked by another committer aborts and
419 /// releases every lock it already took. A lock kept there is never released: every later
420 /// transaction touching that variable retries forever.
421 #[test]
422 fn commit_aborting_on_a_held_lock_releases_the_locks_it_took() {
423 use super::Transaction;
424 use std::sync::Arc;
425 use std::sync::atomic::Ordering;
426
427 let stm = Stm::new();
428 let (a, b) = (stm.tvar(1i64), stm.tvar(2i64));
429 // Commit locks in address order: hold the later variable's lock, as a concurrent
430 // committer would, so the earlier one is taken first.
431 let (first, second) = if Arc::as_ptr(&a.0) < Arc::as_ptr(&b.0) {
432 (&a, &b)
433 } else {
434 (&b, &a)
435 };
436 second.0.version_lock.fetch_or(1, Ordering::AcqRel);
437 {
438 let guard = kovan::pin();
439 let mut tx = Transaction::new(&stm, &guard);
440 tx.store(first, 10).unwrap();
441 tx.store(second, 20).unwrap();
442 assert!(!tx.commit(), "a commit meeting a held lock must abort");
443 }
444 assert_eq!(
445 first.0.load_version_lock(),
446 (false, 0),
447 "the aborted commit kept the lock it took"
448 );
449 second.0.version_lock.fetch_and(!1, Ordering::AcqRel);
450
451 stm.atomically(|tx| {
452 tx.store(first, 11)?;
453 tx.store(second, 21)
454 });
455 let both = stm.atomically(|tx| Ok((tx.load(first)?, tx.load(second)?)));
456 assert_eq!(both, (11, 21));
457 }
458}