Files
puter/src/backend/benchUtil.test.ts
T
Daniel Salazar 9ca1acf634 Benchmarks that gate PRs on I/O regressions, wider test baseline, and npm run check (#4644)
* feat(bench): backend benchmarks that fail a PR for waterfalled or uncached I/O

A scenario runs a request against the in-memory backend and records every
SQL, key-value, Redis and object-storage round trip on a modeled clock, then
reports round trips per destination, serial stages and modeled latency.
tools/bench.mjs runs the scenarios on a base commit and on the head and fails
on a regression the pull request description does not accept; benchmarks.yaml
runs that on every pull request.

Also adds npm run check (lint, type check, related tests and the benchmark
comparison for the files a branch changed) and describes the distributed
deployment in AGENTS.md.

* test(bench): scenarios for fs, kv, auth, apps, permissions, sharing and hosted sites

* test(puter-js): count the SDK unit tests in the coverage report

Only the bundle the API runners load was instrumented, so the unit tests next
to the SDK source never counted. In coverage mode the vitest config now
instruments SDK source for them and writes one shard per test file.

* test(puter-js): unit tests for ui messaging, dialogs, components, uploads, peer and smaller modules

* test(backend): cover fs, permission, app, worker, sharing, broadcast and user edge cases

* fix(backend): fs write flags are stored as booleans, app stats weeks are ISO weeks

- A write's boolean flags reach the store only once read as booleans; any
  positive number reads as true.
- App open stats grouped by week use ISO 8601 weeks for both the buckets
  and their labels on every database engine, so the two agree across a
  year boundary.

* fix(puter-js): dialog token source, legacy upload cancel, submenu state, typed-array views

- The sign-in dialog takes the token only from the popup it opened, and
  stops listening when it leaves the page.
- Cancelling a legacy upload rejects with `upload_aborted` and no longer
  runs the `error` callback.
- A context menu's submenu stays in step with its parent when the parent
  item is pressed or the submenu closes itself.
- The FileReader polyfill reads a typed-array view through its own offset
  and length.

* ci(bench): benchmark a pull request as merged into its base

The comparison ran the branch's own head against the tip of the base
branch, so a branch behind its base was charged for (or credited with)
what the base gained since. The head side is now the merge commit and
the base side its first parent. Shards also get a 15 minute timeout.

* test(broadcast): shutdown drain tests send boot's own events first

Boot queues cache updates that flush 10 ms later. A test body that
started after that flush counted it as its own request, which failed
'bounds a hung flush in onServerShutdown' on a slow runner.
2026-11-14 13:57:03 -07:00

160 lines
5.2 KiB
TypeScript

import { afterEach, describe, expect, it } from 'vitest';
import {
DISTRIBUTED_LATENCY_MS,
instrumentClientIo,
profileIo,
type IoInstrumentation,
} from './benchUtil.js';
import type { PuterServer } from './server.js';
const fakeClients = () => {
const db = {
read: async () => [{ id: 1 }],
// As in the SQLite client, a primary read is a read underneath.
pread: async () => db.read(),
write: async () => ({ affectedRows: 1 }),
batchWrite: async () => undefined,
hasReadReplica: () => false,
};
const dynamo = {
get: async () => ({ Item: {} }),
put: async () => ({}),
batchGet: async () => ({}),
};
const redis = {
get: async () => 'value',
set: async () => 'OK',
xread: async () => null,
pipeline: () => ({ exec: async () => [] }),
};
const s3Client = { send: async () => ({}) };
const s3 = { get: () => s3Client };
return { db, dynamo, redis, s3 };
};
describe('instrumentClientIo', () => {
let io: IoInstrumentation | undefined;
const setup = () => {
const clients = fakeClients();
io = instrumentClientIo({ clients } as unknown as PuterServer);
return clients;
};
const profile = async (run: () => Promise<unknown>) => {
io!.begin();
await run();
const answeredAt = io!.now();
return profileIo(await io!.end(), answeredAt);
};
afterEach(() => io?.restore());
it('counts calls issued together as one stage', async () => {
const { db } = setup();
const result = await profile(() =>
Promise.all([db.read(), db.read(), db.read()]),
);
expect(result).toEqual({
roundTrips: { dbRead: 3 },
serialStages: 1,
latencyMs: DISTRIBUTED_LATENCY_MS.dbRead,
});
});
it('keeps real time between calls off the modeled clock', async () => {
const { db } = setup();
const result = await profile(() =>
Promise.all([
db.read(),
(async () => {
await new Promise((resolve) => setTimeout(resolve, 1));
await db.read();
})(),
]),
);
expect(result.serialStages).toBe(1);
expect(result.latencyMs).toBe(DISTRIBUTED_LATENCY_MS.dbRead);
});
it('counts calls issued one after another as a waterfall', async () => {
const { db } = setup();
const result = await profile(async () => {
await db.read();
await db.read();
await db.read();
});
expect(result).toEqual({
roundTrips: { dbRead: 3 },
serialStages: 3,
latencyMs: 3 * DISTRIBUTED_LATENCY_MS.dbRead,
});
});
it('charges a primary read and a write the cross-region cost', async () => {
const { db } = setup();
const result = await profile(async () => {
await db.pread();
await db.write();
});
// The primary read's inner `read()` is the same round trip.
expect(result.roundTrips).toEqual({ dbPrimaryRead: 1, dbWrite: 1 });
expect(result.latencyMs).toBe(
DISTRIBUTED_LATENCY_MS.dbPrimaryRead +
DISTRIBUTED_LATENCY_MS.dbWrite,
);
});
it('takes the slowest branch of parallel work as the latency', async () => {
const { db, redis, dynamo } = setup();
const result = await profile(() =>
Promise.all([
db.write(),
(async () => {
await redis.get();
await dynamo.get();
})(),
]),
);
expect(result.roundTrips).toEqual({
dbWrite: 1,
redis: 1,
dynamoRead: 1,
});
expect(result.serialStages).toBe(2);
expect(result.latencyMs).toBe(DISTRIBUTED_LATENCY_MS.dbWrite);
});
it('counts work left running after the answer as load, not latency', async () => {
const { db, redis } = setup();
const result = await profile(async () => {
await redis.get();
void db.write();
});
expect(result.roundTrips).toEqual({ redis: 1, dbWrite: 1 });
expect(result.serialStages).toBe(1);
expect(result.latencyMs).toBe(DISTRIBUTED_LATENCY_MS.redis);
});
it('counts a pipeline as one round trip and skips blocking polls', async () => {
const { redis, s3 } = setup();
const result = await profile(async () => {
await redis.pipeline().exec();
await redis.xread();
await s3.get().send();
});
expect(result.roundTrips).toEqual({ redis: 1, s3: 1 });
});
it('reports a read replica while instrumented and restores the clients', async () => {
const clients = setup();
const original = fakeClients();
expect(clients.db.hasReadReplica()).toBe(true);
io!.restore();
expect(clients.db.hasReadReplica()).toBe(false);
expect(Object.keys(clients.db)).toEqual(Object.keys(original.db));
io!.begin();
await clients.db.read();
expect(await io!.end()).toEqual([]);
});
});