kovan-stm 0.2.6

Software Transactional Memory (STM) implementation using Kovan for memory reclamation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
use super::node::StmNode;
use super::var::TVarInner;
use super::{Stm, StmError, TVar};
use alloc::boxed::Box;
use kovan::{Guard, Shared, alloc_node, retire_node};
use std::any::Any;
use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::atomic::Ordering;

// See `var.rs`: must resolve to the identical concrete type as
// `TVarInner::version_lock`, since `lock_atomic` below is a raw pointer to
// that same field.
#[cfg(feature = "shuttle")]
use shuttle::sync::atomic::AtomicU64;
#[cfg(not(feature = "shuttle"))]
use std::sync::atomic::AtomicU64;

/// Unique ID for a TVar (memory address) to sort locks.
type TVarId = usize;

/// Internal entry for the Read Set.
#[derive(Clone)]
struct ReadEntry {
    /// The version of the TVar observed when reading.
    version: u64,
    /// Store the pointer to the `AtomicU64` directly
    lock_atomic: *const AtomicU64,
    // NOTE: back in times I used OCC style, then switched to locking.
    // Maybe I will just use that over all `*Entry` types later.
    /// An `Arc` clone that keeps the `TVarInner` (and thus
    /// `version_lock`) alive for the entire lifetime of this read entry.
    _keep_alive: Arc<dyn Any + Send + Sync>,
}

/// A value a transaction stores in one variable, published at commit.
///
/// Type erasure lets one write set hold the writes of variables of different types. The
/// entry owns the value until commit moves it into the node it publishes, or until the
/// transaction rolls back and drops it: either way the value is dropped exactly once.
trait PendingWrite: Send {
    /// The value, for the transaction's own reads of the variable.
    fn value(&self) -> &dyn Any;
    /// The variable's version lock.
    fn lock(&self) -> &AtomicU64;
    /// Publishes the value in a new node, retires the node it replaces, and releases the
    /// variable's lock with `version`.
    fn commit(self: Box<Self>, version: u64);
}

/// The [`PendingWrite`] of a variable of `T`. Holding the variable's `Arc` keeps its
/// `version_lock` and `data` alive until the commit, even if every `TVar` handle is gone.
struct Write<T: Send + Sync + 'static> {
    var: Arc<TVarInner<T>>,
    value: T,
}

impl<T: Any + Send + Sync + 'static> PendingWrite for Write<T> {
    fn value(&self) -> &dyn Any {
        &self.value
    }

    fn lock(&self) -> &AtomicU64 {
        &self.var.version_lock
    }

    fn commit(self: Box<Self>, version: u64) {
        let Write { var, value } = *self;
        let node = alloc_node(StmNode::new(value));
        let guard = kovan::pin();
        // SAFETY: a fresh node, published here once.
        let old = var
            .data
            .swap(unsafe { Shared::from_raw(node) }, Ordering::AcqRel, &guard);
        if !old.is_null() {
            // SAFETY: unlinked by the swap, which only this committer (holding the
            // variable's lock) makes; every node of `data` comes from `alloc_node`, and
            // `StmNode` is #[repr(C)] with its RetiredNode at offset 0.
            unsafe { retire_node(old.as_raw()) };
        }
        // Release: a reader that sees the new version sees the new node.
        var.version_lock.store(version, Ordering::Release);
    }
}

type WriteEntry = Box<dyn PendingWrite>;

/// Clear the lock bit of every entry an aborting commit locked, leaving each version as it was.
fn unlock<'e>(locked: impl Iterator<Item = &'e WriteEntry>) {
    for entry in locked {
        entry.lock().fetch_and(!1, Ordering::Release);
    }
}

/// Representation of a transaction in STM.
pub struct Transaction<'a> {
    stm: &'a Stm,
    guard: &'a Guard,
    /// Timestamp at the start of the transaction.
    read_version: u64,
    /// Map of TVar address -> Read Record.
    read_set: BTreeMap<TVarId, ReadEntry>,
    /// Map of TVar address -> Write Record.
    write_set: BTreeMap<TVarId, WriteEntry>, // BTreeMap for deterministic locking order
    /// Side effects to run only after a successful commit.
    post_commit_hooks: Vec<Box<dyn FnOnce() + Send>>,
    /// Side effects to run only if the transaction aborts/rolls back.
    post_rollback_hooks: Vec<Box<dyn FnOnce() + Send>>,
    /// Tracks if the transaction committed successfully to prevent rollback hooks in Drop.
    committed: bool,
}

