Skip to content

sui_v1.38.0_1731482478_ci

@mystenmark mystenmark tagged this 13 Nov 05:21
The previous version of this code was based on a misunderstanding of the
Moka Cache API. It assumed that:

    let entry = cache.entry(k).or_insert_with(|| v);
    entry.is_fresh()

could be used to detect whether there was a race with

    cache.insert(k, v)

In fact this is not the case! Both threads must use `or_insert_with` in
order to handle the race correctly.

The bug is instantly reproducible with the following code:

    use moka::sync::Cache;
    use std::sync::{Arc, Mutex};

fn monotonic_update(cache: Arc<Cache<u64, Arc<Mutex<u64>>>>, key: u64,
value: u64) {
        let entry = cache
            .entry(key)
            .or_insert_with(|| Arc::new(Mutex::new(value)));

        if !entry.is_fresh() {
            let mut entry = entry.value().lock().unwrap();
// only update if the new value is greater than the current value
            if value > *entry {
                *entry = value;
            }
        }
    }

fn blind_write(cache: Arc<Cache<u64, Arc<Mutex<u64>>>>, key: u64, value:
u64) {
        cache.insert(key, Arc::new(Mutex::new(value)));
    }

    fn main() {
        for _ in 0..1000 {
            let cache = Arc::new(Cache::new(1000));
            let cache1 = cache.clone();
            let cache2 = cache.clone();

            let handle1 = std::thread::spawn(move || {
                monotonic_update(cache1, 1, 1);
            });
            let handle2 = std::thread::spawn(move || {
                // Correct way to update the value
                // monotonic_update(cache2, 1, 2);

                // Incorrect way to update the value
                blind_write(cache2, 1, 2);
            });

            handle1.join().unwrap();
            handle2.join().unwrap();

            let entry = cache.get(&1).unwrap();
            let value = entry.lock().unwrap();
            assert_eq!(*value, 2);
        }
    }

## Description 

Describe the changes or additions included in this PR.

## Test plan 

How did you test the new or updated feature?

---

## Release notes

Check each box that your changes affect. If none of the boxes relate to
your changes, release notes aren't required.

For each box you select, include information after the relevant heading
that describes the impact of your changes that a user might notice and
any actions they must take to implement updates.

- [ ] Protocol: 
- [ ] Nodes (Validators and Full nodes): 
- [ ] Indexer: 
- [ ] JSON-RPC: 
- [ ] GraphQL: 
- [ ] CLI: 
- [ ] Rust SDK:
- [ ] REST API:
Assets 2
Loading