---
title: "Project: a coherence simulator"
heading: MESI caches on a snooping bus, with traffic counts, data values and invariant checks
eyebrow: S4 · Lesson 51 · Coherence simulator project
xp: 80
---

::: hook
Coherence protocols are small state machines, but they're easy to get subtly wrong: one missing transition and, once in a million accesses, a core reads a stale value. Protocol designers guard against that the way verification engineers do (S3.25): they write a model of the protocol and drive it with random traffic while checking invariants after every step. In this project you'll build that model, MESI caches on a snooping bus carrying real data values, count the bus traffic it generates, and run it against a testbench that checks the single-writer invariant and that every read returns the most recent write, then extend it to MSI and compare.
:::

::: predict
## Four cores each read and then write their own private line. How many bus transactions does MESI need, and MSI?

- [ ] 8 and 8
- [x] 4 and 8
- [ ] 4 and 4
- [ ] 0 and 4

::: reveal
MESI: 4. Each read miss finds no other copy and loads the line in E, and the write moves E to M silently. MSI: 8. Without an E state, each read loads S, and the write needs a BusUpgr to invalidate copies that don't exist. You'll check both counts with your simulator in step 3.
:::
:::

::: nameit
## The model

- n cores, each with a cache that holds any number of lines (no evictions), each line in state M, E, S or I (absent means I).
- A **trace** is a list of `(core, op, line)` with op `'R'` or `'W'`. The write at trace position t stores the value t + 1, so every write is distinguishable; memory starts at 0 everywhere.
- Each step is atomic on the bus: the requesting cache decides its transaction, every other cache snoops it, then the request completes.

## The protocol tables

`on_processor(state, op, shared)` returns the new state and the bus transaction (or None), where `shared` says whether any other cache holds a valid copy:

| State | Read | Write |
|---|---|---|
| I | BusRd → E (S if shared) | BusRdX → M |
| S | → S | BusUpgr → M |
| E | → E | → M, silently |
| M | → M | → M |

`on_snoop(state, bus)` returns the new state and whether to **flush** (supply the data and update memory):

| State | BusRd | BusRdX or BusUpgr |
|---|---|---|
| M | → S, flush | → I, flush (BusRdX) |
| E | → S | → I |
| S | → S | → I |
| I | → I | → I |

## The simulator

For each trace step: look up the requester's state and whether others share the line; get its new state and transaction; if there's a transaction, count it and apply `on_snoop` to every other cache (counting flushes, and copying flushed data to memory); on BusRd or BusRdX the requester then takes its data from memory; finally set its state, and either store the new value (write) or record the value it read. `run(trace, n, protocol)` returns `{'counts': ..., 'reads': [...], 'states': [...]}`.

## The invariants the tests check after every prefix of random traces

- **Single writer:** if any cache holds a line in M or E, no other cache holds it at all.
- **Data value:** every read returns the value of the latest write to that line in trace order.
:::

::: example
## Trace the counts and read values for `(0, W, 0)`, `(1, R, 0)`, `(1, W, 0)`, `(0, R, 0)` on two caches.

::: solution
1. **Core 0 writes.** I → M with a BusRdX; it holds value 1.
2. **Core 1 reads.** A BusRd: core 0 flushes (M → S, memory = 1), and core 1 gets S and reads 1.
3. **Core 1 writes.** A BusUpgr: core 0 invalidates, and core 1 holds value 3 in M.
4. **Core 0 reads.** A BusRd: core 1 flushes (memory = 3) and drops to S, and core 0 reads 3.

**Answer:** the counts are BusRd 2, BusRdX 1, BusUpgr 1 and Flush 2, and the reads return [1, 3].
:::
:::

::: example
## Two cores alternately write the same line k times each. How many transactions per write, and what does this say about false sharing?

::: solution
1. **Each write after the first.** It finds the line in M in the other cache, so it needs a BusRdX that forces a flush and an invalidation.
2. **Count.** That's two bus events per write, about 4k for 2k writes, however little data actually changes.
3. **False sharing.** If the two cores were writing different words of that line, all of that traffic would be false sharing, which separate lines would remove entirely.

