tests/sims/retry.test.ts
The automated tests for the /simulators/retry-strategy 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 backoff policy stays inside its range and under the cap; full jitter averages half the exponential.
- The load simulation accounts for every client and never serves more than capacity.
// /simulators/retry-strategy
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { simulate, sleep, rng, POLICIES, type Params } from '../../src/lib/sims/retry.ts';
import { checker } from './check.ts';
test('every backoff policy stays inside its range and under the cap; full jitter averages half the exponential', () => {
const { ok, done } = checker();
const r = rng(3);
for (const pol of POLICIES) {
const p: Params = { policy: pol.id, base: 10, cap: 1000, maxAttempts: 10 };
let prev = 10, sum = 0;
for (let k = 0; k < 9; k++) for (let i = 0; i < 2000; i++) {
const s = sleep(p, k, prev, r);
ok(s.v >= s.lo - 1e-9 && s.v <= s.hi + 1e-9 && s.v <= p.cap + 1e-9, `${pol.id} sleep ${s.v} outside [${s.lo}, ${s.hi}]`);
if (k === 4 && pol.id === 'full') sum += s.v;
if (pol.id === 'decorrelated') prev = s.v;
}
// attempt 4: base·2^4 = 160 ms, so full jitter averages 80 ms
if (pol.id === 'full') ok(Math.abs(sum / 2000 - 80) < 4, `full jitter mean ${sum / 2000}`);
}
done();
});
test('the load simulation accounts for every client and never serves more than capacity', () => {
for (const pol of POLICIES) {
const sim = simulate({ policy: pol.id, base: 10, cap: 1000, maxAttempts: 10 }, 500, 20, 50, 5, 4000);
assert.equal(sim.succeeded + sim.gaveUp, 500, pol.id);
assert.equal(sim.attempts, sim.ticks.reduce((a, b) => a + b, 0), pol.id);
assert.equal(sim.succeeded, sim.ok.reduce((a, b) => a + b, 0), pol.id);
assert.ok(sim.ok.every((x) => x <= 20), pol.id);
}
});
Shared helpers: tests/sims/check.ts. The model under test is imported from src/lib/sims/.