460 lines
18 KiB
TypeScript
460 lines
18 KiB
TypeScript
/** Real authenticated APIs + disposable PostgreSQL + isolated candidate/Rust execution. No finance mocks. */
|
|
import { createHash, randomUUID } from 'node:crypto';
|
|
import { readFileSync } from 'node:fs';
|
|
import { afterEach, describe, expect, test } from 'bun:test';
|
|
import { Hono } from 'hono';
|
|
import { Pool } from 'pg';
|
|
import { createHttpSecurity } from '@stock-bot/di';
|
|
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
|
import { PostgreSQLClient } from '@stock-bot/postgres';
|
|
import type { StrategyVersionPackage } from '@stock-bot/types';
|
|
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
|
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
|
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
|
import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
|
|
import { createResearchAgentRoutes } from '../../apps/stock/web-api/src/routes/research-agents.routes';
|
|
import { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes';
|
|
import { createStrategyRoutes } from '../../apps/stock/web-api/src/routes/strategies.routes';
|
|
import { ResearchAgentsService } from '../../apps/stock/web-api/src/services/research-agents.service';
|
|
import { ResearchService } from '../../apps/stock/web-api/src/services/research.service';
|
|
import {
|
|
runResearchCycle,
|
|
type ResearchCycleEvent,
|
|
type ResearchCyclePlan,
|
|
} from '../../scripts/examples/research-cycle';
|
|
import { retainResearchDataset } from '../../scripts/import-research-dataset';
|
|
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
|
|
import { ResearchClient } from '../../scripts/research-client';
|
|
import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';
|
|
import { canonicalRegimeSelection } from '../fixtures/canonical-regime-research';
|
|
import { walkForwardDataset } from '../fixtures/walk-forward';
|
|
|
|
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
|
const logger = getLogger('ai-research-workflow');
|
|
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
|
const cleanups: (() => Promise<void>)[] = [];
|
|
afterEach(async () => {
|
|
for (const close of cleanups.splice(0).reverse()) {
|
|
await close();
|
|
}
|
|
});
|
|
let packages: ReturnType<typeof packageBuiltinStrategies> | undefined;
|
|
async function fixture() {
|
|
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
|
throw new Error('Disposable safety database required');
|
|
}
|
|
const schema = `stock_bot_safety_ai_cycle_${randomUUID().replaceAll('-', '')}`;
|
|
const admin = new Pool({ connectionString: url });
|
|
await admin.query(`CREATE SCHEMA ${schema}`);
|
|
const pool = new Pool({
|
|
connectionString: url,
|
|
max: 4,
|
|
options: `-c search_path=${schema} -c statement_timeout=10000`,
|
|
});
|
|
cleanups.push(async () => {
|
|
await pool.end();
|
|
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
|
await admin.end();
|
|
});
|
|
const postgres = new PostgreSQLClient(
|
|
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
|
logger
|
|
);
|
|
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
|
const base = await canonicalAdmissionFixture(pool, postgres);
|
|
for (const name of [
|
|
'20-research-workspace.sql',
|
|
'27-research-evidence-sources.sql',
|
|
'28-research-agents.sql',
|
|
'29-isolated-candidates.sql',
|
|
'31-research-agent-project-links.sql',
|
|
]) {
|
|
await pool.query(
|
|
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
|
);
|
|
}
|
|
const dataset = walkForwardDataset();
|
|
await retainResearchDataset(pool, dataset.dataset);
|
|
const draft = await base.api.createBacktest(
|
|
{
|
|
...base.definition,
|
|
name: 'AI workflow granted source',
|
|
startDate: new Date(dataset.dataset.manifest.bounds.tradeStart).toISOString(),
|
|
endDate: new Date(dataset.dataset.manifest.bounds.tradeEnd).toISOString(),
|
|
config: { ...base.definition.config, datasetHash: dataset.dataset.manifest.hash },
|
|
},
|
|
{ autoStart: false }
|
|
);
|
|
const container = { postgres, logger };
|
|
const agents = new ResearchAgentsService(container),
|
|
research = new ResearchService(container);
|
|
const project = await research.createProject({ title: 'AI research acceptance' }, 'operator');
|
|
const provisioned = await agents.create({
|
|
name: 'Workflow researcher',
|
|
allowedProjectIds: [project.id],
|
|
allowedBacktestIds: [draft.id],
|
|
allowOwnCandidateBacktestIds: [draft.id],
|
|
limits: {
|
|
maxActiveTrials: 4,
|
|
maxTrialsPerExperiment: 4,
|
|
maxBarEvaluationsPerExperiment: 10000,
|
|
maxAttemptWallMs: 60000,
|
|
maxAttempts: 1,
|
|
},
|
|
});
|
|
const app = new Hono();
|
|
const security = createHttpSecurity({
|
|
adminToken: 'operator-test-secret-12345678901234567890',
|
|
serviceToken: 'service-test-secret-123456789012345678901',
|
|
environment: 'test',
|
|
resolveResearchCredential: request => agents.authenticate(request),
|
|
});
|
|
security.mount(app);
|
|
app.route('/', createResearchAgentRoutes(container, security.researchEnabled));
|
|
app.route('/', createStrategyRoutes(container));
|
|
app.route('/', createResearchRoutes(container));
|
|
app.route('/', createExperimentRoutes(container));
|
|
const engine = new RustBacktestAdapter({
|
|
logger,
|
|
storage: {
|
|
async getHistoricalBars() {
|
|
throw new Error('Research must use the frozen dataset');
|
|
},
|
|
},
|
|
});
|
|
const runner = new BacktestRunner({
|
|
engine,
|
|
engineName: 'native',
|
|
repository: new PostgresBacktestRunRepository(postgres),
|
|
logger,
|
|
});
|
|
const executionErrors: unknown[] = [];
|
|
let pending = Promise.resolve();
|
|
// A small test worker drives the existing durable runner. It changes no engine/fill behavior.
|
|
const drain = () => {
|
|
pending = pending.then(async () => {
|
|
for (const row of (
|
|
await pool.query<{ id: string }>(
|
|
"SELECT id FROM runs WHERE status='pending' ORDER BY created_at,id"
|
|
)
|
|
).rows) {
|
|
try {
|
|
await runner.runQueued(row.id);
|
|
} catch (error) {
|
|
executionErrors.push(error);
|
|
}
|
|
}
|
|
});
|
|
};
|
|
cleanups.push(async () => {
|
|
await pending;
|
|
await runner.shutdown();
|
|
await engine.shutdown();
|
|
});
|
|
const requests: {
|
|
path: string;
|
|
method: string;
|
|
key: string | null;
|
|
body: unknown;
|
|
status: number;
|
|
}[] = [];
|
|
const transport: typeof fetch = (async (input: string | URL | Request, init?: RequestInit) => {
|
|
const request = new Request(input, init);
|
|
const body: unknown = request.body === null ? undefined : await request.clone().json();
|
|
const response = await app.fetch(request);
|
|
requests.push({
|
|
path: new URL(request.url).pathname,
|
|
method: request.method,
|
|
key: request.headers.get('Idempotency-Key'),
|
|
body,
|
|
status: response.status,
|
|
});
|
|
if (response.status === 202) {
|
|
drain();
|
|
}
|
|
return response;
|
|
}) as typeof fetch;
|
|
const client = new ResearchClient({
|
|
origin: 'http://127.0.0.1:2003',
|
|
token: provisioned.token,
|
|
fetch: transport,
|
|
});
|
|
const prepared = await (packages ??= packageBuiltinStrategies());
|
|
function candidate(index: number): StrategyVersionPackage {
|
|
const pkg = prepared[index];
|
|
if (!pkg) {
|
|
throw new Error('Missing prepared fixture');
|
|
}
|
|
return { ...structuredClone(pkg), execution: { kind: 'isolated-candidate/v1', warmupBars: 3 } };
|
|
}
|
|
function suggestions(): ResearchCyclePlan {
|
|
const trend = candidate(0),
|
|
regime = candidate(1),
|
|
failure = candidate(0);
|
|
failure.artifact.content += '\nthrow new Error("Deliberate research candidate failure");\n';
|
|
failure.artifact.sha256 = createHash('sha256').update(failure.artifact.content).digest('hex');
|
|
const common = {
|
|
recipe: dataset.windows[0]!,
|
|
costScenarios: [{ feeRate: '0.02', slippageRate: '0.01' }],
|
|
};
|
|
// Deterministic fake-model suggestions; bundles are inert input until the real isolated worker.
|
|
return {
|
|
cycleId: 'acceptance-cycle',
|
|
projectId: project.id,
|
|
backtestId: draft.id,
|
|
maxTotalTrials: 16,
|
|
hypothesis: {
|
|
title: 'Trend and regime-aware mean reversion',
|
|
proposition:
|
|
'These independent candidates may respond differently to the same market observations',
|
|
validationCriteria:
|
|
'Train-only selection, held-out diagnostics, fixed cost scenarios; no fitted-model or profitable-strategy claim',
|
|
},
|
|
candidates: [
|
|
{
|
|
...common,
|
|
key: 'trend',
|
|
name: 'Trend candidate',
|
|
rationale: 'Short/long trend signals',
|
|
package: trend,
|
|
parameters: { fastPeriod: 2, slowPeriod: 3 },
|
|
grid: { fastPeriod: [1, 2] },
|
|
},
|
|
{
|
|
...common,
|
|
key: 'regime',
|
|
name: 'Regime candidate',
|
|
rationale: 'Mean reversion with momentum, trend, volume and volatility gates',
|
|
package: regime,
|
|
parameters: canonicalRegimeSelection().parameters,
|
|
grid: {},
|
|
},
|
|
{
|
|
...common,
|
|
key: 'broken',
|
|
name: 'Broken candidate',
|
|
rationale: 'Failure is evidence of implementation failure, not a zero return',
|
|
package: failure,
|
|
parameters: { fastPeriod: 2, slowPeriod: 3 },
|
|
grid: {},
|
|
},
|
|
],
|
|
};
|
|
}
|
|
return {
|
|
...base,
|
|
pool,
|
|
agents,
|
|
research,
|
|
project,
|
|
provisioned,
|
|
app,
|
|
client,
|
|
requests,
|
|
suggestions,
|
|
executionErrors,
|
|
transport,
|
|
drain,
|
|
};
|
|
}
|
|
|
|
describe.skipIf(!url)('AI research workflow through authenticated APIs and Rust', () => {
|
|
test('two generated candidates, train-only selection, costs, exact saved evidence and a retained failure', async () => {
|
|
const f = await fixture();
|
|
const events: ResearchCycleEvent[] = [];
|
|
const result = await runResearchCycle(f.client, f.suggestions(), {
|
|
onEvent: async event => {
|
|
events.push(structuredClone(event));
|
|
},
|
|
poll: { timeoutMs: 60000, intervalMs: 20 },
|
|
});
|
|
expect(result.totalPlannedTrials).toBe(16);
|
|
expect(result.outcomes).toHaveLength(3);
|
|
expect(result.hypothesis.latestRevision.contentOrigin).toBe('ai');
|
|
expect(result.hypothesis.latestRevision.validationState).toBe('unvalidated');
|
|
expect(result.regimeAttribution).toContain('unavailable');
|
|
for (const outcome of result.outcomes.slice(0, 2)) {
|
|
expect(outcome.stoppedReason).toBeNull();
|
|
expect(
|
|
outcome.screening?.trials.every(trial => trial.status === 'completed' && trial.comparable)
|
|
).toBeTrue();
|
|
const report = outcome.validation?.report,
|
|
selection = outcome.validation?.selection;
|
|
if (!report || !selection || !outcome.costs) {
|
|
throw new Error('Missing sealed native evidence');
|
|
}
|
|
expect(outcome.validation?.preview.policy.model).toBe('unverified-candidate');
|
|
expect(selection.training.every(run => run.phase === 'train')).toBeTrue();
|
|
expect(report.test.phase).toBe('test');
|
|
expect(outcome.costs.trials).toHaveLength(2);
|
|
for (const trial of outcome.costs.trials) {
|
|
expect(trial.status).toBe('completed');
|
|
expect(trial.comparable).toBeTrue();
|
|
expect(trial.parameters).toEqual(selection.winner.parameters);
|
|
}
|
|
const finding = outcome.findings[0]!;
|
|
expect(finding.latestRevision.source).toEqual({
|
|
kind: 'chronological-report/v1',
|
|
validationId: outcome.validation!.id,
|
|
previewHash: outcome.validation!.previewHash,
|
|
reportId: report.id,
|
|
reportHash: report.reportHash,
|
|
});
|
|
expect(finding.latestRevision.evidence).toHaveLength(6);
|
|
for (const evidence of finding.latestRevision.evidence) {
|
|
const saved = await f.api.getRunResults(evidence.runId);
|
|
if (!saved || !('kind' in saved) || saved.kind !== 'canonical-result/v1') {
|
|
throw new Error('Missing native result');
|
|
}
|
|
expect(saved.strategyExecution).toBe('typescript-isolated-candidate/v1');
|
|
expect(saved.request.strategy.versionId).toBe(outcome.versionId);
|
|
expect(saved.request.strategy.package.artifact.sha256).toHaveLength(64);
|
|
expect(evidence.datasetHash).toBe(saved.request.datasetHash);
|
|
const metric = evidence.metricPath.slice('analytics.metrics.'.length) as
|
|
| 'totalReturn'
|
|
| 'maxDrawdown'
|
|
| 'sharpeRatio';
|
|
expect(evidence.value).toBe(saved.analytics.metrics[metric]);
|
|
expect(evidence.availability).toBe(evidence.value === null ? 'unavailable' : 'available');
|
|
if (evidence.value === null) {
|
|
expect(evidence.unavailableReason).toBeTruthy();
|
|
}
|
|
}
|
|
}
|
|
const broken = result.outcomes[2]!;
|
|
expect(broken.screening?.trials[0]?.status).toBe('failed');
|
|
expect(broken.screening?.trials[0]?.metrics).toBeNull();
|
|
expect(broken.screening?.trials[0]?.error).toContain('Deliberate research candidate failure');
|
|
expect(broken.validation?.report).toBeNull();
|
|
expect(broken.validation?.selection).toBeNull();
|
|
expect(
|
|
broken.validation?.phases.slice(1).every(phase => phase.status === 'not-admitted')
|
|
).toBeTrue();
|
|
expect(broken.findings).toEqual([]);
|
|
expect(broken.stoppedReason).toContain('failed');
|
|
expect(result.comparison?.rows).toHaveLength(4);
|
|
expect(result.comparison?.selection.leftId).toBe(result.outcomes[0]!.costs!.id);
|
|
expect(result.comparison?.selection.rightId).toBe(result.outcomes[1]!.costs!.id);
|
|
expect(
|
|
events.filter(event => event.phase === 'accepted' && event.operation === 'submit-training')
|
|
).toHaveLength(3);
|
|
const keyed = events.filter(event => event.phase === 'intent' && event.key);
|
|
expect(new Set(keyed.map(event => event.key)).size).toBe(keyed.length);
|
|
expect(
|
|
keyed.every(
|
|
event =>
|
|
f.requests.some(
|
|
request =>
|
|
request.key === event.key &&
|
|
JSON.stringify(request.body) === JSON.stringify(event.input)
|
|
) || event.operation === 'publish-version'
|
|
)
|
|
).toBeTrue();
|
|
expect(
|
|
f.requests.some(request =>
|
|
/\/(?:paper(?:-deployments)?|deployments|live|reviews)(?:\/|$)/.test(request.path)
|
|
)
|
|
).toBeFalse();
|
|
expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(12);
|
|
const accepted = events.find(
|
|
event => event.operation === 'submit-training' && event.phase === 'intent'
|
|
)!;
|
|
const before = (await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count;
|
|
const replay = await f.client.submitValidation(
|
|
accepted.input as Parameters<ResearchClient['submitValidation']>[0],
|
|
accepted.key!
|
|
);
|
|
expect(replay.id).toBe(result.outcomes[0]!.validation!.id);
|
|
expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(
|
|
before
|
|
);
|
|
const reopened = await f.client.validation(result.outcomes[0]!.validation!.id);
|
|
expect(reopened.report).toEqual(result.outcomes[0]!.validation!.report);
|
|
}, 180000);
|
|
|
|
test('real quota refusal and oversized search create no runs; nonmember evidence cannot become a finding', async () => {
|
|
const f = await fixture(),
|
|
plan = f.suggestions();
|
|
const hypothesis = await f.client.createHypothesis(f.project.id, plan.hypothesis);
|
|
const family = await f.client.createStrategy({
|
|
name: 'Bounded candidate',
|
|
description: 'Budget adversary',
|
|
});
|
|
const version = await f.client.publishVersion(
|
|
family.id,
|
|
plan.candidates[0]!.package,
|
|
'bounded-version'
|
|
);
|
|
const input = {
|
|
backtestId: plan.backtestId,
|
|
name: 'Exceeds admission',
|
|
candidate: { versionId: version.id, parameters: { fastPeriod: 2, slowPeriod: 10 } },
|
|
grid: { fastPeriod: [1, 2, 3, 4, 5] },
|
|
};
|
|
const overBudget = await f.client.previewExperiment(input);
|
|
await expect(
|
|
f.client.submitExperiment(
|
|
{ ...overBudget.input, previewHash: overBudget.previewHash },
|
|
'over-budget'
|
|
)
|
|
).rejects.toMatchObject({
|
|
status: 429,
|
|
uncertain: false,
|
|
});
|
|
expect(() =>
|
|
f.client.previewExperiment({
|
|
...input,
|
|
grid: { fastPeriod: Array.from({ length: 101 }, (_, i) => i + 1) },
|
|
})
|
|
).toThrow();
|
|
expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(0);
|
|
const good = await f.client.previewExperiment({ ...input, grid: {} });
|
|
const admitted = await f.client.submitExperiment(
|
|
{ ...good.input, previewHash: good.previewHash },
|
|
'bounded-admitted'
|
|
);
|
|
const complete = await f.client.waitForExperiment(admitted.id, {
|
|
timeoutMs: 60000,
|
|
intervalMs: 20,
|
|
});
|
|
expect(complete.trials[0]?.status).toBe('completed');
|
|
const evidence = {
|
|
kind: 'finding' as const,
|
|
title: 'Incorrect evidence',
|
|
body: 'Must not be retained',
|
|
hypothesisRevisionId: hypothesis.latestRevision.id,
|
|
source: {
|
|
kind: 'experiment/v1' as const,
|
|
experimentId: admitted.id,
|
|
previewHash: admitted.previewHash,
|
|
},
|
|
evidence: [
|
|
{
|
|
runId: randomUUID(),
|
|
strategyVersionId: version.id,
|
|
metricsVersion: 'canonical-analytics/v1' as const,
|
|
metricPath: 'analytics.metrics.totalReturn' as const,
|
|
},
|
|
],
|
|
};
|
|
await expect(f.client.saveFinding(f.project.id, evidence)).rejects.toMatchObject({
|
|
uncertain: false,
|
|
});
|
|
expect(
|
|
(await f.pool.query('SELECT count(*)::int AS count FROM analysis_artifacts')).rows[0].count
|
|
).toBe(0);
|
|
const wrongVersion = {
|
|
...evidence,
|
|
evidence: [
|
|
{
|
|
...evidence.evidence[0]!,
|
|
runId: complete.trials[0]!.runId!,
|
|
strategyVersionId: f.version.id,
|
|
},
|
|
],
|
|
};
|
|
await expect(f.client.saveFinding(f.project.id, wrongVersion)).rejects.toMatchObject({
|
|
uncertain: false,
|
|
});
|
|
}, 60000);
|
|
});
|