**Answer:** two bus events per write (a BusRdX and the flush it forces), about 4k for 2k writes; if the cores write different words of the line, all of it is false sharing.
:::
:::

::: check
kind: python

## Step 1. Write `on_processor` and `on_snoop`, the MESI protocol tables.

```python starter
def on_processor(state, op, shared, protocol='MESI'):
    # state: 'M', 'E', 'S' or 'I'; op: 'R' or 'W'; shared: does another cache hold a valid copy?
    # Return (new state, bus transaction or None).
    return state, None

def on_snoop(state, bus):
    # Another cache put bus ('BusRd', 'BusRdX' or 'BusUpgr') on the bus.
    # Return (new state, whether this cache must flush its modified data).
    return state, False

print(on_processor('I', 'R', False), on_snoop('M', 'BusRd'))
```

```python solution
def on_processor(state, op, shared, protocol='MESI'):
    if state == 'I':
        if op == 'R':
            return ('S' if shared or protocol == 'MSI' else 'E'), 'BusRd'
        return 'M', 'BusRdX'
    if state == 'S':
        return ('S', None) if op == 'R' else ('M', 'BusUpgr')
    if state == 'E':
        return ('E', None) if op == 'R' else ('M', None)
    return 'M', None

def on_snoop(state, bus):
    if bus == 'BusRd':
        return ('S', True) if state == 'M' else ('S' if state in 'ES' else 'I', False)
    return 'I', state == 'M'

print(on_processor('I', 'R', False), on_snoop('M', 'BusRd'))
```

```python tests
import random
def rand_trace(seed, n, length=60, lines=3):
    rng = random.Random(seed)
    return [(rng.randrange(n), rng.choice('RRW'), rng.randrange(lines)) for _ in range(length)]
def check_prefixes(trace, n, protocol='MESI'):
    for k in range(1, len(trace) + 1):
        r = run(trace[:k], n, protocol)
        for line in {l for _, _, l in trace[:k]}:
            st = [r['states'][c].get(line, 'I') for c in range(n)]
            owners = sum(s in 'ME' for s in st)
            valid = sum(s != 'I' for s in st)
            assert owners == 0 or valid == 1, f"After step {k} of {trace[:k]}, line {line} is {st}: an M or E copy must be the only valid copy."
            assert protocol == 'MESI' or 'E' not in st, f"MSI has no E state, but line {line} is {st}."
        latest, want = {}, []
        for t, (c, op, line) in enumerate(trace[:k]):
            if op == 'W':
                latest[line] = t + 1
            else:
                want.append(latest.get(line, 0))
        assert r['reads'] == want, f"After step {k}, reads returned {r['reads']} but the latest writes were {want}."
want_p = {('I', 'R', False): ('E', 'BusRd'), ('I', 'R', True): ('S', 'BusRd'), ('I', 'W', False): ('M', 'BusRdX'), ('I', 'W', True): ('M', 'BusRdX'),
          ('S', 'R', True): ('S', None), ('S', 'W', True): ('M', 'BusUpgr'), ('E', 'R', False): ('E', None), ('E', 'W', False): ('M', None),
          ('M', 'R', False): ('M', None), ('M', 'W', False): ('M', None)}
for (s, op, sh), v in want_p.items():
    got = on_processor(s, op, sh)
    assert tuple(got) == v, f"on_processor({s!r}, {op!r}, shared={sh}) should be {v}; got {got}."
want_s = {('M', 'BusRd'): ('S', True), ('E', 'BusRd'): ('S', False), ('S', 'BusRd'): ('S', False), ('I', 'BusRd'): ('I', False),
          ('M', 'BusRdX'): ('I', True), ('E', 'BusRdX'): ('I', False), ('S', 'BusRdX'): ('I', False), ('I', 'BusRdX'): ('I', False),
          ('S', 'BusUpgr'): ('I', False), ('I', 'BusUpgr'): ('I', False)}
for (s, b), v in want_s.items():
    got = on_snoop(s, b)
    assert tuple(got) == v, f"on_snoop({s!r}, {b!r}) should be {v}; got {got}."
```

::: right
Right. Two small tables are the whole protocol: what a cache does when its own core reads or writes, and what it does when it sees another cache's request.
:::
:::