impl<'a> Drop for Transaction<'a> {
    fn drop(&mut self) {
        if !self.committed {
            // Transaction is being dropped without a successful commit.
            // Run rollback hooks.
            let hooks = std::mem::take(&mut self.post_rollback_hooks);
            for hook in hooks {
                hook();
            }
        }
    }
}

impl<'a> Transaction<'a> {
    pub(crate) fn new(stm: &'a Stm, guard: &'a Guard) -> Self {
        Self {
            stm,
            guard,
            read_version: stm.global_clock.load(Ordering::Acquire),
            read_set: BTreeMap::new(),
            write_set: BTreeMap::new(),
            post_commit_hooks: Vec::new(),
            post_rollback_hooks: Vec::new(),
            committed: false,
        }
    }

    /// Schedule a side-effect (I/O) to run ONLY if the transaction commits successfully.
    ///
    /// This closure will run *after* all locks are released.
    pub fn on_commit<F>(&mut self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
        self.post_commit_hooks.push(Box::new(f));
    }

    /// Schedule a side-effect to run ONLY if the transaction aborts or fails.
    ///
    /// This is useful for cleaning up temporary resources or logging failures.
    /// It runs when the transaction is dropped without committing.
    ///
    /// # Example
    /// ```text
    /// let tmp_file = create_temp_file();
    /// tx.on_rollback(move || remove_file(tmp_file));
    /// ```
    pub fn on_rollback<F>(&mut self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
        self.post_rollback_hooks.push(Box::new(f));
    }

    /// Read a TVar.
    ///
    /// The `TVar` wrapper contains an `Arc<TVarInner<T>>`. This method clones the Arc
    /// into the read entry (`_keep_alive`), so the `version_lock` pointer stored in
    /// `ReadEntry.lock_atomic` remains valid even if the `TVar` handle is dropped before
    /// `commit()` runs.  The stable identity key is `Arc::as_ptr(&tvar.0)` - the address
    /// of the heap-allocated `TVarInner`, which is invariant across `TVar` clones.
    pub fn load<T: Any + Send + Sync + Clone>(&mut self, tvar: &TVar<T>) -> Result<T, StmError> {
        // Use the address of the heap-allocated TVarInner as the stable id,
        // not the address of the TVar wrapper (which may live on the stack).
        let id = Arc::as_ptr(&tvar.0) as usize;

        // 1. Check Write Set (Read-Your-Own-Writes)
        // The id is the address of this variable's `TVarInner<T>`, which the entry keeps
        // alive, so an entry under it is a `Write<T>` and holds a `T`.
        if let Some(value) = self
            .write_set
            .get(&id)
            .and_then(|e| e.value().downcast_ref::<T>())
        {
            return Ok(value.clone());
        }

        // 2. A validated read, a repeated one too: a commit may have replaced the value since
        // the first read, and a transaction that read both would see two values of it.
        let (locked, version) = tvar.0.load_version_lock();

        // If locked by someone else, or version is newer than our start time, abort
        if locked || version > self.read_version {
            return Err(StmError::Retry);
        }

        // Load data from Kovan Atomic
        let shared = tvar.0.data.load(Ordering::Acquire, self.guard);

        // Post-validate: check lock again to ensure consistent snapshot
        let (locked_after, version_after) = tvar.0.load_version_lock();
        if locked_after || version_after != version {
            return Err(StmError::Retry);
        }

        // Record in Read Set, or find the version the first read recorded.
        match self.read_set.get(&id) {
            Some(first) if first.version != version => return Err(StmError::Retry),
            Some(_) => {}
            None => {
                let inner_arc = Arc::clone(&tvar.0);
                let keep_alive: Arc<dyn Any + Send + Sync> = inner_arc;
                self.read_set.insert(
                    id,
                    ReadEntry {
                        version,
                        lock_atomic: &tvar.0.version_lock as *const _,
                        _keep_alive: keep_alive,
                    },
                );
            }
        }

        // SAFETY: Guard is active, pointer is valid.
        unsafe {
            let val = shared.as_ref().ok_or(StmError::Retry)?;
            Ok(val.data.clone())
        }
    }

