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

581 lines
23 KiB
TypeScript

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: 1,
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('automatic publication lineage accepts and retains the server-selected parent', async () => {
const detail = ordinary();
const pkg = detail.preview.request.strategy.package;
const saved = {
id: detail.strategyVersionId,
strategyId: detail.preview.request.strategy.familyId,
ordinal: 2,
origin: 'candidate',
createdBy: agent,
parentVersionId: 'abcdefab-abcd-4bcd-8bcd-000000000002',
package: pkg,
};
const publication = client(() => Response.json({ version: saved }, { status: 201 }));
const implicit = await publication.value.publishVersion(saved.strategyId, pkg, requestKey);
const explicitNull = await publication.value.publishVersion(
saved.strategyId,
pkg,
requestKey,
null
);
expect(implicit).toMatchObject({ id: saved.id, parentVersionId: saved.parentVersionId });
expect(explicitNull).toEqual(implicit);
expect(publication.calls).toHaveLength(2);
expect(publication.calls[0]!.body).toEqual({ package: pkg, parentVersionId: null });
expect(publication.calls[1]!.init.body).toBe(publication.calls[0]!.init.body!);
});
test('automatic lineage receipt retries retain the original key/body after a newer publication', async () => {
const detail = ordinary();
const pkg = detail.preview.request.strategy.package;
const second = {
id: detail.strategyVersionId,
strategyId: detail.preview.request.strategy.familyId,
ordinal: 2,
origin: 'candidate',
createdBy: agent,
parentVersionId: 'abcdefab-abcd-4bcd-8bcd-000000000002',
package: pkg,
};
const third = {
...second,
id: 'abcdefab-abcd-4bcd-8bcd-000000000003',
ordinal: 3,
parentVersionId: second.id,
};
const publication = client((_call, index) => {
if (index === 0) {
throw new Error('Response lost after the second version committed');
}
return Response.json({ version: index === 1 ? third : second }, { status: 201 });
});
await expect(
publication.value.publishVersion(second.strategyId, pkg, requestKey)
).rejects.toMatchObject({ uncertain: true });
expect(publication.calls).toHaveLength(1);
expect(
await publication.value.publishVersion(second.strategyId, pkg, `${requestKey}:new`)
).toMatchObject({ id: third.id, parentVersionId: second.id });
expect(
await publication.value.publishVersion(second.strategyId, pkg, requestKey)
).toMatchObject({ id: second.id, parentVersionId: second.parentVersionId });
expect(publication.calls).toHaveLength(3);
expect(publication.calls.every(call => call.init.method === 'POST')).toBeTrue();
expect(publication.calls[2]!.init.body).toBe(publication.calls[0]!.init.body!);
expect(publication.calls[2]!.body).toEqual({ package: pkg, parentVersionId: null });
for (const index of [0, 2]) {
expect(new Headers(publication.calls[index]!.init.headers).get('idempotency-key')).toBe(
requestKey
);
}
});
test('publication still rejects wrong explicit lineage, malformed parents, family, origin and hashes', async () => {
const detail = ordinary();
const pkg = detail.preview.request.strategy.package;
const saved = {
id: detail.strategyVersionId,
strategyId: detail.preview.request.strategy.familyId,
ordinal: 2,
origin: 'candidate',
createdBy: agent,
parentVersionId: 'abcdefab-abcd-4bcd-8bcd-000000000002',
package: pkg,
};
const explicit = client(() => Response.json({ version: saved }, { status: 201 }));
await expect(
explicit.value.publishVersion(saved.strategyId, pkg, requestKey, saved.id)
).rejects.toMatchObject({ uncertain: true });
expect(explicit.calls).toHaveLength(1);
expect(explicit.calls[0]!.body).toEqual({ package: pkg, parentVersionId: saved.id });
for (const invalid of [
{ ...saved, parentVersionId: 'not-a-version-id' },
{ ...saved, parentVersionId: 2 },
{ ...saved, parentVersionId: undefined },
{ ...saved, strategyId: 'abcdefab-abcd-4bcd-8bcd-000000000003' },
{ ...saved, origin: 'builtin' },
{ ...saved, package: { ...pkg, artifact: { ...pkg.artifact, sha256: 'f'.repeat(64) } } },
{
...saved,
package: { ...pkg, dependencyLock: { ...pkg.dependencyLock, sha256: 'f'.repeat(64) } },
},
]) {
const rejected = client(() => Response.json({ version: invalid }, { status: 201 }));
await expect(
rejected.value.publishVersion(saved.strategyId, pkg, requestKey)
).rejects.toMatchObject({ uncertain: true });
expect(rejected.calls).toHaveLength(1);
}
});
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 });
});