::: check
kind: python

## Step 2. Write `run(trace, n)`: a snooping bus of n MESI caches, with traffic counts and real data values.

```python starter
def on_processor(state, op, shared, protocol='MESI'):
    if state == 'I':
        if op == 'R':
            return ('S' if shared or protocol == 'MSI' else 'E'), 'BusRd'
        return 'M', 'BusRdX'
    if state == 'S':
        return ('S', None) if op == 'R' else ('M', 'BusUpgr')
    if state == 'E':
        return ('E', None) if op == 'R' else ('M', None)
    return 'M', None

def on_snoop(state, bus):
    if bus == 'BusRd':
        return ('S', True) if state == 'M' else ('S' if state in 'ES' else 'I', False)
    return 'I', state == 'M'

def run(trace, n, protocol='MESI'):
    # trace: list of (core, 'R' or 'W', line). The write at trace index t stores the value t + 1;
    # memory starts at 0. Return {'counts': {...}, 'reads': [values read], 'states': [dict per core]}.
    counts = {'BusRd': 0, 'BusRdX': 0, 'BusUpgr': 0, 'Flush': 0}
    return {'counts': counts, 'reads': [], 'states': [dict() for _ in range(n)]}

print(run([(0, 'W', 0), (1, 'R', 0)], 2))
```

```python solution
def on_processor(state, op, shared, protocol='MESI'):
    if state == 'I':
        if op == 'R':
            return ('S' if shared or protocol == 'MSI' else 'E'), 'BusRd'
        return 'M', 'BusRdX'
    if state == 'S':
        return ('S', None) if op == 'R' else ('M', 'BusUpgr')
    if state == 'E':
        return ('E', None) if op == 'R' else ('M', None)
    return 'M', None

def on_snoop(state, bus):
    if bus == 'BusRd':
        return ('S', True) if state == 'M' else ('S' if state in 'ES' else 'I', False)
    return 'I', state == 'M'

def run(trace, n, protocol='MESI'):
    states = [dict() for _ in range(n)]
    data = [dict() for _ in range(n)]
    memory = {}
    counts = {'BusRd': 0, 'BusRdX': 0, 'BusUpgr': 0, 'Flush': 0}
    reads = []
    for t, (core, op, line) in enumerate(trace):
        st = states[core].get(line, 'I')
        shared = any(states[c].get(line, 'I') != 'I' for c in range(n) if c != core)
        new, bus = on_processor(st, op, shared, protocol)
        if bus:
            counts[bus] += 1
            for c in range(n):
                if c != core:
                    s2, flush = on_snoop(states[c].get(line, 'I'), bus)
                    if flush:
                        counts['Flush'] += 1
                        memory[line] = data[c][line]
                    states[c][line] = s2
            if bus != 'BusUpgr':
                data[core][line] = memory.get(line, 0)
        states[core][line] = new
        if op == 'W':
            data[core][line] = t + 1
        else:
            reads.append(data[core][line])
    return {'counts': counts, 'reads': reads, 'states': states}

print(run([(0, 'W', 0), (1, 'R', 0)], 2))
```

```python tests
import random
def rand_trace(seed, n, length=60, lines=3):
    rng = random.Random(seed)
    return [(rng.randrange(n), rng.choice('RRW'), rng.randrange(lines)) for _ in range(length)]
def check_prefixes(trace, n, protocol='MESI'):
    for k in range(1, len(trace) + 1):
        r = run(trace[:k], n, protocol)
        for line in {l for _, _, l in trace[:k]}:
            st = [r['states'][c].get(line, 'I') for c in range(n)]
            owners = sum(s in 'ME' for s in st)
            valid = sum(s != 'I' for s in st)
            assert owners == 0 or valid == 1, f"After step {k} of {trace[:k]}, line {line} is {st}: an M or E copy must be the only valid copy."
            assert protocol == 'MESI' or 'E' not in st, f"MSI has no E state, but line {line} is {st}."
        latest, want = {}, []
        for t, (c, op, line) in enumerate(trace[:k]):
            if op == 'W':
                latest[line] = t + 1
            else:
                want.append(latest.get(line, 0))
        assert r['reads'] == want, f"After step {k}, reads returned {r['reads']} but the latest writes were {want}."
r = run([(0, 'R', 0), (0, 'W', 0)], 2)
assert r['counts'] == {'BusRd': 1, 'BusRdX': 0, 'BusUpgr': 0, 'Flush': 0}, f"Read then write of private data needs one BusRd; got {r['counts']}."
r = run([(0, 'W', 0), (1, 'R', 0), (1, 'W', 0), (0, 'R', 0)], 2)
assert r['counts'] == {'BusRd': 2, 'BusRdX': 1, 'BusUpgr': 1, 'Flush': 2} and r['reads'] == [1, 3], f"The ping-pong trace should give BusRd 2, BusRdX 1, BusUpgr 1, Flush 2 and reads [1, 3]; got {r['counts']} and {r['reads']}."
for seed in range(25):
    n = 2 + seed % 3
    check_prefixes(rand_trace(seed, n), n)
```

