About: how pages are checked

tests/sims/quorum.test.ts

The automated tests for the /simulators/read-write-quorum 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. Every read set meets every write set exactly when R + W > N (checked over all subsets).
  2. The exact stale-read probability agrees with a Monte Carlo run.
  3. With overlapping quorums, no successful read ever returns a stale value.
  4. Right after a write to 2 of 5 replicas, C(3,2) of the C(5,2) read sets are stale.
// /simulators/read-write-quorum
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { cluster, write, read, catchUp, staleExact, staleSimulated, staleSets, choose } from '../../src/lib/sims/quorum.ts';
import { checker } from './check.ts';

test('every read set meets every write set exactly when R + W > N (checked over all subsets)', () => {
	const { ok, done } = checker();
	const bits = (x: number) => x.toString(2).split('1').length - 1;
	for (const n of [3, 4, 5, 7]) for (let r = 1; r <= n; r++) for (let w = 1; w <= n; w++) {
		let all = true;
		for (let a = 0; a < 1 << n && all; a++) if (bits(a) === r) for (let b = 0; b < 1 << n; b++) if (bits(b) === w && (a & b) === 0) { all = false; break; }
		ok(all === r + w > n, `N=${n} R=${r} W=${w}`);
		ok((staleExact(n, r, w) === 0) === r + w > n, `stale probability N=${n} R=${r} W=${w}`);
	}
	done();
});

test('the exact stale-read probability agrees with a Monte Carlo run', () => {
	for (const [n, r, w] of [[3, 1, 1], [3, 1, 2], [5, 2, 2], [5, 1, 3], [5, 2, 3]]) {
		const e = staleExact(n, r, w), s = staleSimulated(n, r, w, 40000);
		assert.ok(Math.abs(e - s) < 0.01, `N=${n} R=${r} W=${w}: ${e} vs ${s}`);
	}
});

test('with overlapping quorums, no successful read ever returns a stale value', () => {
	const { ok, done } = checker();
	for (let seed = 1; seed < 300; seed++) for (const [n, r, w] of [[3, 2, 2], [5, 3, 3], [5, 1, 5], [5, 4, 2]]) {
		const c = cluster(n, r, w, seed % 2 === 0, seed);
		for (let k = 0; k < 40; k++) {
			const x = c.seed % 4;
			if (x === 1) { const res = read(c); ok(!res.ok || !res.stale, `stale read N=${n} R=${r} W=${w} seed ${seed}`); }
			else if (x === 2) catchUp(c);
			else write(c);
			c.seed = (c.seed * 69069 + 1) >>> 0;
		}
	}
	done();
});

test('right after a write to 2 of 5 replicas, C(3,2) of the C(5,2) read sets are stale', () => {
	const c = cluster(5, 2, 2, false, 3);
	write(c);
	const s = staleSets(c);
	assert.equal(s.stale, choose(3, 2));
	assert.equal(s.total, choose(5, 2));
});

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

Published