Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions packages/stim-cli/src/__tests__/daemon-ladder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { dormantCandidates, pendingDormant, runDormantPass } from '../daemon/sta
import { recordCreatedDevice } from '../devices/created-devices.ts';
import { parkSim, readParked } from '../devices/sim-pool.ts';
import * as android from '../devices/android.ts';
import * as simPool from '../devices/sim-pool.ts';
import * as ios from '../devices/ios.ts';
import type { IosSimRecord } from '../devices/ios.ts';
import * as teardown from '../devices/teardown.ts';
Expand Down Expand Up @@ -1226,3 +1227,77 @@ describe.skipIf(process.platform === 'win32')(
}, 20_000);
},
);

describe('rung timing records', () => {
const steps = () =>
log.mock.calls
.filter(([, event]) => event === 'daemon_step')
.map(([logLevel, , , fields]) => Object.assign({ logLevel }, fields));
const run = (operation?: ReturnType<typeof testContext>) => {
const config = loadConfig();
if (!config) throw new Error('missing fixture config');
return runLadder(
{
config,
act: true,
log,
devices: [],
simsFailed: false,
remeasure: async () => pressure('high'),
fromRung: 2,
lastRung: 2,
...(operation ? { operation } : {}),
},
pressure('high'),
);
};

beforeEach(() => {
let clock = 0;
vi.spyOn(performance, 'now').mockImplementation(() => (clock += 100));
});

test('a rung that finishes records its start, duration, actions and outcome', async () => {
vi.spyOn(simPool, 'readParked').mockReturnValue([]);

await run();

expect(steps()).toEqual([
{
logLevel: 'debug',
step: 'rung',
rung: 2,
pressureLevel: 'high',
startedAt: expect.stringMatching(/^\d{4}-\d\d-\d\dT[\d:.]+Z$/),
durationMs: 100,
items: 0,
outcome: 'finished',
},
]);
});

test('a rung that throws records the failure, and the ladder goes on as before', async () => {
vi.spyOn(simPool, 'readParked').mockImplementation(() => {
throw new Error('boom');
});

const { actions } = await run();

expect(steps()).toMatchObject([{ step: 'rung', rung: 2, outcome: 'threw', error: 'boom' }]);
expect(actions).toMatchObject([{ rung: 2, kind: 'rung', outcome: 'failed', detail: 'boom' }]);
expect(log).toHaveBeenCalledWith('warn', 'pressure_rung_failed', 'rung 2 failed: boom');
});

test('a rung stopped by an abort records it and the abort still reaches the caller', async () => {
const controller = new AbortController();
vi.spyOn(simPool, 'readParked').mockImplementation(() => {
controller.abort();
throw new Error('stopped');
});

await expect(run(testContext({ signal: controller.signal }))).rejects.toMatchObject({ name: 'AbortError' });

expect(steps()).toMatchObject([{ step: 'rung', rung: 2, outcome: 'aborted' }]);
expect(steps()[0]).not.toHaveProperty('error');
});
});
130 changes: 130 additions & 0 deletions packages/stim-cli/src/__tests__/daemon-step-timing.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import { dormantCandidates } from '../daemon/stages.ts';
import { timedStep, type DaemonLog } from '../daemon/step-timing.ts';

const log = vi.fn<DaemonLog>();

beforeEach(() => {
log.mockReset();
});

test('the step returns what it returned and records the items it visited', async () => {
const result = { rows: [1, 2, 3] };

const returned = await timedStep(log, 'idle_stage_candidates', async (tally) => ((tally.items = 7), result));

expect(returned).toBe(result);
expect(log).toHaveBeenCalledWith(
'debug',
'daemon_step',
expect.any(String),
expect.objectContaining({ step: 'idle_stage_candidates', items: 7, outcome: 'finished' }),
);
});

test('the step rethrows the error object it threw, with its properties, and a failing log does not replace it', async () => {
const failure = Object.assign(new Error('unverified cleanup'), {
code: 'STIM_CLAIM_UNAVAILABLE',
reportCleanup: true,
});
log.mockImplementation(() => {
throw new Error('log full');
});

await expect(
timedStep<string[]>(log, 'plan_history', () => Promise.reject(failure), { items: (planned) => planned?.length }),
).rejects.toBe(failure);

expect(log).toHaveBeenCalledTimes(1);
});

test('without a log the step only runs the function', async () => {
await expect(timedStep(undefined, 'plan_rung6', async () => 'plan')).resolves.toBe('plan');
});

test('a throw is recorded as threw with its message, and the same error object is rethrown', async () => {
const failure = new Error('boom');

await expect(timedStep(log, 'plan_rung6', () => Promise.reject(failure))).rejects.toBe(failure);

expect(log.mock.calls[0]?.[3]).toMatchObject({ step: 'plan_rung6', outcome: 'threw', error: 'boom' });
});