::: right
Right. On every prefix of every random trace, a modified or exclusive copy is the only valid one, and every read returns the latest write.
:::
:::

::: check
kind: python

## Step 3. Make `protocol='MSI'` work: no E state, so every read miss lands in S.

```python starter
def on_processor(state, op, shared, protocol='MESI'):
    # Step 3: make protocol='MSI' work too (MSI has no E state).
    if state == 'I':
        if op == 'R':
            return ('S' if shared else 'E'), 'BusRd'
        return 'M', 'BusRdX'
    if state == 'S':
        return ('S', None) if op == 'R' else ('M', 'BusUpgr')
    if state == 'E':
        return ('E', None) if op == 'R' else ('M', None)
    return 'M', None

def on_snoop(state, bus):
    if bus == 'BusRd':
        return ('S', True) if state == 'M' else ('S' if state in 'ES' else 'I', False)
    return 'I', state == 'M'

def run(trace, n, protocol='MESI'):
    states = [dict() for _ in range(n)]
    data = [dict() for _ in range(n)]
    memory = {}
    counts = {'BusRd': 0, 'BusRdX': 0, 'BusUpgr': 0, 'Flush': 0}
    reads = []
    for t, (core, op, line) in enumerate(trace):
        st = states[core].get(line, 'I')
        shared = any(states[c].get(line, 'I') != 'I' for c in range(n) if c != core)
        new, bus = on_processor(st, op, shared, protocol)
        if bus:
            counts[bus] += 1
            for c in range(n):
                if c != core:
                    s2, flush = on_snoop(states[c].get(line, 'I'), bus)
                    if flush:
                        counts['Flush'] += 1
                        memory[line] = data[c][line]
                    states[c][line] = s2
            if bus != 'BusUpgr':
                data[core][line] = memory.get(line, 0)
        states[core][line] = new
        if op == 'W':
            data[core][line] = t + 1
        else:
            reads.append(data[core][line])
    return {'counts': counts, 'reads': reads, 'states': states}

print(run([(0, 'R', 0), (0, 'W', 0)], 2, 'MSI')['counts'])
```

```python solution
def on_processor(state, op, shared, protocol='MESI'):
    if state == 'I':
        if op == 'R':
            return ('S' if shared or protocol == 'MSI' else 'E'), 'BusRd'
        return 'M', 'BusRdX'
    if state == 'S':
        return ('S', None) if op == 'R' else ('M', 'BusUpgr')
    if state == 'E':
        return ('E', None) if op == 'R' else ('M', None)
    return 'M', None

def on_snoop(state, bus):
    if bus == 'BusRd':
        return ('S', True) if state == 'M' else ('S' if state in 'ES' else 'I', False)
    return 'I', state == 'M'

def run(trace, n, protocol='MESI'):
    states = [dict() for _ in range(n)]
    data = [dict() for _ in range(n)]
    memory = {}
    counts = {'BusRd': 0, 'BusRdX': 0, 'BusUpgr': 0, 'Flush': 0}
    reads = []
    for t, (core, op, line) in enumerate(trace):
        st = states[core].get(line, 'I')
        shared = any(states[c].get(line, 'I') != 'I' for c in range(n) if c != core)
        new, bus = on_processor(st, op, shared, protocol)
        if bus:
            counts[bus] += 1
            for c in range(n):
                if c != core:
                    s2, flush = on_snoop(states[c].get(line, 'I'), bus)
                    if flush:
                        counts['Flush'] += 1
                        memory[line] = data[c][line]
                    states[c][line] = s2
            if bus != 'BusUpgr':
                data[core][line] = memory.get(line, 0)
        states[core][line] = new
        if op == 'W':
            data[core][line] = t + 1
        else:
            reads.append(data[core][line])
    return {'counts': counts, 'reads': reads, 'states': states}

print(run([(0, 'R', 0), (0, 'W', 0)], 2, 'MSI')['counts'])
```

