stock-bot/scripts/test/research-cycle.test.ts

389 lines
14 KiB
TypeScript

import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
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);
});
});
describe('research cycle CLI recovery output', () => {
const repository = fileURLToPath(new URL('../..', import.meta.url));
const credential = 'sb-research.fixture-cli-secret-never-print';
const acceptedHypothesis = () => ({
id: '33333333-3333-4333-8333-333333333333',
projectId,
latestRevision: {
id: '44444444-4444-4444-8444-444444444444',
ordinal: 1,
...plan().hypothesis,
contentOrigin: 'ai',
submittedBy: budget().agent.id,
validationState: 'unvalidated',
},
});
async function invoke(
fault: 'accepted-write' | 'accepted-sync' | 'stopped-write' | 'intent-write' | 'none',
closeFailure = false,
existingJournal = false
) {
const directory = await mkdtemp(join(tmpdir(), 'stock-bot-cycle-cli-'));
try {
const planPath = join(directory, 'plan.json');
const receiptsPath = join(directory, 'receipts.jsonl');
const requestsPath = join(directory, 'requests.jsonl');
const fixturePath = join(directory, 'fixture.json');
await writeFile(planPath, JSON.stringify(plan()));
await writeFile(requestsPath, '');
if (existingJournal) {
await writeFile(receiptsPath, 'existing journal must remain unchanged\n');
}
await writeFile(
fixturePath,
JSON.stringify({
fault,
closeFailure,
receiptsPath,
requestsPath,
budget: budget(),
hypothesis: acceptedHypothesis(),
})
);
const child = Bun.spawn(
[
process.execPath,
'--preload',
'scripts/test/fixtures/research-cycle-cli-preload.ts',
'scripts/examples/research-cycle.ts',
'--plan',
planPath,
'--receipts',
receiptsPath,
],
{
cwd: repository,
env: {
...process.env,
RESEARCH_API_ORIGIN: 'http://127.0.0.1:2003',
RESEARCH_API_TOKEN: credential,
RESEARCH_CYCLE_CLI_FIXTURE: fixturePath,
},
stdout: 'pipe',
stderr: 'pipe',
}
);
const [status, stdout, stderr] = await Promise.all([
child.exited,
new Response(child.stdout).text(),
new Response(child.stderr).text(),
]);
return {
status,
stdout,
stderr,
receipts: await readFile(receiptsPath, 'utf8'),
requests: (await readFile(requestsPath, 'utf8'))
.split('\n')
.filter(Boolean)
.map(line => JSON.parse(line) as { pathname: string; method: string; body?: string }),
};
} finally {
await rm(directory, { recursive: true, force: true });
}
}
const originalIntent = () => ({
cycleId: plan().cycleId,
candidateKey: null,
operation: 'create-hypothesis',
phase: 'intent',
key: null,
input: { ...plan().hypothesis, contentOrigin: 'ai' },
resourceId: projectId,
});
test.each([
['accepted-write', false],
['accepted-sync', false],
['accepted-write', true],
['accepted-sync', true],
] as const)('%s failure retains the exact receipt (close fails: %s)', async (fault, closeFailure) => {
const result = await invoke(fault, closeFailure);
expect(result.status).toBe(1);
expect(result.stdout).toBe('');
const recovery = JSON.parse(result.stderr);
const accepted = { ...originalIntent(), phase: 'accepted', result: acceptedHypothesis() };
expect(recovery.event).toEqual(accepted);
expect(recovery.error).toContain('stopped at create-hypothesis');
const retained = result.receipts.trim().split('\n').map(line => JSON.parse(line));
expect(retained[0]).toEqual(originalIntent());
expect(retained).toHaveLength(fault === 'accepted-write' ? 1 : 2);
if (fault === 'accepted-sync') {
expect(retained[1]).toEqual(accepted);
}
expect(result.requests.map(request => [request.method, request.pathname])).toEqual([
['GET', '/api/v2/research-agent/budget'],
['POST', `/api/v2/research-projects/${projectId}/hypotheses`],
]);
expect(JSON.parse(result.requests[1]!.body!)).toEqual(originalIntent().input);
expect(result.stderr + result.stdout + result.receipts).not.toContain(credential);
});
test('a rejected request and failed stopped-event write preserve rejection without claiming acceptance', async () => {
const result = await invoke('stopped-write', true);
expect(result.status).toBe(1);
expect(result.stdout).toBe('');
expect(JSON.parse(result.stderr).event).toEqual({
...originalIntent(),
phase: 'stopped',
error: 'Fixture admission refused',
uncertain: false,
});
expect(JSON.parse(result.receipts)).toEqual(originalIntent());
expect(result.requests).toHaveLength(2);
expect(result.stderr).not.toContain(acceptedHypothesis().id);
expect(result.stderr + result.stdout + result.receipts).not.toContain(credential);
});
test('an intent write failure stays an ordinary error and prevents the mutation even if close fails', async () => {
const result = await invoke('intent-write', true);
expect(result.status).toBe(1);
expect(result.stdout).toBe('');
expect(result.stderr.trim()).toBe('Injected journal write failure');
expect(result.receipts).toBe('');
expect(result.requests.map(request => request.method)).toEqual(['GET']);
expect(result.stderr).not.toContain(credential);
});
test('an existing journal is never overwritten or treated as a new cycle', async () => {
const result = await invoke('none', false, true);
expect(result.status).toBe(1);
expect(result.stdout).toBe('');
expect(result.stderr).toContain('EEXIST');
expect(result.stderr).not.toContain('"event"');
expect(result.receipts).toBe('existing journal must remain unchanged\n');
expect(result.requests).toEqual([]);
expect(result.stderr).not.toContain(credential);
});
});