    /// Write to a TVar.
    ///
    /// This method clones the `Arc<TVarInner<T>>` from the `TVar` wrapper and moves it
    /// into the `committer` closure. The committer is invoked during `commit()`, which
    /// may run after the `TVar` handle is dropped. The Arc clone ensures the
    /// `TVarInner` (and thus `version_lock` and `data`) remains alive until the
    /// commit closure executes.
    pub fn store<T: Any + Send + Sync + 'static>(
        &mut self,
        tvar: &TVar<T>,
        val: T,
    ) -> Result<(), StmError> {
        // Use the address of the heap-allocated TVarInner as the stable id.
        let id = Arc::as_ptr(&tvar.0) as usize;

        // A second store to the variable replaces (and drops) the first one's value.
        let entry: WriteEntry = Box::new(Write {
            var: Arc::clone(&tvar.0),
            value: val,
        });
        self.write_set.insert(id, entry);
        Ok(())
    }

    /// Commit the transaction.
    /// Returns true if successful, false if conflict (caller should retry).
    pub(crate) fn commit(mut self) -> bool {
        // Because we implement Drop, we cannot move fields out of self directly.
        // We use std::mem::take to ownership of the sets.
        let write_set = std::mem::take(&mut self.write_set);
        let post_commit_hooks = std::mem::take(&mut self.post_commit_hooks);

        // 0. Read-only optimization
        if write_set.is_empty() {
            // Mark committed so Drop doesn't run rollback hooks
            self.committed = true;
            for hook in post_commit_hooks {
                hook();
            }
            return true;
        }

        // 1. Acquire Locks
        for (id, entry) in &write_set {
            let lock_atomic = entry.lock();
            let mut current = lock_atomic.load(Ordering::Acquire);
            loop {
                if current & 1 == 1 {
                    // Locked by another committer: abort, releasing the locks already taken.
                    // One kept is never released, and no transaction touching it could commit.
                    // self is dropped here, committed is false -> rollback hooks run
                    unlock(write_set.range(..*id).map(|(_, e)| e));
                    return false;
                }
                match lock_atomic.compare_exchange_weak(
                    current,
                    current | 1,
                    Ordering::Acquire,
                    Ordering::Relaxed,
                ) {
                    Ok(_) => break,        // Locked
                    Err(x) => current = x, // Retry CAS
                }
            }

            // Check if we read this variable. If so, validate version.
            if let Some(read_entry) = self.read_set.get(id) {
                // current is the value before we set bit 0
                if current > read_entry.version {
                    // Version changed since we read it: abort, releasing this lock and
                    // every one taken before it.
                    unlock(write_set.range(..=*id).map(|(_, e)| e));
                    return false;
                }
            }
        }

        // 2. Increment Global Clock
        // We increment by 2 to keep the clock even (odd numbers indicate locks).
        //
        // Clock is advanced HERE, *before* read-set validation.
        // If validation subsequently fails and the transaction aborts, this
        // increment is NOT rolled back - the global clock advances permanently.
        // Under heavy contention this creates a feedback loop: aborts push the
        // clock forward, causing other concurrent transactions to see version
        // mismatches and also abort.  This is a performance degradation, not a
        // correctness issue.
        // TLII is still safe (stale reads are caught by validation), but throughput suffers.
        // TODO(vclq): A correct alternative is to increment the clock *after* validation succeeds,
        // while holding all write locks.
        let global_ver = self.stm.global_clock.fetch_add(2, Ordering::AcqRel);
        let write_version = global_ver + 2;

        // 3. Validate Read Set
        //
        // `ReadEntry` stores `lock_atomic: *const AtomicU64` - a direct pointer
        // to the `version_lock` field captured at read time. We load the atomic directly,
        // decode the (locked, version) pair, and validate without any TVar pointer cast.
        let mut valid = true;
        for (id, entry) in &self.read_set {
            // If writing to this var, we have lock, no need to check
            if write_set.contains_key(id) {
                continue;
            }

            let (locked, ver) = unsafe {
                let lock = &*entry.lock_atomic;
                let val = lock.load(std::sync::atomic::Ordering::Acquire);
                (val & 1 == 1, val & !1)
            };
            if locked || ver > entry.version {
                valid = false;
                break;
            }
        }

        if !valid {
            // Release locks and abort
            unlock(write_set.values());
            // self dropped here -> rollback hooks run
            return false;
        }

        // 4. Commit Writes
        for (_, entry) in write_set {
            entry.commit(write_version);
        }

        // 5. Success
        self.committed = true; // Disable rollback hooks in Drop

        // Run post-commit hooks
        for hook in post_commit_hooks {
            hook();
        }

        true
    }
}

#[cfg(test)]
mod tests {
    use crate::Stm;

    /// Verify that TVars defined outside the `atomically` closure work correctly
    /// with the documented lifetime invariant.
    ///
    /// The `atomically` closure uses a higher-rank trait bound, which makes it impossible
    /// to enforce `'v: 'a` without also updating `Stm::atomically`'s signature. The
    /// architectural invariant (TVars must outlive the transaction) is documented on
    /// `load` and `store` and must be upheld by callers. This test demonstrates correct
    /// usage with TVars whose lifetimes clearly exceed the transaction.
    #[test]
    fn test_tvar_lifetime_valid_usage() {
        let stm = Stm::new();
        let var = stm.tvar(10i32);

        let result = stm.atomically(|tx| {
            let val = tx.load(&var)?;
            tx.store(&var, val + 1)?;
            Ok(val)
        });

        assert_eq!(result, 10);

        let val = stm.atomically(|tx| tx.load(&var));
        assert_eq!(val, 11);
    }

    /// Verify that the read-set validation using a direct `*const AtomicU64`
    /// pointer (instead of a type-erased TVar cast) works correctly.
    ///
    /// This test confirms that read-set validation correctly reads the current version
    /// without non comforming layout cast that we had before...
    #[test]
    fn test_read_set_validation_correct_type() {
        // Tests that the read set validation works correctly
        // by verifying that concurrent read validation detects version changes
        let stm = Stm::new();
        let var = stm.tvar(42i32);

        let result = stm.atomically(|tx| tx.load(&var));
        assert_eq!(result, 42);
    }

    /// A commit that meets a write-set variable locked by another committer aborts and
    /// releases every lock it already took. A lock kept there is never released: every later
    /// transaction touching that variable retries forever.
    #[test]
    fn commit_aborting_on_a_held_lock_releases_the_locks_it_took() {
        use super::Transaction;
        use std::sync::Arc;
        use std::sync::atomic::Ordering;

        let stm = Stm::new();
        let (a, b) = (stm.tvar(1i64), stm.tvar(2i64));
        // Commit locks in address order: hold the later variable's lock, as a concurrent
        // committer would, so the earlier one is taken first.
        let (first, second) = if Arc::as_ptr(&a.0) < Arc::as_ptr(&b.0) {
            (&a, &b)
        } else {
            (&b, &a)
        };
        second.0.version_lock.fetch_or(1, Ordering::AcqRel);
        {
            let guard = kovan::pin();
            let mut tx = Transaction::new(&stm, &guard);
            tx.store(first, 10).unwrap();
            tx.store(second, 20).unwrap();
            assert!(!tx.commit(), "a commit meeting a held lock must abort");
        }
        assert_eq!(
            first.0.load_version_lock(),
            (false, 0),
            "the aborted commit kept the lock it took"
        );
        second.0.version_lock.fetch_and(!1, Ordering::AcqRel);

        stm.atomically(|tx| {
            tx.store(first, 11)?;
            tx.store(second, 21)
        });
        let both = stm.atomically(|tx| Ok((tx.load(first)?, tx.load(second)?)));
        assert_eq!(both, (11, 21));
    }
}