feat(research): cut over canonical runtime and enforce agent budgets
This commit is contained in:
parent
ab08db82fd
commit
bbf0dd4453
103 changed files with 6138 additions and 3112 deletions
13
test/fixtures/backtest-crash-owner.ts
vendored
13
test/fixtures/backtest-crash-owner.ts
vendored
|
|
@ -17,16 +17,21 @@ if (
|
|||
!schema ||
|
||||
!/^stock_bot_safety_[a-f0-9]+$/.test(schema) ||
|
||||
!runId
|
||||
)
|
||||
) {
|
||||
throw new Error('Unsafe crash fixture target');
|
||||
}
|
||||
const logger = getLogger('crash-owner');
|
||||
const pool = new Pool({ connectionString: url, options: `-c search_path=${schema}` });
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
const repository = new PostgresBacktestRunRepository(postgres, 500);
|
||||
repository.loadCanonicalDataset = async () => {
|
||||
process.send?.({ type: 'claimed' });
|
||||
return new Promise(() => {});
|
||||
};
|
||||
const runner = new BacktestRunner({
|
||||
engine: new RustBacktestAdapter({
|
||||
logger,
|
||||
|
|
@ -36,9 +41,5 @@ const runner = new BacktestRunner({
|
|||
repository,
|
||||
logger,
|
||||
heartbeatMs: 50,
|
||||
prepare: async () => {
|
||||
process.send?.({ type: 'claimed' });
|
||||
await new Promise<void>(() => {});
|
||||
},
|
||||
});
|
||||
await runner.runQueued(runId);
|
||||
|
|
|
|||
75
test/fixtures/canonical-admission.ts
vendored
Normal file
75
test/fixtures/canonical-admission.ts
vendored
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
import { readFileSync } from 'node:fs';
|
||||
import type { Pool } from 'pg';
|
||||
import type { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
|
||||
import { retainResearchDataset } from '../../scripts/import-research-dataset';
|
||||
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
|
||||
import { canonicalSettings } from './canonical-research';
|
||||
import { canonicalSmaFixture } from './canonical-sma';
|
||||
import { logger } from './execution';
|
||||
|
||||
let packages: ReturnType<typeof packageBuiltinStrategies> | undefined;
|
||||
/** Real approved admission on a caller-owned disposable PostgreSQL schema. */
|
||||
export async function canonicalAdmissionFixture(
|
||||
pool: Pool,
|
||||
postgres: PostgreSQLClient,
|
||||
initializeTables = true
|
||||
) {
|
||||
for (const name of initializeTables
|
||||
? [
|
||||
'06-create-backtest-tables.sql',
|
||||
'07-fix-execution-time-type.sql',
|
||||
'08-create-runs-table.sql',
|
||||
'09-backtest-run-contract.sql',
|
||||
'10-durable-backtest-dispatch.sql',
|
||||
'12-historical-datasets.sql',
|
||||
'14-backtest-submission.sql',
|
||||
'16-strategy-catalog.sql',
|
||||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
'26-cost-sensitivity.sql',
|
||||
]
|
||||
: []) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
);
|
||||
}
|
||||
if (!Object.hasOwn(postgres, 'query')) {
|
||||
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
|
||||
}
|
||||
const dataset = canonicalSmaFixture().dataset;
|
||||
const api = new BacktestServiceV2({ postgres, logger });
|
||||
const catalog = new StrategyCatalogService({ postgres, logger });
|
||||
const pkg = (await (packages ??= packageBuiltinStrategies()))[0]!;
|
||||
const version = await catalog.seedBuiltin('Cutover retained SMA', pkg, 'seed');
|
||||
await catalog.reviewVersion(
|
||||
version.id,
|
||||
{ decision: 'approve', reason: 'Cutover native fixture' },
|
||||
'operator'
|
||||
);
|
||||
await retainResearchDataset(pool, dataset);
|
||||
const definition = {
|
||||
name: 'Canonical cutover fixture',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: version.id,
|
||||
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
symbols: dataset.manifest.executionSeries.map(series => series.instrumentId),
|
||||
startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
|
||||
endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
|
||||
initialCapital: 10000,
|
||||
config: {
|
||||
datasetHash: dataset.manifest.hash,
|
||||
dataFrequency: dataset.manifest.series[0]!.interval,
|
||||
canonical: canonicalSettings,
|
||||
},
|
||||
};
|
||||
const draft = await api.createBacktest(definition, { autoStart: false });
|
||||
return { api, catalog, version, draft, definition, dataset };
|
||||
}
|
||||
192
test/fixtures/canonical-runner.ts
vendored
Normal file
192
test/fixtures/canonical-runner.ts
vendored
Normal file
|
|
@ -0,0 +1,192 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { expect } from 'bun:test';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
type CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import type { HistoricalDatasetV2 } from '@stock-bot/types';
|
||||
import { builtinCatalogDescriptors } from '../../apps/stock/config/src/contracts/strategy';
|
||||
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||
import { type BacktestExecutionEngine } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
||||
import { type BacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/run-repository';
|
||||
import { canonicalSmaFixture } from './canonical-sma';
|
||||
|
||||
const logger = { error() {} };
|
||||
export function canonicalRunnerFixture() {
|
||||
const versionId = randomUUID(),
|
||||
runId = randomUUID(),
|
||||
ownerId = `strategy:${versionId}`;
|
||||
const { dataset, config, selections } = canonicalSmaFixture([ownerId]);
|
||||
config.matching.risk.ledger.sessionId = runId;
|
||||
config.matching.risk.ledger.accountId = `research:${runId}`;
|
||||
const descriptor = builtinCatalogDescriptors.find(d => d.program.strategyId === 'sma_crossover')!;
|
||||
const request = canonicalRunRequestSchema.parse({
|
||||
kind: 'canonical-research/v1',
|
||||
runId,
|
||||
backtestId: randomUUID(),
|
||||
name: 'Runner boundary',
|
||||
strategy: {
|
||||
familyId: randomUUID(),
|
||||
versionId,
|
||||
origin: 'builtin',
|
||||
reviewId: randomUUID(),
|
||||
selection: selections[0],
|
||||
package: {
|
||||
version: 1,
|
||||
program: descriptor.program,
|
||||
parameterSchema: descriptor.parameterSchema,
|
||||
artifact: {
|
||||
format: 'esm-bundle/v1',
|
||||
entryExport: descriptor.entryExport,
|
||||
content: 'not executed by this lifecycle fixture',
|
||||
sha256: 'a'.repeat(64),
|
||||
},
|
||||
dependencyLock: { format: 'bun-lock/v1', content: 'fixture', sha256: 'b'.repeat(64) },
|
||||
source: { revision: 'c'.repeat(40), dirty: false },
|
||||
build: { tool: 'bun', version: 'fixture', target: 'browser' },
|
||||
},
|
||||
},
|
||||
datasetHash: dataset.manifest.hash,
|
||||
policy: config,
|
||||
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
|
||||
modelArtifacts: [],
|
||||
build: {
|
||||
version: 1,
|
||||
workerSha256: 'd'.repeat(64),
|
||||
engineWrapperSha256: 'e'.repeat(64),
|
||||
engineBinarySha256: 'f'.repeat(64),
|
||||
dependencyLockSha256: 'b'.repeat(64),
|
||||
runtime: 'bun',
|
||||
runtimeVersion: 'fixture',
|
||||
platform: 'linux',
|
||||
arch: 'x64',
|
||||
},
|
||||
});
|
||||
const events: string[] = [];
|
||||
let result: CanonicalRunResult | undefined;
|
||||
let heartbeatFailure = false;
|
||||
let status = 'pending';
|
||||
const repo: BacktestRunRepository = {
|
||||
async start() {
|
||||
throw new Error('legacy claim must not run');
|
||||
},
|
||||
async startCanonical(input) {
|
||||
events.push('claim');
|
||||
status = 'running';
|
||||
return {
|
||||
runId,
|
||||
backtestId: request.backtestId,
|
||||
attemptId: 'attempt',
|
||||
config: structuredClone(input),
|
||||
};
|
||||
},
|
||||
async load() {
|
||||
return { status, config: structuredClone(request) };
|
||||
},
|
||||
async rejectPending() {
|
||||
events.push('reject');
|
||||
status = 'failed';
|
||||
},
|
||||
async heartbeat() {
|
||||
events.push('heartbeat');
|
||||
if (heartbeatFailure) {
|
||||
throw new Error('lost');
|
||||
}
|
||||
return { cancelRequested: false };
|
||||
},
|
||||
async loadDataset() {
|
||||
throw new Error('v1 data must not run');
|
||||
},
|
||||
async freezeDataset() {
|
||||
throw new Error('provider freeze must not run');
|
||||
},
|
||||
async loadCanonicalDataset(_id, _attempt, hash) {
|
||||
expect(hash).toBe(dataset.manifest.hash);
|
||||
events.push('dataset');
|
||||
return dataset;
|
||||
},
|
||||
async complete() {
|
||||
throw new Error('legacy completion must not run');
|
||||
},
|
||||
async completeCanonical(input) {
|
||||
events.push('complete');
|
||||
result = input;
|
||||
status = 'completed';
|
||||
},
|
||||
async updateProgress() {
|
||||
events.push('progress');
|
||||
},
|
||||
async fail() {
|
||||
events.push('fail');
|
||||
status = 'failed';
|
||||
},
|
||||
async cancel() {
|
||||
events.push('cancel');
|
||||
status = 'cancelled';
|
||||
},
|
||||
async updateControl() {},
|
||||
};
|
||||
const engine = Object.assign(new EventEmitter(), {
|
||||
async runBacktest(): Promise<never> {
|
||||
throw new Error('legacy simulator must not run');
|
||||
},
|
||||
async runCanonical(
|
||||
_input: typeof request,
|
||||
resolve: (signal: AbortSignal) => Promise<HistoricalDatasetV2>
|
||||
) {
|
||||
await resolve(new AbortController().signal);
|
||||
events.push('execute');
|
||||
// Economic validation belongs to the actual worker/SQL fixtures; this fixture probes lifecycle only.
|
||||
return {
|
||||
financial: {} as CanonicalRunResult['financial'],
|
||||
analytics: {} as CanonicalRunResult['analytics'],
|
||||
};
|
||||
},
|
||||
async stopBacktest() {
|
||||
events.push('stop');
|
||||
},
|
||||
async pauseBacktest() {},
|
||||
async resumeBacktest() {},
|
||||
setSpeedMultiplier() {},
|
||||
getStatus() {
|
||||
return { isRunning: false, isPaused: false, progress: 0, currentTime: 0 };
|
||||
},
|
||||
async shutdown() {},
|
||||
}) satisfies BacktestExecutionEngine;
|
||||
const runner = new BacktestRunner({
|
||||
engine,
|
||||
repository: repo,
|
||||
engineName: 'native',
|
||||
logger,
|
||||
heartbeatMs: 5,
|
||||
heartbeatTimeoutMs: 50,
|
||||
});
|
||||
return {
|
||||
request,
|
||||
dataset,
|
||||
repo,
|
||||
engine,
|
||||
runner,
|
||||
events,
|
||||
get result() {
|
||||
return result;
|
||||
},
|
||||
setStatus(next: string) {
|
||||
status = next;
|
||||
},
|
||||
loseLease() {
|
||||
heartbeatFailure = true;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (error: Error) => void;
|
||||
const promise = new Promise<T>((a, b) => {
|
||||
resolve = a;
|
||||
reject = b;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
62
test/fixtures/historical-run.ts
vendored
Normal file
62
test/fixtures/historical-run.ts
vendored
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import type { Pool } from 'pg';
|
||||
import { backtestRequestFromDefinition } from '@stock-bot/stock-config/backtest';
|
||||
import type {
|
||||
BacktestServiceV2,
|
||||
RunSubmission,
|
||||
} from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
|
||||
/** Insert an already accepted pre-cutover row for read/custody compatibility tests.
|
||||
* This is not an admission API or executable simulator, and cannot seed catalog requests.
|
||||
*/
|
||||
export async function seedHistoricalRun(
|
||||
pool: Pool,
|
||||
api: BacktestServiceV2,
|
||||
input: { backtestId: string },
|
||||
receipt?: RunSubmission
|
||||
) {
|
||||
const definition = await api.getBacktest(input.backtestId);
|
||||
if (!definition || definition.strategyVersionId !== null || definition.strategy === 'catalog') {
|
||||
throw new Error('Historical fixture requires a legacy template');
|
||||
}
|
||||
const runId = randomUUID();
|
||||
const snapshot = backtestRequestFromDefinition(
|
||||
{
|
||||
name: definition.name,
|
||||
strategy: definition.strategy,
|
||||
symbols: definition.symbols,
|
||||
startDate: definition.startDate.toISOString(),
|
||||
endDate: definition.endDate.toISOString(),
|
||||
initialCapital: definition.initialCapital,
|
||||
config: definition.config,
|
||||
},
|
||||
{ runId, backtestId: definition.id, speedMultiplier: null }
|
||||
);
|
||||
const hash = receipt
|
||||
? createHash('sha256')
|
||||
.update(JSON.stringify({ version: 1, backtestId: definition.id, speedMultiplier: null }))
|
||||
.digest('hex')
|
||||
: null;
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
await client.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [definition.id]);
|
||||
await client.query(
|
||||
`INSERT INTO runs(id,backtest_id,run_number,request_snapshot,submission_principal,submission_key,submission_hash)
|
||||
SELECT $1,$2,COALESCE(MAX(run_number),0)+1,$3,$4,$5,$6 FROM runs WHERE backtest_id=$2`,
|
||||
[runId, definition.id, snapshot, receipt?.principal ?? null, receipt?.key ?? null, hash]
|
||||
);
|
||||
await client.query('INSERT INTO backtest_dispatch(run_id) VALUES($1)', [runId]);
|
||||
await client.query('COMMIT');
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK');
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
const saved = await api.getRun(runId);
|
||||
if (!saved) {
|
||||
throw new Error('Historical fixture row missing');
|
||||
}
|
||||
return saved;
|
||||
}
|
||||
11
test/fixtures/native-backtest-worker.ts
vendored
11
test/fixtures/native-backtest-worker.ts
vendored
|
|
@ -1,3 +1,4 @@
|
|||
import { executeReplayTrace } from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import {
|
||||
nativeWorkerRequestSchema,
|
||||
type NativeWorkerMessage,
|
||||
|
|
@ -11,13 +12,13 @@ function send(message: NativeWorkerMessage | { invalid: boolean }): Promise<void
|
|||
|
||||
process.once('message', async (input: unknown) => {
|
||||
const request = nativeWorkerRequestSchema.parse(input);
|
||||
if (request.type !== 'run') {
|
||||
throw new Error('Legacy fixture only');
|
||||
if (request.type !== 'runReplayTrace') {
|
||||
throw new Error('Canonical replay lifecycle fixture only');
|
||||
}
|
||||
const { config } = request;
|
||||
// Fixture controls are run labels, not unsupported production strategy parameters.
|
||||
const behavior = config.name?.startsWith('fixture:')
|
||||
? config.name.slice('fixture:'.length)
|
||||
const behavior = config.matching.risk.ledger.sessionId.startsWith('fixture:')
|
||||
? config.matching.risk.ledger.sessionId.slice('fixture:'.length)
|
||||
: undefined;
|
||||
if (!behavior) {
|
||||
// The same adapter can recover and run the actual Rust engine after a failed worker.
|
||||
|
|
@ -49,7 +50,7 @@ process.once('message', async (input: unknown) => {
|
|||
process.exit(0);
|
||||
return;
|
||||
case 'result-then-block':
|
||||
await send({ type: 'result', result: '{}' });
|
||||
await send({ type: 'result', result: JSON.stringify(executeReplayTrace(request).result) });
|
||||
while (true) {
|
||||
Math.sqrt(Math.random());
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue