394 lines
15 KiB
TypeScript
394 lines
15 KiB
TypeScript
import { describe, expect, mock, test } from 'bun:test';
|
|
import { Hono } from 'hono';
|
|
import { createHttpSecurity } from '@stock-bot/di';
|
|
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
|
import type { IServiceContainer } from '@stock-bot/services';
|
|
import type { HistoricalDatasetInputV2 } from '@stock-bot/types';
|
|
import {
|
|
NativeReplaySession,
|
|
prepareReplayLoad,
|
|
runReplayConformance,
|
|
} from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
|
import {
|
|
createDatasetV2,
|
|
validateDatasetV2,
|
|
} from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
|
|
import { retainResearchDataset } from '../../apps/stock/orchestrator/src/data/retained-research-dataset';
|
|
import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes';
|
|
import { readCanonicalDataset } from '../../apps/stock/web-api/src/services/canonical-research.service';
|
|
import {
|
|
previewDatasetPreparation,
|
|
retainDatasetPreparation,
|
|
} from '../../apps/stock/web-api/src/services/dataset-preparation.service';
|
|
import { retainResearchDataset as cliRetain } from '../../scripts/import-research-dataset';
|
|
import { datasetInput } from '../fixtures/historical-v2/dataset';
|
|
import { nativeReplayFixture } from '../fixtures/native-replay';
|
|
|
|
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
|
const logger = getLogger('dataset-source-preparation-test');
|
|
const tokens = {
|
|
admin: 'source-preparation-admin-fixture-123456789',
|
|
read: 'source-preparation-read-fixture-1234567890',
|
|
service: 'source-preparation-service-fixture-12345678',
|
|
};
|
|
type Mutable<T> = { -readonly [K in keyof T]: T[K] extends object ? Mutable<T[K]> : T[K] };
|
|
const source = () => structuredClone(datasetInput()) as Mutable<HistoricalDatasetInputV2>;
|
|
function at<T>(values: readonly T[], index = 0): T {
|
|
const value = values[index];
|
|
if (value === undefined) {
|
|
throw new Error('Missing fixture item');
|
|
}
|
|
return value;
|
|
}
|
|
function fixture(
|
|
query: (
|
|
sql: string,
|
|
values?: unknown[]
|
|
) => Promise<{ rows: Record<string, unknown>[] }> = async () => {
|
|
throw new Error('Preview/rejected request reached storage');
|
|
}
|
|
) {
|
|
const database = { query: mock(query) };
|
|
const app = new Hono();
|
|
createHttpSecurity({
|
|
adminToken: tokens.admin,
|
|
serviceToken: tokens.service,
|
|
readToken: tokens.read,
|
|
environment: 'test',
|
|
hostname: '127.0.0.1',
|
|
browserSessions: true,
|
|
}).mount(app);
|
|
app.route(
|
|
'/',
|
|
createDatasetRoutes({ postgres: database, logger } as unknown as IServiceContainer)
|
|
);
|
|
const request = (
|
|
operation: 'preview' | 'retain',
|
|
body: unknown,
|
|
headers: Record<string, string> = { Authorization: `Bearer ${tokens.admin}` }
|
|
) =>
|
|
app.request(`/api/v2/datasets/canonical/${operation}`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json', ...headers },
|
|
body: JSON.stringify(body),
|
|
});
|
|
return { app, database, request };
|
|
}
|
|
|
|
describe('explicit source-export preparation', () => {
|
|
test('preview is pure, stable under normalized permutation and preserves declared evidence without mutating input', async () => {
|
|
const f = fixture();
|
|
const input = source(),
|
|
before = structuredClone(input);
|
|
const reply = await f.request('preview', { input });
|
|
expect(reply.status).toBe(200);
|
|
expect(reply.headers.get('Cache-Control')).toBe('no-store');
|
|
const expected = previewDatasetPreparation({ input });
|
|
expect(await reply.json()).toEqual({ preparation: expected });
|
|
expect(expected).toMatchObject({
|
|
version: 'canonical-dataset-preparation/v1',
|
|
available: true,
|
|
reason: null,
|
|
});
|
|
expect(expected.manifest.series).toEqual(input.metadata.series);
|
|
expect(expected.manifest.calendars).toEqual(input.metadata.calendars);
|
|
expect(expected.manifest.universe).toEqual(input.metadata.universe);
|
|
expect(expected.manifest.corporateActions).toEqual(input.metadata.corporateActions);
|
|
expect(expected.manifest.parentDatasetHash).toBeNull();
|
|
expect(expected.manifest.limitations.some(value => value.includes('interval end'))).toBe(true);
|
|
expect(input).toEqual(before);
|
|
input.bars.reverse();
|
|
at(input.metadata.calendars).sessions.reverse();
|
|
const permuted = structuredClone(input);
|
|
expect(previewDatasetPreparation({ input })).toEqual(expected);
|
|
expect(input).toEqual(permuted);
|
|
expect(f.database.query).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test('complete strict source validation rejects missing metadata, bad declarations, duplicate/invalid observations with actionable safe diagnostics', async () => {
|
|
const f = fixture();
|
|
const invalid: unknown[] = [
|
|
null,
|
|
{},
|
|
{ bars: source().bars },
|
|
{ metadata: source().metadata },
|
|
{ ...source(), extra: 'not permitted' },
|
|
];
|
|
const mutations: Array<(value: Mutable<HistoricalDatasetInputV2>) => void> = [
|
|
value => {
|
|
at(value.metadata.calendars).revision = '';
|
|
},
|
|
value => {
|
|
at(value.metadata.calendars).timeZone = 'private-invalid-timezone';
|
|
},
|
|
value => {
|
|
value.metadata.corporateActions = [];
|
|
},
|
|
value => {
|
|
at(value.metadata.series).source.revision = '';
|
|
},
|
|
value => {
|
|
at(value.metadata.series).availability = 'explicit';
|
|
},
|
|
value => {
|
|
value.bars.push({ ...at(value.bars) });
|
|
},
|
|
value => {
|
|
at(value.bars).high = 1;
|
|
},
|
|
value => {
|
|
at(value.bars).volume = -1;
|
|
},
|
|
value => {
|
|
at(value.bars).timestamp = '2024-03-09';
|
|
},
|
|
];
|
|
for (const change of mutations) {
|
|
const input = source();
|
|
change(input);
|
|
invalid.push(input);
|
|
}
|
|
for (const input of invalid) {
|
|
const response = await f.request('preview', { input });
|
|
expect(response.status).toBe(400);
|
|
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
|
expect(await response.text()).not.toContain('private-invalid-timezone');
|
|
}
|
|
const missing = await f.request('preview', { input: { bars: [] } });
|
|
expect(await missing.text()).toContain('metadata');
|
|
const duplicate = source();
|
|
duplicate.bars.push({ ...at(duplicate.bars) });
|
|
expect(await (await f.request('preview', { input: duplicate })).text()).toContain(
|
|
'Duplicate or conflicting'
|
|
);
|
|
expect(f.database.query).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test('preview availability exactly matches the existing workbench gate for valid exploratory, adjusted, known-action and multiasset datasets', async () => {
|
|
const variants: Array<(value: Mutable<HistoricalDatasetInputV2>) => void> = [
|
|
value => {
|
|
value.metadata.universe.selection = 'unknown';
|
|
value.metadata.universe.asOf = null;
|
|
},
|
|
value => {
|
|
at(value.metadata.corporateActions).status = 'unknown';
|
|
},
|
|
value => {
|
|
at(value.metadata.series).adjustment = 'provider-adjusted';
|
|
},
|
|
value => {
|
|
const coverage = at(value.metadata.corporateActions);
|
|
coverage.status = 'known-actions';
|
|
coverage.actions.push({
|
|
effectiveAt: value.metadata.bounds.tradeStart,
|
|
kind: 'split',
|
|
reference: 'operator-declared-action',
|
|
});
|
|
},
|
|
value => {
|
|
value.metadata.series.push({
|
|
...at(value.metadata.series),
|
|
id: 'B.US:daily:raw',
|
|
instrumentId: 'B.US',
|
|
});
|
|
value.metadata.executionSeries.push({ instrumentId: 'B.US', seriesId: 'B.US:daily:raw' });
|
|
value.metadata.universe.instrumentIds.push('B.US');
|
|
value.metadata.corporateActions.push({
|
|
...at(value.metadata.corporateActions),
|
|
instrumentId: 'B.US',
|
|
});
|
|
value.bars.push(...value.bars.map(bar => ({ ...bar, seriesId: 'B.US:daily:raw' })));
|
|
},
|
|
];
|
|
for (const mutate of variants) {
|
|
const input = source();
|
|
mutate(input);
|
|
const prepared = previewDatasetPreparation({ input });
|
|
expect(prepared.available).toBe(false);
|
|
expect(prepared.manifest).toEqual(createDatasetV2(input).manifest);
|
|
await expect(
|
|
readCanonicalDataset(
|
|
{ query: async () => ({ rows: [{ payload: createDatasetV2(input) }] }) },
|
|
prepared.hash
|
|
)
|
|
).rejects.toThrow(prepared.reason ?? 'missing reason');
|
|
const stored = new Map<string, unknown>();
|
|
const retained = await retainDatasetPreparation(
|
|
{
|
|
async query(sql, values) {
|
|
if (sql.startsWith('INSERT')) {
|
|
stored.set(String(values?.[0]), JSON.parse(String(values?.[1])));
|
|
return { rows: [] };
|
|
}
|
|
return { rows: [{ payload: stored.get(String(values?.[0])) }] };
|
|
},
|
|
},
|
|
{ input, expectedHash: prepared.hash }
|
|
);
|
|
expect(retained).toEqual(prepared);
|
|
}
|
|
});
|
|
|
|
test('retained explicit delay and missing VWAP survive normalization; native decisions cannot observe unpublished bars', async () => {
|
|
const f = nativeReplayFixture(5),
|
|
manifest = f.dataset.manifest;
|
|
const delayedAt = f.start + 2.5 * f.minute;
|
|
const input: HistoricalDatasetInputV2 = {
|
|
metadata: {
|
|
calendars: manifest.calendars,
|
|
series: manifest.series,
|
|
executionSeries: manifest.executionSeries,
|
|
bounds: manifest.bounds,
|
|
universe: manifest.universe,
|
|
corporateActions: manifest.corporateActions,
|
|
},
|
|
bars: f.dataset.bars.map(bar => ({
|
|
seriesId: bar.seriesId,
|
|
timestamp: bar.intervalStart,
|
|
sourceSequence: bar.sourceSequence,
|
|
availableAt: bar.sourceSequence === 0 ? delayedAt : bar.availableAt,
|
|
open: bar.open,
|
|
high: bar.high,
|
|
low: bar.low,
|
|
close: bar.close,
|
|
volume: bar.volume,
|
|
})),
|
|
};
|
|
let stored: unknown;
|
|
const prepared = previewDatasetPreparation({ input });
|
|
await retainDatasetPreparation(
|
|
{
|
|
async query(sql, values) {
|
|
if (sql.startsWith('INSERT')) {
|
|
stored = JSON.parse(String(values?.[1]));
|
|
return { rows: [] };
|
|
}
|
|
return { rows: [{ payload: stored }] };
|
|
},
|
|
},
|
|
{ input, expectedHash: prepared.hash }
|
|
);
|
|
const retained = validateDatasetV2(stored);
|
|
expect(retained.bars.find(bar => bar.sourceSequence === 0)?.availableAt).toBe(delayedAt);
|
|
expect(retained.bars.every(bar => bar.vwap === null)).toBe(true);
|
|
expect(retained.manifest.series).toEqual(manifest.series);
|
|
const decisions: Array<{ at: number; sequence: number[] }> = [];
|
|
runReplayConformance(
|
|
new NativeReplaySession(prepareReplayLoad(retained, f.config)),
|
|
(_owner, context, observations) => {
|
|
expect(observations.every(bar => bar.available_at <= context.barrier.at)).toBe(true);
|
|
decisions.push({
|
|
at: context.barrier.at,
|
|
sequence: observations.map(bar => bar.source_sequence),
|
|
});
|
|
return { mode: 'target', targets: [] };
|
|
}
|
|
);
|
|
expect(decisions.some(decision => decision.at < delayedAt)).toBe(true);
|
|
expect(
|
|
decisions
|
|
.filter(decision => decision.at < delayedAt)
|
|
.every(decision => !decision.sequence.includes(0))
|
|
).toBe(true);
|
|
expect(
|
|
decisions.some(decision => decision.at >= delayedAt && decision.sequence.includes(0))
|
|
).toBe(true);
|
|
});
|
|
|
|
test('strict bodies, malformed JSON and hash drift reject before any write; errors are not cacheable', async () => {
|
|
const f = fixture(),
|
|
input = source(),
|
|
expectedHash = previewDatasetPreparation({ input }).hash;
|
|
for (const [operation, body] of [
|
|
['preview', {}],
|
|
['preview', { input, extra: true }],
|
|
['preview', { input, expectedHash }],
|
|
['retain', { input }],
|
|
['retain', { input, expectedHash: expectedHash.toUpperCase() }],
|
|
['retain', { input, expectedHash, extra: true }],
|
|
['retain', { input: null, expectedHash }],
|
|
] as const) {
|
|
const response = await f.request(operation, body);
|
|
expect(response.status).toBe(400);
|
|
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
|
}
|
|
const mismatch = await f.request('retain', { input, expectedHash: '0'.repeat(64) });
|
|
expect(mismatch.status).toBe(409);
|
|
expect(mismatch.headers.get('Cache-Control')).toBe('no-store');
|
|
const malformed = await f.app.request('/api/v2/datasets/canonical/preview', {
|
|
method: 'POST',
|
|
headers: { Authorization: `Bearer ${tokens.admin}`, 'Content-Type': 'application/json' },
|
|
body: '{',
|
|
});
|
|
expect(malformed.status).toBe(400);
|
|
expect(f.database.query).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test('storage exceptions and corrupt conflicting content fail as sanitized 500, never input errors or success', async () => {
|
|
const input = source(),
|
|
expectedHash = previewDatasetPreparation({ input }).hash;
|
|
for (const query of [
|
|
async () => {
|
|
throw new Error('private-storage-details');
|
|
},
|
|
async () => ({ rows: [{ payload: { private: 'private-storage-details' } }] }),
|
|
async () => ({ rows: [] }),
|
|
]) {
|
|
const response = await fixture(query).request('retain', { input, expectedHash });
|
|
expect(response.status).toBe(500);
|
|
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
|
expect(await response.text()).not.toContain('private-storage-details');
|
|
}
|
|
});
|
|
|
|
test('existing mounted global auth rejects read tokens and protects browser mutations with trusted Origin', async () => {
|
|
const input = source(),
|
|
expectedHash = previewDatasetPreparation({ input }).hash;
|
|
const stored = createDatasetV2(input);
|
|
const f = fixture(async () => ({ rows: [{ payload: stored }] }));
|
|
for (const operation of ['preview', 'retain'] as const) {
|
|
const body = operation === 'preview' ? { input } : { input, expectedHash };
|
|
expect((await f.request(operation, body, {})).status).toBe(401);
|
|
expect(
|
|
(await f.request(operation, body, { Authorization: `Bearer ${tokens.read}` })).status
|
|
).toBe(403);
|
|
}
|
|
const login = await f.app.request('/api/auth/session', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json', Origin: 'http://localhost' },
|
|
body: JSON.stringify({ token: tokens.admin }),
|
|
});
|
|
expect(login.status).toBe(200);
|
|
const cookie = login.headers.get('Set-Cookie')?.split(';')[0];
|
|
if (!cookie) {
|
|
throw new Error('Missing authenticated browser session');
|
|
}
|
|
for (const operation of ['preview', 'retain'] as const) {
|
|
const body = operation === 'preview' ? { input } : { input, expectedHash };
|
|
expect((await f.request(operation, body, { Cookie: cookie })).status).toBe(403);
|
|
expect(
|
|
(await f.request(operation, body, { Cookie: cookie, Origin: 'https://foreign.invalid' }))
|
|
.status
|
|
).toBe(403);
|
|
}
|
|
expect(f.database.query).not.toHaveBeenCalled();
|
|
expect(
|
|
(await f.request('preview', { input }, { Cookie: cookie, Origin: 'http://localhost' })).status
|
|
).toBe(200);
|
|
expect(f.database.query).not.toHaveBeenCalled();
|
|
expect(
|
|
(
|
|
await f.request(
|
|
'retain',
|
|
{ input, expectedHash },
|
|
{ Cookie: cookie, Origin: 'http://localhost' }
|
|
)
|
|
).status
|
|
).toBe(200);
|
|
expect(f.database.query).toHaveBeenCalledTimes(2);
|
|
});
|
|
|
|
test('existing CLI imports reexport the same retained custody helper without executing the CLI', () => {
|
|
expect(cliRetain).toBe(retainResearchDataset);
|
|
});
|
|
});
|