tests/sims/sharding.test.ts
The automated tests for the /simulators/database-sharding 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.
- For every shard key and method, each row lives on exactly one shard and every query is sent to every shard holding a matching row.
- The number of rows reported as moving when a shard is added is the number that really change shard.
// /simulators/database-sharding: shard keys, hash slots versus ranges, query routing and resharding.
import { test } from 'node:test';
import { workload, layout, addShard, distribution, shardOf, queries, route, KEYS, METHODS } from '../../src/lib/sims/sharding.ts';
import { checker } from './check.ts';
const rows = workload(1);
test('for every shard key and method, each row lives on exactly one shard and every query is sent to every shard holding a matching row', () => {
const { ok, done } = checker();
const qs = queries(rows);
for (const k of KEYS) for (const m of METHODS) {
const L = layout(rows, k.id, m.id, 4);
ok(distribution(rows, L).reduce((a, b) => a + b) === rows.length, `${k.id}/${m.id}: shard row counts do not add up`);
for (const q of qs) {
const sent = route(L, q);
const holders = distribution(rows, L, q.match).map((c, i) => (c ? i : -1)).filter((i) => i >= 0);
ok(holders.every((h) => sent.includes(h)), `${k.id}/${m.id}: query ${q.id} misses a shard that holds matching rows`);
}
}
done();
});
test('the number of rows reported as moving when a shard is added is the number that really change shard', () => {
const { ok, done } = checker();
for (const k of KEYS) for (const m of METHODS) {
let L = layout(rows, k.id, m.id, 4);
for (let step = 0; step < 4; step++) {
const { next, moved } = addShard(rows, L);
let real: number;
if (m.id === 'range') {
// a range split renumbers later shards, so count rows that leave the shard being split
const d = distribution(rows, L), big = d.indexOf(Math.max(...d));
real = rows.filter((r) => shardOf(L, r) === big && shardOf(next, r) !== big).length;
} else real = rows.filter((r) => shardOf(L, r) !== shardOf(next, r)).length;
ok(real === moved, `${k.id}/${m.id} ${L.n} -> ${next.n} shards: ${moved} reported, ${real} really moved`);
L = next;
}
}
done();
});
Shared helpers: tests/sims/check.ts. The model under test is imported from src/lib/sims/.