test('a throw while the signal is aborted is recorded as aborted, without an error field', async () => {
const controller = new AbortController();
const failure = new Error('stopped');

await expect(
timedStep(
log,
'plan_worktrees',
async () => {
controller.abort();
throw failure;
},
{ signal: controller.signal },
),
).rejects.toBe(failure);

expect(log.mock.calls[0]?.[3]).toMatchObject({ outcome: 'aborted' });
expect(log.mock.calls[0]?.[3]).not.toHaveProperty('error');
});

test('a thrown value that cannot be described is still the value that is rethrown', async () => {
const odd = {
toString() {
throw new Error('no string');
},
};

await expect(timedStep(log, 'plan_history', () => Promise.reject(odd))).rejects.toBe(odd);

expect(log.mock.calls[0]?.[3]).toMatchObject({ outcome: 'threw' });
});

test('through the shape every daemon log writer builds, the record keeps its severity and the pressure level', async () => {
const written: Record<string, unknown>[] = [];
const writer: DaemonLog = (level, event, msg, fields = {}) =>
written.push({ src: 'stimd', level, event, msg, ...fields });

await timedStep(writer, 'rung', async () => undefined, {
fields: { rung: 5, pressureLevel: 'critical', level: 'critical', src: 'x', event: 'x', msg: 'x', ts: 1 },
});

expect(written).toEqual([
expect.objectContaining({
src: 'stimd',
level: 'debug',
event: 'daemon_step',
step: 'rung',
rung: 5,
pressureLevel: 'critical',
outcome: 'finished',
}),
]);
expect(written[0]).not.toHaveProperty('ts');
expect(written[0]?.msg).toMatch(/^rung 5 finished in \d+ms$/);
});

test('an evidence loop returns what it returned without a log, and writes its record with one', async () => {
const config = { version: 2 as const, projects: {}, repos: {} };
const reading = { devices: [], simsFailed: false };

const plain = await dormantCandidates(config, reading, 1000);
const timed = await dormantCandidates(config, { ...reading, log }, 1000);

expect(timed).toEqual(plain);
expect(log.mock.calls[0]?.[3]).toMatchObject({ step: 'dormant_candidates', items: 0, outcome: 'finished' });
});

test('an error whose name cannot be read is still the error that is rethrown, recorded as threw', async () => {
const odd = new Error('odd');
Object.defineProperty(odd, 'name', {
get() {
throw new Error('no name');
},
});

await expect(timedStep(log, 'plan_history', () => Promise.reject(odd))).rejects.toBe(odd);

expect(log.mock.calls[0]?.[3]).toMatchObject({ outcome: 'threw' });
});
37 changes: 35 additions & 2 deletions packages/stim-cli/src/__tests__/disk-usage.integration.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { releaseClaim, tryAcquireClaim } from '@stim-cli/core/ownership-claim';
import { diskUsageWalkClaims, readDiskUsage, readDiskUsageFailure } from '@stim-cli/core/state';
import {
diskUsageCacheFile,
diskUsageWalkClaims,
readDiskUsage,
readDiskUsageFailure,
readJsonObject,
} from '@stim-cli/core/state';
import { knownPrivateBytes, refreshMeasure, trustedMeasure } from '../disk-usage.ts';
import { getExecutor, resetExecutor, setExecutor } from '../exec.ts';

Expand Down Expand Up @@ -130,3 +136,30 @@ test('a claimed walk whose child exits before its identity can be recorded is st

expect(result.outcome).toBe('measured');
});

test('a walk records how long it took, and an entry written without it still reads', async () => {
const plain = join(scratch, 'timed');
mkdirSync(plain);
writeFileSync(join(plain, 'blob'), Buffer.alloc(10_000));
let clock = Date.parse('2026-11-04T10:00:00.000Z');
const real = getExecutor();
setExecutor({
...real,
runFileAsync: (file, args, opts) => {
if (file === 'nice') clock += 1234;
return real.runFileAsync(file, args, opts);
},
});

const walked = await refreshMeasure(plain, { ...options, now: () => clock, claim: true });

expect(walked.outcome).toBe('measured');
expect(readJsonObject(diskUsageCacheFile(plain))?.walkMs).toBe(1234);
expect(readDiskUsage(plain)).toEqual(walked.measure);

const { walkMs: _walkMs, ...legacy } = JSON.parse(readFileSync(diskUsageCacheFile(plain), 'utf8'));
writeFileSync(diskUsageCacheFile(plain), JSON.stringify(legacy));
expect(readJsonObject(diskUsageCacheFile(plain))?.walkMs).toBeUndefined();
expect(readDiskUsage(plain)).toEqual(walked.measure);
expect((await refreshMeasure(plain, { ...options, now: () => clock })).outcome).toBe('fresh');
});
Loading
Loading