tests/sims/distcache.test.ts
The automated tests for the /simulators/distributed-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.
- Adding a node to n moves about n/(n+1) of keys with modulo placement and about 1/(n+1) with a hash ring.
- With request coalescing, one hot key costs one database fetch per expiry instead of one per waiting request.
- After a write deletes the cached copy, the next read gets the new value.
// /simulators/distributed-cache: key placement, request coalescing and invalidation.
import { test } from 'node:test';
import { Sim, moved, owner } from '../../src/lib/sims/distCache.ts';
import { checker } from './check.ts';
test('adding a node to n moves about n/(n+1) of keys with modulo placement and about 1/(n+1) with a hash ring', () => {
const { ok, done } = checker();
for (const n of [3, 4, 5, 8]) {
const before = Array.from({ length: n }, (_, i) => i), after = [...before, n];
const mm = moved(5000, before, after, 'modulo'), mr = moved(5000, before, after, 'ring');
ok(Math.abs(mm - n / (n + 1)) < 0.03, `${n} -> ${n + 1} nodes, modulo: ${(mm * 100).toFixed(1)}% moved, expected ${((100 * n) / (n + 1)).toFixed(1)}%`);
ok(Math.abs(mr - 1 / (n + 1)) < 0.06, `${n} -> ${n + 1} nodes, ring: ${(mr * 100).toFixed(1)}% moved, expected ${(100 / (n + 1)).toFixed(1)}%`);
}
const counts = [0, 0, 0, 0];
for (let k = 0; k < 20000; k++) counts[owner(k, [0, 1, 2, 3], 'ring')]++;
ok(Math.max(...counts) / Math.min(...counts) < 1.5, `ring load is uneven: ${counts}`);
done();
});
test('with request coalescing, one hot key costs one database fetch per expiry instead of one per waiting request', () => {
const { ok, done } = checker();
const s = new Sim({ coalesce: true, keys: 1, zipf: 1 });
s.run(30_000);
const expected = Math.ceil(30_000 / s.cfg.ttlMs) + 1;
ok(s.totals.dbFetches <= expected + 1, `${s.totals.dbFetches} fetches with coalescing, expected about ${expected}`);
const s2 = new Sim({ coalesce: false, keys: 1, zipf: 1 });
s2.run(30_000);
ok(s2.totals.dbFetches > 10 * s.totals.dbFetches, `without coalescing only ${s2.totals.dbFetches} fetches`);
done();
});
test('after a write deletes the cached copy, the next read gets the new value', () => {
const { ok, done } = checker();
const s = new Sim({ keys: 1, zipf: 1 });
s.run(1000);
s.update(0);
s.run(200);
const e = s.store[s.live[0]].get(0) ?? [...s.store].map((m) => m.get(0)).find(Boolean);
ok(!!e && e.v === 1, 'the cache still serves the old value');
done();
});
Shared helpers: tests/sims/check.ts. The model under test is imported from src/lib/sims/.