```python tests
import random
def rand_trace(seed, n, length=60, lines=3):
    rng = random.Random(seed)
    return [(rng.randrange(n), rng.choice('RRW'), rng.randrange(lines)) for _ in range(length)]
def check_prefixes(trace, n, protocol='MESI'):
    for k in range(1, len(trace) + 1):
        r = run(trace[:k], n, protocol)
        for line in {l for _, _, l in trace[:k]}:
            st = [r['states'][c].get(line, 'I') for c in range(n)]
            owners = sum(s in 'ME' for s in st)
            valid = sum(s != 'I' for s in st)
            assert owners == 0 or valid == 1, f"After step {k} of {trace[:k]}, line {line} is {st}: an M or E copy must be the only valid copy."
            assert protocol == 'MESI' or 'E' not in st, f"MSI has no E state, but line {line} is {st}."
        latest, want = {}, []
        for t, (c, op, line) in enumerate(trace[:k]):
            if op == 'W':
                latest[line] = t + 1
            else:
                want.append(latest.get(line, 0))
        assert r['reads'] == want, f"After step {k}, reads returned {r['reads']} but the latest writes were {want}."
r = run([(0, 'R', 0), (0, 'W', 0)], 2, 'MSI')
assert r['counts']['BusRd'] == 1 and r['counts']['BusUpgr'] == 1, f"Under MSI, read then write of private data needs a BusRd and a BusUpgr; got {r['counts']}."
priv = [(c, op, c) for c in range(4) for op in 'RW']
a, b = run(priv, 4, 'MSI')['counts'], run(priv, 4)['counts']
assert sum(a.values()) == 8 and sum(b.values()) == 4, f"Four cores each reading then writing a private line: MSI 8 transactions, MESI 4; got {sum(a.values())} and {sum(b.values())}."
for seed in range(25):
    n = 2 + seed % 3
    check_prefixes(rand_trace(100 + seed, n), n, 'MSI')
```

::: right
Right. The same traces stay coherent under MSI, and private data costs twice the bus transactions.
:::
:::

::: explain
## Why do protocol designers test coherence with random traces and invariants instead of a list of hand-written cases?

::: model
A coherence protocol's states multiply across caches and lines, and its bugs usually need an unlucky combination: a particular state in one cache, a request from another, then a third access in a certain order. Hand-written cases cover the situations a designer thought of, which are exactly the ones least likely to hide a bug. Random traces reach combinations nobody listed, and invariants such as "a modified copy is the only copy" and "a read returns the latest write" define correctness for every possible trace at once, so the checker doesn't need to know the right answer in advance. Running thousands of random traces and checking after every step finds the rare sequence that breaks the protocol, and the failing trace can then be shrunk to a short example.
:::
:::

::: practice

::: check
given: n = 3 | 8 | 20
answer: n
tolerance: 0

## Under MESI, {n} cores each read then write their own private line. How many bus transactions in all?

::: misses
- [any] One BusRd each; the writes move E to M silently.
:::
:::

::: check
given: n = 3 | 8 | 20
answer: 2*n
tolerance: 0

## Under MSI, {n} cores each read then write their own private line. How many bus transactions?

::: misses
- [any] A BusRd and a BusUpgr each.
:::
:::

::: check
given: k = 5 | 20 | 100
answer: 2*k
tolerance: 0

## Two cores alternately write one line, {k} times each, starting with core 0. How many BusRdX transactions are there?

::: misses
- [any] Every write misses, the first included: the first finds the line nowhere, every later one finds it modified in the other cache.
:::
:::
:::
