About: how pages are checked

tests/sims/mesi.test.ts

The automated tests for the /simulators/cpu-cache simulator. They run the model on its own, outside the browser, and compare it with a reference that doesn't depend on the model being right. They run on every change to the simulator's code.

  1. On 300 random runs of 400 reads and writes, every read returns the value last written to that address.
  2. A line is never Modified or Exclusive in one cache while any other cache holds it, and no cache holds more than four lines.
// /simulators/cpu-cache: MESI cache coherence across four cores.
import { test } from 'node:test';
import { System, CORES, LINE, WORD } from '../../src/lib/sims/mesi.ts';
import { checker, lcg } from './check.ts';

test('on 300 random runs of 400 reads and writes, every read returns the value last written to that address', () => {
	const { ok, done } = checker();
	const r = lcg(5);
	for (let t = 0; t < 300; t++) {
		const sys = new System(), mem = new Map<number, number>();
		const lines = 2 + Math.floor(r() * 8);
		for (let k = 0; k < 400; k++) {
			const core = Math.floor(r() * CORES), addr = Math.floor(r() * lines) * LINE + Math.floor(r() * 8) * WORD;
			if (r() < 0.5) { const v = Math.floor(r() * 1e6); sys.run({ core, kind: 'W', addr, value: v }); mem.set(addr, v); }
			else { const res = sys.run({ core, kind: 'R', addr }); ok(res.value === (mem.get(addr) ?? 0), `core ${core} read ${res.value} at ${addr}, last write was ${mem.get(addr) ?? 0}`); }
		}
	}
	done();
});

test('a line is never Modified or Exclusive in one cache while any other cache holds it, and no cache holds more than four lines', () => {
	const { ok, done } = checker();
	const r = lcg(6);
	for (let t = 0; t < 300; t++) {
		const sys = new System();
		const lines = 2 + Math.floor(r() * 8);
		for (let k = 0; k < 400; k++) {
			const core = Math.floor(r() * CORES), addr = Math.floor(r() * lines) * LINE + Math.floor(r() * 8) * WORD;
			sys.run(r() < 0.5 ? { core, kind: 'W', addr, value: k } : { core, kind: 'R', addr });
			// checked here from the raw cache contents, not with the model's own invariant check
			const holders = new Map<number, string[]>();
			sys.l1.forEach((set) => set.forEach((l) => { if (l.state !== 'I') holders.set(l.tag, [...(holders.get(l.tag) ?? []), l.state]); }));
			for (const [tag, states] of holders) ok(!(states.some((s) => s === 'M' || s === 'E') && states.length > 1), `line ${tag} held as ${states.join(',')}`);
			ok(sys.l1.every((set) => set.length <= 4), 'a cache holds more than four lines');
		}
	}
	done();
});

Shared helpers: tests/sims/check.ts. The model under test is imported from src/lib/sims/.

Published