tests/sims/lsm.test.ts
The automated tests for the /simulators/lsm-tree 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.
- Every read returns what a plain map would, through puts, deletes and compactions.
- The Bloom filter's false-positive rate matches (1 − e^(−kn/m))^k.
// /simulators/lsm-tree: an LSM tree with leveled or tiered compaction and Bloom filters.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { LSM, rng, Bloom } from '../../src/lib/sims/lsm.ts';
import { checker } from './check.ts';
test('every read returns what a plain map would, through puts, deletes and compactions', () => {
const { ok, done } = checker();
for (const style of ['leveled', 'tiered'] as const) for (const bits of [0, 5, 10]) for (const seed of [1, 2, 3]) {
const t = new LSM({ style, bitsPerKey: bits });
const ref = new Map<number, string>();
const r = rng(seed);
for (let i = 0; i < 6000; i++) {
const x = r(), k = Math.floor(r() * 1000);
if (x < 0.55) { t.put(k, 'v' + i); ref.set(k, 'v' + i); }
else if (x < 0.65) { t.del(k); ref.delete(k); }
else ok(t.get(k) === (ref.get(k) ?? null), `${style} bits=${bits} seed=${seed} op ${i}: get(${k}) = ${t.get(k)}, expected ${ref.get(k)}`);
if (i % 500 === 0) {
t.levels.forEach((runs, li) => runs.forEach((run) => { for (let j = 1; j < run.length; j++) ok(run[j].min > run[j - 1].max, `${style}: files overlap in level ${li}`); }));
if (style === 'leveled') t.levels.forEach((runs, li) => ok(li === 0 || runs.length <= 1, `leveled: level ${li} has ${runs.length} runs`));
ok(t.live() === ref.size, `${style}: ${t.live()} live keys, expected ${ref.size}`);
}
}
}
done();
});
test('the Bloom filter\'s false-positive rate matches (1 − e^(−kn/m))^k', () => {
for (const b of [5, 10]) {
const bl = new Bloom(1000, b);
for (let k = 0; k < 1000; k++) bl.add(k * 7919);
let fp = 0;
for (let k = 0; k < 100000; k++) if (bl.mayContain(10_000_000 + k)) fp++;
const theory = (1 - Math.exp((-bl.h * 1000) / bl.m)) ** bl.h;
assert.ok(Math.abs(fp / 100000 - theory) / theory < 0.25, `${b} bits per key: measured ${fp / 100000}, theory ${theory}`);
for (let k = 0; k < 1000; k++) assert.ok(bl.mayContain(k * 7919), 'false negative');
}
});
Shared helpers: tests/sims/check.ts. The model under test is imported from src/lib/sims/.