refactor(api): validate shared product response contracts (CL25)

This commit is contained in:
Boki 2026-10-28 13:57:37 -04:00
parent e2292e4883
commit 366a6054bf
22 changed files with 989 additions and 451 deletions

View file

@ -83,7 +83,11 @@ function request(path: string, method = 'GET') {
}
return found;
}
function reply(pending: Request, body: unknown, status = 200) {
function reply(
pending: Request,
body: unknown,
status = pending.method === 'POST' && pending.path === '/api/v2/backtests' ? 201 : 200
) {
pending.settled = true;
pending.resolve(Response.json(body, { status }));
}
@ -729,7 +733,7 @@ describe('run selection and persisted status authority', () => {
await flush(() => reply(first, run('A', 'running', { progress: 20 })));
expect(requests.filter(item => item.path === '/api/v2/runs/A')).toHaveLength(3);
await flush(() => fail(request('/api/v2/runs/A')));
expect(latest.error).toContain('Network unavailable');
expect(latest.error).toContain('The backtest response was lost');
expect(latest.currentRun?.progress).toBe(20);
expect(polls()).toBe(1);
await advance(1000);
@ -793,7 +797,9 @@ describe('run selection and persisted status authority', () => {
await selectRunning('A', initial);
await flush(() => click('Cancel run'));
expect(host.textContent).toContain('Cancellation requested');
await flush(() => reply(request('/api/v2/runs/A/cancel', 'POST'), { accepted: true }, 202));
await flush(() =>
reply(request('/api/v2/runs/A/cancel', 'POST'), { message: 'Cancellation requested' }, 202)
);
expect(latest.currentRun?.status).toBe(initial);
const acknowledged = initial === 'pending' ? 'cancelled' : 'running';
await flush(() =>
@ -831,9 +837,11 @@ describe('run selection and persisted status authority', () => {
await flush(() => click('Cancel run'));
await flush(() => fail(request('/api/v2/runs/A/cancel', 'POST')));
expect(latest.cancelRequested).toBe(false);
expect(latest.error).toContain('Network unavailable');
expect(latest.error).toContain('The backtest response was lost');
await flush(() => click('Cancel run'));
await flush(() => reply(request('/api/v2/runs/A/cancel', 'POST'), { accepted: true }, 202));
await flush(() =>
reply(request('/api/v2/runs/A/cancel', 'POST'), { message: 'Cancellation requested' }, 202)
);
await flush(() => reply(request('/api/v2/runs/A'), run('A', 'completed')));
await flush(() => reply(request('/api/v2/runs/A/results'), results('A')));
expect(latest.currentRun?.status).toBe('completed');
@ -889,7 +897,9 @@ describe('actual detail page result states', () => {
await mountPage('running');
await flush(() => click('Cancel run'));
expect(host.textContent).toContain('Cancellation requested');
await flush(() => reply(request('/api/v2/runs/A/cancel', 'POST'), {}, 202));
await flush(() =>
reply(request('/api/v2/runs/A/cancel', 'POST'), { message: 'Cancellation requested' }, 202)
);
expect(host.textContent).not.toContain('Run cancelled');
await flush(() => reply(request('/api/v2/runs/A'), run('A', 'cancelled')));
expect(host.textContent).toContain('Run cancelled');
@ -939,14 +949,41 @@ describe('actual detail page result states', () => {
});
async function selectBacktestStrategy(preselected = false) {
const family = { id: 'family', name: 'Test strategy', archived: false };
const family = {
id: 'family',
name: 'Test strategy',
description: '',
archived: false,
ownerPrincipal: 'operator',
updatedBy: 'operator',
createdAt: '2026-01-01',
updatedAt: '2026-01-01',
};
const version = {
id: 'version-one',
strategyId: 'family',
ordinal: 1,
origin: 'builtin',
parentVersionId: null,
createdBy: 'operator',
createdAt: '2026-01-01',
reviewStatus: 'approved',
runnable: false,
reason: 'Configure canonical settings',
package: {
version: 1,
program: {
strategyId: 'fixture',
strategyVersion: 'v1',
apiVersion: 'canonical-ts/v1',
checkpointVersion: 'fixture/v1',
},
artifact: { format: 'esm-bundle/v1', entryExport: 'createFixture', sha256: 'a'.repeat(64) },
dependencyLock: { format: 'bun-lock/v1', sha256: 'b'.repeat(64) },
source: { revision: 'c'.repeat(40), dirty: false },
build: { tool: 'bun', version: '1.2.17', target: 'browser' },
parameterSchema: {
version: 1,
type: 'object',
properties: {},
required: [],
@ -1390,7 +1427,7 @@ describe('explicit save and repeat-safe run submission', () => {
await flush(() => reply(request('/api/v2/runs/B'), run('B', 'failed', { error: 'B failure' })));
await flush(() => fail(submitting));
expect(pageLocation).toBe('/backtests/definition/run/B');
expect(host.textContent).toContain('Run submission failed: Network unavailable');
expect(host.textContent).toContain('Run submission failed: The backtest response was lost');
expect(host.textContent).toContain('Run failed: B failure');
await flush(() => click('Retry submission'));
const retry = request('/api/v2/backtests/definition/runs', 'POST');
@ -1409,7 +1446,7 @@ describe('explicit save and repeat-safe run submission', () => {
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
expect(latest.isSubmitting).toBe(true);
await flush(() => fail(first));
expect(latest.submissionError).toContain('Network unavailable');
expect(latest.submissionError).toContain('The backtest response was lost');
await flush(() => {
void latest.updateBacktest('definition', { initialCapital: 2000 });
});
@ -1450,7 +1487,7 @@ describe('explicit save and repeat-safe run submission', () => {
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
await flush(() => reply(first, { error: 'Submission unavailable' }, 503));
expect(host.textContent).toContain('Run submission failed');
expect(host.textContent).toContain('Network unavailable');
expect(host.textContent).toContain('The backtest response was lost');
expect(host.textContent).toContain('Submit the current configuration');
await flush(() => click('Retry submission'));
const retry = request('/api/v2/backtests/definition/runs', 'POST');
@ -1698,7 +1735,7 @@ describe('template archive and restore', () => {
expect(original.signal?.aborted).toBe(true);
await flush(() => (lateFailure ? fail(original) : reply(original, [definition])));
expect(host.textContent).toContain('Loading backtests...');
expect(host.textContent).not.toContain('Network unavailable');
expect(host.textContent).not.toContain('The backtest response was lost');
await flush(() => reply(current, []));
expect(host.textContent).toContain('No backtests yet.');
expect(host.textContent).not.toContain('Loading backtests...');

View file

@ -0,0 +1,351 @@
import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';
import { GlobalWindow } from 'happy-dom';
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import type { IServiceContainer } from '@stock-bot/services';
import type {
ResearchArtifact,
ResearchAuthorship,
ResearchHypothesis,
StrategyVersionSummary,
} from '@stock-bot/types';
import {
backtestResponseSchema,
researchArtifactResponseSchema,
researchHypothesisResponseSchema,
researchProjectResponseSchema,
runResponseSchema,
strategyVersionResponseSchema,
type RunResponse,
} from '../../apps/stock/config/src/contracts/product-responses';
import { builtinCatalogDescriptors } from '../../apps/stock/config/src/contracts/strategy';
import { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes';
import { createStrategyRoutes } from '../../apps/stock/web-api/src/routes/strategies.routes';
import { mapBacktest, mapRun } from '../../apps/stock/web-api/src/services/backtests/mapping';
import { RunControls } from '../../apps/stock/web-app/src/features/backtest/components/RunControls';
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
const original = Object.getOwnPropertyDescriptor(globalThis, 'window');
let backtest: typeof import('../../apps/stock/web-app/src/features/backtest/services/backtestApiV2');
let research: typeof import('../../apps/stock/web-app/src/features/research/services/researchApi');
let strategies: typeof import('../../apps/stock/web-app/src/features/strategies/services/strategyApi');
beforeAll(async () => {
Object.defineProperty(globalThis, 'window', { value: browser, configurable: true });
backtest = await import('../../apps/stock/web-app/src/features/backtest/services/backtestApiV2');
research = await import('../../apps/stock/web-app/src/features/research/services/researchApi');
strategies = await import(
'../../apps/stock/web-app/src/features/strategies/services/strategyApi'
);
});
beforeEach(() => {
Object.defineProperty(globalThis, 'window', { value: browser, configurable: true });
});
afterAll(() => {
if (original) {
Object.defineProperty(globalThis, 'window', original);
} else {
Reflect.deleteProperty(globalThis, 'window');
}
browser.happyDOM.abort();
});
const now = new Date('2026-10-28T14:32:00Z');
const backtestId = '11111111-1111-4111-8111-111111111111';
const runId = '22222222-2222-4222-8222-222222222222';
const row = {
id: backtestId,
name: 'Saved research',
strategy: 'sma_crossover',
symbols: ['AAPL.US'],
start_date: now,
end_date: new Date('2026-10-29'),
initial_capital: '10000',
config: {},
created_at: now,
updated_at: now,
archived_at: null,
};
const run = () =>
mapRun({
id: runId,
backtest_id: backtestId,
run_number: 1,
status: 'running',
speed_multiplier: null,
error: null,
started_at: now,
completed_at: null,
paused_at: null,
progress: '12.5',
current_simulation_date: now,
created_at: now,
updated_at: now,
cancel_requested: false,
attempt_number: 1,
});
function respond(body: unknown, status = 200) {
const fetch = mock(async (_input: unknown, _init?: RequestInit) =>
status === 204 ? new Response(null, { status }) : Response.json(body, { status })
);
browser.fetch = fetch as unknown as typeof browser.fetch;
return fetch;
}
test('real server backtest/run mappings survive JSON serialization and display the server clock field', async () => {
const mapped = mapBacktest(row);
respond(mapped);
const saved = await backtest.backtestApiV2.getBacktest(backtestId);
expect(saved).toEqual(backtestResponseSchema.parse(await Response.json(mapped).json()));
expect(saved.initialCapital).toBe(10000);
expect(saved.startDate).toBe(now.toISOString());
expect(saved.archivedAt).toBeNull();
respond(run());
const savedRun = await backtest.backtestApiV2.getRun(runId);
expect(savedRun.currentDate).toBe(now.toISOString());
expect(savedRun.completedAt).toBeNull();
expect(savedRun.dataset?.state).toBe('unknown');
const noop = () => {};
const html = renderToStaticMarkup(
createElement(RunControls, {
run: savedRun,
onPause: noop,
onResume: noop,
onCancel: noop,
onSpeedChange: noop,
})
);
expect(html).toContain(now.toLocaleString());
expect(html).toContain('12.5%');
});
test('existing optional fields remain optional without accepting malformed rendered fields', async () => {
const legacy: RunResponse = {
id: 'old-run',
backtestId: 'old-template',
runNumber: 1,
status: 'completed',
speedMultiplier: null,
progress: 100,
createdAt: '2024-01-01',
updatedAt: '2024-01-01',
};
expect(runResponseSchema.parse(legacy)).toEqual(legacy);
const serialized = await Response.json(mapBacktest(row)).json();
for (const bad of [
{ ...serialized, symbols: 'AAPL' },
{ ...serialized, initialCapital: '10000' },
{ ...serialized, config: null },
]) {
respond(bad);
await expect(backtest.backtestApiV2.getBacktest(backtestId)).rejects.toThrow(
'could not be verified'
);
}
for (const bad of [
{ ...legacy, progress: '100' },
{ ...legacy, runNumber: null },
{ ...legacy, currentDate: 'not a date' },
]) {
respond(bad);
await expect(backtest.backtestApiV2.getRun('old-run')).rejects.toThrow('could not be verified');
}
});
test('strategy and research records roundtrip from actual routes through browser clients', async () => {
const databaseRow = {
...row,
title: 'Research project',
description: 'Unvalidated narrative',
revision: 1,
owner_principal: 'operator',
updated_by: 'operator',
};
const container = {
postgres: { query: async () => ({ rows: [databaseRow] }) },
logger: { error: () => {} },
} as unknown as IServiceContainer;
const researchRoutes = createResearchRoutes(container);
browser.fetch = ((input: unknown, init?: RequestInit) =>
researchRoutes.request(String(input), init)) as unknown as typeof browser.fetch;
const projects = await research.researchApi.listProjects();
expect(projects.projects).toEqual([
researchProjectResponseSchema.parse({
id: backtestId,
title: databaseRow.title,
description: databaseRow.description,
revision: 1,
ownerPrincipal: 'operator',
updatedBy: 'operator',
archived: false,
createdAt: now.toISOString(),
updatedAt: now.toISOString(),
}),
]);
const catalogRoutes = createStrategyRoutes(container);
browser.fetch = ((input: unknown, init?: RequestInit) =>
catalogRoutes.request(String(input), init)) as unknown as typeof browser.fetch;
const catalog = await strategies.strategyApi.list();
expect(catalog.strategies[0]).toMatchObject({ id: backtestId, name: row.name, archived: false });
expect(catalog.strategies[0]?.createdAt).toBe(now.toISOString());
});
const authorship: ResearchAuthorship & { createdAt: string } = {
submittedBy: 'operator',
contentOrigin: 'human',
createdAt: now.toISOString(),
};
const record: Omit<ResearchHypothesis, 'latestRevision'> = {
id: 'record',
projectId: 'project',
ownerPrincipal: 'operator',
updatedBy: 'operator',
archived: false,
createdAt: now.toISOString(),
updatedAt: now.toISOString(),
};
const hypothesis: ResearchHypothesis = {
...record,
latestRevision: {
...authorship,
id: 'revision',
hypothesisId: 'record',
ordinal: 1,
title: 'Hypothesis',
proposition: 'Testable claim',
validationCriteria: '',
validationState: 'unvalidated',
},
};
const artifact: ResearchArtifact = {
...record,
kind: 'note',
hypothesisRevisionId: null,
latestRevision: {
...authorship,
id: 'revision',
artifactId: 'record',
ordinal: 1,
title: 'Notes',
body: '',
validationState: 'unvalidated',
evidenceState: 'none',
evidence: [],
},
};
test('research parsers validate nested rendered fields and revision ownership, preserving legacy source omission', async () => {
expect(researchHypothesisResponseSchema.parse(hypothesis)).toEqual(hypothesis);
expect(researchArtifactResponseSchema.parse(artifact)).toEqual(artifact);
for (const malformed of [
{ ...artifact, latestRevision: { ...artifact.latestRevision, evidence: null } },
{ ...artifact, latestRevision: { ...artifact.latestRevision, contentOrigin: 'verified' } },
{ ...artifact, latestRevision: { ...artifact.latestRevision, artifactId: 'another' } },
{ ...artifact, latestRevision: { ...artifact.latestRevision, source: {} } },
]) {
respond({ artifact: malformed }, 201);
await expect(
research.researchApi.createArtifact('project', { kind: 'note', title: 'Notes', body: '' })
).rejects.toMatchObject({ ambiguous: true, status: null });
}
respond({ projects: [{ id: 'project', title: 'Partial', revision: 1 }] });
await expect(research.researchApi.listProjects()).rejects.toBeInstanceOf(
research.ResearchApiError
);
});
test('catalog schema reuses retained parameter and package shapes without requiring a new execution declaration', async () => {
const builtin = builtinCatalogDescriptors[0]!;
const version: StrategyVersionSummary = {
id: 'version',
strategyId: 'family',
ordinal: 1,
parentVersionId: null,
createdBy: 'operator',
origin: 'builtin',
createdAt: now.toISOString(),
package: {
version: 1,
program: builtin.program,
parameterSchema: builtin.parameterSchema,
artifact: {
format: 'esm-bundle/v1',
entryExport: builtin.entryExport,
sha256: 'a'.repeat(64),
},
dependencyLock: { format: 'bun-lock/v1', sha256: 'b'.repeat(64) },
source: { revision: 'c'.repeat(40), dirty: false },
build: { tool: 'bun', version: '1.2.17', target: 'browser' },
},
reviewStatus: 'approved',
runnable: false,
reason: 'Explicit policy required',
};
const parsed: StrategyVersionSummary = strategyVersionResponseSchema.parse(version);
expect(parsed).toEqual(version);
respond({ versions: [version] });
const catalog: { versions: StrategyVersionSummary[] } =
await strategies.strategyApi.versions('family');
expect(catalog).toEqual({ versions: [version] });
respond({ versions: [{ ...version, package: { ...version.package, parameterSchema: {} } }] });
await expect(strategies.strategyApi.versions('family')).rejects.toThrow('could not be verified');
});
test('reproduction receipts preserve identity, status, idempotency key and no automatic write retry', async () => {
const originalRunId = '33333333-3333-4333-8333-333333333333';
const accepted = { ...run(), originalRunId };
const fetch = respond(accepted, 202);
const value = await backtest.backtestApiV2.reproduceRun(originalRunId, 'retained-key');
expect(value.id).toBe(runId);
expect(fetch).toHaveBeenCalledTimes(1);
expect(fetch.mock.calls[0]?.[1]).toMatchObject({
credentials: 'include',
headers: { 'Idempotency-Key': 'retained-key' },
});
for (const [body, status] of [
[{ ...accepted, originalRunId: runId }, 202],
[accepted, 200],
[{ id: runId }, 202],
] as const) {
const calls = respond(body, status);
await expect(
backtest.backtestApiV2.reproduceRun(originalRunId, 'retained-key')
).rejects.toMatchObject({ ambiguous: true, status: null });
expect(calls).toHaveBeenCalledTimes(1);
}
respond({ error: 'Review revoked' }, 409);
await expect(
backtest.backtestApiV2.reproduceRun(originalRunId, 'retained-key')
).rejects.toMatchObject({ ambiguous: false, status: 409, message: 'Review revoked' });
});
test('204 acknowledgements are accepted only where intended; cancellations remain acknowledged 202 writes', async () => {
respond(null, 204);
await expect(research.researchApi.linkStrategy('project', 'strategy')).resolves.toBeUndefined();
respond(null, 204);
await expect(backtest.backtestApiV2.deleteBacktest(backtestId)).resolves.toBeUndefined();
respond({ message: 'Cancellation requested' }, 202);
await expect(backtest.backtestApiV2.cancelRun(runId)).resolves.toBeUndefined();
const calls = respond({}, 202);
await expect(backtest.backtestApiV2.cancelRun(runId)).rejects.toThrow('could not be verified');
expect(calls).toHaveBeenCalledTimes(1);
respond({}, 200);
await expect(research.researchApi.linkStrategy('project', 'strategy')).rejects.toMatchObject({
ambiguous: true,
});
});
test('all shared transports preserve abort causes and classify lost research writes as ambiguous without retries', async () => {
const controller = new AbortController();
controller.abort();
const cause = new DOMException('Cancelled', 'AbortError');
const fetch = mock(async () => {
throw cause;
});
browser.fetch = fetch as unknown as typeof browser.fetch;
await expect(backtest.backtestApiV2.getRun(runId, controller.signal)).rejects.toBe(cause);
await expect(strategies.strategyApi.list(controller.signal)).rejects.toBe(cause);
await expect(research.researchApi.listProjects(false, controller.signal)).rejects.toBe(cause);
await expect(
research.researchApi.createProject({ title: 'Potentially saved' })
).rejects.toMatchObject({ ambiguous: true, status: null });
expect(fetch).toHaveBeenCalledTimes(4);
});

View file

@ -439,7 +439,9 @@ describe('saved-result finding', () => {
201
)
);
expect(host.textContent).toContain('saved finding response could not be verified');
expect(host.textContent).toMatch(
/saved finding response could not be verified|The research response could not be read/
);
expect(host.textContent).not.toContain('Finding saved.');
expect(field('Finding title').value).toBe('Exact finding');
expect(field('Finding body').value).toBe('Keep this narrative');
@ -453,7 +455,9 @@ describe('saved-result finding', () => {
await draft();
await preflight();
await flush(() => reply(post(), { artifact: { ...acceptedFinding(), archived: true } }, 201));
expect(host.textContent).toContain('saved finding response could not be verified');
expect(host.textContent).toMatch(
/saved finding response could not be verified|The research response could not be read/
);
expect(button('Save finding').disabled).toBe(true);
});
test.each([
@ -507,7 +511,9 @@ describe('saved-result finding', () => {
break;
}
await flush(() => reply(post(), { artifact: saved }, 201));
expect(host.textContent).toContain('saved finding response could not be verified');
expect(host.textContent).toMatch(
/saved finding response could not be verified|The research response could not be read/
);
expect(host.textContent).toContain('Check saved records before creating another');
expect(host.textContent).not.toContain('Finding saved.');
expect(host.textContent).not.toContain('Open saved finding');

View file

@ -60,7 +60,7 @@ function request(path: string, method = 'GET') {
}
return found;
}
function reply(item: Pending, body: unknown, status = 200) {
function reply(item: Pending, body: unknown, status = item.method === 'POST' ? 201 : 200) {
item.settled = true;
item.resolve(status === 204 ? new Response(null, { status }) : Response.json(body, { status }));
}
@ -787,8 +787,8 @@ describe('research workspace', () => {
201
)
);
expect(host.textContent).toContain(
'The saved research entry response could not be verified.'
expect(host.textContent).toMatch(
/The saved research entry response could not be verified\.|The research response could not be read\./
);
expect(field(kind === 'hypothesis' ? 'Hypothesis title' : 'Note title').value).toBe(
creationDraft.title
@ -996,7 +996,9 @@ describe('research workspace', () => {
},
})
);
expect(host.textContent).toContain('The saved revision response could not be verified.');
expect(host.textContent).toMatch(
/The saved revision response could not be verified\.|The research response could not be read\./
);
expect(field('Revision title').value).toBe(revisionDraft.title);
expect(field('Revision body').value).toBe(revisionDraft.body);
expect(field('Revision content origin').value).toBe('unknown');
@ -1045,7 +1047,9 @@ describe('research workspace', () => {
artifact: { ...saved, latestRevision: { ...saved.latestRevision, ...change } },
})
);
expect(host.textContent).toContain('The saved revision response could not be verified.');
expect(host.textContent).toMatch(
/The saved revision response could not be verified\.|The research response could not be read\./
);
expect(field('Revision body').value).toBe(revisionDraft.body);
expect(button('Save new revision').disabled).toBe(true);
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
@ -1240,7 +1244,9 @@ describe('research workspace', () => {
},
})
);
expect(host.textContent).toContain('The archive response could not be verified.');
expect(host.textContent).toMatch(
/The archive response could not be verified\.|The research response could not be read\./
);
expect(field('Revision title').value).toBe(revisionDraft.title);
expect(field('Revision body').value).toBe(revisionDraft.body);
expect(button('Save new revision').disabled).toBe(true);
@ -1259,7 +1265,9 @@ describe('research workspace', () => {
: artifact('a1', { archived: true });
const patch = await submitEntryArchive(original);
await flush(() => reply(patch, { [kind]: original }));
expect(host.textContent).toContain('The archive response could not be verified.');
expect(host.textContent).toMatch(
/The archive response could not be verified\.|The research response could not be read\./
);
expect(button('Restore entry').disabled).toBe(true);
expect(requests.filter(item => !item.settled)).toHaveLength(0);
});
@ -1514,7 +1522,7 @@ describe('research workspace', () => {
unavailableReason: null,
resultKind: 'canonical',
financialEngine: 'rust',
datasetHash: 'frozen-dataset',
datasetHash: 'f'.repeat(64),
limitations: [],
},
],

View file

@ -699,7 +699,7 @@ describe('strategy workbench', () => {
autoStart: false,
});
expect((post.body as { config: object }).config).not.toHaveProperty('fastPeriod');
await flush(() => reply(post, definition));
await flush(() => reply(post, definition, 201));
expect(saved).toEqual(definition);
expect(requests.some(item => item.path.endsWith('/runs'))).toBe(false);
});