230 lines
8.1 KiB
TypeScript
230 lines
8.1 KiB
TypeScript
import { describe, expect, test } from 'bun:test';
|
|
import { walkForwardDataset } from '../../test/fixtures/walk-forward';
|
|
import { tableFixture } from '../benchmark-experiment-tables';
|
|
import {
|
|
runResearchCycle,
|
|
validateResearchCycle,
|
|
type ResearchCycleEvent,
|
|
type ResearchCyclePlan,
|
|
} from '../examples/research-cycle';
|
|
import { ResearchClient } from '../research-client';
|
|
|
|
const projectId = '22222222-2222-4222-8222-222222222222';
|
|
const detail = tableFixture(1);
|
|
const plan = (): ResearchCyclePlan => ({
|
|
cycleId: 'bounded-example',
|
|
projectId,
|
|
backtestId: detail.backtestId,
|
|
maxTotalTrials: 5,
|
|
hypothesis: {
|
|
title: 'Unvalidated suggestion',
|
|
proposition: 'A regime filter may help',
|
|
validationCriteria: 'Train-only selection then untouched test and costs',
|
|
},
|
|
candidates: [
|
|
{
|
|
key: 'trend',
|
|
name: 'Trend',
|
|
rationale: 'Test an explicit volatility filter',
|
|
package: {
|
|
...structuredClone(detail.preview.request.strategy.package),
|
|
execution: { kind: 'isolated-candidate/v1', warmupBars: 3 },
|
|
},
|
|
parameters: { fastPeriod: 2, slowPeriod: 3 },
|
|
grid: {},
|
|
recipe: walkForwardDataset().windows[0]!,
|
|
costScenarios: [{ feeRate: '0.02', slippageRate: '0.01' }],
|
|
},
|
|
],
|
|
});
|
|
const budget = () => ({
|
|
agent: {
|
|
id: 'agent:11111111-1111-4111-8111-111111111111',
|
|
name: 'Research only',
|
|
enabled: true,
|
|
revision: 1,
|
|
allowedProjectIds: [projectId],
|
|
grants: [
|
|
{ backtestId: detail.backtestId, policyHash: 'a'.repeat(64), allowOwnCandidates: true },
|
|
],
|
|
limits: {
|
|
maxActiveTrials: 4,
|
|
maxTrialsPerExperiment: 4,
|
|
maxBarEvaluationsPerExperiment: 10000,
|
|
maxAttemptWallMs: 60000,
|
|
maxAttempts: 1,
|
|
},
|
|
createdAt: '2026-01-01T00:00:00.000Z',
|
|
updatedAt: '2026-01-01T00:00:00.000Z',
|
|
},
|
|
activeTrials: 0,
|
|
remainingActiveTrials: 4,
|
|
});
|
|
function client(reply: (path: string, body: unknown) => Response | Promise<Response>) {
|
|
const calls: { path: string; body: unknown }[] = [];
|
|
const api = new ResearchClient({
|
|
origin: 'http://127.0.0.1:2003',
|
|
token: 'sb-research.fixture-only-token',
|
|
fetch: (async (input: string | URL | Request, init?: RequestInit) => {
|
|
const path = new URL(String(input)).pathname,
|
|
body: unknown = init?.body ? JSON.parse(String(init.body)) : undefined;
|
|
calls.push({ path, body });
|
|
return reply(path, body);
|
|
}) as typeof fetch,
|
|
});
|
|
return { api, calls };
|
|
}
|
|
describe('bounded executable research cycle', () => {
|
|
test('counts training, future holdouts and baseline costs before any request', async () => {
|
|
const value = plan();
|
|
expect(validateResearchCycle(value).totalTrials).toBe(5);
|
|
value.maxTotalTrials = 4;
|
|
const f = client(() => {
|
|
throw new Error('No network expected');
|
|
});
|
|
await expect(
|
|
runResearchCycle(f.api, value, { onEvent: async () => {}, poll: { timeoutMs: 1000 } })
|
|
).rejects.toThrow('total trial bound');
|
|
expect(f.calls).toHaveLength(0);
|
|
});
|
|
test('rejects Cartesian overflow, duplicate candidate keys and nonisolated packages', () => {
|
|
const overflow = plan();
|
|
overflow.maxTotalTrials = 10000;
|
|
overflow.candidates[0]!.grid = {
|
|
a: Array.from({ length: 11 }, (_, i) => i),
|
|
b: Array.from({ length: 10 }, (_, i) => i),
|
|
};
|
|
expect(() => validateResearchCycle(overflow)).toThrow('experiment trial bound');
|
|
const duplicate = plan();
|
|
duplicate.candidates.push(structuredClone(duplicate.candidates[0]!));
|
|
expect(() => validateResearchCycle(duplicate)).toThrow('unique');
|
|
const unsafe = plan();
|
|
delete unsafe.candidates[0]!.package.execution;
|
|
expect(() => validateResearchCycle(unsafe)).toThrow('explicitly isolated');
|
|
});
|
|
test('grant, per-admission budgets and poll input fail before hypothesis mutation', async () => {
|
|
const revoked = budget();
|
|
revoked.agent.grants[0]!.allowOwnCandidates = false;
|
|
const f = client(() => Response.json(revoked));
|
|
await expect(
|
|
runResearchCycle(f.api, plan(), { onEvent: async () => {}, poll: { timeoutMs: 1000 } })
|
|
).rejects.toThrow('explicit');
|
|
expect(f.calls).toHaveLength(1);
|
|
const narrow = budget();
|
|
narrow.agent.limits.maxActiveTrials = 1;
|
|
const g = client(() => Response.json(narrow));
|
|
await expect(
|
|
runResearchCycle(g.api, plan(), { onEvent: async () => {}, poll: { timeoutMs: 1000 } })
|
|
).rejects.toThrow('trial budget');
|
|
expect(g.calls).toHaveLength(1);
|
|
await expect(
|
|
runResearchCycle(g.api, plan(), { onEvent: async () => {}, poll: { timeoutMs: 0 } })
|
|
).rejects.toThrow();
|
|
expect(g.calls).toHaveLength(1);
|
|
});
|
|
test('a lost non-idempotent hypothesis response stops once and retains its exact intent', async () => {
|
|
const events: ResearchCycleEvent[] = [];
|
|
const f = client(path => {
|
|
if (path.endsWith('/budget')) {
|
|
return Response.json(budget());
|
|
}
|
|
throw new Error('Accepted response lost');
|
|
});
|
|
const value = plan();
|
|
await expect(
|
|
runResearchCycle(f.api, value, {
|
|
onEvent: async event => {
|
|
events.push(event);
|
|
},
|
|
poll: { timeoutMs: 1000 },
|
|
})
|
|
).rejects.toMatchObject({
|
|
name: 'ResearchCycleStopped',
|
|
event: { phase: 'stopped', key: null, operation: 'create-hypothesis', uncertain: true },
|
|
});
|
|
expect(f.calls).toHaveLength(2);
|
|
expect(events.map(event => event.phase)).toEqual(['intent', 'stopped']);
|
|
expect(events[0]!.input).toEqual({ ...value.hypothesis, contentOrigin: 'ai' });
|
|
expect(events[0]!.resourceId).toBe(projectId);
|
|
});
|
|
test('receipt persistence and cancellation stop subsequent writes', async () => {
|
|
const f = client(() => Response.json(budget()));
|
|
await expect(
|
|
runResearchCycle(f.api, plan(), {
|
|
onEvent: async () => {
|
|
throw new Error('Journal unavailable');
|
|
},
|
|
poll: { timeoutMs: 1000 },
|
|
})
|
|
).rejects.toThrow('Journal unavailable');
|
|
expect(f.calls).toHaveLength(1);
|
|
const controller = new AbortController();
|
|
await expect(
|
|
runResearchCycle(f.api, plan(), {
|
|
onEvent: async () => {
|
|
controller.abort(new Error('Stop here'));
|
|
},
|
|
signal: controller.signal,
|
|
poll: { timeoutMs: 1000 },
|
|
})
|
|
).rejects.toThrow('Stop here');
|
|
expect(f.calls).toHaveLength(2);
|
|
});
|
|
test('a receipt journal failure preserves the accepted resource in the thrown error', async () => {
|
|
const value = plan();
|
|
const saved = {
|
|
id: '33333333-3333-4333-8333-333333333333',
|
|
projectId,
|
|
latestRevision: {
|
|
id: '44444444-4444-4444-8444-444444444444',
|
|
ordinal: 1,
|
|
...value.hypothesis,
|
|
contentOrigin: 'ai',
|
|
submittedBy: budget().agent.id,
|
|
validationState: 'unvalidated',
|
|
},
|
|
};
|
|
const f = client(path =>
|
|
path.endsWith('/budget')
|
|
? Response.json(budget())
|
|
: Response.json({ hypothesis: saved }, { status: 201 })
|
|
);
|
|
await expect(
|
|
runResearchCycle(f.api, value, {
|
|
poll: { timeoutMs: 1000 },
|
|
onEvent: async event => {
|
|
if (event.phase === 'accepted') {
|
|
throw new Error('Disk unavailable after acceptance');
|
|
}
|
|
},
|
|
})
|
|
).rejects.toMatchObject({
|
|
name: 'ResearchCycleStopped',
|
|
event: {
|
|
phase: 'accepted',
|
|
key: null,
|
|
resourceId: projectId,
|
|
result: { id: saved.id, latestRevision: { id: saved.latestRevision.id } },
|
|
},
|
|
});
|
|
expect(f.calls).toHaveLength(2);
|
|
});
|
|
test('a definitive 429 stops without retries or creating another family', async () => {
|
|
const events: ResearchCycleEvent[] = [];
|
|
const f = client(path =>
|
|
path.endsWith('/budget')
|
|
? Response.json(budget())
|
|
: Response.json({ error: 'Research budget exceeded' }, { status: 429 })
|
|
);
|
|
await expect(
|
|
runResearchCycle(f.api, plan(), {
|
|
onEvent: async event => {
|
|
events.push(event);
|
|
},
|
|
poll: { timeoutMs: 1000 },
|
|
})
|
|
).rejects.toMatchObject({ event: { uncertain: false } });
|
|
expect(events.at(-1)?.error).toBe('Research budget exceeded');
|
|
expect(f.calls).toHaveLength(2);
|
|
});
|
|
});
|