feat(research): isolate candidates and add reviewed paper promotion
This commit is contained in:
parent
26b97265c6
commit
25b5cbf481
128 changed files with 13038 additions and 1388 deletions
|
|
@ -89,6 +89,8 @@ describe('orchestrator architecture boundaries', () => {
|
|||
'@stock-bot/stock-config/strategy',
|
||||
'@stock-bot/stock-config/canonical-replay',
|
||||
'@stock-bot/stock-config/canonical-research',
|
||||
'@stock-bot/stock-config/candidate-execution',
|
||||
'@stock-bot/stock-config/paper-deployments',
|
||||
'@stock-bot/calculations/analytics',
|
||||
'@stock-bot/calculations/returns',
|
||||
].includes(specifier)
|
||||
|
|
@ -122,6 +124,8 @@ describe('orchestrator architecture boundaries', () => {
|
|||
'strategy-names.ts',
|
||||
'canonical-research.ts',
|
||||
'canonical-replay.ts',
|
||||
'candidate-execution.ts',
|
||||
'paper-deployments.ts',
|
||||
'research.ts',
|
||||
]) {
|
||||
for (const specifier of runtimeImports(join(directory, name))) {
|
||||
|
|
@ -133,6 +137,8 @@ describe('orchestrator architecture boundaries', () => {
|
|||
'./strategy-names',
|
||||
'./strategy',
|
||||
'./canonical-replay',
|
||||
'./candidate-execution',
|
||||
'./research',
|
||||
].includes(specifier)
|
||||
).toBe(true);
|
||||
}
|
||||
|
|
|
|||
471
scripts/test/research-client.test.ts
Normal file
471
scripts/test/research-client.test.ts
Normal file
|
|
@ -0,0 +1,471 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import type { ExperimentDetail } from '@stock-bot/stock-config/experiments';
|
||||
import { comparisonFixture, tableFixture } from '../benchmark-experiment-tables';
|
||||
import {
|
||||
pollResearch,
|
||||
ResearchClient,
|
||||
ResearchRequestError,
|
||||
ResearchWaitExpired,
|
||||
} from '../research-client';
|
||||
|
||||
const token = 'sb-research.fixture-only-token';
|
||||
const agent = 'agent:11111111-1111-4111-8111-111111111111';
|
||||
const projectId = '22222222-2222-4222-8222-222222222222';
|
||||
const hypothesisId = '33333333-3333-4333-8333-333333333333';
|
||||
const revisionId = '44444444-4444-4444-8444-444444444444';
|
||||
const artifactId = '55555555-5555-4555-8555-555555555555';
|
||||
const requestKey = 'research-cycle-fixture:trial:1';
|
||||
type Call = { url: URL; init: RequestInit; body: unknown };
|
||||
function client(handler: (call: Call, index: number) => Response | Promise<Response>) {
|
||||
const calls: Call[] = [];
|
||||
const value = new ResearchClient({
|
||||
origin: 'http://127.0.0.1:2003',
|
||||
token,
|
||||
fetch: ((url: string | URL | Request, init?: RequestInit) => {
|
||||
const call = {
|
||||
url: new URL(String(url)),
|
||||
init: init!,
|
||||
body: init?.body ? JSON.parse(String(init.body)) : undefined,
|
||||
};
|
||||
calls.push(call);
|
||||
return Promise.resolve(handler(call, calls.length - 1));
|
||||
}) as typeof fetch,
|
||||
});
|
||||
return { value, calls };
|
||||
}
|
||||
const ordinary = () => tableFixture(1) as ExperimentDetail;
|
||||
|
||||
describe('authorized research client', () => {
|
||||
test('only research credentials, fixed API origin, no trading methods or redirect credential forwarding', async () => {
|
||||
for (const origin of [
|
||||
'http://example.org',
|
||||
'https://u:p@example.org',
|
||||
'https://example.org/a',
|
||||
'https://example.org/?token=x',
|
||||
'file:///tmp/a',
|
||||
]) {
|
||||
expect(() => new ResearchClient({ origin, token })).toThrow();
|
||||
}
|
||||
expect(
|
||||
() => new ResearchClient({ origin: 'https://example.org', token: 'operator-secret' })
|
||||
).toThrow();
|
||||
const detail = ordinary();
|
||||
const { value, calls } = client(() => Response.json({ experiment: detail }));
|
||||
await value.experiment(detail.id);
|
||||
expect(calls[0]!.url.origin).toBe('http://127.0.0.1:2003');
|
||||
expect(calls[0]!.url.pathname).toBe(`/api/v2/experiments/${detail.id}`);
|
||||
expect(calls[0]!.init.redirect).toBe('error');
|
||||
expect(calls[0]!.init.credentials).toBe('omit');
|
||||
expect(new Headers(calls[0]!.init.headers).get('authorization')).toBe(`Bearer ${token}`);
|
||||
expect(JSON.stringify(value)).not.toContain(token);
|
||||
expect('activate' in value || 'paper' in value || 'request' in value).toBe(false);
|
||||
expect(() =>
|
||||
value.advanceValidation(
|
||||
detail.id,
|
||||
'../../paper/activate' as 'select',
|
||||
{ previewHash: detail.previewHash },
|
||||
requestKey
|
||||
)
|
||||
).toThrow();
|
||||
expect(calls).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('preview and admission preserve captured inputs; uncertain submission recovers with the same exact key and body', async () => {
|
||||
const detail = ordinary();
|
||||
let release!: (response: Response) => void;
|
||||
const { value, calls } = client((_call, index) =>
|
||||
index === 0
|
||||
? new Promise<Response>(resolve => {
|
||||
release = resolve;
|
||||
})
|
||||
: index === 1
|
||||
? Promise.reject(new Error('Response lost after durable admission'))
|
||||
: Response.json({ experiment: detail }, { status: 202 })
|
||||
);
|
||||
const input = structuredClone(detail.preview.input);
|
||||
const checking = value.previewExperiment(input);
|
||||
input.name = 'Changed after sending';
|
||||
release(Response.json({ preview: detail.preview }));
|
||||
expect((await checking).input.name).toBe(detail.name);
|
||||
const body = { ...detail.preview.input, previewHash: detail.previewHash };
|
||||
await expect(value.submitExperiment(body, requestKey)).rejects.toMatchObject({
|
||||
uncertain: true,
|
||||
});
|
||||
expect(calls).toHaveLength(2);
|
||||
expect((await value.submitExperiment(body, requestKey)).id).toBe(detail.id);
|
||||
expect(String(calls[1]!.init.body)).toBe(String(calls[2]!.init.body));
|
||||
expect(new Headers(calls[1]!.init.headers).get('idempotency-key')).toBe(requestKey);
|
||||
expect(new Headers(calls[2]!.init.headers).get('idempotency-key')).toBe(requestKey);
|
||||
});
|
||||
|
||||
test('wrong receipt identities, lost response and 429 are surfaced without automatic new admission', async () => {
|
||||
const detail = ordinary(),
|
||||
body = { ...detail.preview.input, previewHash: detail.previewHash };
|
||||
const malformed = client(() =>
|
||||
Response.json({ experiment: { ...detail, previewHash: 'f'.repeat(64) } }, { status: 202 })
|
||||
);
|
||||
await expect(malformed.value.submitExperiment(body, requestKey)).rejects.toMatchObject({
|
||||
status: null,
|
||||
uncertain: true,
|
||||
});
|
||||
expect(malformed.calls).toHaveLength(1);
|
||||
const lost = client(() => {
|
||||
throw new Error('private transport details');
|
||||
});
|
||||
await expect(lost.value.submitExperiment(body, requestKey)).rejects.toMatchObject({
|
||||
status: null,
|
||||
uncertain: true,
|
||||
});
|
||||
const denied = client(() =>
|
||||
Response.json({ error: 'Bounded work budget exceeded' }, { status: 429 })
|
||||
);
|
||||
await expect(denied.value.previewExperiment(detail.preview.input)).rejects.toMatchObject({
|
||||
status: 429,
|
||||
uncertain: false,
|
||||
message: 'Bounded work budget exceeded',
|
||||
});
|
||||
expect(denied.calls).toHaveLength(1);
|
||||
const oversized = {
|
||||
...detail.preview.input,
|
||||
grid: { fastPeriod: Array.from({ length: 101 }, (_, i) => i + 1) },
|
||||
};
|
||||
expect(() => denied.value.previewExperiment(oversized)).toThrow();
|
||||
expect(denied.calls).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('candidate publication is inert data; it cannot import generated source or substitute a version identity', async () => {
|
||||
const detail = ordinary();
|
||||
const pkg = structuredClone(detail.preview.request.strategy.package);
|
||||
pkg.artifact.content =
|
||||
'globalThis.__research_client_executed = true; throw new Error("Never import");';
|
||||
pkg.artifact.sha256 = createHash('sha256').update(pkg.artifact.content).digest('hex');
|
||||
const saved = {
|
||||
id: detail.strategyVersionId,
|
||||
strategyId: detail.preview.request.strategy.familyId,
|
||||
ordinal: 2,
|
||||
origin: 'candidate',
|
||||
createdBy: agent,
|
||||
parentVersionId: null,
|
||||
package: pkg,
|
||||
};
|
||||
const good = client(() => Response.json({ version: saved }, { status: 201 }));
|
||||
expect((await good.value.publishVersion(saved.strategyId, pkg, requestKey)).id).toBe(saved.id);
|
||||
expect((globalThis as Record<string, unknown>).__research_client_executed).toBeUndefined();
|
||||
expect(good.calls[0]!.body).toEqual({ package: pkg, parentVersionId: null });
|
||||
const bad = client(() =>
|
||||
Response.json({ version: { ...saved, origin: 'builtin' } }, { status: 201 })
|
||||
);
|
||||
await expect(bad.value.publishVersion(saved.strategyId, pkg, requestKey)).rejects.toMatchObject(
|
||||
{ uncertain: true }
|
||||
);
|
||||
});
|
||||
|
||||
test('normalizes uppercase identities before captures and binds cancellation and publication receipts', async () => {
|
||||
const detail = ordinary();
|
||||
detail.id = 'abcdefab-abcd-4bcd-8bcd-abcdefabcdef';
|
||||
detail.cancelRequested = true;
|
||||
const cancel = client(() => Response.json({ experiment: detail }));
|
||||
expect((await cancel.value.cancelExperiment(detail.id.toUpperCase())).id).toBe(detail.id);
|
||||
expect(cancel.calls[0]!.url.pathname).toContain(detail.id);
|
||||
const strategyId = 'abcdefab-abcd-4bcd-8bcd-000000000001';
|
||||
const parentVersionId = 'abcdefab-abcd-4bcd-8bcd-000000000002';
|
||||
const pkg = detail.preview.request.strategy.package;
|
||||
const saved = {
|
||||
id: detail.strategyVersionId,
|
||||
strategyId,
|
||||
parentVersionId,
|
||||
ordinal: 2,
|
||||
origin: 'candidate',
|
||||
createdBy: agent,
|
||||
package: pkg,
|
||||
};
|
||||
const publication = client(() => Response.json({ version: saved }, { status: 201 }));
|
||||
expect(
|
||||
(
|
||||
await publication.value.publishVersion(
|
||||
strategyId.toUpperCase(),
|
||||
pkg,
|
||||
requestKey,
|
||||
parentVersionId.toUpperCase()
|
||||
)
|
||||
).strategyId
|
||||
).toBe(strategyId);
|
||||
expect(publication.calls[0]!.body).toMatchObject({ parentVersionId });
|
||||
});
|
||||
|
||||
test('malformed selection/finalization receipts are uncertain and never resubmitted automatically', async () => {
|
||||
const request = client(() =>
|
||||
Response.json(
|
||||
{ receipt: { id: projectId }, validation: {}, walkForward: {} },
|
||||
{ status: 202 }
|
||||
)
|
||||
);
|
||||
await expect(
|
||||
request.value.advanceValidation(
|
||||
projectId,
|
||||
'select',
|
||||
{ previewHash: 'a'.repeat(64) },
|
||||
requestKey
|
||||
)
|
||||
).rejects.toMatchObject({ uncertain: true });
|
||||
await expect(
|
||||
request.value.advanceValidation(
|
||||
projectId,
|
||||
'finalize',
|
||||
{ previewHash: 'a'.repeat(64), selectionHash: 'b'.repeat(64) },
|
||||
requestKey
|
||||
)
|
||||
).rejects.toMatchObject({ uncertain: true });
|
||||
await expect(
|
||||
request.value.finalizeWalkForward(projectId, 'a'.repeat(64), requestKey)
|
||||
).rejects.toMatchObject({ uncertain: true });
|
||||
expect(request.calls).toHaveLength(3);
|
||||
});
|
||||
|
||||
test('failed, cancelled, missing and noncomparable outcomes survive polling and comparison', async () => {
|
||||
const detail = tableFixture(25);
|
||||
for (const trial of detail.trials) {
|
||||
if (['pending', 'running', 'paused'].includes(trial.status)) {
|
||||
trial.status = 'failed';
|
||||
trial.error = 'Explicit worker diagnostic';
|
||||
}
|
||||
}
|
||||
for (const status of [
|
||||
'pending',
|
||||
'running',
|
||||
'paused',
|
||||
'completed',
|
||||
'failed',
|
||||
'cancelled',
|
||||
] as const) {
|
||||
detail.counts[status] = detail.trials.filter(trial => trial.status === status).length;
|
||||
}
|
||||
const polling = client(() => Response.json({ experiment: detail }));
|
||||
const result = await polling.value.waitForExperiment(detail.id, { timeoutMs: 1000 });
|
||||
expect(result.trials).toEqual(detail.trials);
|
||||
expect(result.trials.some(trial => trial.status === 'failed' && trial.error)).toBe(true);
|
||||
expect(result.trials.some(trial => trial.status === 'missing')).toBe(true);
|
||||
expect(result.trials.some(trial => trial.status === 'completed' && !trial.comparable)).toBe(
|
||||
true
|
||||
);
|
||||
expect(polling.calls).toHaveLength(1);
|
||||
const comparison = comparisonFixture();
|
||||
const read = client(() => Response.json({ comparison }));
|
||||
expect((await read.value.compareExperiments(comparison.selection)).rows).toEqual(
|
||||
comparison.rows
|
||||
);
|
||||
expect(comparison.rows.some(row => !row.ready)).toBe(true);
|
||||
});
|
||||
|
||||
test('AI hypotheses stay unvalidated and findings retain exact canonical sources without validating prose', async () => {
|
||||
const detail = ordinary(),
|
||||
runId = detail.trials[0]!.runId!;
|
||||
const input = {
|
||||
title: 'A hypothesis',
|
||||
proposition: 'Trend might persist',
|
||||
validationCriteria: 'Use chronological holdouts',
|
||||
};
|
||||
const evidence = [
|
||||
{
|
||||
runId,
|
||||
strategyVersionId: detail.strategyVersionId,
|
||||
metricsVersion: 'canonical-analytics/v1' as const,
|
||||
metricPath: 'analytics.metrics.totalReturn' as const,
|
||||
},
|
||||
];
|
||||
const source = {
|
||||
kind: 'experiment/v1' as const,
|
||||
experimentId: detail.id,
|
||||
previewHash: detail.previewHash,
|
||||
};
|
||||
const finding = {
|
||||
kind: 'finding' as const,
|
||||
hypothesisRevisionId: revisionId,
|
||||
title: 'Observed fixture',
|
||||
body: 'This synthetic result is not a profitability claim.',
|
||||
evidence,
|
||||
source,
|
||||
};
|
||||
let metric = {
|
||||
value: 0 as number | null,
|
||||
availability: 'available',
|
||||
unavailableReason: null as string | null,
|
||||
};
|
||||
const { value, calls } = client((_call, index) =>
|
||||
Response.json(
|
||||
index === 0
|
||||
? {
|
||||
hypothesis: {
|
||||
id: hypothesisId,
|
||||
projectId,
|
||||
latestRevision: {
|
||||
...input,
|
||||
id: revisionId,
|
||||
ordinal: 1,
|
||||
contentOrigin: 'ai',
|
||||
submittedBy: agent,
|
||||
validationState: 'unvalidated',
|
||||
},
|
||||
},
|
||||
}
|
||||
: {
|
||||
artifact: {
|
||||
id: artifactId,
|
||||
projectId,
|
||||
hypothesisRevisionId: revisionId,
|
||||
kind: 'finding',
|
||||
latestRevision: {
|
||||
id: revisionId,
|
||||
title: finding.title,
|
||||
body: finding.body,
|
||||
contentOrigin: 'ai',
|
||||
submittedBy: agent,
|
||||
validationState: 'unvalidated',
|
||||
evidenceState: 'referenced',
|
||||
source,
|
||||
evidence: [
|
||||
{
|
||||
...evidence[0],
|
||||
...metric,
|
||||
datasetHash: detail.datasetHash,
|
||||
resultKind: 'canonical',
|
||||
financialEngine: 'rust',
|
||||
limitations: [{ code: 'fixture', message: 'Synthetic demonstration' }],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{ status: 201 }
|
||||
)
|
||||
);
|
||||
const hypothesis = await value.createHypothesis(projectId, input);
|
||||
expect(hypothesis.latestRevision.validationState).toBe('unvalidated');
|
||||
const saved = await value.saveFinding(projectId, finding);
|
||||
expect(calls[1]!.url.pathname).toBe(
|
||||
`/api/v2/research-projects/${projectId}/analysis-artifacts`
|
||||
);
|
||||
expect(saved.latestRevision.validationState).toBe('unvalidated');
|
||||
expect(saved.latestRevision.evidence[0]!.value).toBe(0);
|
||||
expect(saved.latestRevision.source).toEqual(source);
|
||||
for (const bad of [
|
||||
{ value: null, availability: 'available', unavailableReason: null },
|
||||
{ value: 1, availability: 'unavailable', unavailableReason: 'Too few bars' },
|
||||
{ value: null, availability: 'unavailable', unavailableReason: null },
|
||||
{ value: null, availability: 'unavailable', unavailableReason: ' ' },
|
||||
{ value: 0, availability: 'available', unavailableReason: 'Contradictory reason' },
|
||||
]) {
|
||||
metric = bad;
|
||||
await expect(value.saveFinding(projectId, finding)).rejects.toMatchObject({
|
||||
uncertain: true,
|
||||
});
|
||||
}
|
||||
metric = { value: null, availability: 'unavailable', unavailableReason: 'Too few bars' };
|
||||
expect((await value.saveFinding(projectId, finding)).latestRevision.evidence[0]).toMatchObject(
|
||||
metric
|
||||
);
|
||||
|
||||
expect((calls[0]!.body as { contentOrigin: string }).contentOrigin).toBe('ai');
|
||||
const denied = client(() =>
|
||||
Response.json({ error: 'Evidence is not a member of this source' }, { status: 409 })
|
||||
);
|
||||
await expect(denied.value.saveFinding(projectId, finding)).rejects.toMatchObject({
|
||||
status: 409,
|
||||
uncertain: false,
|
||||
});
|
||||
expect(denied.calls).toHaveLength(1);
|
||||
expect(() => denied.value.saveFinding(projectId, { ...finding, evidence: [] })).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('bounded research polling', () => {
|
||||
test('deadline preserves last diagnostic snapshot and never cancels server work', async () => {
|
||||
let reads = 0;
|
||||
const error = await pollResearch(
|
||||
async () => ({ status: 'running', attempt: ++reads }),
|
||||
() => false,
|
||||
{ timeoutMs: 15, intervalMs: 5 }
|
||||
).catch(error => error);
|
||||
expect(error).toBeInstanceOf(ResearchWaitExpired);
|
||||
expect(error.last.status).toBe('running');
|
||||
expect(reads).toBeGreaterThan(0);
|
||||
});
|
||||
test('explicit abort and failed read stop polling without hiding 429 or other diagnostics', async () => {
|
||||
const controller = new AbortController();
|
||||
const aborted = pollResearch(
|
||||
async () => {
|
||||
controller.abort(new Error('Owner stopped waiting'));
|
||||
return 1;
|
||||
},
|
||||
() => false,
|
||||
{ timeoutMs: 1000, intervalMs: 1, signal: controller.signal }
|
||||
);
|
||||
await expect(aborted).rejects.toThrow('Owner stopped waiting');
|
||||
let calls = 0;
|
||||
const error = new ResearchRequestError('Budget unavailable', 429, false, 'GET fixture');
|
||||
await expect(
|
||||
pollResearch(
|
||||
async () => {
|
||||
calls++;
|
||||
throw error;
|
||||
},
|
||||
() => false,
|
||||
{ timeoutMs: 1000 }
|
||||
)
|
||||
).rejects.toBe(error);
|
||||
expect(calls).toBe(1);
|
||||
expect(
|
||||
() => new ResearchClient({ origin: 'http://localhost', token, requestTimeoutMs: Infinity })
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
test('polling deadlines and aborts bound a transport that ignores cancellation', async () => {
|
||||
const never = () => new Promise<never>(() => {});
|
||||
const timeout = await pollResearch(never, () => false, { timeoutMs: 10 }).catch(error => error);
|
||||
expect(timeout).toBeInstanceOf(ResearchWaitExpired);
|
||||
expect(timeout.last).toBeNull();
|
||||
const controller = new AbortController();
|
||||
const pending = pollResearch(never, () => false, { timeoutMs: 1000, signal: controller.signal });
|
||||
controller.abort(new Error('Stop uncooperative transport'));
|
||||
await expect(pending).rejects.toThrow('Stop uncooperative transport');
|
||||
const bounded = new ResearchClient({
|
||||
origin: 'http://localhost',
|
||||
token,
|
||||
requestTimeoutMs: 10,
|
||||
fetch: never as unknown as typeof fetch,
|
||||
});
|
||||
await expect(bounded.budget()).rejects.toMatchObject({ uncertain: false, status: null });
|
||||
});
|
||||
|
||||
test('captured recipe inputs normalize template UUIDs before preview and receipt submission', async () => {
|
||||
const value = ordinary();
|
||||
const read = client(() =>
|
||||
Response.json({ error: 'Fixture stops before admission' }, { status: 429 })
|
||||
);
|
||||
const backtestId = 'abcdefab-abcd-4bcd-8bcd-abcdefabcdef';
|
||||
await expect(
|
||||
read.value.previewExperiment({ ...value.preview.input, backtestId: backtestId.toUpperCase() })
|
||||
).rejects.toMatchObject({ status: 429 });
|
||||
expect(read.calls[0]!.body).toMatchObject({ backtestId });
|
||||
await expect(
|
||||
read.value.submitExperiment(
|
||||
{
|
||||
...value.preview.input,
|
||||
backtestId: backtestId.toUpperCase(),
|
||||
previewHash: value.previewHash,
|
||||
},
|
||||
requestKey
|
||||
)
|
||||
).rejects.toMatchObject({ status: 429 });
|
||||
expect(read.calls[1]!.body).toMatchObject({ backtestId });
|
||||
await expect(
|
||||
read.value.previewCosts({
|
||||
name: 'Uppercase costs',
|
||||
backtestId: backtestId.toUpperCase(),
|
||||
scenarios: [{ feeRate: '0.01', slippageRate: '0.01' }],
|
||||
})
|
||||
).rejects.toMatchObject({ status: 429 });
|
||||
expect(read.calls[2]!.body).toMatchObject({ backtestId });
|
||||
});
|
||||
230
scripts/test/research-cycle.test.ts
Normal file
230
scripts/test/research-cycle.test.ts
Normal file
|
|
@ -0,0 +1,230 @@
|
|||
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);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue