diff --git a/apps/stock/data-ingestion/test/intraday-crawl.test.ts b/apps/stock/data-ingestion/test/intraday-crawl.test.ts deleted file mode 100644 index 3ea9f482..00000000 --- a/apps/stock/data-ingestion/test/intraday-crawl.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env bun - -/** - * Test script for intraday crawl functionality - */ - -import { createTestContext } from '../src/test-utils'; -import { QMHandler } from '../src/handlers/qm/qm.handler'; - -async function testIntradayCrawl() { - console.log('Testing intraday crawl functionality...\n'); - - const context = await createTestContext(); - const handler = new QMHandler(context.services); - - // Wait for operation registry to initialize - await new Promise(resolve => setTimeout(resolve, 1000)); - - try { - // Test 1: Schedule crawls for never-run symbols - console.log('Test 1: Scheduling crawls for never-run symbols...'); - const result1 = await handler.scheduleIntradayCrawls({ - limit: 5, - priorityMode: 'never_run', - targetOldestDate: '2023-01-01' // Just 1 year for testing - }); - console.log('Result:', result1); - console.log(''); - - // Test 2: Check crawl state for a specific symbol - console.log('Test 2: Checking crawl state for symbol X...'); - const tracker = handler.operationRegistry.getTracker('qm'); - const isComplete = await tracker.isIntradayCrawlComplete('X', 'intraday_bars', new Date('2023-01-01')); - console.log('Is crawl complete for X?', isComplete); - - // Get detailed state - const symbols = await tracker.getSymbolsForIntradayCrawl('intraday_bars', { - limit: 1, - targetOldestDate: new Date('2023-01-01') - }); - - const symbolX = symbols.find(s => s.symbol === 'X'); - if (symbolX) { - console.log('Symbol X state:', JSON.stringify(symbolX, null, 2)); - } - console.log(''); - - // Test 3: Manually crawl a single symbol - console.log('Test 3: Manually crawling intraday data for X...'); - - // First get symbol data - const symbolData = await context.services.mongodb.findOne('qmSymbols', { - symbol: 'X' - }); - - if (symbolData && symbolData.symbolId) { - const crawlResult = await handler.crawlIntradayData({ - symbol: 'X', - symbolId: symbolData.symbolId, - qmSearchCode: symbolData.qmSearchCode, - targetOldestDate: '2024-01-01', // Just current year for quick test - batchSize: 7 - }); - console.log('Crawl result:', crawlResult); - } else { - console.log('Symbol X not found or missing symbolId'); - } - - } catch (error) { - console.error('Test failed:', error); - } finally { - await context.cleanup(); - } -} - -// Run the test -testIntradayCrawl().catch(console.error); \ No newline at end of file diff --git a/libs/core/cache/test/redis-cache.test.ts b/libs/core/cache/test/redis-cache.test.ts index 13cbe060..601ae57c 100644 --- a/libs/core/cache/test/redis-cache.test.ts +++ b/libs/core/cache/test/redis-cache.test.ts @@ -2,7 +2,9 @@ import { beforeEach, describe, expect, it } from 'bun:test'; import { RedisCache } from '../src/redis-cache'; import type { CacheOptions } from '../src/types'; -describe('RedisCache', () => { +const hasTestRedis = Boolean(process.env.BACKTEST_TEST_REDIS_URL); + +describe.skipIf(!hasTestRedis)('RedisCache', () => { let cache: RedisCache; beforeEach(() => { diff --git a/libs/core/queue/test/utils.test.ts b/libs/core/queue/test/utils.test.ts index 6f4a2e45..664e0e67 100644 --- a/libs/core/queue/test/utils.test.ts +++ b/libs/core/queue/test/utils.test.ts @@ -14,7 +14,7 @@ describe('Queue Utils', () => { process.env = originalEnv; }); - it('should return test connection in test environment', () => { + it('should preserve explicit endpoint in test environment', () => { process.env.NODE_ENV = 'test'; const config: RedisConfig = { @@ -25,12 +25,12 @@ describe('Queue Utils', () => { const connection = getRedisConnection(config); - expect(connection.host).toBe('localhost'); - expect(connection.port).toBe(6379); - expect(connection.password).toBeUndefined(); + expect(connection.host).toBe('production.redis.com'); + expect(connection.port).toBe(6380); + expect(connection.password).toBe('secret'); }); - it('should return test connection when BUNIT is set', () => { + it('should preserve explicit endpoint when BUNIT is set', () => { process.env.BUNIT = '1'; const config: RedisConfig = { @@ -40,8 +40,8 @@ describe('Queue Utils', () => { const connection = getRedisConnection(config); - expect(connection.host).toBe('localhost'); - expect(connection.port).toBe(6379); + expect(connection.host).toBe('production.redis.com'); + expect(connection.port).toBe(6380); }); it('should return actual config in non-test environment', () => { @@ -66,7 +66,7 @@ describe('Queue Utils', () => { expect(connection.enableReadyCheck).toBe(false); expect(connection.connectTimeout).toBe(3000); expect(connection.lazyConnect).toBe(false); - expect(connection.keepAlive).toBe(true); + expect(connection.keepAlive).toBe(10000); expect(typeof connection.retryStrategy).toBe('function'); }); diff --git a/libs/core/shutdown/test/shutdown-signals.test.ts b/libs/core/shutdown/test/shutdown-signals.test.ts index 709b44a9..be3f4118 100644 --- a/libs/core/shutdown/test/shutdown-signals.test.ts +++ b/libs/core/shutdown/test/shutdown-signals.test.ts @@ -5,14 +5,14 @@ describe('Shutdown Signal Handlers', () => { let shutdown: Shutdown; let processOnceSpy: any; let processExitSpy: any; - const originalOnce = process.once; + const originalOn = process.on; const originalExit = process.exit; beforeEach(() => { // Reset singleton instance (Shutdown as any).instance = null; - // Mock process.once to capture signal handlers + // Mock process.on to capture signal handlers const listeners: Record = {}; processOnceSpy = mock((event: string, handler: Function) => { if (!listeners[event]) { @@ -21,7 +21,7 @@ describe('Shutdown Signal Handlers', () => { listeners[event].push(handler); return process; }); - process.once = processOnceSpy as any; + process.on = processOnceSpy as any; // Mock process.exit processExitSpy = mock((_code?: number) => { @@ -36,7 +36,7 @@ describe('Shutdown Signal Handlers', () => { afterEach(() => { // Restore original methods - process.once = originalOnce; + process.on = originalOn; process.exit = originalExit; // Clean up diff --git a/scripts/test-e2e.ts b/scripts/test-e2e.ts index c663b06a..6d510a6d 100644 --- a/scripts/test-e2e.ts +++ b/scripts/test-e2e.ts @@ -37,7 +37,7 @@ const build = Bun.spawn([process.execPath, 'run', '--cwd', 'apps/stock/web-app', if (await build.exited) { throw new Error('Browser application build failed'); } -const tests = Bun.spawn([process.execPath, 'test', 'test/e2e/workbench.test.ts', '--timeout', '60000'], { +const tests = Bun.spawn([process.execPath, 'test', 'test/e2e/workbench.e2e.ts', '--timeout', '60000'], { env: { ...process.env, STOCK_BOT_E2E_BUILT: '1' }, stdin: 'inherit', stdout: 'inherit', stderr: 'inherit', }); diff --git a/studio.config.json b/studio.config.json index 4ff52d81..8289bc2a 100644 --- a/studio.config.json +++ b/studio.config.json @@ -11,7 +11,7 @@ } }, "test": { - "command": "bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/pipeline-safety.test.ts test/postgres/research-agents.test.ts", + "command": "bun --env-file=/home/boki/.studio/test-env/stock-bot.env test", "env": {} }, "ci": "off", diff --git a/test/e2e/workbench.test.ts b/test/e2e/workbench.e2e.ts similarity index 100% rename from test/e2e/workbench.test.ts rename to test/e2e/workbench.e2e.ts diff --git a/test/postgres/ai-research-workflow.test.ts b/test/postgres/ai-research-workflow.test.ts deleted file mode 100644 index 9c6d1476..00000000 --- a/test/postgres/ai-research-workflow.test.ts +++ /dev/null @@ -1,908 +0,0 @@ -/** 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 { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes'; -import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes'; -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 { createResearchServices } from '../../apps/stock/web-api/src/services/research-services'; -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)[] = []; -afterEach(async () => { - for (const close of cleanups.splice(0).reverse()) { - await close(); - } -}); -let packages: ReturnType | 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', - '32-candidate-parameter-defaults.sql', - '33-candidate-decimal-normalization.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 = createResearchServices(container).research; - 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)); - app.route('/', createBacktestV2Routes(container)); - app.route('/', createDatasetRoutes(container)); - const engine = new RustBacktestAdapter({ - logger, - }); - const runner = new BacktestRunner({ - engine, - 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, - // Exercise default expansion throughout training, holdouts and saved evidence. - parameters: { slowPeriod: 6 }, - 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('hypothesis reads retain original questions, human revisions and archival without writes', async () => { - const f = await fixture(); - const created = await f.client.createHypothesis(f.project.id, f.suggestions().hypothesis); - const original = (await f.research.getHypothesis(created.id)).latestRevision; - const revised = await f.research.reviseHypothesis( - created.id, - { - expectedRevision: original.ordinal, - title: 'Human follow-up question', - proposition: 'A changed proposition is not the original research question.', - validationCriteria: 'Additional validation remains necessary.', - contentOrigin: 'human', - }, - 'operator' - ); - const archived = await f.research.archiveHypothesis(created.id, { archived: true }, 'operator'); - const serviceQuestion = await f.research.createHypothesis( - f.project.id, - { title: 'Service diagnostic', proposition: 'No measured claim.', contentOrigin: 'unknown' }, - 'service' - ); - const totals = async () => - ( - await f.pool.query(`SELECT - (SELECT count(*)::int FROM runs) AS runs, - (SELECT count(*)::int FROM research_experiments) AS experiments, - (SELECT count(*)::int FROM research_hypotheses) AS hypotheses, - (SELECT count(*)::int FROM research_hypothesis_revisions) AS revisions, - (SELECT count(*)::int FROM analysis_artifacts) AS artifacts`) - ).rows[0]; - const before = await totals(); - const requestStart = f.requests.length; - expect(await f.client.hypothesis(created.id)).toEqual(archived); - const history = await f.client.hypothesisRevisions(created.id); - expect(history).toEqual([original, revised.latestRevision]); - expect(history.find(item => item.id === created.latestRevision.id)).toEqual(original); - expect(history[0]!.submittedBy).toBe(f.provisioned.agent.id); - expect(history[0]!.contentOrigin).toBe('ai'); - expect(history[1]!.submittedBy).toBe('operator'); - expect(history[1]!.contentOrigin).toBe('human'); - expect(history.every(item => item.validationState === 'unvalidated')).toBeTrue(); - expect(await f.client.hypothesis(serviceQuestion.id)).toEqual(serviceQuestion); - expect(await f.client.hypothesisRevisions(serviceQuestion.id)).toEqual([ - serviceQuestion.latestRevision, - ]); - const missing = randomUUID(); - await expect(f.client.hypothesis(missing)).rejects.toMatchObject({ - status: 404, - uncertain: false, - }); - await expect(f.client.hypothesisRevisions(missing)).rejects.toMatchObject({ - status: 404, - uncertain: false, - }); - expect( - f.requests - .slice(requestStart) - .every( - request => request.method === 'GET' && request.key === null && request.body === undefined - ) - ).toBeTrue(); - expect(await totals()).toEqual(before); - await f.agents.update(f.provisioned.agent.id, { expectedRevision: 1, enabled: false }); - await expect(f.client.hypothesis(created.id)).rejects.toMatchObject({ - status: 401, - uncertain: false, - }); - await expect(f.client.hypothesisRevisions(created.id)).rejects.toMatchObject({ - status: 401, - uncertain: false, - }); - expect(await totals()).toEqual(before); - expect(f.executionErrors).toEqual([]); - }); - - test('research credentials export known immutable snapshots with exact read-only scope', async () => { - const f = await fixture(); - const hash = f.dataset.manifest.hash; - const totals = async () => - ( - await f.pool.query(`SELECT - (SELECT count(*)::int FROM runs) AS runs, - (SELECT count(*)::int FROM research_experiments) AS experiments, - (SELECT count(*)::int FROM backtest_datasets) AS datasets`) - ).rows[0]; - const before = await totals(); - expect(await f.client.canonicalDataset(hash)).toEqual(f.dataset); - const head = await f.transport( - `http://127.0.0.1:2003/api/v2/datasets/canonical/${hash}/export`, - { - method: 'HEAD', - headers: { Authorization: `Bearer ${f.provisioned.token}` }, - } - ); - expect(head.status).toBe(200); - expect(head.headers.get('cache-control')).toBe('no-store'); - expect(head.headers.get('x-content-type-options')).toBe('nosniff'); - expect(head.headers.get('content-disposition')).toBe( - `attachment; filename="dataset-${hash}.json"` - ); - expect(await head.text()).toBe(''); - for (const [path, method] of [ - ['/datasets/canonical', 'GET'], - ['/datasets/stored-eod/coverage', 'GET'], - ['/datasets/canonical/preview', 'POST'], - ['/datasets/canonical/retain', 'POST'], - ['/datasets/canonical/stored-source', 'POST'], - ['/datasets/stored-eod/inspect', 'POST'], - [`/datasets/canonical/${hash}/export`, 'POST'], - ]) { - const response = await f.transport(`http://127.0.0.1:2003/api/v2${path}`, { - method, - headers: { Authorization: `Bearer ${f.provisioned.token}` }, - }); - expect(response.status).toBe(403); - } - await expect(f.client.canonicalDataset('0'.repeat(64))).rejects.toMatchObject({ - status: 404, - uncertain: false, - }); - expect(await totals()).toEqual(before); - const badHash = 'f'.repeat(64); - await f.pool.query('INSERT INTO backtest_datasets(hash,payload) VALUES($1,$2::jsonb)', [ - badHash, - f.dataset, - ]); - const afterFixtureInsert = await totals(); - await expect(f.client.canonicalDataset(badHash)).rejects.toMatchObject({ - status: 409, - uncertain: false, - }); - expect(await totals()).toEqual(afterFixtureInsert); - await f.agents.update(f.provisioned.agent.id, { expectedRevision: 1, enabled: false }); - await expect(f.client.canonicalDataset(hash)).rejects.toMatchObject({ - status: 401, - uncertain: false, - }); - expect(f.executionErrors).toEqual([]); - }); - - test('defaulted candidate validation accepts, reopens and replays the exact original input', async () => { - const f = await fixture(); - const plan = f.suggestions(); - const family = await f.client.createStrategy({ - name: 'Defaulted validation candidate', - description: 'Omitted and partial parameter defaults', - }); - const version = await f.client.publishVersion( - family.id, - plan.candidates[0]!.package, - 'defaults:version' - ); - const cases: { parameters: Record; normalized: Record }[] = [ - { parameters: {}, normalized: { fastPeriod: 5, slowPeriod: 15 } }, - { parameters: { slowPeriod: 6 }, normalized: { fastPeriod: 5, slowPeriod: 6 } }, - ]; - for (const [index, item] of cases.entries()) { - const input = { - backtestId: plan.backtestId, - name: `Defaulted candidate ${index}`, - candidate: { versionId: version.id, parameters: item.parameters }, - grid: {}, - recipe: plan.candidates[0]!.recipe, - }; - const preview = await f.client.previewValidation(input); - expect(preview.input).toEqual(input); - expect(preview.partitions[0].request.strategy.selection.parameters).toEqual(item.normalized); - const submission = { ...preview.input, previewHash: preview.previewHash }; - const key = `defaults:validation:${index}`; - const saved = await f.client.submitValidation(submission, key); - expect(saved.preview.input).toEqual(input); - expect(saved.phases[0]!.experiment!.preview.input.candidate).toEqual({ - versionId: version.id, - parameters: item.normalized, - }); - const reopened = await f.client.waitForValidation(saved.id, { - timeoutMs: 60000, - intervalMs: 20, - }); - expect(reopened.previewHash).toBe(preview.previewHash); - expect(reopened.preview.input).toEqual(input); - expect(reopened.phases[0]!.experiment!.trials[0]!.status).toBe('completed'); - const replayed = await f.client.submitValidation(submission, key); - expect(replayed.id).toBe(saved.id); - expect(replayed.previewHash).toBe(preview.previewHash); - expect(replayed.phases[0]!.experiment!.trials[0]!.runId).toBe( - reopened.phases[0]!.experiment!.trials[0]!.runId! - ); - const writes = f.requests.filter(request => request.key === key); - expect(writes).toHaveLength(2); - expect(writes[0]).toEqual(writes[1]!); - expect(writes[0]!.body).toEqual(submission); - expect(writes[0]!.status).toBe(202); - } - expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(2); - expect(f.executionErrors).toEqual([]); - }, 60000); - - test('candidate revisions retain automatic and explicit lineage across delayed receipt replay', async () => { - const f = await fixture(); - const family = await f.client.createStrategy({ - name: 'Refined candidate', - description: 'Successive revisions and a delayed publication receipt', - }); - const pkg = f.suggestions().candidates[0]!.package; - const first = await f.client.publishVersion(family.id, pkg, 'lineage:first'); - expect(first).toMatchObject({ - ordinal: 1, - parentVersionId: null, - createdBy: f.provisioned.agent.id, - }); - const second = await f.client.publishVersion(family.id, pkg, 'lineage:second'); - expect(second).toMatchObject({ ordinal: 2, parentVersionId: first.id }); - const third = await f.client.publishVersion(family.id, pkg, 'lineage:third', null); - expect(third).toMatchObject({ ordinal: 3, parentVersionId: second.id }); - // An explicit branch parent remains binding even when another version is latest. - const branch = await f.client.publishVersion(family.id, pkg, 'lineage:branch', first.id); - expect(branch).toMatchObject({ ordinal: 4, parentVersionId: first.id }); - const replayed = await f.client.publishVersion(family.id, pkg, 'lineage:second'); - expect(replayed).toEqual(second); - const publications = f.requests.filter( - request => request.path === `/api/v2/strategies/${family.id}/versions` - ); - expect(publications).toHaveLength(5); - expect( - publications.every(request => request.status === 201 && request.method === 'POST') - ).toBeTrue(); - expect(publications[1]).toEqual(publications[4]!); - expect(publications[1]!.body).toEqual({ package: pkg, parentVersionId: null }); - expect(publications[3]!.body).toEqual({ package: pkg, parentVersionId: first.id }); - expect( - ( - await f.pool.query( - 'SELECT count(*)::int AS count FROM strategy_versions WHERE strategy_id=$1', - [family.id] - ) - ).rows[0].count - ).toBe(4); - expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(0); - expect(f.executionErrors).toEqual([]); - }); - - 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); - const reopenedFinding = await f.client.artifact(finding.id); - expect(reopenedFinding.latestRevision).toMatchObject(finding.latestRevision); - expect(await f.client.artifactRevisions(finding.id)).toEqual([ - reopenedFinding.latestRevision, - ]); - for (const evidence of finding.latestRevision.evidence) { - const saved = await f.client.canonicalRunResult(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'); - const retained = await f.api.getRunResults(evidence.runId); - if (!retained || !('kind' in retained) || retained.kind !== 'canonical-result/v1') { - throw new Error('Missing retained canonical result'); - } - expect(saved).toEqual(retained); - 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'); - await expect( - f.client.canonicalRunResult(broken.screening!.trials[0]!.runId!) - ).rejects.toMatchObject({ status: 404, uncertain: false }); - await expect(f.client.canonicalRunResult(randomUUID())).rejects.toMatchObject({ - status: 404, - uncertain: false, - }); - 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[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); - - // A comparison across candidates has no single aggregate report attachment. - // Each reference must still resolve to its exact retained native result. - const originalQuestion = await f.client.hypothesis(result.hypothesis.id); - expect(originalQuestion.latestRevision).toMatchObject(result.hypothesis.latestRevision); - const revisedQuestion = await f.research.reviseHypothesis( - result.hypothesis.id, - { - expectedRevision: originalQuestion.latestRevision.ordinal, - title: 'Later human interpretation', - proposition: 'This revision must not replace the candidate study question.', - validationCriteria: 'Further validation is required.', - contentOrigin: 'human', - }, - 'operator' - ); - expect((await f.client.hypothesis(result.hypothesis.id)).latestRevision).toEqual( - revisedQuestion.latestRevision - ); - const questionHistory = await f.client.hypothesisRevisions(result.hypothesis.id); - expect(questionHistory).toEqual([ - originalQuestion.latestRevision, - revisedQuestion.latestRevision, - ]); - const comparisonInput = { - kind: 'finding' as const, - title: 'Cross-candidate observations', - body: 'AI-generated comparison, unvalidated; no comparability or profitability claim.', - hypothesisRevisionId: result.hypothesis.latestRevision.id, - evidence: result.outcomes.slice(0, 2).map(outcome => ({ - runId: outcome.validation!.report!.test.runId, - strategyVersionId: outcome.versionId, - metricsVersion: 'canonical-analytics/v1' as const, - metricPath: 'analytics.metrics.totalReturn' as const, - })), - }; - expect(new Set(comparisonInput.evidence.map(item => item.strategyVersionId)).size).toBe(2); - for (const source of [null, undefined]) { - const finding = await f.client.saveFinding(f.project.id, { ...comparisonInput, source }); - expect(finding.latestRevision).toMatchObject({ - source: null, - contentOrigin: 'ai', - submittedBy: f.provisioned.agent.id, - validationState: 'unvalidated', - evidenceState: 'referenced', - }); - expect(finding.latestRevision.evidence).toHaveLength(2); - const savedInput = f.requests.at(-1)!.body as Record; - expect(Object.hasOwn(savedInput, 'source')).toBe(source === null); - expect(savedInput.evidence).toEqual(comparisonInput.evidence); - for (const reference of finding.latestRevision.evidence) { - const native = await f.client.canonicalRunResult(reference.runId); - if (!native || !('kind' in native) || native.kind !== 'canonical-result/v1') { - throw new Error('Missing native comparison evidence'); - } - expect(reference.strategyVersionId).toBe(native.request.strategy.versionId); - expect(reference.datasetHash).toBe(native.request.datasetHash); - expect(reference.value).toBe(native.analytics.metrics.totalReturn); - } - const retained = await f.client.artifact(finding.id); - expect(retained.hypothesisRevisionId).toBe(originalQuestion.latestRevision.id); - expect(questionHistory.find(item => item.id === retained.hypothesisRevisionId)).toEqual( - originalQuestion.latestRevision - ); - expect(retained.latestRevision.id).toBe(finding.latestRevision.id); - expect(retained.latestRevision.source).toBeNull(); - expect(retained.latestRevision.evidence).toMatchObject(finding.latestRevision.evidence); - expect(retained.latestRevision.validationState).toBe('unvalidated'); - const revised = await f.research.reviseArtifact( - finding.id, - { - expectedRevision: retained.latestRevision.ordinal, - title: 'Human follow-up to saved AI comparison', - body: 'A revised interpretation, still unvalidated.', - contentOrigin: 'human', - evidence: comparisonInput.evidence, - source: null, - }, - 'operator' - ); - const latest = await f.client.artifact(finding.id); - expect(latest.latestRevision.id).toBe(revised.latestRevision.id); - expect(latest.latestRevision.contentOrigin).toBe('human'); - expect(latest.latestRevision.submittedBy).toBe('operator'); - const history = await f.client.artifactRevisions(finding.id); - expect(history).toHaveLength(2); - expect(history.find(item => item.id === finding.latestRevision.id)).toEqual( - retained.latestRevision - ); - expect(history.find(item => item.id === revised.latestRevision.id)).toEqual( - latest.latestRevision - ); - expect(latest.latestRevision.evidence).toEqual(retained.latestRevision.evidence); - expect(f.requests.slice(-3).every(item => item.method === 'GET' && item.key === null)).toBe( - true - ); - } - const note = await f.research.createArtifact( - f.project.id, - { - kind: 'note', - title: 'Service diagnostic note', - body: 'No measured claim.', - contentOrigin: 'unknown', - }, - 'service' - ); - expect((await f.client.artifact(note.id)).latestRevision).toMatchObject({ - contentOrigin: 'unknown', - submittedBy: 'service', - evidence: [], - evidenceState: 'none', - source: null, - }); - const artifactsBeforeRefusals = ( - await f.pool.query('SELECT count(*)::int AS count FROM analysis_artifacts') - ).rows[0].count; - const reference = comparisonInput.evidence[0]!; - for (const invalid of [ - { ...reference, strategyVersionId: result.outcomes[1]!.versionId }, - { ...reference, runId: randomUUID() }, - { - ...reference, - runId: broken.screening!.trials[0]!.runId!, - strategyVersionId: broken.versionId, - }, - ]) { - await expect( - f.client.saveFinding(f.project.id, { - ...comparisonInput, - source: null, - evidence: [invalid], - }) - ).rejects.toMatchObject({ status: 422, uncertain: false }); - } - await expect( - f.client.saveFinding(randomUUID(), { ...comparisonInput, source: null }) - ).rejects.toMatchObject({ status: 403, uncertain: false }); - expect( - (await f.pool.query('SELECT count(*)::int AS count FROM analysis_artifacts')).rows[0].count - ).toBe(artifactsBeforeRefusals); - expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe( - before - ); - const original = await f.client.canonicalRunResult(reference.runId); - const snapshot = await f.client.canonicalDataset(original.request.datasetHash); - expect(snapshot).toEqual( - ( - await f.pool.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [ - original.request.datasetHash, - ]) - ).rows[0].payload - ); - const template = await f.api.getBacktest(original.backtestId); - if (!template) { - throw new Error('Missing original template'); - } - await f.api.updateBacktest(original.backtestId, { - startDate: new Date(f.dataset.manifest.bounds.tradeStart).toISOString(), - endDate: new Date(f.dataset.manifest.bounds.tradeEnd).toISOString(), - symbols: f.dataset.manifest.executionSeries.map(series => series.instrumentId), - config: { - ...template.config, - datasetHash: f.dataset.manifest.hash, - dataFrequency: f.dataset.manifest.series[0]!.interval, - }, - }); - expect(await f.client.canonicalDataset(original.request.datasetHash)).toEqual(snapshot); - expect(await f.client.canonicalRunResult(reference.runId)).toEqual(original); - expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe( - before - ); - await f.agents.update(f.provisioned.agent.id, { - expectedRevision: f.provisioned.agent.revision, - enabled: false, - }); - await expect(f.client.artifact(note.id)).rejects.toMatchObject({ - status: 401, - uncertain: false, - }); - await expect(f.client.canonicalRunResult(reference.runId)).rejects.toMatchObject({ - status: 401, - uncertain: false, - }); - await expect(f.client.artifactRevisions(note.id)).rejects.toMatchObject({ - status: 401, - uncertain: false, - }); - }, 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); -}); diff --git a/test/postgres/candidate-parameter-defaults.test.ts b/test/postgres/candidate-parameter-defaults.test.ts deleted file mode 100644 index 5baee14d..00000000 --- a/test/postgres/candidate-parameter-defaults.test.ts +++ /dev/null @@ -1,439 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { readFileSync } from 'node:fs'; -import { afterEach, describe, expect, test } from 'bun:test'; -import { Pool } from 'pg'; -import { getLogger, setLoggerConfig } from '@stock-bot/logger'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import { parseFinancialDecimal, type StrategyVersionPackage } from '@stock-bot/types'; -import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service'; -import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies'; -import { canonicalAdmissionFixture } from '../fixtures/canonical-admission'; -import { canonicalRegimeSelection } from '../fixtures/canonical-regime-research'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('candidate-parameter-defaults-test'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const cleanups: (() => Promise)[] = []; -afterEach(async () => { - for (const close of cleanups.splice(0).reverse()) { - await close(); - } -}); -const migrations = [ - '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', - '20-research-workspace.sql', - '21-run-reproduction.sql', - '22-experiments.sql', - '23-experiment-retries.sql', - '24-chronological-validation.sql', - '25-walk-forward.sql', - '26-cost-sensitivity.sql', - '27-research-evidence-sources.sql', - '28-research-agents.sql', - '29-isolated-candidates.sql', -]; -async function fixture(kind: 'sma' | 'mean-reversion' | 'string' = 'sma') { - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Disposable safety database required'); - } - const schema = 'stock_bot_safety_defaults_' + 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 apply = (file = '32-candidate-parameter-defaults.sql') => - pool.query( - readFileSync(new URL(`../../database/postgres/init/${file}`, import.meta.url), 'utf8') - ); - for (const file of migrations) { - await apply(file); - } - 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, false); - const family = await base.catalog.createStrategy( - { name: 'Defaulted SMA', description: 'SQL admission fixture; never executed' }, - 'operator' - ); - let pkg = await base.catalog.getVersionArtifact(base.version.id); - if (kind === 'mean-reversion') { - pkg = (await packageBuiltinStrategies()).find( - item => item.program.strategyId === 'mean_reversion' - )!; - } else if (kind === 'string') { - pkg = { - ...pkg, - program: { - strategyId: 'mean_reversion', - strategyVersion: 'custom-string/v1', - apiVersion: 'canonical-ts/v1', - checkpointVersion: '1', - }, - parameterSchema: { - version: 1, - type: 'object', - additionalProperties: false, - properties: { - minNotionalVolume: { type: 'string' }, - label: { type: 'string', default: '0' }, - note: { type: 'string' }, - }, - required: ['minNotionalVolume'], - }, - } satisfies StrategyVersionPackage; - } - const candidate = await base.catalog.publishVersion( - family.id, - { - ...pkg, - execution: { kind: 'isolated-candidate/v1', warmupBars: 0 }, - }, - null, - 'operator', - randomUUID() - ); - const experiments = new ExperimentsService({ postgres, logger }); - const readManifest = async (id: string) => - (await pool.query('SELECT to_jsonb(e) AS value FROM research_experiments e WHERE id=$1', [id])) - .rows[0].value; - const validate = (row: unknown) => - pool.query( - 'SELECT validate_experiment_manifest(jsonb_populate_record(NULL::research_experiments,$1))', - [row] - ); - const snapshot = async () => - ( - await pool.query(`SELECT - (SELECT jsonb_agg(to_jsonb(e) ORDER BY id) FROM research_experiments e) AS experiments, - (SELECT jsonb_agg(to_jsonb(r) ORDER BY id) FROM runs r) AS runs, - (SELECT jsonb_agg(to_jsonb(v) ORDER BY id) FROM strategy_versions v) AS versions`) - ).rows; - return { ...base, pool, candidate, experiments, apply, readManifest, validate, snapshot }; -} -const suite = url ? describe : describe.skip; -suite('candidate parameter default SQL admission', () => { - test('SQL32 preserves retained rows and admits empty/partial defaults without rewriting input', async () => { - const f = await fixture(); - const explicit = await f.experiments.preview({ - name: 'Explicit before upgrade', - backtestId: f.draft.id, - grid: {}, - candidate: { versionId: f.candidate.id, parameters: { fastPeriod: 2, slowPeriod: 3 } }, - }); - const existing = await f.experiments.submit( - { ...explicit.input, previewHash: explicit.previewHash }, - { principal: 'operator', key: 'explicit' } - ); - const builtin = await f.experiments.preview({ - name: 'Builtin before upgrade', - backtestId: f.draft.id, - grid: {}, - }); - const existingBuiltin = await f.experiments.submit( - { ...builtin.input, previewHash: builtin.previewHash }, - { principal: 'operator', key: 'builtin' } - ); - const empty = await f.experiments.preview({ - ...explicit.input, - name: 'Empty defaults', - candidate: { versionId: f.candidate.id, parameters: {} }, - }); - const row = await f.readManifest(existing.id); - const defaulted = { - ...row, - name: empty.input.name, - preview_hash: empty.previewHash, - preview: empty, - }; - // Demonstrate the old guard rejects this otherwise valid service-produced manifest. - await expect(f.validate(defaulted)).rejects.toMatchObject({ code: '23514' }); - const before = await f.snapshot(); - await f.apply(); - await f.apply(); - await f.apply('33-candidate-decimal-normalization.sql'); - expect(await f.snapshot()).toEqual(before); - await f.validate(row); - await f.validate(await f.readManifest(existingBuiltin.id)); - await f.validate(defaulted); - - const inputs: Record[] = [{}, { fastPeriod: 2 }]; - for (const parameters of inputs) { - const preview = await f.experiments.preview({ - ...empty.input, - candidate: { versionId: f.candidate.id, parameters }, - }); - expect(preview.input.candidate!.parameters).toEqual(parameters); - expect(preview.request.strategy.selection.parameters).toEqual({ - fastPeriod: 5, - slowPeriod: 15, - ...parameters, - }); - const submission = { ...preview.input, previewHash: preview.previewHash }; - const receipt = { principal: 'operator', key: randomUUID() }; - const admitted = await f.experiments.submit(submission, receipt); - const retained = await f.readManifest(admitted.id); - expect(retained.preview).toEqual(preview); - expect(retained.preview_hash).toBe(preview.previewHash); - expect((await f.experiments.submit(submission, receipt)).id).toBe(admitted.id); - expect( - (await f.pool.query('SELECT id FROM runs WHERE experiment_id=$1', [admitted.id])).rows - ).toHaveLength(1); - } - }, 30000); - - test('SQL32 still rejects altered explicit/default values, malformed input and forged schema defaults', async () => { - const f = await fixture(); - await f.apply(); - await f.apply('33-candidate-decimal-normalization.sql'); - const preview = await f.experiments.preview({ - name: 'Partial defaults guard', - backtestId: f.draft.id, - grid: {}, - candidate: { versionId: f.candidate.id, parameters: { fastPeriod: 2 } }, - }); - const admitted = await f.experiments.submit( - { ...preview.input, previewHash: preview.previewHash }, - { principal: 'operator', key: 'partial' } - ); - const row = await f.readManifest(admitted.id); - await f.validate(row); - for (const [path, value] of [ - [['input', 'candidate', 'parameters', 'fastPeriod'], 3], - [['input', 'candidate', 'parameters', 'undeclared'], 1], - [['input', 'candidate', 'parameters'], null], - [['input', 'candidate', 'parameters'], []], - [['input', 'candidate', 'parameters'], undefined], - [['request', 'strategy', 'selection', 'parameters', 'fastPeriod'], 4], - [['request', 'strategy', 'selection', 'parameters', 'slowPeriod'], 14], - [['request', 'strategy', 'selection', 'parameters', 'slowPeriod'], undefined], - [['request', 'strategy', 'selection', 'parameters', 'undeclared'], 1], - ] as const) { - const forged = structuredClone(row); - let parent = forged.preview; - for (const key of path.slice(0, -1)) { - parent = parent[key]; - } - parent[path.at(-1)!] = value; - await expect(f.validate(forged)).rejects.toMatchObject({ code: '23514' }); - } - const forgedPackage = structuredClone(row); - forgedPackage.preview.request.strategy.package.parameterSchema.properties.slowPeriod.default = 14; - forgedPackage.preview.request.strategy.selection.parameters.slowPeriod = 14; - await expect(f.validate(forgedPackage)).rejects.toMatchObject({ code: '23514' }); - - const builtin = await f.experiments.preview({ - name: 'No candidate equality', - backtestId: f.draft.id, - grid: {}, - }); - const builtinRow = { - ...row, - name: builtin.input.name, - preview_hash: builtin.previewHash, - preview: builtin, - }; - await f.validate(builtinRow); - builtinRow.preview.request.strategy.selection.parameters = { fastPeriod: 5, slowPeriod: 15 }; - await expect(f.validate(builtinRow)).rejects.toMatchObject({ code: '23514' }); - }, 30000); - - test('SQL33 admits the exact failed raw mean-reversion receipt and preserves decimal input spellings', async () => { - const f = await fixture('mean-reversion'); - await f.apply(); - const input = (minNotionalVolume: string) => ({ - name: `Notional ${minNotionalVolume}`, - backtestId: f.draft.id, - grid: {}, - candidate: { - versionId: f.candidate.id, - parameters: { ...canonicalRegimeSelection().parameters, minNotionalVolume }, - }, - }); - const canonical = await f.experiments.preview(input('0.00000000')); - const existing = await f.experiments.submit( - { ...canonical.input, previewHash: canonical.previewHash }, - { principal: 'operator', key: 'before-decimal-migration' } - ); - const raw = await f.experiments.preview(input('0')); - const submission = { ...raw.input, previewHash: raw.previewHash }; - const receipt = { principal: 'operator', key: 'raw-zero-original-receipt' }; - const original = JSON.stringify(submission); - const before = await f.snapshot(); - await expect(f.experiments.submit(submission, receipt)).rejects.toMatchObject({ - code: '23514', - }); - expect(await f.snapshot()).toEqual(before); - await f.apply('33-candidate-decimal-normalization.sql'); - await f.apply('33-candidate-decimal-normalization.sql'); - expect(await f.snapshot()).toEqual(before); - await f.validate(await f.readManifest(existing.id)); - const admitted = await f.experiments.submit(submission, receipt); - const replayed = await f.experiments.submit(submission, receipt); - expect(JSON.stringify(submission)).toBe(original); - expect(replayed.id).toBe(admitted.id); - expect(replayed.trials.map(trial => trial.runId)).toEqual( - admitted.trials.map(trial => trial.runId) - ); - expect(admitted.preview.input).toEqual(raw.input); - expect(admitted.previewHash).toBe(raw.previewHash); - expect(admitted.preview.request.strategy.selection.parameters).toMatchObject({ - minNotionalVolume: '0.00000000', - }); - expect( - (await f.pool.query('SELECT id FROM runs WHERE experiment_id=$1', [admitted.id])).rows - ).toHaveLength(1); - - for (const value of [ - '12.3', - '-0', - '-0.000', - '0.00000000', - '0.00000001', - '792281625142643375935.43950335', - ]) { - const preview = await f.experiments.preview(input(value)); - const saved = await f.experiments.submit( - { ...preview.input, previewHash: preview.previewHash }, - { principal: 'operator', key: randomUUID() } - ); - expect(saved.preview.input.candidate!.parameters.minNotionalVolume).toBe(value); - expect(saved.preview.request.strategy.selection.parameters).toMatchObject({ - minNotionalVolume: parseFinancialDecimal(value), - }); - expect((await f.readManifest(saved.id)).preview).toEqual(preview); - } - const after = await f.snapshot(); - await f.apply('33-candidate-decimal-normalization.sql'); - expect(await f.snapshot()).toEqual(after); - expect((await f.experiments.submit(submission, receipt)).id).toBe(admitted.id); - }, 30000); - - test('SQL33 rejects decimal coercion, altered amounts and missing or extra parameters', async () => { - const f = await fixture('mean-reversion'); - await f.apply(); - await f.apply('33-candidate-decimal-normalization.sql'); - const preview = await f.experiments.preview({ - name: 'Strict decimal guard', - backtestId: f.draft.id, - grid: {}, - candidate: { - versionId: f.candidate.id, - parameters: { ...canonicalRegimeSelection().parameters, minNotionalVolume: '0' }, - }, - }); - const saved = await f.experiments.submit( - { ...preview.input, previewHash: preview.previewHash }, - { principal: 'operator', key: randomUUID() } - ); - const row = await f.readManifest(saved.id); - for (const value of [ - '1', - '-1', - '-0.00000001', - '1e0', - '+0', - '00', - '.1', - '1.', - '0.000000000', - '792281625142643375935.43950336', - '1000000000000000000000', - '0\n', - '\n0', - ' 0', - '0 ', - 0, - true, - null, - {}, - [], - undefined, - ]) { - const forged = structuredClone(row); - forged.preview.input.candidate.parameters.minNotionalVolume = value; - await expect(f.validate(forged)).rejects.toMatchObject({ code: '23514' }); - } - // Keep both sides equal after naive padding/sign stripping, so only the strict - // lexical/range checks reject these rows rather than an unrelated value mismatch. - for (const [raw, padded] of [ - ['792281625142643375935.43950336', '792281625142643375935.43950336'], - ['1000000000000000000000', '1000000000000000000000.00000000'], - ['-1', '1.00000000'], - ['-0.00000001', '0.00000001'], - ['1e0', '1e0.00000000'], - ['00', '00.00000000'], - ['+0', '+0.00000000'], - ['0.000000000', '0.00000000'], - ['0\n', '0\n.00000000'], - ]) { - const forged = structuredClone(row); - forged.preview.input.candidate.parameters.minNotionalVolume = raw; - forged.preview.request.strategy.selection.parameters.minNotionalVolume = padded; - forged.preview.candidates[0].parameters.minNotionalVolume = padded; - await expect(f.validate(forged)).rejects.toMatchObject({ code: '23514' }); - } - for (const [key, value] of [ - ['minNotionalVolume', '1.00000000'], - ['minNotionalVolume', undefined], - ['unknown', '0'], - ] as const) { - const forged = structuredClone(row); - forged.preview.request.strategy.selection.parameters[key] = value; - await expect(f.validate(forged)).rejects.toMatchObject({ code: '23514' }); - } - const extra = structuredClone(row); - extra.preview.input.candidate.parameters.unknown = '0'; - await expect(f.validate(extra)).rejects.toMatchObject({ code: '23514' }); - const forgedProgram = structuredClone(row); - forgedProgram.preview.request.strategy.package.program.strategyVersion = 'custom-string/v1'; - await expect(f.validate(forgedProgram)).rejects.toMatchObject({ code: '23514' }); - }, 30000); - - test('SQL33 leaves other candidate string semantics, defaults and omitted optional values unchanged', async () => { - const f = await fixture('string'); - await f.apply(); - await f.apply('33-candidate-decimal-normalization.sql'); - const preview = await f.experiments.preview({ - name: 'Literal candidate strings', - backtestId: f.draft.id, - grid: {}, - candidate: { versionId: f.candidate.id, parameters: { minNotionalVolume: '0' } }, - }); - const saved = await f.experiments.submit( - { ...preview.input, previewHash: preview.previewHash }, - { principal: 'operator', key: randomUUID() } - ); - expect(saved.preview.request.strategy.selection.parameters).toEqual({ - minNotionalVolume: '0', - label: '0', - }); - const row = await f.readManifest(saved.id); - await f.validate(row); - for (const key of ['minNotionalVolume', 'label']) { - const forged = structuredClone(row); - forged.preview.request.strategy.selection.parameters[key] = '0.00000000'; - await expect(f.validate(forged)).rejects.toMatchObject({ code: '23514' }); - } - }, 30000); -}); diff --git a/test/postgres/canonical-durable-backtest.test.ts b/test/postgres/canonical-durable-backtest.test.ts deleted file mode 100644 index f1f0db0e..00000000 --- a/test/postgres/canonical-durable-backtest.test.ts +++ /dev/null @@ -1,370 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { readFileSync } from 'node:fs'; -import { afterEach, describe, expect, test } from 'bun:test'; -import { Pool } from 'pg'; -import { getLogger, setLoggerConfig } from '@stock-bot/logger'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import type { Queue } from '@stock-bot/services'; -import { parseBacktestRequest } from '@stock-bot/stock-config/backtest'; -import { - canonicalRunRequestSchema, - type CanonicalRunResult, -} from '@stock-bot/stock-config/canonical-research'; -import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner'; -import { readCanonicalBuildIdentity } from '@stock-bot/trading-runtime/canonical-build'; -import { LegacyBacktestRunWriter } from '../../apps/stock/orchestrator/src/backtest/compatibility/LegacyBacktestRunWriter'; -import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine'; -import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository'; -import { BacktestLeaseLostError } from '../../apps/stock/orchestrator/src/backtest/run-repository'; -import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter'; -import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher'; -import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies'; -import { canonicalSmaFixture } from '../fixtures/canonical-sma'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('canonical-durable-test'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const cleanup: (() => Promise)[] = []; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); -let packages: ReturnType | undefined; -async function fixture(options: { corruptDataset?: boolean; buildMismatch?: boolean } = {}) { - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Dedicated stock_bot_safety PostgreSQL required'); - } - const schema = `stock_bot_safety_canonical_${randomUUID().replaceAll('-', '')}`; - const admin = new Pool({ connectionString: url }); - await admin.query(`CREATE SCHEMA ${schema}`); - const pool = new Pool({ connectionString: url, options: `-c search_path=${schema}` }); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - await pool.query(`CREATE TYPE run_status AS ENUM ('pending','running','completed','failed','cancelled','paused'); - CREATE TABLE backtests (id uuid PRIMARY KEY,name text NOT NULL,strategy text NOT NULL,symbols jsonb NOT NULL, - start_date timestamptz NOT NULL,end_date timestamptz NOT NULL,initial_capital numeric NOT NULL,config jsonb, - created_at timestamptz DEFAULT NOW(),updated_at timestamptz DEFAULT NOW()); - CREATE TABLE runs (id uuid PRIMARY KEY,backtest_id uuid REFERENCES backtests(id),run_number integer, - status run_status DEFAULT 'pending',speed_multiplier numeric,progress numeric DEFAULT 0,error text, - started_at timestamptz,completed_at timestamptz,paused_at timestamptz,current_simulation_date timestamptz, - created_at timestamptz DEFAULT NOW(),updated_at timestamptz DEFAULT NOW(),UNIQUE(backtest_id,run_number)); - CREATE TABLE backtest_results(run_id uuid REFERENCES runs(id),completed_at timestamptz, - metrics jsonb NOT NULL,equity_curve jsonb NOT NULL,ohlc_data jsonb NOT NULL,trades jsonb NOT NULL,positions jsonb NOT NULL,analytics jsonb NOT NULL,execution_time integer);`); - for (const filename of [ - '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/${filename}`, import.meta.url), 'utf8') - ); - } - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, - logger - ); - Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); - Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); - const versionId = randomUUID(), - familyId = randomUUID(), - reviewId = randomUUID(), - runId = randomUUID(), - backtestId = randomUUID(); - const oracle = canonicalSmaFixture([`strategy:${versionId}`]); - oracle.config.matching.risk.ledger.sessionId = runId; - oracle.config.matching.risk.ledger.accountId = `research:${runId}`; - const pkg = (await (packages ??= packageBuiltinStrategies())).find( - p => p.program.strategyId === 'sma_crossover' - )!; - const build = await readCanonicalBuildIdentity(); - if (options.buildMismatch) { - build.workerSha256 = '0'.repeat(64); - } - const request = canonicalRunRequestSchema.parse({ - kind: 'canonical-research/v1', - runId, - backtestId, - name: 'Retained canonical oracle', - strategy: { - familyId, - versionId, - reviewId, - origin: 'builtin', - package: pkg, - selection: oracle.selections[0], - }, - datasetHash: oracle.dataset.manifest.hash, - policy: oracle.config, - analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null }, - build, - modelArtifacts: [], - }); - const payload = { - ...oracle.dataset, - bars: oracle.dataset.bars.map((bar, i) => ({ - ...bar, - ...(options.corruptDataset && i === 0 ? { close: 999 } : {}), - })), - }; - await pool.query( - `INSERT INTO strategies(id,name,owner_principal,updated_by,builtin_key) VALUES ($1,'Fixture','operator','operator','sma_crossover')`, - [familyId] - ); - await pool.query( - `INSERT INTO strategy_versions(id,strategy_id,ordinal,envelope,created_by,origin,submission_key,submission_fingerprint) - VALUES ($1,$2,1,$3,'operator','builtin',$4,$5)`, - [versionId, familyId, pkg, randomUUID(), 'a'.repeat(64)] - ); - await pool.query( - `INSERT INTO strategy_review_events(id,version_id,ordinal,decision,actor,reason) VALUES ($1,$2,1,'approve','operator','fixture')`, - [reviewId, versionId] - ); - await pool.query(`INSERT INTO backtest_datasets(hash,payload) VALUES ($1,$2)`, [ - request.datasetHash, - payload, - ]); - await pool.query( - `INSERT INTO backtests(id,name,strategy,symbols,start_date,end_date,initial_capital,config,strategy_version_id,strategy_parameters) - VALUES ($1,$2,'catalog',$3,$4,$5,10000,'{}',$6,$7)`, - [ - backtestId, - request.name, - JSON.stringify(['X0.US']), - new Date(oracle.dataset.manifest.bounds.tradeStart), - new Date(oracle.dataset.manifest.bounds.tradeEnd), - versionId, - request.strategy.selection.parameters, - ] - ); - const admit = async () => { - await pool.query( - `INSERT INTO runs(id,backtest_id,run_number,status,request_snapshot,dataset_hash) VALUES ($1,$2,1,'pending',$3,$4)`, - [runId, backtestId, request, request.datasetHash] - ); - await pool.query('INSERT INTO backtest_dispatch(run_id) VALUES ($1)', [runId]); - }; - const repository = new PostgresBacktestRunRepository(postgres, 5000); - const engine = new RustBacktestAdapter({ logger }, { timeoutMs: 10000 }); - const runner = new BacktestRunner({ - engine, - repository, - logger, - heartbeatMs: 20, - }); - const dispatcher = new BacktestDispatcher( - postgres, - { - async add() { - return {} as Awaited>; - }, - }, - logger, - { intervalMs: 20, republishMs: 20, maxAttempts: 3 } - ); - cleanup.push(() => runner.shutdown()); - cleanup.push(() => dispatcher.shutdown()); - const row = async () => (await pool.query('SELECT * FROM runs WHERE id=$1', [runId])).rows[0]; - const saved = async () => - (await pool.query('SELECT * FROM backtest_results WHERE run_id=$1', [runId])).rows[0]; - return { - pool, - repository, - legacyWriter: new LegacyBacktestRunWriter(postgres, 5000), - engine, - runner, - dispatcher, - request, - dataset: oracle.dataset, - admit, - row, - saved, - }; -} - -(url ? describe : describe.skip)('retained canonical durable PostgreSQL execution', () => { - test('only a matching admitted canonical snapshot can be claimed', async () => { - const f = await fixture(); - await expect(f.repository.startCanonical(f.request)).rejects.toThrow('missing'); - expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0); - const raw = { - ...parseBacktestRequest({ - mode: 'backtest', - strategy: 'sma-crossover', - symbols: ['X.US'], - startDate: '2024-01-01T00:00:00.000Z', - endDate: '2024-02-01T00:00:00.000Z', - initialCapital: 10000, - dataFrequency: '1d', - }), - kind: 'canonical-research/v999', - }; - await expect(f.legacyWriter.start(raw)).rejects.toThrow('Retained strategy versions'); - expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0); - await f.admit(); - await expect(f.repository.startCanonical({ ...f.request, name: 'different' })).rejects.toThrow( - 'snapshot' - ); - expect((await f.row()).attempt_number).toBe(0); - const claim = await f.repository.startCanonical(f.request); - expect(claim.config).toEqual(f.request); - await expect(f.repository.startCanonical(f.request)).rejects.toThrow('claimed'); - }); - test('retained worker result survives template edits/archive and approval revocation; terminal replay is an acknowledgement', async () => { - const f = await fixture(); - await f.admit(); - await f.pool.query( - `UPDATE backtests SET name='edited',strategy_parameters='{"fastPeriod":3,"slowPeriod":8}',archived_at=NOW() WHERE id=$1`, - [f.request.backtestId] - ); - await f.pool.query( - `INSERT INTO strategy_review_events(id,version_id,ordinal,decision,actor,reason) VALUES ($1,$2,2,'revoke','operator','later')`, - [randomUUID(), f.request.strategy.versionId] - ); - expect(await f.runner.runQueued(f.request.runId)).toEqual({ - runId: f.request.runId, - status: 'completed', - }); - const row = await f.saved(), - result = row.canonical_result as CanonicalRunResult; - expect(result.request).toEqual(f.request); - expect(String(result.financial.projection.valuation.equity)).toBe('9969.30000000'); - expect(result.financial.projection.fills).toHaveLength(2); - expect(result.financial.projection.fills.map(fill => String(fill.fee.amount))).toEqual([ - '0.50000000', - '0.20000000', - ]); - for (const key of [ - 'metrics', - 'equity_curve', - 'trades', - 'positions', - 'analytics', - 'configuration', - 'engine', - ]) { - expect(row[key]).toBeNull(); - } - const legacyNulls = ( - await f.pool.query( - `SELECT metrics IS NOT NULL AND metrics='null'::jsonb AS absent_projection FROM backtest_results WHERE run_id=$1`, - [f.request.runId] - ) - ).rows[0]; - expect(legacyNulls.absent_projection).toBe(true); - await f.runner.runQueued(f.request.runId); - expect((await f.row()).attempt_number).toBe(1); - expect((await f.pool.query('SELECT * FROM backtest_results')).rowCount).toBe(1); - await expect( - f.pool.query(`UPDATE backtest_results SET canonical_result='{}' WHERE run_id=$1`, [ - f.request.runId, - ]) - ).rejects.toThrow('Retained'); - }); - test('expired owner is fenced and replacement reuses the identical snapshot and dataset', async () => { - const f = await fixture(); - await f.admit(); - const old = await f.repository.startCanonical(f.request); - expect( - await f.repository.loadCanonicalDataset(old.runId, old.attemptId, f.request.datasetHash) - ).toEqual(f.dataset); - const baseline = await f.engine.runCanonical(f.request, async () => f.dataset); - await f.pool.query( - `UPDATE runs SET lease_expires_at=clock_timestamp()-INTERVAL '1 second' WHERE id=$1`, - [old.runId] - ); - await f.dispatcher.tick(); - expect((await f.row()).status).toBe('pending'); - const replacement = await f.repository.startCanonical(f.request); - const result: CanonicalRunResult = { - kind: 'canonical-result/v1', - runId: f.request.runId, - backtestId: f.request.backtestId, - status: 'completed', - completedAt: new Date().toISOString(), - executionTime: 1, - financialEngine: 'rust', - strategyExecution: 'typescript-retained-builtin/v1', - request: f.request, - ...baseline, - }; - await expect( - f.repository.loadCanonicalDataset(old.runId, old.attemptId, f.request.datasetHash) - ).rejects.toBeInstanceOf(BacktestLeaseLostError); - await expect(f.repository.completeCanonical(result, old.attemptId)).rejects.toBeInstanceOf( - BacktestLeaseLostError - ); - const repeated = await f.engine.runCanonical(replacement.config, signal => - f.repository.loadCanonicalDataset( - replacement.runId, - replacement.attemptId, - replacement.config.datasetHash, - signal - ) - ); - expect(repeated).toEqual(baseline); - await f.repository.completeCanonical({ ...result, ...repeated }, replacement.attemptId); - expect((await f.row()).attempt_number).toBe(2); - expect((await f.saved()).canonical_result.financial).toEqual(baseline.financial); - }); - test('cancellation wins against late canonical completion without a partial result', async () => { - const f = await fixture(); - await f.admit(); - const claim = await f.repository.startCanonical(f.request); - const report = await f.engine.runCanonical(f.request, async () => f.dataset); - await f.pool.query('UPDATE runs SET cancel_requested=true WHERE id=$1', [claim.runId]); - const result: CanonicalRunResult = { - kind: 'canonical-result/v1', - runId: f.request.runId, - backtestId: f.request.backtestId, - status: 'completed', - completedAt: new Date().toISOString(), - executionTime: 1, - financialEngine: 'rust', - strategyExecution: 'typescript-retained-builtin/v1', - request: f.request, - ...report, - }; - await expect(f.repository.completeCanonical(result, claim.attemptId)).rejects.toBeInstanceOf( - BacktestCancelledError - ); - expect(await f.saved()).toBeUndefined(); - await f.repository.cancel(claim.runId, claim.attemptId); - expect((await f.row()).status).toBe('cancelled'); - }); - test('a failed canonical result insert rolls back terminal completion and records failure', async () => { - const f = await fixture(); - await f.admit(); - await f.pool.query( - `ALTER TABLE backtest_results ADD CONSTRAINT injected_result_failure CHECK (canonical_result IS NULL)` - ); - await expect(f.runner.runQueued(f.request.runId)).rejects.toThrow('injected_result_failure'); - expect((await f.row()).status).toBe('failed'); - expect(await f.saved()).toBeUndefined(); - }); - for (const defect of ['corruptDataset', 'buildMismatch'] as const) { - test(`${defect} fails closed without provider fallback or result`, async () => { - const f = await fixture({ [defect]: true }); - await f.admit(); - await expect(f.runner.runQueued(f.request.runId)).rejects.toThrow(); - expect((await f.row()).status).toBe('failed'); - expect(await f.saved()).toBeUndefined(); - expect((await f.row()).request_snapshot).toEqual(f.request); - expect((await f.row()).dataset_hash).toBe(f.request.datasetHash); - }); - } -}); diff --git a/test/postgres/canonical-paper-crash.test.ts b/test/postgres/canonical-paper-crash.test.ts deleted file mode 100644 index 3e28ec41..00000000 --- a/test/postgres/canonical-paper-crash.test.ts +++ /dev/null @@ -1,165 +0,0 @@ -import { fork } from 'node:child_process'; -import { randomUUID } from 'node:crypto'; -import { readFileSync } from 'node:fs'; -import { fileURLToPath } from 'node:url'; -import { afterEach, describe, expect, test } from 'bun:test'; -import { Pool } from 'pg'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import { parseFinancialDecimal } from '@stock-bot/types'; -import { CanonicalPaperExecution } from '../../apps/stock/orchestrator/src/execution/CanonicalPaperExecution'; -import { PostgresCanonicalExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository'; -import { - canonicalConfig, - counterProgram, - markInput, - openInput, - quoteInput, -} from '../fixtures/canonical-paper'; -import { logger } from '../fixtures/execution'; - -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const cleanup: (() => Promise)[] = []; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); - -async function fixture() { - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Dedicated safety database required'); - } - const schema = 'stock_bot_safety_' + randomUUID().replaceAll('-', ''); - const admin = new Pool({ connectionString: url }); - await admin.query('CREATE SCHEMA ' + schema); - const pool = new Pool({ connectionString: url, options: '-c search_path=' + schema }); - cleanup.push(async () => { - await pool.end(); - await admin.query('DROP SCHEMA ' + schema + ' CASCADE'); - await admin.end(); - }); - for (const migration of [ - '11-simulation-execution-ledger.sql', - '13-strategy-recovery.sql', - '15-canonical-paper-intents.sql', - ]) { - await pool.query( - readFileSync(new URL('../../database/postgres/init/' + migration, import.meta.url), 'utf8') - ); - } - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, - logger - ); - Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); - const make = async (onDecision = () => {}) => { - const program = counterProgram(); - const observed: typeof program = { - ...program, - decide(context) { - onDecision(); - return program.decide(context); - }, - }; - const execution = new CanonicalPaperExecution({ - repository: new PostgresCanonicalExecutionRepository(postgres), - programs: [observed], - }); - await execution.initialize(canonicalConfig()); - return execution; - }; - return { schema, pool, make }; -} - -describe.skipIf(!url)('canonical paper process recovery on real PostgreSQL', () => { - test.each(['decision', 'checkpoint', 'dispatch', 'fill'] as const)( - 'hard kill at %s matches uninterrupted state, effects and fees', - async phase => { - const baselineFixture = await fixture(); - const baseline = await baselineFixture.make(); - const interruptedFixture = await fixture(); - const interrupted = await interruptedFixture.make(); - for (const input of [openInput(), markInput(1), quoteInput(2)]) { - await baseline.enqueue(input); - await interrupted.enqueue(input); - } - await baseline.drain(); - const expected = await baseline.snapshot(); - const expectedJournal = await baseline.journal(); - expect(expected.account.checkpoint.orders).toHaveLength(1); - expect(expected.account.checkpoint.orders[0]?.status).toBe('Filled'); - expect(expected.account.view.portfolio.cash).toBe(parseFinancialDecimal('979.80000000')); - expect(expected.account.view.equity).toBe(parseFinancialDecimal('999.80000000')); - const child = fork( - fileURLToPath(new URL('../fixtures/canonical-paper-crash-owner.ts', import.meta.url)), - [], - { - execPath: process.execPath, - execArgv: [], - stdio: ['ignore', 'ignore', 'pipe', 'ipc'], - env: { - ...process.env, - CANONICAL_CRASH_SCHEMA: interruptedFixture.schema, - CANONICAL_CRASH_PHASE: phase, - }, - } - ); - let childError = ''; - child.stderr?.on('data', chunk => { - childError += String(chunk); - }); - const exited = new Promise(resolve => child.once('exit', () => resolve())); - cleanup.push(async () => { - child.kill('SIGKILL'); - await exited; - }); - await new Promise((resolve, reject) => { - const timer = setTimeout( - () => reject(new Error('Canonical crash boundary timeout: ' + childError)), - 10000 - ); - child.once('message', message => { - clearTimeout(timer); - if ((message as { phase?: string }).phase === phase) { - resolve(); - } else { - reject(new Error('Unexpected canonical crash boundary')); - } - }); - child.once('error', error => { - clearTimeout(timer); - reject(error); - }); - child.once('exit', () => { - clearTimeout(timer); - reject(new Error('Canonical child exited before boundary: ' + childError)); - }); - }); - child.kill('SIGKILL'); - await exited; - let recoveredDecisions = 0; - const recovered = await interruptedFixture.make(() => { - recoveredDecisions++; - }); - await recovered.drain(); - expect(recoveredDecisions).toBe(phase === 'decision' ? 1 : 0); - expect(await recovered.snapshot()).toEqual(expected); - expect(await recovered.journal()).toEqual(expectedJournal); - expect(await recovered.getRecoveryStatus()).toMatchObject({ - status: 'Running', - pendingDecisionSequence: null, - pendingBatch: null, - pendingInput: null, - }); - const batches = await interruptedFixture.pool.query( - 'SELECT status FROM simulation_canonical_intents' - ); - expect(batches.rows).toEqual([{ status: 'dispatched' }]); - expect(await recovered.enqueue(markInput(1))).toBe(false); - await recovered.drain(); - expect(await recovered.snapshot()).toEqual(expected); - expect(await recovered.journal()).toEqual(expectedJournal); - }, - 20000 - ); -}); diff --git a/test/postgres/canonical-paper.test.ts b/test/postgres/canonical-paper.test.ts deleted file mode 100644 index 4670f965..00000000 --- a/test/postgres/canonical-paper.test.ts +++ /dev/null @@ -1,996 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { readFileSync } from 'node:fs'; -import { afterEach, describe, expect, test } from 'bun:test'; -import { Pool } from 'pg'; -import { stageFinancialTransaction } from '@stock-bot/engine'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import { parseFinancialDecimal } from '@stock-bot/types'; -import { builtinStrategySelectionSchema } from '@stock-bot/stock-config/strategy'; -import { - parseFinancialTransactionResult, - type CanonicalMatchingConfig, -} from '@stock-bot/stock-config/canonical-execution'; -import type { StrategyProgram } from '@stock-bot/research/strategy-api'; -import { - canonicalPaperInputSchema, - type CanonicalExecutionRepository, - type CanonicalJournalEntry, - type CanonicalPaperInput, - type CanonicalTransaction, -} from '../../apps/stock/orchestrator/src/execution/canonical-paper'; -import { CanonicalPaperExecution } from '../../apps/stock/orchestrator/src/execution/CanonicalPaperExecution'; -import { PostgresCanonicalExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository'; -import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins'; -import { StrategyController } from '../../apps/stock/orchestrator/src/strategies/strategy-controller'; -import { - canonicalConfig, - counterProgram, - markInput, - openInput, - quoteInput, - type CounterState, -} from '../fixtures/canonical-paper'; -import { logger } from '../fixtures/execution'; - -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const cleanup: (() => Promise)[] = []; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); - -async function fixture( - config = canonicalConfig(), - programs: readonly StrategyProgram[] = [counterProgram()] -) { - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Dedicated stock_bot_safety database required'); - } - const schema = 'stock_bot_safety_' + randomUUID().replaceAll('-', ''); - const admin = new Pool({ connectionString: url }); - await admin.query(`CREATE SCHEMA ${schema}`); - const pool = new Pool({ - connectionString: url, - options: `-c search_path=${schema} -c statement_timeout=10000`, - }); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - for (const filename of [ - '11-simulation-execution-ledger.sql', - '13-strategy-recovery.sql', - '15-canonical-paper-intents.sql', - ]) { - const sql = readFileSync( - new URL(`../../database/postgres/init/${filename}`, import.meta.url), - 'utf8' - ); - await pool.query(sql); - await pool.query(sql); - } - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, - logger - ); - Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); - const repository = new PostgresCanonicalExecutionRepository(postgres); - const make = async ( - options: { - repository?: CanonicalExecutionRepository; - programs?: readonly StrategyProgram[]; - publish?: (entries: readonly CanonicalJournalEntry[]) => void | Promise; - } = {} - ) => { - const host = new CanonicalPaperExecution({ repository, programs, ...options }); - await host.initialize(config); - return host; - }; - return { pool, postgres, repository, make, host: await make(), config }; -} -async function send(host: CanonicalPaperExecution, input: CanonicalPaperInput) { - await host.enqueue(input); - await host.drain(); -} -function failOnce( - delegate: CanonicalExecutionRepository, - method: keyof CanonicalTransaction, - stage: 'before' | 'after' | 'commit', - matches: (value: unknown) => boolean = () => true -): CanonicalExecutionRepository { - let armed = true; - return { - initialize: (account, owners) => delegate.initialize(account, owners), - async transact(accountId: string, work: (tx: CanonicalTransaction) => Promise) { - let hit = false; - const result = await delegate.transact(accountId, tx => - work( - new Proxy(tx, { - get(target, key: keyof CanonicalTransaction) { - const value = target[key]; - if (typeof value !== 'function') { - return value; - } - return async (...args: unknown[]) => { - if (armed && key === method && matches(args[0])) { - armed = false; - hit = true; - } - if (hit && stage === 'before') { - throw new Error('injected before commit'); - } - const result = await Reflect.apply(value, target, args); - if (hit && stage === 'after') { - throw new Error('injected before commit'); - } - return result; - }; - }, - }) - ) - ); - if (hit && stage === 'commit') { - throw new Error('lost commit acknowledgement'); - } - return result; - }, - }; -} -const isPending = (value: unknown) => (value as { status?: string })?.status === 'pending'; -const isDispatched = (value: unknown) => (value as { status?: string })?.status === 'dispatched'; - -function explicitProgram( - tif: 'DAY' | 'GTC' | 'IOC' | 'FOK', - quantity = '2' -): StrategyProgram { - return { - ...counterProgram(), - mode: 'orders', - decide: context => ({ - nextState: { count: context.state.count + 1, samples: [context.random()], seen: [] }, - intent: { - mode: 'orders', - orders: - context.state.count === 0 - ? [ - { - kind: 'market', - orderId: 'explicit-order', - instrumentId: 'X', - side: 'buy', - quantity: parseFinancialDecimal(quantity), - timeInForce: tif, - }, - ] - : [], - }, - }), - }; -} -function ordersConfig(): CanonicalMatchingConfig { - const config = canonicalConfig(); - config.owners[0]!.mode = 'Orders'; - return config; -} - -describe.skipIf(!url)('canonical paper custody on real PostgreSQL', () => { - test('research and durable paper retain identical owned state, RNG and admission feedback', async () => { - const config = canonicalConfig(['A', 'B']); - const programs = [counterProgram('B'), counterProgram('A')]; - const f = await fixture(config, programs); - const controller = new StrategyController( - { version: 1, sessionId: config.risk.ledger.sessionId, datasetHash: '0'.repeat(64) }, - programs, - { matching: config } - ); - const diagnostics = async () => (await f.host.snapshot()).owners.map(owner => owner.diagnostic); - const initial = controller.snapshot().strategies; - expect(initial).toEqual(await diagnostics()); - programs[0]!.initialState.samples.push(999); - expect(initial).toEqual(await diagnostics()); - expect(controller.snapshot().strategies).toEqual(initial); - let cursor = 0; - for (const input of [ - openInput(), - markInput(1, ['A', 'B']), - quoteInput(1, '1'), - markInput(2, ['A', 'B']), - ]) { - await send(f.host, input); - const entries = await f.host.journal(cursor); - cursor = entries.at(-1)?.sequence ?? cursor; - const context = entries.find(entry => entry.payload.kind === 'decision')?.payload; - const admitted = entries.find( - entry => entry.payload.kind === 'command' && entry.payload.command.body.kind === 'submit' - )?.payload; - if (context?.kind === 'decision') { - if ( - admitted?.kind !== 'command' || - admitted.command.body.kind !== 'submit' || - !admitted.outcome - ) { - throw new Error('Missing native decision admission in paper journal'); - } - expect( - controller - .stage(context.context, canonicalPaperInputSchema.parse(input).observations) - .sort((a, b) => - Buffer.compare(Buffer.from(a.decision.ownerId), Buffer.from(b.decision.ownerId)) - ) - ).toEqual(admitted.command.body.decisions); - controller.committed(admitted.outcome); - } - expect(controller.snapshot().strategies).toEqual(await diagnostics()); - } - for (const owner of controller.snapshot().strategies) { - expect(owner.rng.draws).toBe(2); - expect( - owner.previousAdmission?.orders.every(order => order.decision.ownerId === owner.ownerId) - ).toBe(true); - } - }); - - test('real strategy state/RNG and economic postings match uninterrupted replacement and the direct Rust command tape', async () => { - const f = await fixture(); - await send(f.host, openInput()); - await send(f.host, markInput(1)); - await send(f.host, quoteInput(1, '1')); - const restored = await f.make(); - await send(restored, quoteInput(2)); - await send(restored, markInput(3)); - const snapshot = await restored.snapshot(); - expect(snapshot.owners[0]!.diagnostic.nextDecisionSequence).toBe(2); - expect(snapshot.owners[0]!.diagnostic.rng.draws).toBe(2); - expect(snapshot.account.view.portfolio.positions[0]!.quantity).toBe( - parseFinancialDecimal('2.00000000') - ); - const entries = await restored.journal(); - const identity = snapshot.account.identity; - let native = parseFinancialTransactionResult( - stageFinancialTransaction( - JSON.stringify({ version: 1, kind: 'initialize', identity, config: f.config }) - ), - identity - ); - for (const row of entries) { - if (row.payload.kind === 'command') { - const commandId = row.payload.command.commandId; - native = parseFinancialTransactionResult( - stageFinancialTransaction( - JSON.stringify({ - version: 1, - kind: 'apply', - identity, - checkpoint: native.checkpoint, - command: row.payload.command, - }) - ), - identity - ); - expect(native.outcome).toEqual(row.payload.outcome); - expect(native.view).toEqual(row.payload.view); - expect( - entries - .filter( - entry => entry.payload.kind === 'effect' && entry.payload.commandId === commandId - ) - .map(entry => (entry.payload.kind === 'effect' ? entry.payload.fact : null)) - ).toEqual(native.journal); - } - } - expect(native.checkpoint).toEqual(snapshot.account.checkpoint); - const baseline = await fixture(); - for (const input of [ - openInput(), - markInput(1), - quoteInput(1, '1'), - quoteInput(2), - markInput(3), - ]) { - await send(baseline.host, input); - } - expect(await baseline.host.snapshot()).toEqual(snapshot); - expect(await baseline.host.journal()).toEqual(entries); - expect((await f.pool.query('SELECT * FROM simulation_orders')).rows).toHaveLength(0); - expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(0); - }); - - test('competing hosts restore locked owner checkpoints and share one revision without duplicate fills or fees', async () => { - const f = await fixture(canonicalConfig(['A', 'B']), [ - counterProgram('A'), - counterProgram('B'), - ]); - const second = await f.make(); - await send(f.host, openInput()); - expect( - await Promise.all([ - f.host.enqueue(markInput(1, ['B', 'A'])), - second.enqueue(markInput(1, ['B', 'A'])), - ]) - ).toEqual([true, false]); - await Promise.all([f.host.drain(), second.drain()]); - await Promise.all([f.host.enqueue(quoteInput(1)), second.enqueue(quoteInput(1))]); - await Promise.all([f.host.drain(), second.drain()]); - const snapshot = await second.snapshot(); - expect(snapshot.owners.map(owner => owner.diagnostic.nextDecisionSequence)).toEqual([1, 1]); - expect(snapshot.account.view.portfolio.positions.map(position => position.quantity)).toEqual([ - parseFinancialDecimal('2.00000000'), - parseFinancialDecimal('2.00000000'), - ]); - const batches = (await f.pool.query('SELECT payload FROM simulation_canonical_intents')).rows; - expect(batches).toHaveLength(1); - const decisions = batches[0]!.payload.command.body.decisions; - expect(decisions[0].revision).toBe(decisions[1].revision); - expect(snapshot.account.view.portfolio.cash).toBe(parseFinancialDecimal('959.60000000')); - const conflict = markInput(1, ['A', 'B'], '12'); - await expect(second.enqueue(conflict)).rejects.toThrow('Conflicting'); - }); - - test('mixed-cadence restart retains every slow owner observation and scoped RNG prefix', async () => { - const config = canonicalConfig(['A', 'B']); - const programs = [counterProgram('A'), counterProgram('B')]; - const f = await fixture(config, programs); - await send(f.host, openInput()); - await send(f.host, markInput(1, ['A'])); - await send(f.host, markInput(2, ['A'])); - const before = await f.host.snapshot(); - expect(before.owners[1]!.pendingObservations.map(row => row.source_sequence)).toEqual([1, 2]); - const restored = await f.make(); - await send(restored, markInput(3, ['A', 'B'])); - const after = await restored.snapshot(); - expect(after.owners[1]!.diagnostic.state).toEqual({ - count: 1, - samples: [1025555898 / 4294967296], - seen: [1, 2, 3], - }); - expect(after.account.observed).toBe(3); - expect(after.owners[1]!.diagnostic.observationCount).toBe(3); - expect(after.owners[1]!.pendingObservations).toEqual([]); - }); - - test('checkpoint and complete batch SQL failure rolls back every owner decision/RNG and resumes before later input', async () => { - const config = canonicalConfig(['A', 'B']); - const programs = [counterProgram('A'), counterProgram('B')]; - const f = await fixture(config, programs); - await send(f.host, openInput()); - await f.pool - .query(`CREATE FUNCTION reject_batch() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'batch write failed'; END $$; - CREATE TRIGGER reject_batch BEFORE INSERT ON simulation_canonical_intents FOR EACH ROW EXECUTE FUNCTION reject_batch()`); - await f.host.enqueue(markInput(1, ['A', 'B'])); - await f.host.enqueue(quoteInput(1)); - await expect(f.host.drain()).rejects.toThrow('batch write failed'); - const failed = await f.host.snapshot(); - expect( - failed.owners.map(owner => [ - owner.diagnostic.nextDecisionSequence, - owner.diagnostic.rng.draws, - ]) - ).toEqual([ - [0, 0], - [0, 0], - ]); - expect(failed.owners.map(owner => owner.pendingObservations.length)).toEqual([1, 1]); - expect((await f.host.getRecoveryStatus()).pendingInput).toBe('quote-1'); - await f.pool.query('DROP TRIGGER reject_batch ON simulation_canonical_intents'); - const restored = await f.make(); - await restored.drain(); - expect((await restored.snapshot()).account.view.portfolio.positions).toHaveLength(2); - }); - - test('effect journal failure rolls back native fills, account and input; no phantom publication', async () => { - const f = await fixture(); - await send(f.host, openInput()); - await send(f.host, markInput(1)); - const before = await f.host.snapshot(); - const publications: CanonicalJournalEntry[] = []; - const host = await f.make({ - publish: entries => { - publications.push(...entries); - }, - }); - await host.enqueue(quoteInput(1)); - await f.pool.query(`CREATE FUNCTION reject_effect() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN - IF NEW.payload->>'kind' = 'effect' THEN RAISE EXCEPTION 'effect write failed'; END IF; RETURN NEW; END $$; - CREATE TRIGGER reject_effect BEFORE INSERT ON simulation_strategy_journal FOR EACH ROW EXECUTE FUNCTION reject_effect()`); - await expect(host.drain()).rejects.toThrow('effect write failed'); - expect((await host.snapshot()).account.checkpoint).toEqual(before.account.checkpoint); - expect(publications).toEqual([]); - expect((await host.getRecoveryStatus()).pendingInput).toBe('quote-1'); - await f.pool.query('DROP TRIGGER reject_effect ON simulation_strategy_journal'); - const restored = await f.make(); - await restored.drain(); - expect((await restored.snapshot()).account.view.portfolio.positions[0]!.quantity).toBe( - parseFinancialDecimal('2.00000000') - ); - }); - - test('lost checkpoint/dispatch commit acknowledgement and throwing publication cannot duplicate decisions, costs or effects', async () => { - for (const [method, matches] of [ - ['putBatch', isPending], - ['putBatch', isDispatched], - ] as const) { - const f = await fixture(); - await send(f.host, openInput()); - const host = await f.make({ - repository: failOnce(f.repository, method, 'commit', matches), - publish: () => { - throw new Error('observer failed'); - }, - }); - await host.enqueue(markInput(1)); - await host.enqueue(quoteInput(1)); - await expect(host.drain()).rejects.toThrow('lost commit acknowledgement'); - const restored = await f.make({ - publish: () => { - throw new Error('observer failed'); - }, - }); - await restored.drain(); - const before = await restored.snapshot(); - const journal = await restored.journal(); - await restored.enqueue(markInput(1)); - await restored.enqueue(quoteInput(1)); - await restored.drain(); - expect(await restored.snapshot()).toEqual(before); - expect(await restored.journal()).toEqual(journal); - expect(before.owners[0]!.diagnostic.nextDecisionSequence).toBe(1); - expect(before.account.view.portfolio.cash).toBe(parseFinancialDecimal('979.80000000')); - expect(await restored.journal(journal.at(-2)!.sequence)).toEqual(journal.slice(-1)); - } - }); - - test('failed owner callback rolls back earlier owner state/RNG, nested inputs cannot mutate another owner', async () => { - let fail = true; - let retained: unknown; - const first: StrategyProgram = { - ...counterProgram('A'), - decide(context) { - retained = context; - expect(Object.isFrozen(context.portfolio.portfolio)).toBe(true); - expect(Object.isFrozen(context.observations[0])).toBe(true); - expect(Object.isFrozen(context.state.samples)).toBe(true); - expect(() => Object.assign(context.observations[0]!, { close: '900' })).toThrow(); - return counterProgram('A').decide(context); - }, - }; - const second: StrategyProgram = { - ...counterProgram('B'), - decide(context) { - expect(context.observations[0]!.close).toBe(parseFinancialDecimal('10.00000000')); - if (fail) { - throw new Error('second owner failed'); - } - return counterProgram('B').decide(context); - }, - }; - const f = await fixture(canonicalConfig(['A', 'B']), [first, second]); - await send(f.host, openInput()); - await f.host.enqueue(markInput(1, ['A', 'B'])); - await expect(f.host.drain()).rejects.toThrow('second owner failed'); - expect((await f.host.snapshot()).owners.map(owner => owner.diagnostic.rng.draws)).toEqual([ - 0, 0, - ]); - expect(() => (retained as { random(): number }).random()).toThrow('only valid'); - fail = false; - await f.host.drain(); - expect((await f.host.snapshot()).owners.map(owner => owner.diagnostic.rng.draws)).toEqual([ - 1, 1, - ]); - }); - - test('alias receipts after later fills do not append observations, decisions or old effect journals', async () => { - const f = await fixture(); - await send(f.host, openInput()); - const quote = quoteInput(1); - quote.observations = markInput(1).observations; - quote.decision = { ...markInput(1).decision!, key: quote.command.key }; - await send(f.host, quote); - await send(f.host, quoteInput(2)); - const before = await f.host.snapshot(); - const journal = await f.host.journal(); - const alias = structuredClone(quote); - alias.command.commandId = 'old-quote-alias'; - await send(f.host, alias); - const after = await f.host.snapshot(); - expect(after.owners).toEqual(before.owners); - expect(after.account.observed).toBe(before.account.observed); - expect(after.account.view).toEqual(before.account.view); - expect(await f.host.journal()).toEqual(journal); - expect(after.account.checkpoint.receipts.length).toBe( - before.account.checkpoint.receipts.length + 1 - ); - }); - - test('exact quote cursor decisions never consume the same quote twice; only a later eligible quote fills', async () => { - const f = await fixture(); - await send(f.host, openInput()); - const quote = quoteInput(1); - quote.observations = markInput(1).observations; - quote.decision = { ...markInput(1).decision!, key: quote.command.key }; - await send(f.host, quote); - expect((await f.host.snapshot()).account.view.portfolio.positions).toHaveLength(0); - const alias = structuredClone(quote); - alias.command.commandId = 'quote-alias'; - await send(f.host, alias); - expect((await f.host.snapshot()).owners[0]!.diagnostic.nextDecisionSequence).toBe(1); - expect((await f.host.snapshot()).account.view.portfolio.positions).toHaveLength(0); - await send(f.host, quoteInput(2)); - expect((await f.host.snapshot()).account.view.portfolio.positions[0]!.quantity).toBe( - parseFinancialDecimal('2.00000000') - ); - }); - - test('version/config/seed/initial-state changes and legacy accounts explicitly refuse reinterpretation', async () => { - const f = await fixture(); - const changed = canonicalConfig(); - changed.risk.feeRate = '0.1'; - await expect(f.host.initialize(changed)).rejects.toThrow('configuration'); - for (const program of [ - { ...counterProgram(), seed: 8 }, - { ...counterProgram(), strategyVersion: '2' }, - { ...counterProgram(), initialState: { count: 1, samples: [], seen: [] } }, - ]) { - await expect(f.make({ programs: [program] })).rejects.toThrow('definition'); - } - await f.pool.query( - 'UPDATE simulation_accounts SET state = \'{"kind":"canonical-paper","version":99}\'' - ); - await expect(f.make()).rejects.toThrow('explicit migration'); - await f.pool.query('UPDATE simulation_accounts SET state = \'{"cash":100}\''); - await expect(f.make()).rejects.toThrow('explicit migration'); - }); - - test('future observations, wrong availability, direct submissions and out-of-order new commands cannot reach a callback', async () => { - let called = 0; - const program: StrategyProgram = { - ...counterProgram(), - decide(context) { - called++; - return counterProgram().decide(context); - }, - }; - const f = await fixture(canonicalConfig(), [program]); - await send(f.host, openInput()); - const future = markInput(1); - future.observations[0]!.available_at = 20; - expect(() => f.host.enqueue(future)).toThrow('unavailable'); - const submit: CanonicalPaperInput = { - command: { - commandId: 'bypass', - key: markInput(1).command.key, - body: { kind: 'submit', decisions: [] }, - }, - observations: [], - }; - expect(() => f.host.enqueue(submit)).toThrow('durable'); - const wrong = markInput(1); - wrong.decision!.inputs[0]!.availability = 'Missing'; - await f.host.enqueue(wrong); - await expect(f.host.drain()).rejects.toThrow('observation prefix'); - expect(called).toBe(0); - expect((await f.host.getRecoveryStatus()).pendingInput).toBe('mark-1'); - // Invalid trusted queued inputs are retained for diagnostics; correction requires an explicit new account/tape. - const g = await fixture(); - await send(g.host, openInput()); - await send(g.host, markInput(2)); - await g.host.enqueue(markInput(1)); - await expect(g.host.drain()).rejects.toThrow(); - expect((await g.host.snapshot()).owners[0]!.diagnostic.nextDecisionSequence).toBe(1); - }); - - test('corrupt envelope/context identities fail before callback or financial changes', async () => { - const f = await fixture(); - await send(f.host, openInput()); - const host = await f.make({ repository: failOnce(f.repository, 'putOwner', 'before') }); - await host.enqueue(markInput(1)); - await expect(host.drain()).rejects.toThrow('injected'); - // Stop after the input transaction, before the actual callback. - const g = await fixture(); - await send(g.host, openInput()); - const stop = await g.make({ - repository: failOnce( - g.repository, - 'appendJournal', - 'commit', - value => (value as { kind: string }).kind === 'decision' - ), - }); - await stop.enqueue(markInput(1)); - await expect(stop.drain()).rejects.toThrow('lost commit'); - const before = (await g.pool.query('SELECT state FROM simulation_accounts')).rows[0]!.state; - await g.pool.query( - `UPDATE simulation_strategy_journal SET payload = jsonb_set(payload, '{context,barrier,revision}', '999') WHERE payload->>'kind' = 'decision'` - ); - await expect(g.host.drain()).rejects.toThrow('no longer matches'); - expect((await g.pool.query('SELECT state FROM simulation_accounts')).rows[0]!.state).toEqual( - before - ); - await g.pool.query( - `UPDATE simulation_accounts SET state = jsonb_set(state, '{identity,sessionId}', '"corrupt"')` - ); - await expect(g.host.snapshot()).rejects.toThrow('identity or revision'); - }); - - test('GTC partial fill, DAY expiry and IOC/FOK policies survive restarts under next-event timing', async () => { - for (const tif of ['GTC', 'DAY', 'IOC', 'FOK'] as const) { - const f = await fixture(ordersConfig(), [explicitProgram(tif)]); - await send(f.host, openInput()); - await send(f.host, markInput(1)); - const restored = await f.make(); - await send(restored, quoteInput(1, '1')); - let snapshot = await restored.snapshot(); - const order = snapshot.account.checkpoint.orders[0]!; - expect(order.filled).toBe(parseFinancialDecimal(tif === 'FOK' ? '0.00000000' : '1.00000000')); - expect(order.status).toBe(tif === 'IOC' || tif === 'FOK' ? 'Cancelled' : 'Open'); - if (tif === 'GTC') { - const again = await f.make(); - await send(again, quoteInput(2)); - expect((await again.snapshot()).account.checkpoint.orders[0]!.status).toBe('Filled'); - } else if (tif === 'DAY') { - await send(restored, { - command: { - commandId: 'close', - key: { at: 10000, phase: 'SessionClose', instrumentId: 'X', sourceSequence: 0 }, - body: { kind: 'closeSession', sessionId: 'venue-1' }, - }, - observations: [], - }); - snapshot = await (await f.make()).snapshot(); - expect(snapshot.account.checkpoint.orders[0]!.status).toBe('Expired'); - } - } - }); - test('portfolio reservations enforce shared cash across owners before matching', async () => { - const config = canonicalConfig(['A', 'B']); - config.risk.ledger.initialCapital = '30'; - const f = await fixture(config, [counterProgram('A'), counterProgram('B')]); - await send(f.host, openInput()); - await send(f.host, markInput(1, ['A', 'B'])); - const admitted = await f.host.snapshot(); - expect(admitted.account.checkpoint.orders.map(order => order.status)).toEqual([ - 'Open', - { Rejected: 'InsufficientCash' }, - ]); - await send(await f.make(), quoteInput(1)); - const snapshot = await f.host.snapshot(); - expect(snapshot.account.view.portfolio.cash).toBe(parseFinancialDecimal('9.80000000')); - expect(snapshot.account.view.portfolio.positions.map(position => position.ownerId)).toEqual([ - 'A', - ]); - }); - - test('daily loss survives restart, allows reductions, and requires explicit risk-session rollover', async () => { - const config = canonicalConfig(); - config.risk.maxDailyLoss = '10'; - const program: StrategyProgram = { - ...counterProgram(), - decide(context) { - const next = counterProgram().decide(context); - return { - ...next, - intent: { - mode: 'target', - targets: [ - { - instrumentId: 'X', - quantity: parseFinancialDecimal(context.state.count === 1 ? '0' : '2'), - }, - ], - }, - }; - }, - }; - const f = await fixture(config, [program]); - await send(f.host, openInput()); - await send(f.host, markInput(1)); - await send(f.host, quoteInput(1)); - await send(f.host, markInput(2, ['A'], '1')); - expect((await f.host.snapshot()).account.view.risk.dailyHalted).toBe(true); - const restored = await f.make(); - await send(restored, quoteInput(2, '100', '1')); - await send(restored, markInput(3, ['A'], '1')); - expect((await restored.snapshot()).account.checkpoint.orders.at(-1)!.status).toEqual({ - Rejected: 'DailyLoss', - }); - await send(restored, { - command: { - commandId: 'risk-rollover', - key: { at: 40, phase: 'Observation', instrumentId: 'X', sourceSequence: 4 }, - body: { - kind: 'riskSessionBoundary', - riskSession: { - calendarId: 'account', - calendarRevision: '1', - sessionId: 'risk-2', - startsAt: 40, - }, - }, - }, - observations: [], - }); - await send(await f.make(), markInput(5, ['A'], '1')); - expect((await restored.snapshot()).account.checkpoint.orders.at(-1)!.status).toBe('Open'); - }); - - test('stale quotes never fill restored orders; GTC cancellation releases reservations durably', async () => { - const f = await fixture(); - await send(f.host, openInput()); - await send(f.host, markInput(1)); - const stale = quoteInput(201); - if (stale.command.body.kind !== 'execute' || stale.command.body.observation.kind !== 'quote') { - throw new Error('fixture'); - } - stale.command.body.observation.observedAt = 10; - await send(await f.make(), stale); - expect((await f.host.snapshot()).account.view.portfolio.positions).toHaveLength(0); - expect((await f.host.snapshot()).account.checkpoint.orders[0]!.status).toEqual({ - Rejected: 'StaleMark', - }); - await send(await f.make(), markInput(202)); - await send(await f.make(), quoteInput(202)); - expect((await f.host.snapshot()).account.view.portfolio.positions[0]!.quantity).toBe( - parseFinancialDecimal('2.00000000') - ); - const program: StrategyProgram = { - ...explicitProgram('GTC'), - decide(context) { - if (context.state.count === 0) { - return explicitProgram('GTC').decide(context); - } - return { - nextState: { count: context.state.count + 1, samples: [], seen: [] }, - intent: { mode: 'orders', orders: [{ kind: 'cancel', orderId: 'explicit-order' }] }, - }; - }, - }; - const g = await fixture(ordersConfig(), [program]); - await send(g.host, openInput()); - await send(g.host, markInput(1)); - await send(g.host, quoteInput(1, '1')); - const restart = await g.make(); - await send(restart, markInput(2)); - expect((await restart.snapshot()).account.checkpoint.orders[0]!.status).toBe('Cancelled'); - expect((await restart.snapshot()).account.view.reservations).toEqual([]); - await send(restart, quoteInput(2)); - expect((await restart.snapshot()).account.view.portfolio.positions[0]!.quantity).toBe( - parseFinancialDecimal('1.00000000') - ); - }); - - test('returned native Failed prefix commits exact fees/effects once and remains terminal across restart', async () => { - const max = '792281625142643375935.43950335'; - const config = canonicalConfig(['A', 'B']); - config.owners.forEach(owner => { - owner.mode = 'Orders'; - }); - config.risk.ledger.initialCapital = '100000000000000000000'; - for (const field of [ - 'maxOrderQuantity', - 'maxPositionQuantity', - 'maxSymbolExposure', - 'maxGrossExposure', - ] as const) { - config.risk[field] = max; - } - const programs: StrategyProgram[] = ['A', 'B'].map(ownerId => ({ - ...counterProgram(ownerId), - mode: 'orders', - decide(context) { - const order = (orderId: string, side: 'buy' | 'sell', quantity: string) => ({ - kind: 'market' as const, - orderId, - instrumentId: 'X', - side, - quantity: parseFinancialDecimal(quantity), - timeInForce: 'GTC' as const, - }); - return { - nextState: { count: context.state.count + 1, samples: [context.random()], seen: [] }, - intent: { - mode: 'orders', - orders: - context.state.count === 0 - ? ownerId === 'A' - ? [order('seed', 'buy', '1')] - : [] - : [ - ownerId === 'A' - ? order('sell', 'sell', '1') - : order('overflow', 'buy', '396140812571321687967'), - ], - }, - }; - }, - })); - const f = await fixture(config, programs); - await send(f.host, openInput()); - await send(f.host, markInput(1, ['A', 'B'], '0.00000001')); - await send(f.host, quoteInput(1, '1', '0.00000001')); - await send(f.host, markInput(2, ['A', 'B'], '0.00000001')); - const failure = quoteInput(2, max, '3'); - await f.host.enqueue(failure); - await expect(f.host.drain()).rejects.toThrow('Canonical account failed'); - const snapshot = await f.host.snapshot(); - const journal = await f.host.journal(); - expect(typeof snapshot.account.checkpoint.status).toBe('object'); - expect( - snapshot.account.checkpoint.orders.find(order => order.order.orderId === 'sell')!.status - ).toBe('Filled'); - expect(snapshot.account.view.portfolio.fees).toEqual([ - { ownerId: 'A', amount: parseFinancialDecimal('0.03000000') }, - { ownerId: 'B', amount: parseFinancialDecimal('0.00000000') }, - ]); - expect( - (await f.pool.query("SELECT status FROM simulation_market_inputs WHERE id = 'quote-2'")) - .rows[0]!.status - ).toBe('applied'); - const restored = await f.make(); - await expect(restored.drain()).rejects.toThrow('Canonical account failed'); - expect(await restored.enqueue(failure)).toBe(false); - await expect(restored.enqueue(quoteInput(3))).rejects.toThrow('terminal'); - expect(await restored.snapshot()).toEqual(snapshot); - expect(await restored.journal()).toEqual(journal); - // Native can return an old successful receipt while the authoritative current checkpoint is Failed. - const old = openInput().command; - const replay = parseFinancialTransactionResult( - stageFinancialTransaction( - JSON.stringify({ - version: 1, - kind: 'apply', - identity: snapshot.account.identity, - checkpoint: snapshot.account.checkpoint, - command: old, - }) - ), - snapshot.account.identity - ); - expect(replay.outcome!.status).toBe('Running'); - expect(replay.checkpoint.status).toEqual(snapshot.account.checkpoint.status); - expect(replay.journal).toEqual([]); - }); - test('canonical SMA checkpoint and buy/sell fills exactly match uninterrupted execution after replacement', async () => { - const selection = builtinStrategySelectionSchema.parse({ - ownerId: 'A', - strategyId: 'sma_crossover', - strategyVersion: 'sma-crossover-long-only/v1', - seed: 7, - instrumentId: 'X', - seriesId: 'X:quote', - ownerBudget: '20', - parameters: { fastPeriod: 2, slowPeriod: 3 }, - }); - const run = async (restart: boolean) => { - const f = await fixture(canonicalConfig(), [createBuiltinStrategy(selection)]); - let host = f.host; - await send(host, openInput()); - for (const [index, price] of ['3', '2', '1', '4', '5', '1', '1'].entries()) { - await send(host, markInput(index + 1, ['A'], price)); - if (restart) { - host = await f.make({ programs: [createBuiltinStrategy(selection)] }); - } - await send(host, quoteInput(index + 1, '100', price)); - } - return { snapshot: await host.snapshot(), journal: await host.journal() }; - }; - const uninterrupted = await run(false); - expect(await run(true)).toEqual(uninterrupted); - const filled = uninterrupted.snapshot.account.checkpoint.orders.filter( - order => order.status === 'Filled' - ); - expect(filled.some(order => order.order.side === 'buy')).toBe(true); - expect(filled.some(order => order.order.side === 'sell')).toBe(true); - }); - test('canonical regime strategy retains fractional entry cancellation and exit through every durable restart', async () => { - const selection = builtinStrategySelectionSchema.parse({ - ownerId: 'A', - strategyId: 'mean_reversion', - strategyVersion: 'mean-reversion-regime-long-only/v1', - seed: 7, - instrumentId: 'X', - seriesId: 'X:quote', - ownerBudget: '80', - parameters: { - lookbackPeriod: 2, - trendPeriod: 3, - momentumPeriod: 1, - volatilityPeriod: 2, - entryZScore: 1, - exitZScore: 0, - minTrendReturn: -0.5, - minMomentumReturn: -0.5, - maxVolatility: 1, - minNotionalVolume: '1', - regimeFilter: 'volatility', - }, - }); - const run = async (restart: boolean) => { - const f = await fixture(canonicalConfig(), [createBuiltinStrategy(selection)]); - let host = f.host; - await send(host, openInput()); - for (const [index, close] of ['10', '10', '8', '7', '10', '10'].entries()) { - const mark = markInput(index + 1, ['A'], close); - if (index >= 3) { - mark.observations[0]!.volume = parseFinancialDecimal('0'); - } - await send(host, mark); - if (restart) { - host = await f.make({ programs: [createBuiltinStrategy(selection)] }); - } - if (index === 3) { - expect((await host.snapshot()).owners[0]!.diagnostic.state).toMatchObject({ - targetQuantity: parseFinancialDecimal('0.5'), - }); - } - const price = ['10', '10', '7', '9', '11', '10'][index]!; - await send(host, quoteInput(index + 1, index === 2 ? '0.5' : '100', price)); - if (restart) { - host = await f.make({ programs: [createBuiltinStrategy(selection)] }); - } - } - return { snapshot: await host.snapshot(), journal: await host.journal() }; - }; - const uninterrupted = await run(false); - expect(await run(true)).toEqual(uninterrupted); - const view = uninterrupted.snapshot.account.view; - expect(view.portfolio.cash).toBe(parseFinancialDecimal('1001.91')); - expect(view.equity).toBe(parseFinancialDecimal('1001.91')); - const position = view.portfolio.positions.find(position => position.ownerId === 'A')!; - expect(position.quantity).toBe(parseFinancialDecimal('0')); - expect(position.remainingCost).toBe(parseFinancialDecimal('0')); - expect(position.realizedGrossPnl).toBe(parseFinancialDecimal('2')); - expect(view.portfolio.fees.find(fee => fee.ownerId === 'A')!.amount).toBe( - parseFinancialDecimal('0.09') - ); - }); - test('a native failed admission prefix atomically makes its durable batch terminal', async () => { - const max = '792281625142643375935.43950335'; - const config = ordersConfig(); - config.risk.ledger.initialCapital = max; - for (const field of [ - 'maxOrderQuantity', - 'maxPositionQuantity', - 'maxSymbolExposure', - 'maxGrossExposure', - ] as const) { - config.risk[field] = max; - } - const program: StrategyProgram = { - ...explicitProgram('GTC'), - decide(context) { - return { - nextState: { count: context.state.count + 1, samples: [context.random()], seen: [] }, - intent: { - mode: 'orders', - orders: ['1', max].map((quantity, index) => ({ - kind: 'market', - orderId: `order-${index}`, - instrumentId: 'X', - side: 'buy', - quantity: parseFinancialDecimal(quantity), - timeInForce: 'GTC', - })), - }, - }; - }, - }; - const f = await fixture(config, [program]); - await send(f.host, openInput()); - await f.host.enqueue(markInput(1)); - await expect(f.host.drain()).rejects.toThrow('Canonical account failed'); - const before = await f.host.snapshot(); - const journal = await f.host.journal(); - expect(typeof before.account.checkpoint.status).toBe('object'); - expect(before.owners[0]!.diagnostic.nextDecisionSequence).toBe(1); - expect( - (await f.pool.query('SELECT status FROM simulation_canonical_intents')).rows.map( - row => row.status - ) - ).toEqual(['failed']); - const restored = await f.make(); - await expect(restored.drain()).rejects.toThrow('Canonical account failed'); - expect(await restored.snapshot()).toEqual(before); - expect(await restored.journal()).toEqual(journal); - }); -}); diff --git a/test/postgres/canonical-research.test.ts b/test/postgres/canonical-research.test.ts deleted file mode 100644 index bc9def36..00000000 --- a/test/postgres/canonical-research.test.ts +++ /dev/null @@ -1,426 +0,0 @@ -import { 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 { getLogger, setLoggerConfig } from '@stock-bot/logger'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import { - canonicalResearchSettingsSchema, - canonicalRunRequestSchema, -} from '@stock-bot/stock-config/canonical-research'; -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 { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2'; -import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes'; -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 { canonicalDailyDataset, canonicalSettings } from '../fixtures/canonical-research'; -import { canonicalSmaFixture } from '../fixtures/canonical-sma'; -import { nativeReplayFixture } from '../fixtures/native-replay'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('canonical-admission'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const cleanup: (() => Promise)[] = []; -let packages: ReturnType | undefined; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); -async function fixture(dataset = canonicalSmaFixture().dataset) { - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Disposable safety database required'); - } - const schema = 'stock_bot_safety_canonical_api_' + randomUUID().replaceAll('-', ''); - const admin = new Pool({ connectionString: url }); - await admin.query(`CREATE SCHEMA ${schema}`); - const pool = new Pool({ - connectionString: url, - application_name: schema, - options: `-c search_path=${schema} -c statement_timeout=10000`, - }); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - for (const name of [ - '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') - ); - } - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, - logger - ); - Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); - Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); - const container = { postgres, logger }; - const api = new BacktestServiceV2(container); - const catalog = new StrategyCatalogService(container); - const pkg = (await (packages ??= packageBuiltinStrategies()))[0]!; - const version = await catalog.seedBuiltin('Retained SMA', pkg, 'seed'); - await retainResearchDataset(pool, dataset); - const definition = { - name: 'Canonical API', - strategy: 'catalog', - strategyVersionId: version.id, - strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, - symbols: dataset.manifest.executionSeries.map(s => s.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 }); - const approve = () => - catalog.reviewVersion( - version.id, - { decision: 'approve', reason: 'Reviewed retained builtin' }, - 'operator' - ); - const execute = async (id: string) => { - const engine = new RustBacktestAdapter({ - logger, - }); - const runner = new BacktestRunner({ - engine, - repository: new PostgresBacktestRunRepository(postgres), - logger, - }); - try { - await runner.runQueued(id); - } finally { - await runner.shutdown(); - } - }; - return { - pool, - schema, - api, - catalog, - pkg, - version, - draft, - definition, - dataset, - approve, - execute, - app: new Hono().route('/', createBacktestV2Routes(container)), - }; -} - -describe.skipIf(!url)('canonical research admission and saved evidence', () => { - test('approved exact artifact/policy/dataset admission, receipt replay and native results survive template and review changes', async () => { - const f = await fixture(); - expect((await f.api.canonicalCapability(f.draft.id)).available).toBe(false); - await expect(f.api.createRun({ backtestId: f.draft.id })).rejects.toThrow('approve'); - expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0); - await f.approve(); - expect(await f.api.canonicalCapability(f.draft.id)).toEqual({ available: true, reason: null }); - const receipt = { principal: 'operator' as const, key: 'original' }; - const run = await f.api.createRun({ backtestId: f.draft.id }, receipt); - const frozen = ( - await f.pool.query('SELECT request_snapshot,dataset_hash FROM runs WHERE id=$1', [run.id]) - ).rows[0]; - const request = canonicalRunRequestSchema.parse(frozen.request_snapshot); - expect(request.strategy.package).toEqual(f.pkg); - expect(request.datasetHash).toBe(f.dataset.manifest.hash); - expect(frozen.dataset_hash).toBe(request.datasetHash); - expect(run.dataset.state).toBe('pinned'); - expect(String(request.policy.matching.risk.ledger.initialCapital)).toBe('10000.00000000'); - await f.api.updateBacktest(f.draft.id, { - name: 'Changed', - strategyParameters: { fastPeriod: 3, slowPeriod: 5 }, - }); - await f.catalog.reviewVersion( - f.version.id, - { decision: 'revoke', reason: 'Block new admissions' }, - 'operator' - ); - await f.api.archiveBacktest(f.draft.id, true); - expect((await f.api.createRun({ backtestId: f.draft.id }, receipt)).id).toBe(run.id); - await expect(f.api.createRun({ backtestId: f.draft.id })).rejects.toThrow('archived'); - await f.execute(run.id); - const result = await f.api.getRunResults(run.id); - expect(result && 'kind' in result && result.kind).toBe('canonical-result/v1'); - if (!result || !('kind' in result)) { - throw new Error('Missing canonical result'); - } - expect(result.request).toEqual(request); - expect(String(result.financial.projection.valuation.equity)).toBe('9969.30000000'); - expect(result.financial.projection.fills).toHaveLength(2); - expect(result.analytics.metrics.roundTripCount).toBeNull(); - expect(result.analytics.unavailable.roundTripCount).toBe('unsupported-round-trips'); - expect(await f.api.getRunResults(run.id)).toEqual(result); - expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(1); - await expect( - f.pool.query('UPDATE backtest_results SET canonical_result=$1 WHERE run_id=$2', [{}, run.id]) - ).rejects.toThrow('Retained'); - }); - - test('exact non-midnight daily bounds and retained DST account boundaries are frozen', async () => { - const f = await fixture(canonicalDailyDataset()); - await f.approve(); - const run = await f.api.createRun({ backtestId: f.draft.id }); - const request = canonicalRunRequestSchema.parse( - (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [run.id])).rows[0] - .request_snapshot - ); - expect(request.policy.matching.risk.ledger.riskSession.startsAt).toBe( - Date.parse('2024-03-08T14:30:00Z') - ); - expect(request.policy.risk_boundaries[0]?.startsAt).toBe(Date.parse('2024-03-11T13:30:00Z')); - expect((await f.api.getBacktest(f.draft.id))?.startDate.toISOString()).toBe( - '2024-03-11T13:30:00.000Z' - ); - await expect( - f.api.updateBacktest(f.draft.id, { startDate: '2024-03-08T00:00:00Z' }) - ).rejects.toThrow('exact trade bounds'); - await f.execute(run.id); - const result = await f.api.getRunResults(run.id); - if (!result || !('kind' in result)) { - throw new Error('Missing canonical result'); - } - expect(result.analytics.metrics.exposureTime).toBe(0); - expect(result.analytics.metrics.totalReturn).toBe(0); - }); - - test('undeclared candidates, legacy settings, wrong asset/timeframe, multi-asset datasets and pacing never admit work', async () => { - const f = await fixture(); - await f.approve(); - const clone = await f.catalog.cloneVersion( - f.version.id, - { name: 'Candidate' }, - 'operator', - 'candidate' - ); - await f.catalog.reviewVersion( - clone.version.id, - { decision: 'approve', reason: 'Still untrusted' }, - 'operator' - ); - const candidate = await f.api.createBacktest( - { ...f.definition, strategyVersionId: clone.version.id }, - { autoStart: false } - ); - await expect(f.api.createRun({ backtestId: candidate.id })).rejects.toThrow( - 'Candidate requires a retained isolated execution declaration' - ); - await expect(f.api.createRun({ backtestId: f.draft.id, speedMultiplier: 2 })).rejects.toThrow( - 'maximum speed' - ); - for (const change of [ - { symbols: ['Y.US'] }, - { config: { ...f.definition.config, commission: 0.1 } }, - { config: { ...f.definition.config, dataFrequency: '1d' } }, - ]) { - await expect(f.api.updateBacktest(f.draft.id, change)).rejects.toThrow(); - } - const multi = nativeReplayFixture(5, 2).dataset; - await retainResearchDataset(f.pool, multi); - await expect( - f.api.updateBacktest(f.draft.id, { - config: { ...f.definition.config, datasetHash: multi.manifest.hash }, - }) - ).rejects.toThrow('one execution asset'); - expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0); - expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(0); - }); - - test('offline import is repeat-safe and rejects corruption; direct SQL cannot bypass snapshot/version binding', async () => { - const f = await fixture(); - await f.approve(); - await retainResearchDataset(f.pool, f.dataset); - expect((await f.pool.query('SELECT * FROM backtest_datasets')).rowCount).toBe(1); - const changed = { - ...f.dataset, - bars: f.dataset.bars.map((bar, index) => ({ - ...bar, - volume: bar.volume + (index === 0 ? 1 : 0), - })), - }; - await expect(retainResearchDataset(f.pool, changed)).rejects.toThrow(); - await expect( - f.pool.query('INSERT INTO runs(id,backtest_id,run_number) VALUES($1,$2,1)', [ - randomUUID(), - f.draft.id, - ]) - ).rejects.toThrow('canonical request'); - const run = await f.api.createRun({ backtestId: f.draft.id }); - const snapshot = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [run.id])) - .rows[0].request_snapshot; - const id = randomUUID(); - snapshot.runId = id; - snapshot.strategy.package.artifact.content += '\n/* forged */'; - await expect( - f.pool.query( - 'INSERT INTO runs(id,backtest_id,run_number,request_snapshot,dataset_hash,speed_multiplier) VALUES($1,$2,2,$3,$4,NULL)', - [id, f.draft.id, snapshot, f.dataset.manifest.hash] - ) - ).rejects.toThrow('exact approved'); - expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1); - }); - - test('extra series and malformed financial settings reject before saving or dispatching', async () => { - const f = await fixture(); - await f.approve(); - const { calendars, series, executionSeries, bounds, universe, corporateActions } = - f.dataset.manifest; - const extraId = 'X0.US:aux'; - const extra = createDatasetV2({ - metadata: { - calendars, - series: [...series, { ...series[0]!, id: extraId }], - executionSeries, - bounds, - universe, - corporateActions, - }, - bars: f.dataset.bars.flatMap( - ({ - instrumentId: _instrument, - eventTime: _event, - intervalEnd: _end, - intervalStart, - ...bar - }) => [ - { ...bar, timestamp: intervalStart }, - { ...bar, seriesId: extraId, timestamp: intervalStart }, - ] - ), - }); - await retainResearchDataset(f.pool, extra); - await expect( - f.api.updateBacktest(f.draft.id, { - config: { ...f.definition.config, datasetHash: extra.manifest.hash }, - }) - ).rejects.toThrow('one retained series'); - for (const change of [ - { config: { ...f.definition.config, canonical: { ...canonicalSettings, feeRate: '1e-3' } } }, - { - config: { ...f.definition.config, canonical: { ...canonicalSettings, ownerBudget: 'wat' } }, - }, - { initialCapital: 1e22 }, - { - config: { - ...f.definition.config, - canonical: { ...canonicalSettings, halfSpreadRate: '1' }, - }, - }, - { - config: { ...f.definition.config, canonical: { ...canonicalSettings, slippageRate: '1' } }, - }, - ]) { - const response = await f.app.request(`/api/v2/backtests/${f.draft.id}`, { - method: 'PUT', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify(change), - }); - expect(response.status).toBe(400); - } - for (const key of ['halfSpreadRate', 'slippageRate'] as const) { - expect( - canonicalResearchSettingsSchema.safeParse({ ...canonicalSettings, [key]: '0.99999999' }) - .success - ).toBe(true); - } - expect((await f.api.getBacktest(f.draft.id))?.config).toEqual(f.draft.config); - expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0); - }); - - test('concurrent approval revocation and admission follow the same family lock in either ordering', async () => { - for (const revokeFirst of [true, false]) { - const f = await fixture(); - await f.approve(); - const held = await f.pool.connect(); - await held.query('BEGIN'); - await held.query('SELECT id FROM strategies WHERE id=$1 FOR UPDATE', [f.version.strategyId]); - const waiters = async (count: number) => { - const deadline = Date.now() + 5000; - while (Date.now() < deadline) { - const waiting = await f.pool.query( - "SELECT count(*)::int AS count FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock'", - [f.schema] - ); - if (waiting.rows[0].count >= count) { - return; - } - await Bun.sleep(10); - } - throw new Error('Expected family row lock waiters'); - }; - const revoke = () => - f.catalog.reviewVersion( - f.version.id, - { decision: 'revoke', reason: 'Concurrent review' }, - 'operator' - ); - const admit = () => f.api.createRun({ backtestId: f.draft.id }); - const first = (revokeFirst ? revoke() : admit()).then( - value => ({ value }), - error => ({ error }) - ); - try { - await waiters(1); - const second = (revokeFirst ? admit() : revoke()).then( - value => ({ value }), - error => ({ error }) - ); - await waiters(2); - await held.query('COMMIT'); - const outcomes = await Promise.all([first, second]); - const admission = outcomes[revokeFirst ? 1 : 0]!; - const revocation = outcomes[revokeFirst ? 0 : 1]!; - expect('error' in revocation).toBe(false); - expect( - ( - await f.pool.query( - 'SELECT decision FROM strategy_review_events WHERE version_id=$1 ORDER BY ordinal DESC LIMIT 1', - [f.version.id] - ) - ).rows[0].decision - ).toBe('revoke'); - expect('error' in admission).toBe(revokeFirst); - if (revokeFirst && 'error' in admission) { - expect(String(admission.error)).toContain('approve'); - } - expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(revokeFirst ? 0 : 1); - if (!revokeFirst && 'value' in admission) { - await f.execute(admission.value.id); - expect((await f.api.getRun(admission.value.id))?.status).toBe('completed'); - } - } finally { - await held.query('ROLLBACK'); - held.release(); - } - } - }); -}); diff --git a/test/postgres/catalog-backtest-drafts.test.ts b/test/postgres/catalog-backtest-drafts.test.ts deleted file mode 100644 index 95a7bb91..00000000 --- a/test/postgres/catalog-backtest-drafts.test.ts +++ /dev/null @@ -1,384 +0,0 @@ -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 { getLogger, setLoggerConfig } from '@stock-bot/logger'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import { parseBacktestRequest } from '@stock-bot/stock-config/backtest'; -import type { StrategyVersionPackage } from '@stock-bot/types'; -import { LegacyBacktestRunWriter } from '../../apps/stock/orchestrator/src/backtest/compatibility/LegacyBacktestRunWriter'; -import { createBacktestRoutes } from '../../apps/stock/web-api/src/routes/backtest.routes'; -import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes'; -import { - BacktestServiceV2, - type BacktestRequest, -} from '../../apps/stock/web-api/src/services/backtest-v2.service'; -import { BacktestService } from '../../apps/stock/web-api/src/services/backtest.service'; -import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service'; -import { seedHistoricalRun } from '../fixtures/historical-run'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('catalog-draft-test'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const cleanup: (() => Promise)[] = []; -const sql = (name: string) => - readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8'); -const hash = (text: string) => createHash('sha256').update(text).digest('hex'); -function pkg(): StrategyVersionPackage { - const content = 'throw new Error("CANDIDATE_MUST_NOT_EXECUTE");'; - const lock = '{"lockfileVersion":1}'; - return { - version: 1, - program: { - strategyId: 'draft-fixture', - strategyVersion: 'v1', - apiVersion: 'canonical-ts/v1', - checkpointVersion: 'v1', - }, - artifact: { - format: 'esm-bundle/v1', - entryExport: 'createStrategy', - content, - sha256: hash(content), - }, - dependencyLock: { format: 'bun-lock/v1', content: lock, sha256: hash(lock) }, - parameterSchema: { - version: 1, - type: 'object', - additionalProperties: false, - required: [], - properties: { - commission: { type: 'number', minimum: 0, default: 0 }, - enabled: { type: 'boolean', default: false }, - budget: { type: 'string', default: '100.25' }, - lookback: { type: 'integer', minimum: 1, default: 3 }, - label: { type: 'string', default: 'πŸ“ˆ' }, - }, - }, - source: { revision: 'a'.repeat(40), dirty: false }, - build: { tool: 'bun', version: 'fixture', target: 'browser' }, - }; -} -const common = { - name: 'Catalog draft', - symbols: ['FIXTURE.TEST'], - startDate: '2024-01-01T00:00:00.000Z', - endDate: '2024-01-05T00:00:00.000Z', - initialCapital: 1000, - config: { commission: 0.001, slippage: 0, dataFrequency: '1d' }, -}; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); -async function fixture() { - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Dedicated safety database required'); - } - const schema = 'stock_bot_safety_drafts_' + randomUUID().replaceAll('-', ''); - const admin = new Pool({ connectionString: url }); - await admin.query(`CREATE SCHEMA ${schema}`); - const pool = new Pool({ - connectionString: url, - application_name: schema, - options: `-c search_path=${schema} -c statement_timeout=10000`, - }); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - for (const name of [ - '06-create-backtest-tables.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(sql(name)); - } - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, - logger - ); - Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); - Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); - const api = new BacktestServiceV2({ postgres, logger }); - const catalog = new StrategyCatalogService({ postgres, logger }); - const family = await catalog.createStrategy({ name: 'Candidate' }, 'operator'); - const version = await catalog.publishVersion(family.id, pkg(), null, 'operator', 'initial'); - const second = await catalog.publishVersion(family.id, pkg(), null, 'operator', 'second'); - const draft = () => ({ - ...common, - strategy: 'catalog', - strategyVersionId: version.id, - strategyParameters: {}, - }); - const app = new Hono() - .route('/', createBacktestV2Routes({ postgres, logger })) - .route('/', createBacktestRoutes({ postgres, logger })); - return { schema, pool, postgres, api, catalog, family, version, second, draft, app }; -} - -describe.skipIf(!url)('saved catalog backtest drafts on PostgreSQL', () => { - test('normalizes exact defaults and separates financial settings from arbitrary strategy parameter names', async () => { - const f = await fixture(); - const saved = await f.api.createBacktest(f.draft(), { autoStart: false }); - expect(saved.strategy).toBe('catalog'); - expect(saved.strategyVersionId).toBe(f.version.id); - expect(saved.strategyParameters).toEqual({ - commission: 0, - enabled: false, - budget: '100.25', - lookback: 3, - label: 'πŸ“ˆ', - }); - expect(saved.config.commission).toBe(0.001); - expect((await f.api.getBacktest(saved.id))?.strategyParameters).toEqual( - saved.strategyParameters! - ); - const edited = await f.api.updateBacktest(saved.id, { name: 'Edited' }); - expect(edited?.strategyVersionId).toBe(f.version.id); - expect(edited?.strategyParameters).toEqual(saved.strategyParameters!); - const revised = await f.api.updateBacktest(saved.id, { - strategyParameters: { - commission: 0.04, - enabled: false, - budget: '0.00', - lookback: 1, - label: '東京', - }, - }); - expect(revised?.config.commission).toBe(0.001); - expect(revised?.strategyParameters?.budget).toBe('0.00'); - expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0); - expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(0); - }); - - test('strict save-only input, version integrity and invalid parameters fail atomically', async () => { - const f = await fixture(); - for (const options of [{}, { autoStart: true }]) { - await expect(f.api.createBacktest(f.draft(), options)).rejects.toThrow('autoStart:false'); - } - const invalidInputs: BacktestRequest[] = [ - { ...f.draft(), strategyVersionId: null }, - { ...f.draft(), strategyParameters: null }, - { ...f.draft(), config: { ...common.config, lookback: 9 } }, - { ...f.draft(), strategyParameters: { unknown: 1 } }, - { ...f.draft(), strategyParameters: { lookback: 0 } }, - { ...f.draft(), strategyParameters: { enabled: 'false' } }, - { ...f.draft(), strategyParameters: { budget: 100.25 } }, - { ...f.draft(), strategyParameters: { label: 'bad\u0000text' } }, - { ...f.draft(), strategyParameters: { label: '\ud800' } }, - { ...f.draft(), strategyParameters: JSON.parse('{"__proto__":1}') }, - ]; - for (const input of invalidInputs) { - await expect(f.api.createBacktest(input, { autoStart: false })).rejects.toThrow(); - } - await expect( - f.api.createBacktest({ ...f.draft(), strategyVersionId: randomUUID() }, { autoStart: false }) - ).rejects.toMatchObject({ status: 404 }); - const corrupt = pkg(); - corrupt.artifact.content += 'changed'; - const invalidVersionId = randomUUID(); - await f.pool.query( - "INSERT INTO strategy_versions(id,strategy_id,ordinal,envelope,created_by,origin,submission_key,submission_fingerprint) VALUES($1,$2,3,$3,'operator','candidate','imported-corrupt',$4)", - [invalidVersionId, f.family.id, JSON.stringify(corrupt), 'f'.repeat(64)] - ); - await expect( - f.api.createBacktest( - { ...f.draft(), strategyVersionId: invalidVersionId }, - { autoStart: false } - ) - ).rejects.toThrow('hash mismatch'); - expect((await f.pool.query('SELECT * FROM backtests')).rows).toHaveLength(0); - }); - - test('partial edits retain selection, explicit changes require parameters, and neither mode silently converts', async () => { - const f = await fixture(); - const saved = await f.api.createBacktest(f.draft(), { autoStart: false }); - await expect( - f.api.updateBacktest(saved.id, { strategyVersionId: f.second.id }) - ).rejects.toThrow('explicit strategyParameters'); - await expect( - f.api.updateBacktest(saved.id, { strategyParameters: JSON.parse('{"__proto__":1}') }) - ).rejects.toThrow('Unsupported strategy metadata key'); - expect((await f.api.getBacktest(saved.id))?.strategyParameters?.lookback).toBe(3); - expect( - ( - await f.api.updateBacktest(saved.id, { - strategyVersionId: f.second.id, - strategyParameters: { lookback: 8 }, - }) - )?.strategyParameters?.lookback - ).toBe(8); - for (const update of [ - { strategy: 'sma-crossover' }, - { strategyVersionId: null }, - { strategyParameters: null }, - { strategyParameters: { lookback: -1 } }, - ]) { - await expect(f.api.updateBacktest(saved.id, update)).rejects.toThrow(); - } - expect((await f.api.getBacktest(saved.id))?.strategyVersionId).toBe(f.second.id); - const legacy = await f.api.createBacktest( - { ...common, strategy: 'sma-crossover' }, - { autoStart: false } - ); - await expect(f.api.updateBacktest(legacy.id, f.draft())).rejects.toThrow( - 'Retained strategy versions' - ); - await expect( - f.pool.query( - "UPDATE backtests SET strategy='sma-crossover',strategy_version_id=NULL,strategy_parameters=NULL WHERE id=$1", - [saved.id] - ) - ).rejects.toThrow('separate template'); - await expect( - f.pool.query( - "UPDATE backtests SET strategy='catalog',strategy_version_id=$2,strategy_parameters='{}' WHERE id=$1", - [legacy.id, f.version.id] - ) - ).rejects.toThrow('separate template'); - }); - - test('family archive serializes new selection while existing selected draft remains editable', async () => { - const f = await fixture(); - const saved = await f.api.createBacktest(f.draft(), { autoStart: false }); - const blocker = await f.pool.connect(); - await blocker.query('BEGIN'); - await blocker.query('SELECT id FROM strategies WHERE id=$1 FOR UPDATE', [f.family.id]); - const admission = f.api.createBacktest(f.draft(), { autoStart: false }).then( - () => null, - error => error - ); - let waiting = false; - for (let n = 0; n < 100; n++) { - if ( - ( - await f.pool.query( - "SELECT 1 FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock'", - [f.schema] - ) - ).rows.length - ) { - waiting = true; - break; - } - await new Promise(resolve => setTimeout(resolve, 10)); - } - expect(waiting).toBe(true); - await blocker.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [f.family.id]); - await blocker.query('COMMIT'); - blocker.release(); - expect(await admission).toMatchObject({ status: 409 }); - await expect( - f.api.updateBacktest(saved.id, { strategyVersionId: f.second.id, strategyParameters: {} }) - ).rejects.toMatchObject({ status: 409 }); - expect( - (await f.api.updateBacktest(saved.id, { strategyParameters: { lookback: 4 } })) - ?.strategyParameters?.lookback - ).toBe(4); - await f.api.archiveBacktest(saved.id, true); - await expect(f.api.updateBacktest(saved.id, { name: 'Blocked' })).rejects.toMatchObject({ - code: 'backtest_archived', - }); - }); - - test('all execution paths refuse catalog drafts and independent legacy receipts still replay unchanged', async () => { - const f = await fixture(); - const saved = await f.api.createBacktest(f.draft(), { autoStart: false }); - await expect(f.api.createRun({ backtestId: saved.id })).rejects.toMatchObject({ - code: 'catalog_execution_unavailable', - }); - const repository = new LegacyBacktestRunWriter(f.postgres); - const legacyConfig = parseBacktestRequest({ - ...common, - mode: 'backtest', - strategy: 'sma-crossover', - dataFrequency: '1d', - backtestId: saved.id, - }); - await expect(repository.start(legacyConfig)).rejects.toThrow('Catalog strategy execution'); - await expect( - repository.start({ ...legacyConfig, strategyVersionId: f.version.id } as typeof legacyConfig) - ).rejects.toThrow('Retained strategy versions'); - await expect( - f.pool.query( - "INSERT INTO runs(backtest_id,run_number,status,request_snapshot) VALUES($1,1,'pending','{}')", - [saved.id] - ) - ).rejects.toThrow('Catalog strategy execution'); - await expect( - new BacktestService({ postgres: f.postgres, logger }).createBacktest(f.draft()) - ).rejects.toThrow('Retained strategy versions'); - const legacy = await f.api.createBacktest( - { ...common, strategy: 'sma-crossover' }, - { autoStart: false } - ); - const receipt = { principal: 'operator' as const, key: 'legacy' }; - await expect(f.api.createRun({ backtestId: legacy.id }, receipt)).rejects.toThrow( - 'Legacy backtest execution is retired' - ); - const run = await seedHistoricalRun(f.pool, f.api, { backtestId: legacy.id }, receipt); - const before = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [run.id])) - .rows[0].request_snapshot; - await f.api.updateBacktest(legacy.id, { name: 'Later edit' }); - await f.api.archiveBacktest(legacy.id, true); - expect((await f.api.createRun({ backtestId: legacy.id }, receipt)).id).toBe(run.id); - expect( - (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [run.id])).rows[0] - .request_snapshot - ).toEqual(before); - expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(1); - expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1); - }); - - test('HTTP persisted selection reopens, malformed drafts reject, and v1 cannot save or run them', async () => { - const f = await fixture(); - const submit = (path: string, input: unknown) => - f.app.request(path, { method: 'POST', body: JSON.stringify(input) }); - for (const input of [ - f.draft(), - { ...f.draft(), autoStart: true }, - { ...f.draft(), autoStart: false, extra: true }, - ]) { - expect((await submit('/api/v2/backtests', input)).status).toBe(400); - } - expect((await submit('/api/backtests', f.draft())).status).toBe(400); - expect((await f.pool.query('SELECT * FROM backtests')).rows).toHaveLength(0); - const created = await submit('/api/v2/backtests', { ...f.draft(), autoStart: false }); - expect(created.status).toBe(201); - const saved = await created.json(); - expect(await (await f.app.request(`/api/v2/backtests/${saved.id}`)).json()).toMatchObject({ - strategyVersionId: f.version.id, - strategyParameters: { enabled: false, budget: '100.25' }, - }); - const denied = await submit(`/api/v2/backtests/${saved.id}/runs`, {}); - expect(denied.status).toBe(409); - expect(await denied.json()).toMatchObject({ code: 'catalog_execution_unavailable' }); - expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0); - await f.pool.query(sql('18-backtest-strategy-versions.sql')); - expect((await f.api.getBacktest(saved.id))?.strategyVersionId).toBe(f.version.id); - const fks = await f.pool.query( - "SELECT confdeltype FROM pg_constraint WHERE conrelid='backtests'::regclass AND conname='backtests_strategy_version_id_fkey'" - ); - expect(fks.rows[0].confdeltype).toBe('r'); - await expect( - f.pool.query('DELETE FROM strategy_versions WHERE id=$1', [f.version.id]) - ).rejects.toThrow(); - }); -}); diff --git a/test/postgres/chronological-validation-durable.test.ts b/test/postgres/chronological-validation-durable.test.ts deleted file mode 100644 index 77d47805..00000000 --- a/test/postgres/chronological-validation-durable.test.ts +++ /dev/null @@ -1,924 +0,0 @@ -import { 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 { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research'; -import type { - ChronologicalValidationInput, - ChronologicalValidationPreview, -} from '@stock-bot/stock-config/chronological-validation'; -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 { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service'; -import { experimentHash } from '../../apps/stock/web-api/src/services/experiment-input'; -import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service'; -import { createResearchServices } from '../../apps/stock/web-api/src/services/research-services'; -import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service'; -import { - selectValidationWinner, - validationEqual, - validationEvidence, - validationPhasePreview, -} from '../../apps/stock/web-api/src/services/validation-evidence'; -import { retainResearchDataset } from '../../scripts/import-research-dataset'; -import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies'; -import { canonicalSettings } from '../fixtures/canonical-research'; -import { chronologicalDataset } from '../fixtures/chronological-validation'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('chronological-validation'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const cleanup: (() => Promise)[] = []; -let packages: ReturnType | undefined; -const tokens = { - operator: 'chronological-operator-fixture-not-a-real-secret-1234', - service: 'chronological-service-fixture-not-a-real-secret-1234', -}; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); -async function fixture(poolMax = 1, withValidation = true) { - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Disposable safety database required'); - } - const schema = 'stock_bot_safety_validation_' + randomUUID().replaceAll('-', ''); - const admin = new Pool({ connectionString: url }); - await admin.query(`CREATE SCHEMA ${schema}`); - // A single connection detects accidental nested pool reads while the admission lock is held. - const pool = new Pool({ - connectionString: url, - application_name: schema, - max: poolMax, - options: `-c search_path=${schema} -c statement_timeout=10000`, - }); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - for (const name of [ - '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', - ...(withValidation - ? ['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') - ); - } - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, - logger - ); - Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); - Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); - const container = { postgres, logger }, - api = new BacktestServiceV2(container), - experiments = new ExperimentsService(container), - catalog = new StrategyCatalogService(container); - const version = await catalog.seedBuiltin( - 'Validation SMA', - (await (packages ??= packageBuiltinStrategies()))[0]!, - 'seed' - ); - const data = chronologicalDataset(), - dataset = data.dataset; - await retainResearchDataset(pool, dataset); - const draft = await api.createBacktest( - { - name: 'Validation template', - strategy: 'catalog', - strategyVersionId: version.id, - strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, - symbols: ['X0.US'], - startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(), - endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(), - initialCapital: 10000, - config: { - datasetHash: dataset.manifest.hash, - dataFrequency: '1m', - canonical: canonicalSettings, - }, - }, - { autoStart: false } - ); - const input: ChronologicalValidationInput = { - backtestId: draft.id, - name: 'Three explicit windows', - grid: { fastPeriod: [1, 2], slowPeriod: [3] }, - recipe: data.recipe, - }; - const app = new Hono(); - createHttpSecurity({ - adminToken: tokens.operator, - serviceToken: tokens.service, - environment: 'test', - hostname: '127.0.0.1', - }).mount(app); - app.route('/', createExperimentRoutes(container)); - const request = (raw: unknown = input, role: keyof typeof tokens = 'operator') => - app.request('/api/v2/experiments/validation/preview', { - method: 'POST', - headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${tokens[role]}` }, - body: JSON.stringify(raw), - }); - const review = async (decision: 'approve' | 'revoke' = 'approve') => { - await catalog.reviewVersion( - version.id, - { decision, reason: 'Disposable validation proof' }, - 'operator' - ); - return (await catalog.getVersionReviews(version.id)).at(-1)!; - }; - const snapshot = async () => { - const tables = ( - await pool.query('SELECT tablename FROM pg_tables WHERE schemaname=$1 ORDER BY tablename', [ - schema, - ]) - ).rows; - const rows: Record = {}; - for (const { tablename } of tables) { - const quoted = '"' + String(tablename).replaceAll('"', '""') + '"'; - rows[String(tablename)] = ( - await pool.query( - `SELECT COALESCE(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text),'[]'::jsonb) AS rows FROM ${quoted} t` - ) - ).rows[0].rows; - } - return rows; - }; - const validations = createResearchServices(container).validations; - const repository = new PostgresBacktestRunRepository(postgres); - const execute = async (id: string) => { - const engine = new RustBacktestAdapter({ - logger, - }); - const runner = new BacktestRunner({ engine, repository, logger }); - try { - await runner.runQueued(id); - } finally { - await runner.shutdown(); - } - }; - return { - cloneTemplate: async (sourceDataset = dataset) => - api.createBacktest( - { - name: 'Other validation template', - strategy: 'catalog', - strategyVersionId: version.id, - strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, - symbols: ['X0.US'], - startDate: new Date(sourceDataset.manifest.bounds.tradeStart).toISOString(), - endDate: new Date(sourceDataset.manifest.bounds.tradeEnd).toISOString(), - initialCapital: 10000, - config: { - datasetHash: sourceDataset.manifest.hash, - dataFrequency: '1m', - canonical: canonicalSettings, - }, - }, - { autoStart: false } - ), - validations, - repository, - execute, - api, - pool, - postgres, - experiments, - catalog, - version, - draft, - dataset, - input, - request, - review, - snapshot, - }; -} - -const actor = (key = randomUUID()) => ({ principal: 'operator' as const, key }); -async function submit(f: Awaited>, key = randomUUID()) { - await f.review(); - const preview = await f.experiments.previewValidation(f.input); - const body = { ...f.input, previewHash: preview.previewHash }, - identity = actor(key); - return { preview, body, identity, validation: await f.validations.submit(body, identity) }; -} -async function train(f: Awaited>, id: string) { - const detail = await f.validations.get(id); - for (const trial of detail.phases[0].experiment!.trials) { - await f.execute(trial.runId!); - } -} - -describe.skipIf(!url)('durable chronological validation', () => { - test('native trainingβ†’write-once winnerβ†’same-winner holdoutsβ†’historical report and immutable receipt reopen', async () => { - const f = await fixture(), - start = await submit(f), - id = start.validation.id; - expect(start.validation.name).toBe(f.input.name); - expect(start.validation.phases.map(p => p.status)).toEqual([ - 'admitted', - 'not-admitted', - 'not-admitted', - ]); - expect(start.validation.phases[0].experiment!.name).toBe(f.input.name + ' Β· train'); - expect(await f.experiments.list()).toEqual([]); - expect((await f.validations.list())[0]!.id).toBe(id); - expect(await f.validations.submit(start.body, start.identity)).toEqual(start.validation); - await expect( - f.validations.select(id, { previewHash: start.preview.previewHash }, actor()) - ).rejects.toThrow('Every train'); - await train(f, id); - const before = await f.validations.get(id); - expect(before.actions.select.available).toBe(true); - const newest = await f.review(); - await f.pool.query( - 'UPDATE backtests SET name=\'Changed template\',strategy_parameters=\'{"fastPeriod":1,"slowPeriod":4}\' WHERE id=$1', - [f.draft.id] - ); - const selectActor = actor(), - selectBody = { previewHash: start.preview.previewHash }; - const selected = await f.validations.select(id, selectBody, selectActor); - expect(selected.receipt.operation).toBe('select-and-admit-holdouts'); - const selection = selected.validation.selection!; - expect(selection.training.map(e => e.sourceCandidateIndex)).toEqual([0, 1]); - expect(selection.reviewId).toBe(newest.id); - expect(selection.training.every(e => e.metrics.totalReturn !== null)).toBe(true); - const ranked = [...selection.training].sort( - (a, b) => - b.metrics.totalReturn! - a.metrics.totalReturn! || - a.sourceCandidateIndex - b.sourceCandidateIndex - ); - expect(selection.winner.index).toBe(ranked[0]!.sourceCandidateIndex); - for (const phase of selected.validation.phases.slice(1)) { - expect(phase.experiment!.trials).toHaveLength(1); - expect(phase.experiment!.name).toBe(f.input.name + ' Β· ' + phase.phase); - expect(phase.experiment!.preview.request.strategy.reviewId).toBe(newest.id); - expect( - validationEqual( - phase.experiment!.preview.request.strategy.selection.parameters, - selection.winner.parameters - ) - ).toBe(true); - expect(phase.experiment!.preview.request.name).toBe(start.preview.source.request.name); - await f.execute(phase.experiment!.trials[0]!.runId!); - } - expect((await f.validations.select(id, selectBody, selectActor)).receipt).toEqual( - selected.receipt - ); - await expect(f.validations.select(id, selectBody, actor())).rejects.toThrow('another receipt'); - await f.review('revoke'); - await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [ - f.version.strategyId, - ]); - await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]); - const finalActor = actor(), - finalBody = { - previewHash: start.preview.previewHash, - selectionHash: selection.selectionHash, - }; - const finalized = await f.validations.finalize(id, finalBody, finalActor), - report = finalized.validation.report!; - expect(report.training).toEqual(selection.training); - expect(report.validation.sourceCandidateIndex).toBe(selection.winner.index); - expect(report.test.sourceCandidateIndex).toBe(selection.winner.index); - expect(report.validation.parameters).toEqual(report.test.parameters); - expect(report.reset).toBe('initial-capital-empty-positions'); - expect(finalized.validation.stage).toBe('reported'); - expect((await f.validations.get(id)).report).toEqual(report); - await f.validations.cancel(id); - expect((await f.validations.finalize(id, finalBody, finalActor)).receipt).toEqual( - finalized.receipt - ); - expect((await f.validations.select(id, selectBody, selectActor)).receipt).toEqual( - selected.receipt - ); - expect((await f.validations.submit(start.body, start.identity)).id).toBe(id); - await expect(f.validations.finalize(id, finalBody, actor())).rejects.toThrow('another receipt'); - expect((await f.pool.query('SELECT count(*)::int AS n FROM runs')).rows[0].n).toBe(4); - expect( - (await f.pool.query('SELECT count(*)::int AS n FROM research_experiments')).rows[0].n - ).toBe(3); - for (const field of [ - 'validation_manifest', - 'validation_selection', - 'validation_report', - 'validation_phase', - ]) { - await expect( - f.pool.query(`UPDATE research_experiments SET ${field}=NULL WHERE id=$1`, [id]) - ).rejects.toThrow(); - } - }, 60_000); - test('ordinary and direct SQL cancellation latch the whole workflow, including pending heldout claims', async () => { - const f = await fixture(), - first = await submit(f); - await f.experiments.cancel(first.validation.id); - expect( - (await f.validations.get(first.validation.id)).phases[0].experiment!.trials.every( - t => t.status === 'cancelled' - ) - ).toBe(true); - await expect( - f.validations.select(first.validation.id, { previewHash: first.preview.previewHash }, actor()) - ).rejects.toThrow('uncancelled'); - const second = await submit(f); - await train(f, second.validation.id); - const selected = await f.validations.select( - second.validation.id, - { previewHash: second.preview.previewHash }, - actor() - ); - await f.pool.query('UPDATE research_experiments SET cancel_requested=TRUE WHERE id=$1', [ - second.validation.id, - ]); - const detail = await f.validations.get(second.validation.id); - expect(detail.phases.every(p => p.experiment!.cancelRequested)).toBe(true); - for (const child of selected.validation.phases.slice(1)) { - const id = child.experiment!.trials[0]!.runId!; - await f.execute(id); - expect((await f.pool.query('SELECT status FROM runs WHERE id=$1', [id])).rows[0].status).toBe( - 'cancelled' - ); - } - await expect( - f.validations.finalize( - detail.id, - { previewHash: detail.previewHash, selectionHash: detail.selection!.selectionHash }, - actor() - ) - ).rejects.toThrow('uncancelled'); - await expect( - f.pool.query('UPDATE research_experiments SET cancel_requested=FALSE WHERE id=$1', [ - detail.id, - ]) - ).rejects.toThrow(); - }, 60_000); - test('a corrupted heldout dataset or numerically forged training analytics cannot seal selection', async () => { - const f = await fixture(), - start = await submit(f); - await train(f, start.validation.id); - const heldout = start.preview.partitions[1].dataset.hash; - await f.pool.query('ALTER TABLE backtest_datasets DISABLE TRIGGER USER'); - await f.pool.query( - "UPDATE backtest_datasets SET payload=jsonb_set(payload,'{bars,0,close}','999') WHERE hash=$1", - [heldout] - ); - await expect( - f.validations.select(start.validation.id, { previewHash: start.preview.previewHash }, actor()) - ).rejects.toThrow('content validation'); - expect((await f.validations.get(start.validation.id)).selection).toBeNull(); - const sourceDataset = ( - await f.pool.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [ - start.preview.source.dataset.hash, - ]) - ).rows[0].payload; - const { prepareChronologicalValidation } = await import( - '../../apps/stock/web-api/src/services/validation-preview' - ); - const prepared = prepareChronologicalValidation(f.input, start.preview.source, sourceDataset); - await f.pool.query('UPDATE backtest_datasets SET payload=$2 WHERE hash=$1', [ - heldout, - prepared.datasets.validation, - ]); - const runId = start.validation.phases[0].experiment!.trials[0]!.runId!; - await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER'); - await f.pool.query( - "UPDATE backtest_results SET canonical_result=jsonb_set(canonical_result,'{analytics,metrics,totalReturn}','900') WHERE run_id=$1", - [runId] - ); - await expect( - f.validations.select(start.validation.id, { previewHash: start.preview.previewHash }, actor()) - ).rejects.toThrow('analytics validation'); - expect((await f.validations.get(start.validation.id)).selection).toBeNull(); - expect( - (await f.pool.query('SELECT count(*)::int AS n FROM research_experiments')).rows[0].n - ).toBe(1); - }, 60_000); -}); - -async function selectionDocument(f: Awaited>, validationId: string) { - const detail = await f.validations.get(validationId), - training = []; - for (const trial of detail.phases[0].experiment!.trials) { - const result = (await f.api.getRunResults(trial.runId!)) as CanonicalRunResult; - training.push(validationEvidence('train', validationId, trial, trial.index, result)); - } - const manifest = { - version: 'chronological-validation-selection/v1' as const, - id: randomUUID(), - validationId, - previewHash: detail.previewHash, - createdAt: new Date().toISOString(), - principal: 'operator' as const, - reviewId: (await f.catalog.getVersionReviews(f.version.id)).at(-1)!.id, - winner: selectValidationWinner(detail.preview.source.candidates, training), - training, - holdoutExperimentIds: { validation: randomUUID(), test: randomUUID() }, - }; - return { - ...manifest, - selectionHash: experimentHash(manifest), - _receipt: { key: randomUUID(), hash: 'a'.repeat(64) }, - }; -} - -describe.skipIf(!url)('durable validation adversarial boundaries', () => { - test('first/idempotent SQL24 upgrade preserves ordinary requests/results/receipts and active leases', async () => { - const f = await fixture(1, false); - await f.review(); - const ordinaryInput = { - backtestId: f.draft.id, - name: 'Existing ordinary sweep', - grid: { fastPeriod: [1, 2] }, - }; - const preview = await f.experiments.preview(ordinaryInput); - const ordinary = await f.experiments.submit( - { ...ordinaryInput, previewHash: preview.previewHash }, - actor() - ); - // Missing historical role metadata must remain readable without admitting a source citation. - expect(ordinary.standalone).toBe(false); - await f.execute(ordinary.trials[0]!.runId!); - const pending = ordinary.trials[1]!.runId!, - request = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [pending])) - .rows[0].request_snapshot; - await f.repository.startCanonical(request); - const before = await f.snapshot(); - const names = [ - 'require_active_backtest_for_new_run', - 'require_experiment_retry_failure', - 'guard_manual_trial_retry', - 'require_consumed_trial_retry', - ]; - const functionBodies = async () => - ( - await f.pool.query( - 'SELECT proname,pg_get_functiondef(oid) AS definition FROM pg_proc WHERE pronamespace=current_schema()::regnamespace AND proname=ANY($1) ORDER BY proname', - [names] - ) - ).rows; - const priorFunctions = await functionBodies(); - const migration = readFileSync( - new URL('../../database/postgres/init/24-chronological-validation.sql', import.meta.url), - 'utf8' - ); - await f.pool.query(migration); - const after = await f.snapshot(); - after.research_experiments = (after.research_experiments as Record[]).map( - ({ - validation_manifest: _manifest, - validation_parent_id: _parent, - validation_phase: _phase, - validation_selection: _selection, - validation_report: _report, - ...row - }) => row - ); - expect(after).toEqual(before); - expect(await functionBodies()).toEqual(priorFunctions); - const first = await f.snapshot(); - await f.pool.query(migration); - expect(await f.snapshot()).toEqual(first); - expect((await f.experiments.list())[0]!.id).toBe(ordinary.id); - expect((await f.experiments.get(ordinary.id)).standalone).toBe(true); - // Current chronological admission can link roots to a walk-forward series. - await f.pool.query( - readFileSync( - new URL('../../database/postgres/init/25-walk-forward.sql', import.meta.url), - 'utf8' - ) - ); - const current = await submit(f); - expect(current.validation.stage).toBe('training'); - expect( - (await f.pool.query('SELECT status,attempt_number FROM runs WHERE id=$1', [pending])).rows[0] - ).toMatchObject({ status: 'running', attempt_number: 1 }); - }, 60_000); - test('SQL independently rejects mixed shapes, changed source/slice/policy, premature or incorrect winners and incomplete commits', async () => { - const f = await fixture(), - start = await submit(f), - id = start.validation.id; - const sourceRow = (await f.pool.query('SELECT * FROM research_experiments WHERE id=$1', [id])) - .rows[0]; - const insertRoot = async ( - manifest: ChronologicalValidationPreview, - phase: string | null = 'train' - ) => { - const trainPreview = validationPhasePreview(manifest, 'train'); - return f.pool.query( - `INSERT INTO research_experiments(id,backtest_id,name,preview,preview_hash,submission_principal,submission_key,submission_hash,validation_manifest,validation_phase) - VALUES($1,$2,$3,$4,$5,'operator',$6,$7,$8,$9)`, - [ - randomUUID(), - f.draft.id, - trainPreview.input.name, - trainPreview, - trainPreview.previewHash, - randomUUID(), - 'a'.repeat(64), - manifest, - phase, - ] - ); - }; - for (const mutate of [ - (p: ChronologicalValidationPreview) => { - p.source.request.policy.matching.risk.feeRate = - '0.02000000' as typeof p.source.request.policy.matching.risk.feeRate; - }, - (p: ChronologicalValidationPreview) => { - p.partitions[0].request.policy.matching.risk.maxGrossExposure = - '999999.00000000' as (typeof p.partitions)[0]['request']['policy']['matching']['risk']['maxGrossExposure']; - }, - (p: ChronologicalValidationPreview) => { - p.partitions[0].counts.admittedWarmup++; - }, - (p: ChronologicalValidationPreview) => { - p.partitions[0].dataset = structuredClone(p.source.dataset); - }, - (p: ChronologicalValidationPreview) => { - p.input.recipe.train.tradeStart++; - }, - (p: ChronologicalValidationPreview) => { - p.source.candidates[0]!.parameters.fastPeriod = 99; - }, - ]) { - const manifest = structuredClone(start.preview); - mutate(manifest); - await expect(insertRoot(manifest)).rejects.toThrow(); - } - await expect(insertRoot(start.preview, null)).rejects.toThrow(); - // A correct root without its run/outbox set fails at COMMIT, not merely at service validation. - await expect(insertRoot(start.preview)).rejects.toThrow('complete exact run'); - expect( - (await f.pool.query('SELECT count(*)::int AS n FROM research_experiments')).rows[0].n - ).toBe(1); - await train(f, id); - const correct = await selectionDocument(f, id); - for (const mutate of [ - (s: typeof correct) => { - s.winner = structuredClone(start.preview.source.candidates[1 - correct.winner.index]!); - }, - (s: typeof correct) => { - s.training[0]!.metrics.totalReturn = 999; - }, - (s: typeof correct) => { - s.training.reverse(); - }, - (s: typeof correct) => { - s.training.pop(); - }, - (s: typeof correct) => { - s.training[0]!.datasetHash = start.preview.partitions[1].dataset.hash; - }, - ]) { - const changed = structuredClone(correct); - mutate(changed); - await expect( - f.pool.query('UPDATE research_experiments SET validation_selection=$2 WHERE id=$1', [ - id, - changed, - ]) - ).rejects.toThrow(); - } - await expect( - f.pool.query('UPDATE research_experiments SET validation_selection=$2 WHERE id=$1', [ - id, - correct, - ]) - ).rejects.toThrow('atomically admit both'); - expect((await f.validations.get(id)).selection).toBeNull(); - expect( - ( - await f.pool.query('SELECT preview,submission_key FROM research_experiments WHERE id=$1', [ - id, - ]) - ).rows[0] - ).toEqual({ preview: sourceRow.preview, submission_key: sourceRow.submission_key }); - }, 60_000); - test('injected training/outbox/second-holdout insert failures roll back every new input, receipt and selection', async () => { - const f = await fixture(); - await f.review(); - const preview = await f.experiments.previewValidation(f.input), - body = { ...f.input, previewHash: preview.previewHash }; - const fail = async (table: string, name: string, condition: string) => { - await f.pool.query( - `CREATE OR REPLACE FUNCTION ${name}() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF ${condition} THEN RAISE EXCEPTION 'Injected ${name}'; END IF; RETURN NEW; END $$` - ); - await f.pool.query( - `CREATE TRIGGER ${name} BEFORE INSERT ON ${table} FOR EACH ROW EXECUTE FUNCTION ${name}()` - ); - }; - for (const [table, condition] of [ - ['runs', 'NEW.trial_index=1'], - ['backtest_dispatch', 'TRUE'], - ]) { - await fail(table!, 'injected_root_failure', condition!); - const before = await f.snapshot(); - await expect(f.validations.submit(body, actor())).rejects.toThrow('Injected'); - expect(await f.snapshot()).toEqual(before); - await f.pool.query(`DROP TRIGGER injected_root_failure ON ${table}`); - } - const root = await f.validations.submit(body, actor()); - await train(f, root.id); - await fail('research_experiments', 'injected_holdout_failure', "NEW.validation_phase='test'"); - const before = await f.snapshot(); - await expect( - f.validations.select(root.id, { previewHash: preview.previewHash }, actor()) - ).rejects.toThrow('Injected'); - expect(await f.snapshot()).toEqual(before); - await f.pool.query('DROP TRIGGER injected_holdout_failure ON research_experiments'); - expect( - (await f.validations.select(root.id, { previewHash: preview.previewHash }, actor())) - .validation.phases - ).toHaveLength(3); - }, 60_000); - test('same and cross-parent receipt races have exactly one atomic owner; conflicting intent never gains children', async () => { - const f = await fixture(5); - await f.review(); - const preview = await f.experiments.previewValidation(f.input), - body = { ...f.input, previewHash: preview.previewHash }, - same = actor(); - const [first, replay] = await Promise.all([ - f.validations.submit(body, same), - f.validations.submit(body, same), - ]); - expect(first.id).toBe(replay.id); - const other = await f.cloneTemplate(), - otherInput = { ...f.input, backtestId: other.id }; - const otherPreview = await f.experiments.previewValidation(otherInput), - otherBody = { ...otherInput, previewHash: otherPreview.previewHash }; - const key = actor(), - results = await Promise.allSettled([ - f.validations.submit(body, key), - f.validations.submit(otherBody, key), - ]); - expect(results.filter(r => r.status === 'fulfilled')).toHaveLength(1); - expect(results.filter(r => r.status === 'rejected')).toHaveLength(1); - const second = await f.validations.submit(otherBody, actor()); - await train(f, first.id); - await train(f, second.id); - const action = actor(), - selections = await Promise.allSettled([ - f.validations.select(first.id, { previewHash: preview.previewHash }, action), - f.validations.select(second.id, { previewHash: otherPreview.previewHash }, action), - ]); - expect(selections.filter(r => r.status === 'fulfilled')).toHaveLength(1); - expect(selections.filter(r => r.status === 'rejected')).toHaveLength(1); - const selectedRoot = selections[0]!.status === 'fulfilled' ? first : second; - const selectedBody = { previewHash: selectedRoot.previewHash }; - const a = await f.validations.select(selectedRoot.id, selectedBody, action); - const [b, c] = await Promise.all([ - f.validations.select(selectedRoot.id, selectedBody, action), - f.validations.select(selectedRoot.id, selectedBody, action), - ]); - expect(b.receipt).toEqual(a.receipt); - expect(c.receipt).toEqual(a.receipt); - expect( - ( - await f.pool.query( - "SELECT count(*)::int AS n FROM research_experiments WHERE validation_phase IN ('validation','test')" - ) - ).rows[0].n - ).toBe(2); - }, 60_000); - test('failed training and holdout trials reuse existing manual retry receipts and immutable requests', async () => { - const f = await fixture(), - start = await submit(f), - training = start.validation.phases[0].experiment!.trials[0]!, - runId = training.runId!; - const request = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])) - .rows[0].request_snapshot; - const claim = await f.repository.startCanonical(request); - await f.repository.fail(runId, 'Training fixture failure', claim.attemptId); - await expect( - f.validations.select(start.validation.id, { previewHash: start.preview.previewHash }, actor()) - ).rejects.toThrow('Every train'); - await f.experiments.retryTrial( - start.validation.id, - runId, - { expectedAttemptNumber: 1, expectedRetryCount: 0 }, - actor() - ); - await train(f, start.validation.id); - await expect(f.repository.heartbeat(runId, claim.attemptId)).rejects.toThrow(); - const selected = await f.validations.select( - start.validation.id, - { previewHash: start.preview.previewHash }, - actor() - ), - child = selected.validation.phases[1].experiment!, - childRun = child.trials[0]!.runId!; - await f.pool.query( - "UPDATE runs SET status='failed',error='Before claim',completed_at=NOW() WHERE id=$1", - [childRun] - ); - await f.experiments.retryTrial( - child.id, - childRun, - { expectedAttemptNumber: 0, expectedRetryCount: 0 }, - actor() - ); - await f.execute(childRun); - await f.execute(selected.validation.phases[2].experiment!.trials[0]!.runId!); - const saved = await f.validations.finalize( - start.validation.id, - { - previewHash: start.preview.previewHash, - selectionHash: selected.validation.selection!.selectionHash, - }, - actor() - ); - expect(saved.validation.report).not.toBeNull(); - expect( - (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])).rows[0] - .request_snapshot - ).toEqual(request); - expect( - (await f.experiments.listTrialRetries(start.validation.id, runId))[0]!.previousAttemptNumber - ).toBe(1); - expect( - (await f.experiments.listTrialRetries(child.id, childRun))[0]!.previousAttemptNumber - ).toBe(0); - }, 60_000); -}); - -describe.skipIf(!url)('durable validation isolation proofs', () => { - test('selection racing direct SQL cancellation leaves no live orphan holdout work', async () => { - const f = await fixture(4), - start = await submit(f); - await train(f, start.validation.id); - const outcomes = await Promise.allSettled([ - f.validations.select( - start.validation.id, - { previewHash: start.preview.previewHash }, - actor() - ), - f.pool.query('UPDATE research_experiments SET cancel_requested=TRUE WHERE id=$1', [ - start.validation.id, - ]), - ]); - expect(outcomes[1]!.status).toBe('fulfilled'); - const detail = await f.validations.get(start.validation.id); - expect(detail.cancelRequested).toBe(true); - const children = ( - await f.pool.query( - 'SELECT id,cancel_requested FROM research_experiments WHERE validation_parent_id=$1', - [detail.id] - ) - ).rows; - expect(children.length).toBe(detail.selection ? 2 : 0); - expect(children.every(c => c.cancel_requested)).toBe(true); - const childRuns = ( - await f.pool.query( - 'SELECT r.status,r.cancel_requested FROM runs r JOIN research_experiments e ON e.id=r.experiment_id WHERE e.validation_parent_id=$1', - [detail.id] - ) - ).rows; - expect(childRuns.every(r => r.status === 'cancelled' && r.cancel_requested)).toBe(true); - expect(detail.report).toBeNull(); - }, 60_000); - test('changing only future test prices cannot change native training scores or frozen winner', async () => { - const f = await fixture(), - first = await submit(f); - await train(f, first.validation.id); - const chosen = await f.validations.select( - first.validation.id, - { previewHash: first.preview.previewHash }, - actor() - ); - const changed = chronologicalDataset(900).dataset; - await retainResearchDataset(f.pool, changed); - const template = await f.cloneTemplate(changed), - secondInput = { ...f.input, backtestId: template.id }; - const preview = await f.experiments.previewValidation(secondInput); - const second = await f.validations.submit( - { ...secondInput, previewHash: preview.previewHash }, - actor() - ); - expect(preview.partitions[0].dataset.hash).toBe(first.preview.partitions[0].dataset.hash); - expect(preview.partitions[2].dataset.hash).not.toBe(first.preview.partitions[2].dataset.hash); - await train(f, second.id); - const next = await f.validations.select( - second.id, - { previewHash: preview.previewHash }, - actor() - ); - expect(next.validation.selection!.winner).toEqual(chosen.validation.selection!.winner); - expect(next.validation.selection!.training.map(e => e.metrics)).toEqual( - chosen.validation.selection!.training.map(e => e.metrics) - ); - expect( - ( - await f.pool.query( - "SELECT count(*)::int AS n FROM runs r JOIN research_experiments e ON e.id=r.experiment_id WHERE e.validation_phase IN ('validation','test') AND r.status<>'pending'" - ) - ).rows[0].n - ).toBe(0); - }, 60_000); - test('missing, failed, incomparable and unavailable training candidates each block durable selection', async () => { - const f = await fixture(), - start = await submit(f), - id = start.validation.id, - trial = start.validation.phases[0].experiment!.trials[0]!; - await f.pool.query('ALTER TABLE runs DISABLE TRIGGER USER'); - await f.pool.query( - 'UPDATE runs SET experiment_id=NULL,trial_index=NULL,trial_key=NULL WHERE id=$1', - [trial.runId] - ); - expect((await f.validations.get(id)).phases[0].experiment!.trials[0]!.status).toBe('missing'); - await expect( - f.validations.select(id, { previewHash: start.preview.previewHash }, actor()) - ).rejects.toThrow('Every train'); - await f.pool.query('UPDATE runs SET experiment_id=$2,trial_index=$3,trial_key=$4 WHERE id=$1', [ - trial.runId, - id, - trial.index, - trial.trialKey, - ]); - await f.pool.query('ALTER TABLE runs ENABLE TRIGGER USER'); - await f.pool.query( - "UPDATE runs SET status='failed',error='Incomplete candidate',completed_at=NOW() WHERE id=$1", - [trial.runId] - ); - await expect( - f.validations.select(id, { previewHash: start.preview.previewHash }, actor()) - ).rejects.toThrow('Every train'); - await f.experiments.retryTrial( - id, - trial.runId!, - { expectedAttemptNumber: 0, expectedRetryCount: 0 }, - actor() - ); - await train(f, id); - const result = ( - await f.pool.query('SELECT canonical_result FROM backtest_results WHERE run_id=$1', [ - trial.runId, - ]) - ).rows[0].canonical_result; - await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER'); - for (const changed of [ - { - ...result, - financial: { - ...result.financial, - identity: { ...result.financial.identity, datasetHash: 'a'.repeat(64) }, - }, - }, - { - ...result, - analytics: { - ...result.analytics, - metrics: { ...result.analytics.metrics, totalReturn: null }, - unavailable: { ...result.analytics.unavailable, totalReturn: 'nonfinite-result' }, - }, - }, - ]) { - await f.pool.query('UPDATE backtest_results SET canonical_result=$2 WHERE run_id=$1', [ - trial.runId, - changed, - ]); - await expect( - f.validations.select(id, { previewHash: start.preview.previewHash }, actor()) - ).rejects.toThrow(); - expect((await f.validations.get(id)).selection).toBeNull(); - expect( - ( - await f.pool.query( - 'SELECT count(*)::int AS n FROM research_experiments WHERE validation_parent_id=$1', - [id] - ) - ).rows[0].n - ).toBe(0); - } - await f.pool.query('UPDATE backtest_results SET canonical_result=$2 WHERE run_id=$1', [ - trial.runId, - result, - ]); - }, 60_000); -}); diff --git a/test/postgres/chronological-validation.test.ts b/test/postgres/chronological-validation.test.ts deleted file mode 100644 index e9f5ace8..00000000 --- a/test/postgres/chronological-validation.test.ts +++ /dev/null @@ -1,336 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { readFileSync } from 'node:fs'; -import { afterEach, describe, expect, test } from 'bun:test'; -import { Hono } from 'hono'; -import { Pool, type PoolClient } from 'pg'; -import { createHttpSecurity } from '@stock-bot/di'; -import { getLogger, setLoggerConfig } from '@stock-bot/logger'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import type { - ChronologicalValidationInput, - ChronologicalValidationPreview, -} from '@stock-bot/stock-config/chronological-validation'; -import { parseFinancialDecimal } from '@stock-bot/types'; -import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes'; -import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service'; -import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.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 '../fixtures/canonical-research'; -import { chronologicalDataset } from '../fixtures/chronological-validation'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('chronological-validation'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const cleanup: (() => Promise)[] = []; -let packages: ReturnType | undefined; -const tokens = { - operator: 'chronological-operator-fixture-not-a-real-secret-1234', - service: 'chronological-service-fixture-not-a-real-secret-1234', -}; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); -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_validation_' + randomUUID().replaceAll('-', ''); - const admin = new Pool({ connectionString: url }); - await admin.query(`CREATE SCHEMA ${schema}`); - // A single connection detects accidental nested pool reads while the admission lock is held. - const pool = new Pool({ - connectionString: url, - application_name: schema, - max: 1, - options: `-c search_path=${schema} -c statement_timeout=10000`, - }); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - for (const name of [ - '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') - ); - } - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, - logger - ); - Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); - Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); - const container = { postgres, logger }, - api = new BacktestServiceV2(container), - experiments = new ExperimentsService(container), - catalog = new StrategyCatalogService(container); - const version = await catalog.seedBuiltin( - 'Validation SMA', - (await (packages ??= packageBuiltinStrategies()))[0]!, - 'seed' - ); - const data = chronologicalDataset(), - dataset = data.dataset; - await retainResearchDataset(pool, dataset); - const draft = await api.createBacktest( - { - name: 'Validation template', - strategy: 'catalog', - strategyVersionId: version.id, - strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, - symbols: ['X0.US'], - startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(), - endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(), - initialCapital: 10000, - config: { - datasetHash: dataset.manifest.hash, - dataFrequency: '1m', - canonical: canonicalSettings, - }, - }, - { autoStart: false } - ); - const input: ChronologicalValidationInput = { - backtestId: draft.id, - name: 'Three explicit windows', - grid: { fastPeriod: [1, 2], slowPeriod: [3] }, - recipe: data.recipe, - }; - const app = new Hono(); - createHttpSecurity({ - adminToken: tokens.operator, - serviceToken: tokens.service, - environment: 'test', - hostname: '127.0.0.1', - }).mount(app); - app.route('/', createExperimentRoutes(container)); - const request = (raw: unknown = input, role: keyof typeof tokens = 'operator') => - app.request('/api/v2/experiments/validation/preview', { - method: 'POST', - headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${tokens[role]}` }, - body: JSON.stringify(raw), - }); - const review = async (decision: 'approve' | 'revoke' = 'approve') => { - await catalog.reviewVersion( - version.id, - { decision, reason: 'Disposable validation proof' }, - 'operator' - ); - return (await catalog.getVersionReviews(version.id)).at(-1)!; - }; - const snapshot = async () => { - const tables = ( - await pool.query('SELECT tablename FROM pg_tables WHERE schemaname=$1 ORDER BY tablename', [ - schema, - ]) - ).rows; - const rows: Record = {}; - for (const { tablename } of tables) { - const quoted = '"' + String(tablename).replaceAll('"', '""') + '"'; - rows[String(tablename)] = ( - await pool.query( - `SELECT COALESCE(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text),'[]'::jsonb) AS rows FROM ${quoted} t` - ) - ).rows[0].rows; - } - return rows; - }; - return { - pool, - postgres, - experiments, - catalog, - version, - draft, - dataset, - input, - request, - review, - snapshot, - }; -} - -describe.skipIf(!url)('chronological validation PostgreSQL preflight', () => { - test('real approved retained preview uses one transaction/connection, writes no tables and leaves ordinary economic policy unchanged', async () => { - const f = await fixture(), - review = await f.review(), - before = await f.snapshot(); - const observed: string[] = [], - transaction = f.postgres.transaction.bind(f.postgres); - Object.defineProperty(f.postgres, 'transaction', { - value: (work: (client: PoolClient) => Promise) => - transaction(client => - work( - new Proxy(client, { - get(target, property) { - if (property === 'query') { - return (sql: string, values?: unknown[]) => { - observed.push(sql); - return target.query(sql, values); - }; - } - const value = Reflect.get(target, property); - return typeof value === 'function' ? value.bind(target) : value; - }, - }) - ) - ), - }); - const response = await f.request(); - expect(response.status).toBe(200); - expect(response.headers.get('Cache-Control')).toBe('no-store'); - const { preview } = (await response.json()) as { preview: ChronologicalValidationPreview }; - expect(preview.source.request.strategy.reviewId).toBe(review.id); - expect(preview.source.dataset).toEqual(f.dataset.manifest); - expect(preview.execution).toBe('preview-only'); - expect(preview.source.candidates).toHaveLength(2); - expect(preview.partitions.map(p => p.phase)).toEqual(['train', 'validation', 'test']); - expect(preview.source.request.build.engineBinarySha256).toMatch(/^[a-f0-9]{64}$/); - expect(observed.length).toBeGreaterThan(0); - expect(observed.every(sql => sql.trimStart().startsWith('SELECT'))).toBe(true); - expect(observed[0]).toContain('FROM backtests WHERE id=$1 FOR UPDATE'); - expect(observed[1]).toContain('FOR UPDATE OF s'); - expect(await f.snapshot()).toEqual(before); - const ordinary = await f.experiments.preview({ - backtestId: f.draft.id, - name: f.input.name, - grid: f.input.grid, - }); - expect(preview.source).toEqual(ordinary); - expect(ordinary.request.policy.matching.risk).toEqual({ - ledger: { - version: 1, - sessionId: ordinary.request.runId, - accountId: `research:${ordinary.request.runId}`, - baseCurrency: 'USD', - reserveOwnerId: 'reserve', - ownerIds: [`strategy:${f.version.id}`], - initialCapital: parseFinancialDecimal('10000'), - riskSession: { - calendarId: 'fixture-calendar', - calendarRevision: '1', - sessionId: '2024-01-01', - startsAt: f.dataset.manifest.bounds.warmupStart, - }, - }, - feeRate: parseFinancialDecimal(canonicalSettings.feeRate), - maxOrderQuantity: parseFinancialDecimal(canonicalSettings.maxOrderQuantity), - maxPositionQuantity: parseFinancialDecimal(canonicalSettings.maxPositionQuantity), - maxSymbolExposure: parseFinancialDecimal(canonicalSettings.maxSymbolExposure), - maxGrossExposure: parseFinancialDecimal(canonicalSettings.maxGrossExposure), - maxDailyLoss: parseFinancialDecimal(canonicalSettings.maxDailyLoss), - maxDrawdownAmount: parseFinancialDecimal(canonicalSettings.maxDrawdownAmount), - maxMarkAgeMs: canonicalSettings.maxMarkAgeMs, - }); - expect(ordinary.request.policy.risk_boundaries).toEqual([]); - expect(await (await f.request(f.input, 'service')).json()).toEqual({ preview }); - expect(await f.snapshot()).toEqual(before); - }, 30_000); - test('current approval, family/template availability and exact saved dataset remain authoritative', async () => { - const f = await fixture(); - expect((await f.request()).status).toBe(409); - const first = await f.review(), - initial = (await (await f.request()).json()) as { preview: ChronologicalValidationPreview }; - expect(initial.preview.source.request.strategy.reviewId).toBe(first.id); - await f.review('revoke'); - expect((await f.request()).status).toBe(409); - const latest = await f.review(), - newer = (await (await f.request()).json()) as { preview: ChronologicalValidationPreview }; - expect(newer.preview.source.request.strategy.reviewId).toBe(latest.id); - expect(newer.preview.previewHash).not.toBe(initial.preview.previewHash); - expect(newer.preview.partitions.map(p => p.dataset.hash)).toEqual( - initial.preview.partitions.map(p => p.dataset.hash) - ); - await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [ - f.version.strategyId, - ]); - const archivedFamily = await f.snapshot(); - expect((await f.request()).status).toBe(409); - expect(await f.snapshot()).toEqual(archivedFamily); - await f.pool.query('UPDATE strategies SET archived_at=NULL WHERE id=$1', [ - f.version.strategyId, - ]); - await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]); - expect((await f.request()).status).toBe(409); - expect((await f.request({ ...f.input, backtestId: randomUUID() })).status).toBe(404); - expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(0); - }, 30_000); - test('recipe cuts, insufficient candidate history and invalid or excessive grids reject without persistence', async () => { - const f = await fixture(); - await f.review(); - const before = await f.snapshot(); - for (const raw of [ - { - ...f.input, - recipe: { - ...f.input.recipe, - train: { ...f.input.recipe.train, tradeStart: f.input.recipe.train.tradeStart + 1 }, - }, - }, - { - ...f.input, - recipe: { - ...f.input.recipe, - train: { - ...f.input.recipe.train, - warmupStart: f.input.recipe.train.warmupStart - 60_000, - }, - }, - }, - { ...f.input, grid: { fastPeriod: [1], slowPeriod: [5] } }, - { ...f.input, grid: { unknown: [1] } }, - { ...f.input, grid: { fastPeriod: [1, 1] } }, - { - ...f.input, - grid: { - fastPeriod: Array.from({ length: 11 }, (_, i) => i + 1), - slowPeriod: Array.from({ length: 10 }, (_, i) => i + 20), - }, - }, - ]) { - const response = await f.request(raw); - expect(response.status).toBe(400); - expect(await f.snapshot()).toEqual(before); - } - }, 30_000); - test('missing or corrupt retained input is unavailable, arbitrary storage failures remain sanitized500', async () => { - const f = await fixture(); - await f.review(); - await f.pool.query('ALTER TABLE backtest_datasets DISABLE TRIGGER USER'); - await f.pool.query( - "UPDATE backtest_datasets SET payload=jsonb_set(payload,'{bars,0,close}','999') WHERE hash=$1", - [f.dataset.manifest.hash] - ); - const corrupt = await f.snapshot(); - expect((await f.request()).status).toBe(409); - expect(await f.snapshot()).toEqual(corrupt); - await f.pool.query('DELETE FROM backtest_datasets WHERE hash=$1', [f.dataset.manifest.hash]); - expect((await f.request()).status).toBe(409); - await f.pool.query('ALTER TABLE backtest_datasets RENAME TO unavailable_datasets'); - const response = await f.request(); - expect(response.status).toBe(500); - expect(await response.json()).toEqual({ error: 'Experiment operation unavailable' }); - }, 30_000); -}); diff --git a/test/postgres/cost-sensitivity.test.ts b/test/postgres/cost-sensitivity.test.ts deleted file mode 100644 index d849be31..00000000 --- a/test/postgres/cost-sensitivity.test.ts +++ /dev/null @@ -1,661 +0,0 @@ -import { 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 { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research'; -import type { CostSensitivityInput } from '@stock-bot/stock-config/cost-sensitivity'; -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 { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service'; -import { ExperimentError } from '../../apps/stock/web-api/src/services/experiment-input'; -import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service'; -import { canonicalReproductionHash } from '../../apps/stock/web-api/src/services/reproduction-comparison'; -import { createResearchServices } from '../../apps/stock/web-api/src/services/research-services'; -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 '../fixtures/canonical-research'; -import { canonicalSmaFixture } from '../fixtures/canonical-sma'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('chronological-validation'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const cleanup: (() => Promise)[] = []; -let packages: ReturnType | undefined; -const tokens = { - operator: 'chronological-operator-fixture-not-a-real-secret-1234', - service: 'chronological-service-fixture-not-a-real-secret-1234', -}; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); -async function fixture(poolMax = 1, withCosts = true, capital = 10000) { - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Disposable safety database required'); - } - const schema = 'stock_bot_safety_validation_' + randomUUID().replaceAll('-', ''); - const admin = new Pool({ connectionString: url }); - await admin.query(`CREATE SCHEMA ${schema}`); - // A single connection detects accidental nested pool reads while the admission lock is held. - const pool = new Pool({ - connectionString: url, - application_name: schema, - max: poolMax, - options: `-c search_path=${schema} -c statement_timeout=10000`, - }); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - for (const name of [ - '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', - ...(withCosts ? ['26-cost-sensitivity.sql'] : []), - ]) { - await pool.query( - readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') - ); - } - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, - logger - ); - Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); - Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); - const container = { postgres, logger }, - api = new BacktestServiceV2(container), - experiments = new ExperimentsService(container), - catalog = new StrategyCatalogService(container); - const version = await catalog.seedBuiltin( - 'Validation SMA', - (await (packages ??= packageBuiltinStrategies()))[0]!, - 'seed' - ); - const data = canonicalSmaFixture(), - dataset = data.dataset; - await retainResearchDataset(pool, dataset); - const draft = await api.createBacktest( - { - name: 'Validation template', - strategy: 'catalog', - strategyVersionId: version.id, - strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, - symbols: ['X0.US'], - startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(), - endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(), - initialCapital: capital, - config: { - datasetHash: dataset.manifest.hash, - dataFrequency: '1m', - canonical: canonicalSettings, - }, - }, - { autoStart: false } - ); - const input: CostSensitivityInput = { - backtestId: draft.id, - name: 'Explicit cost diagnostics', - scenarios: [ - { feeRate: '0.001', slippageRate: '0' }, - { feeRate: '0', slippageRate: '0.01' }, - ], - }; - const app = new Hono(); - createHttpSecurity({ - adminToken: tokens.operator, - serviceToken: tokens.service, - environment: 'test', - hostname: '127.0.0.1', - }).mount(app); - app.route('/', createExperimentRoutes(container)); - const request = (raw: unknown = input, role: keyof typeof tokens = 'operator') => - app.request('/api/v2/experiments/cost-sensitivity/preview', { - method: 'POST', - headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${tokens[role]}` }, - body: JSON.stringify(raw), - }); - const review = async (decision: 'approve' | 'revoke' = 'approve') => { - await catalog.reviewVersion( - version.id, - { decision, reason: 'Disposable validation proof' }, - 'operator' - ); - return (await catalog.getVersionReviews(version.id)).at(-1)!; - }; - const snapshot = async () => { - const tables = ( - await pool.query('SELECT tablename FROM pg_tables WHERE schemaname=$1 ORDER BY tablename', [ - schema, - ]) - ).rows; - const rows: Record = {}; - for (const { tablename } of tables) { - const quoted = '"' + String(tablename).replaceAll('"', '""') + '"'; - rows[String(tablename)] = ( - await pool.query( - `SELECT COALESCE(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text),'[]'::jsonb) AS rows FROM ${quoted} t` - ) - ).rows[0].rows; - } - return rows; - }; - const validations = createResearchServices(container).validations; - const repository = new PostgresBacktestRunRepository(postgres); - const execute = async (id: string) => { - const engine = new RustBacktestAdapter({ - logger, - }); - const runner = new BacktestRunner({ engine, repository, logger }); - try { - await runner.runQueued(id); - } finally { - await runner.shutdown(); - } - }; - return { - cloneTemplate: async (sourceDataset = dataset) => - api.createBacktest( - { - name: 'Other validation template', - strategy: 'catalog', - strategyVersionId: version.id, - strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, - symbols: ['X0.US'], - startDate: new Date(sourceDataset.manifest.bounds.tradeStart).toISOString(), - endDate: new Date(sourceDataset.manifest.bounds.tradeEnd).toISOString(), - initialCapital: capital, - config: { - datasetHash: sourceDataset.manifest.hash, - dataFrequency: '1m', - canonical: canonicalSettings, - }, - }, - { autoStart: false } - ), - validations, - repository, - execute, - api, - pool, - postgres, - experiments, - catalog, - version, - draft, - dataset, - input, - request, - review, - snapshot, - }; -} - -const actor = (key = randomUUID()) => ({ principal: 'operator' as const, key }); -type Fixture = Awaited>; -async function submit(f: Fixture, identity = actor()) { - await f.review(); - const preview = await f.experiments.previewCosts(f.input), - body = { ...f.input, previewHash: preview.previewHash }; - return { preview, body, identity, experiment: await f.experiments.submitCosts(body, identity) }; -} -describe.skipIf(!url)('bounded cost-sensitivity experiments', () => { - test('pool1 native baseline agrees with ordinary empty-grid; saved scenarios expose exact costs and immutable results', async () => { - const f = await fixture(), - start = await submit(f); - expect(start.experiment.kind).toBe('cost-sensitivity'); - expect(start.experiment.trials).toHaveLength(3); - const input = { backtestId: f.draft.id, name: 'Ordinary reference', grid: {} }; - const preview = await f.experiments.preview(input), - ordinary = await f.experiments.submit( - { ...input, previewHash: preview.previewHash }, - actor() - ); - for (const trial of [...start.experiment.trials, ...ordinary.trials]) { - await f.execute(trial.runId!); - } - const detail = await f.experiments.get(start.experiment.id); - expect(detail.counts.completed).toBe(3); - expect(detail.trials.every(t => t.comparable)).toBe(true); - const baseline = await f.api.getRunResults(detail.trials[0]!.runId!), - reference = await f.api.getRunResults(ordinary.trials[0]!.runId!); - expect(canonicalReproductionHash(baseline as CanonicalRunResult)).toBe( - canonicalReproductionHash(reference as CanonicalRunResult) - ); - expect(await f.experiments.get(detail.id)).toEqual(detail); - expect((await f.experiments.list()).find(e => e.id === detail.id)!.kind).toBe( - 'cost-sensitivity' - ); - expect((await f.experiments.submitCosts(start.body, start.identity)).id).toBe(detail.id); - }, 60000); -}); - -const result = async (f: Fixture, id: string) => - (await f.api.getRunResults(id)) as CanonicalRunResult; -describe.skipIf(!url)('cost financial and recovery proofs', () => { - test('Rust alone applies exact execution fees and adverse slippage, resetting capital for every scenario', async () => { - const f = await fixture(); - f.input.scenarios.push({ feeRate: '0.02', slippageRate: '0.01' }); - const start = await submit(f); - const oracle = [ - { prices: ['5.00000000', '2.00000000'], fees: '0.70000000', equity: '9969.30000000' }, - { prices: ['5.00000000', '2.00000000'], fees: '0.07000000', equity: '9969.93000000' }, - { prices: ['5.05000000', '1.98000000'], fees: '0.00000000', equity: '9969.30000000' }, - { prices: ['5.05000000', '1.98000000'], fees: '1.40600000', equity: '9967.89400000' }, - ]; - for (const [index, trial] of start.experiment.trials.entries()) { - await f.execute(trial.runId!); - const saved = await result(f, trial.runId!), - expected = oracle[index]!; - expect(String(saved.financial.reporting.initialEquity)).toBe('10000.00000000'); - expect(saved.financial.projection.fills.map(fill => String(fill.price))).toEqual( - expected.prices - ); - expect(saved.financial.projection.fills.map(fill => String(fill.quantity))).toEqual([ - '10.00000000', - '10.00000000', - ]); - expect(String(saved.financial.projection.valuation.fees)).toBe(expected.fees); - expect(String(saved.financial.projection.valuation.equity)).toBe(expected.equity); - } - }, 60000); - test('fee-inclusive funding cannot be bypassed by a lower-cost scenario; unchanged risk may change fills', async () => { - const f = await fixture(1, true, 50); - f.input.scenarios = [{ feeRate: '0', slippageRate: '0' }]; - const start = await submit(f); - for (const trial of start.experiment.trials) { - await f.execute(trial.runId!); - } - const baseline = await result(f, start.experiment.trials[0]!.runId!), - zero = await result(f, start.experiment.trials[1]!.runId!); - expect(baseline.financial.projection.fills).toEqual([]); - expect(String(baseline.financial.projection.valuation.cash)).toBe('50.00000000'); - expect(zero.financial.projection.fills).toHaveLength(2); - expect(String(zero.financial.projection.valuation.cash)).toBe('20.00000000'); - expect(baseline.request.policy.matching.risk.maxGrossExposure).toBe( - zero.request.policy.matching.risk.maxGrossExposure - ); - }, 60000); - test('frozen source survives template edit, manual retry retains costs and reproduction retains exact economics', async () => { - const f = await fixture(), - start = await submit(f), - trial = start.experiment.trials[1]!, - runId = trial.runId!; - const snapshot = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])) - .rows[0].request_snapshot; - const claim = await f.repository.startCanonical(snapshot); - await f.repository.fail(runId, 'Cost attempt failure', claim.attemptId); - await f.api.updateBacktest(f.draft.id, { - name: 'Changed template', - initialCapital: 12000, - config: { - datasetHash: f.dataset.manifest.hash, - dataFrequency: '1m', - canonical: { ...canonicalSettings, feeRate: '0.03', slippageRate: '0.04' }, - }, - }); - const newReview = await f.review(); - const retry = await f.experiments.retryTrial( - start.experiment.id, - runId, - { expectedAttemptNumber: 1, expectedRetryCount: 0 }, - actor() - ); - expect(retry.retry.error).toBe('Cost attempt failure'); - expect(retry.retry.reviewId).toBe(newReview.id); - expect( - (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])).rows[0] - .request_snapshot - ).toEqual(snapshot); - await f.execute(runId); - const original = await result(f, runId); - expect(String(original.request.policy.matching.risk.feeRate)).toBe('0.00100000'); - const reproduction = await f.api.reproduceRun(runId, actor()); - await f.execute(reproduction.id); - expect(canonicalReproductionHash(await result(f, reproduction.id))).toBe( - canonicalReproductionHash(original) - ); - expect((await f.experiments.get(start.experiment.id)).preview).toEqual(start.preview); - await expect(f.repository.heartbeat(runId, claim.attemptId)).rejects.toThrow(); - await f.review('revoke'); - await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]); - expect((await f.experiments.submitCosts(start.body, start.identity)).id).toBe( - start.experiment.id - ); - await expect(f.experiments.submitCosts(start.body, actor())).rejects.toThrow(); - }, 60000); -}); - -describe.skipIf(!url)('cost SQL and admission boundaries', () => { - test('first/idempotent upgrade preserves old evidence/leases and leaves v1 callable and non-request guard bodies unchanged', async () => { - const f = await fixture(1, false); - await f.review(); - const input = { backtestId: f.draft.id, name: 'Old sweep', grid: { fastPeriod: [1, 2] } }, - preview = await f.experiments.preview(input), - ordinary = await f.experiments.submit( - { ...input, previewHash: preview.previewHash }, - actor() - ); - await f.execute(ordinary.trials[0]!.runId!); - const pending = ordinary.trials[1]!.runId!, - request = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [pending])) - .rows[0].request_snapshot; - await f.repository.startCanonical(request); - const before = await f.snapshot(); - const functions = async () => - ( - await f.pool.query( - 'SELECT proname,pg_get_functiondef(oid) AS definition FROM pg_proc WHERE pronamespace=current_schema()::regnamespace ORDER BY proname' - ) - ).rows; - const oldFunctions = await functions(), - migration = readFileSync( - new URL('../../database/postgres/init/26-cost-sensitivity.sql', import.meta.url), - 'utf8' - ); - await f.pool.query(migration); - expect(await f.snapshot()).toEqual(before); - const changed = [ - 'require_experiment_manifest', - 'require_active_backtest_for_new_run', - 'require_experiment_retry_failure', - ]; - expect( - (await functions()).filter( - row => - oldFunctions.some(old => old.proname === row.proname) && !changed.includes(row.proname) - ) - ).toEqual(oldFunctions.filter(row => !changed.includes(row.proname))); - const expectedBlocks = { - require_active_backtest_for_new_run: [ - " expected := jsonb_set(experiment.preview->'request','{runId}',to_jsonb(NEW.id::text));\n expected := jsonb_set(expected,'{policy,matching,risk,ledger,sessionId}',to_jsonb(NEW.id::text));\n expected := jsonb_set(expected,'{policy,matching,risk,ledger,accountId}',to_jsonb('research:'||NEW.id::text));\n expected := jsonb_set(expected,'{strategy,selection,parameters}',candidate->'parameters');", - ' expected := experiment_trial_request(experiment.preview,NEW.trial_index,NEW.id);', - ], - require_experiment_retry_failure: [ - " expected := jsonb_set(experiment.preview->'request','{runId}',to_jsonb(original.id::text));\n expected := jsonb_set(expected,'{policy,matching,risk,ledger,sessionId}',to_jsonb(original.id::text));\n expected := jsonb_set(expected,'{policy,matching,risk,ledger,accountId}',to_jsonb('research:'||original.id::text));\n expected := jsonb_set(expected,'{strategy,selection,parameters}',candidate->'parameters');", - ' expected := experiment_trial_request(experiment.preview,original.trial_index,original.id);', - ], - }; - const now = await functions(); - for (const [name, [oldBlock, newBlock]] of Object.entries(expectedBlocks)) { - expect(now.find(r => r.proname === name)!.definition).toBe( - oldFunctions.find(r => r.proname === name)!.definition.replace(oldBlock, newBlock) - ); - } - await f.pool.query(migration); - expect(await f.snapshot()).toEqual(before); - expect((await submit(f)).experiment.trials).toHaveLength(3); - }, 60000); - test('late candidate, outbox failure and omitted dispatch roll back all children and receipt', async () => { - const f = await fixture(); - await f.review(); - const preview = await f.experiments.previewCosts(f.input), - body = { ...f.input, previewHash: preview.previewHash }; - for (const [table, condition, action, message] of [ - ['runs', 'NEW.trial_index=2', "RAISE EXCEPTION 'Injected failure';", 'Injected'], - [ - 'backtest_dispatch', - 'EXISTS(SELECT 1 FROM runs r WHERE r.id=NEW.run_id AND r.trial_index=2)', - "RAISE EXCEPTION 'Injected failure';", - 'Injected', - ], - ['backtest_dispatch', 'TRUE', 'RETURN NULL;', 'atomically'], - ]) { - await f.pool.query( - `CREATE OR REPLACE FUNCTION cost_injection() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF ${condition} THEN ${action} END IF; RETURN NEW; END $$` - ); - await f.pool.query( - `CREATE TRIGGER cost_injection BEFORE INSERT ON ${table} FOR EACH ROW EXECUTE FUNCTION cost_injection()` - ); - const before = await f.snapshot(); - await expect(f.experiments.submitCosts(body, actor())).rejects.toThrow(message); - expect(await f.snapshot()).toEqual(before); - await f.pool.query(`DROP TRIGGER cost_injection ON ${table}`); - } - expect((await f.experiments.submitCosts(body, actor())).trials).toHaveLength(3); - }, 60000); - test('same/cross-parent/cross-kind receipt races produce exactly one operation owner', async () => { - const f = await fixture(5); - await f.review(); - const preview = await f.experiments.previewCosts(f.input), - body = { ...f.input, previewHash: preview.previewHash }, - identity = actor(); - const [first, replay] = await Promise.all([ - f.experiments.submitCosts(body, identity), - f.experiments.submitCosts(body, identity), - ]); - expect(first.id).toBe(replay.id); - const other = await f.cloneTemplate(), - otherInput = { ...f.input, backtestId: other.id }, - otherPreview = await f.experiments.previewCosts(otherInput), - cross = actor(); - const race = await Promise.allSettled([ - f.experiments.submitCosts(body, cross), - f.experiments.submitCosts({ ...otherInput, previewHash: otherPreview.previewHash }, cross), - ]); - expect(race.filter(r => r.status === 'fulfilled')).toHaveLength(1); - expect(race.filter(r => r.status === 'rejected')).toHaveLength(1); - const normalInput = { backtestId: f.draft.id, name: 'Parameter sweep', grid: {} }, - normal = await f.experiments.preview(normalInput), - mixed = actor(); - const mixedRace = await Promise.allSettled([ - f.experiments.submitCosts(body, mixed), - f.experiments.submit({ ...normalInput, previewHash: normal.previewHash }, mixed), - ]); - expect(mixedRace.filter(r => r.status === 'fulfilled')).toHaveLength(1); - expect(mixedRace.filter(r => r.status === 'rejected')).toHaveLength(1); - for (const item of [...race, ...mixedRace]) { - if (item.status === 'rejected') { - expect(item.reason).toBeInstanceOf(ExperimentError); - expect(item.reason.status).toBe(409); - } - } - expect((await f.pool.query('SELECT count(*)::int n FROM research_experiments')).rows[0].n).toBe( - 3 - ); - await expect(f.experiments.submitCosts({ ...body, name: 'Changed' }, identity)).rejects.toThrow( - 'different' - ); - }, 60000); - test('SQL targets exact source, baseline, cost shape, parameters and two-path request isolation', async () => { - const f = await fixture(), - start = await submit(f), - row = ( - await f.pool.query('SELECT * FROM research_experiments WHERE id=$1', [start.experiment.id]) - ).rows[0]; - const validate = async (preview: unknown) => - f.pool.query( - 'SELECT validate_cost_manifest(jsonb_populate_record(NULL::research_experiments,$1))', - [{ ...row, preview }] - ); - await validate(start.preview); - for (const [mutate, message] of [ - [(p: typeof start.preview) => (p.source.input.grid = { fastPeriod: [1] }), 'empty-grid'], - [ - (p: typeof start.preview) => - (p.request = structuredClone({ ...p.request, name: 'Foreign' })), - 'empty-grid', - ], - [ - (p: typeof start.preview) => (p.candidates[0]!.costs = { feeRate: '0', slippageRate: '0' }), - 'exact ordered', - ], - [ - (p: typeof start.preview) => - (p.candidates[1]!.parameters = { fastPeriod: 1, slowPeriod: 3 }), - 'fixed parameters', - ], - [ - (p: typeof start.preview) => - (p.candidates[1]!.costs = { feeRate: '0.001', slippageRate: '0.00000000' }), - 'exact ordered', - ], - [ - (p: typeof start.preview) => { - p.input.scenarios[0]!.slippageRate = '1.00000000'; - p.candidates[1]!.costs.slippageRate = '1.00000000'; - }, - 'canonical bounds', - ], - [ - (p: typeof start.preview) => { - p.input.scenarios[0] = { ...p.candidates[0]!.costs }; - p.candidates[1]!.costs = { ...p.candidates[0]!.costs }; - }, - 'distinct', - ], - ] as const) { - const preview = structuredClone(start.preview); - mutate(preview); - await expect(validate(preview)).rejects.toThrow(message); - } - const ordinaryInput = { backtestId: f.draft.id, name: 'Ordinary', grid: {} }, - normal = await f.experiments.preview(ordinaryInput); - await expect( - f.pool.query( - 'INSERT INTO research_experiments(id,backtest_id,name,preview,preview_hash,submission_principal,submission_key,submission_hash) VALUES($1,$2,$3,$4,$5,$6,$7,$8)', - [ - randomUUID(), - f.draft.id, - ordinaryInput.name, - { - ...normal, - candidates: normal.candidates.map(c => ({ - ...c, - costs: { feeRate: '0', slippageRate: '0' }, - })), - }, - normal.previewHash, - 'operator', - randomUUID(), - 'a'.repeat(64), - ] - ) - ).rejects.toThrow('cannot contain'); - const clone = { ...row, id: randomUUID(), submission_key: randomUUID() }; - await expect( - f.pool.query( - 'INSERT INTO research_experiments SELECT * FROM jsonb_populate_record(NULL::research_experiments,$1)', - [clone] - ) - ).rejects.toThrow('atomically'); - const run = ( - await f.pool.query('SELECT * FROM runs WHERE id=$1', [start.experiment.trials[1]!.runId]) - ).rows[0]; - const inserted = async (mutate: (r: Record) => void) => { - const client = await f.pool.connect(); - try { - await client.query('BEGIN'); - const exp = { ...row, id: randomUUID(), submission_key: randomUUID() }; - await client.query( - 'INSERT INTO research_experiments SELECT * FROM jsonb_populate_record(NULL::research_experiments,$1)', - [exp] - ); - const id = randomUUID(), - candidate = { - ...run, - id, - experiment_id: exp.id, - run_number: 999, - request_snapshot: structuredClone(run.request_snapshot), - }; - candidate.request_snapshot.runId = id; - candidate.request_snapshot.policy.matching.risk.ledger.sessionId = id; - candidate.request_snapshot.policy.matching.risk.ledger.accountId = `research:${id}`; - mutate(candidate); - await client.query('INSERT INTO runs SELECT * FROM jsonb_populate_record(NULL::runs,$1)', [ - candidate, - ]); - } finally { - await client.query('ROLLBACK'); - client.release(); - } - }; - await expect( - inserted(r => (r.request_snapshot.policy.matching.risk.feeRate = '0.90000000')) - ).rejects.toThrow('exact frozen'); - await expect( - inserted(r => (r.request_snapshot.policy.matching.halfSpreadRate = '0.10000000')) - ).rejects.toThrow('exact frozen'); - await expect(inserted(r => (r.trial_index = 99))).rejects.toThrow('exact candidate'); - expect((await f.experiments.get(start.experiment.id)).trials).toHaveLength(3); - }, 60000); - test('cancel overlaps a blocked manual retry, leaving no live work and retaining failure evidence', async () => { - const f = await fixture(5), - start = await submit(f), - runId = start.experiment.trials[1]!.runId!; - await f.pool.query( - "UPDATE runs SET status='failed',error='Cost failure',completed_at=NOW() WHERE id=$1", - [runId] - ); - const before = (await f.pool.query('SELECT to_jsonb(r) row FROM runs r WHERE id=$1', [runId])) - .rows; - const blocker = await f.pool.connect(); - await blocker.query('BEGIN'); - await blocker.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [f.draft.id]); - const pending = Promise.allSettled([ - f.experiments.retryTrial( - start.experiment.id, - runId, - { expectedAttemptNumber: 0, expectedRetryCount: 0 }, - actor() - ), - ]); - try { - let count = 0; - for (let i = 0; i < 100; i++) { - count = Number( - ( - await f.pool.query( - "SELECT count(*)::int n FROM pg_stat_activity WHERE application_name=current_schema() AND wait_event_type='Lock'" - ) - ).rows[0].n - ); - if (count > 0) { - break; - } - await new Promise(resolve => setTimeout(resolve, 10)); - } - expect(count).toBeGreaterThan(0); - await f.experiments.cancel(start.experiment.id); - await blocker.query('COMMIT'); - } finally { - await blocker.query('ROLLBACK'); - blocker.release(); - } - const outcome = (await pending)[0]!; - expect(outcome.status).toBe('rejected'); - if (outcome.status === 'rejected') { - expect(outcome.reason).toBeInstanceOf(ExperimentError); - expect(outcome.reason.status).toBe(409); - } - expect( - (await f.pool.query('SELECT to_jsonb(r) row FROM runs r WHERE id=$1', [runId])).rows - ).toEqual(before); - const detail = await f.experiments.get(start.experiment.id); - expect(detail.cancelRequested).toBe(true); - expect(detail.trials.filter(t => t.status === 'cancelled')).toHaveLength(2); - }, 60000); -}); diff --git a/test/postgres/dataset-catalog.test.ts b/test/postgres/dataset-catalog.test.ts deleted file mode 100644 index 029732e1..00000000 --- a/test/postgres/dataset-catalog.test.ts +++ /dev/null @@ -1,368 +0,0 @@ -import { 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 { getLogger, setLoggerConfig } from '@stock-bot/logger'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import type { HistoricalDatasetManifest } from '@stock-bot/types'; -import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes'; -import { - BacktestServiceV2, - type BacktestRequest, -} from '../../apps/stock/web-api/src/services/backtest-v2.service'; -import { DatasetCatalogService } from '../../apps/stock/web-api/src/services/dataset-catalog.service'; -import { seedHistoricalRun } from '../fixtures/historical-run'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('dataset-catalog-test'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const cleanup: (() => Promise)[] = []; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); -const hash = '1'.repeat(64); -const manifest = (key = hash): HistoricalDatasetManifest => ({ - version: 1, - hash: key, - instruments: [{ id: 'FIXTURE.TEST', symbol: 'FIXTURE', exchange: 'TEST' }], - startDate: '2024-01-01T00:00:00.000Z', - endDate: '2024-01-03T00:00:00.000Z', - interval: '1d', - policy: { adjustment: 'raw', timestamp: 'utc-session-date' }, - volumePolicy: 'reported', - qualityPolicy: 'reject-invalid-no-interpolation', - sources: [{ instrumentId: 'FIXTURE.TEST', provider: 'eod', revision: 'fixture-v1' }], - barCount: 1, -}); -const request = (): BacktestRequest => ({ - name: 'Dataset choice', - strategy: 'sma-crossover', - symbols: ['FIXTURE.TEST'], - startDate: manifest().startDate, - endDate: manifest().endDate, - initialCapital: 1000, - config: { fastPeriod: 2, slowPeriod: 3, datasetHash: hash, dataFrequency: '1d' }, -}); -async function fixture() { - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Dedicated stock_bot_safety database required'); - } - const schema = 'stock_bot_safety_' + randomUUID().replaceAll('-', ''); - const admin = new Pool({ connectionString: url }); - await admin.query(`CREATE SCHEMA ${schema}`); - const pool = new Pool({ - connectionString: url, - application_name: schema, - options: `-c search_path=${schema} -c statement_timeout=10000`, - }); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - for (const name of [ - '06-create-backtest-tables.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') - ); - } - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, - logger - ); - Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); - Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); - const insert = async (key: string, payload: unknown) => - pool.query( - "INSERT INTO backtest_datasets(hash,payload,created_at) VALUES($1,$2::jsonb,'2024-02-01T00:00:00Z')", - [key, JSON.stringify(payload)] - ); - const api = new BacktestServiceV2({ postgres, logger }, async () => { - throw new Error('Catalog must not fetch source data'); - }); - return { - pool, - schema, - postgres, - api, - insert, - catalog: new DatasetCatalogService(postgres), - routes: new Hono().route('/', createDatasetRoutes({ postgres, logger })), - }; -} - -describe.skipIf(!url)('dataset catalog and selected-run submission on real PostgreSQL', () => { - test('dataset_list_metadata_only projects no bars and diagnoses malformed shapes without SQL errors', async () => { - const f = await fixture(); - await f.insert(hash, { - manifest: manifest(), - bars: [{ payloadMustStayInPostgres: 'SECRET_BAR_CONTENT' }], - }); - const cases = [ - null, - [], - 'malformed', - { manifest: manifest('2'.repeat(64)), bars: {} }, - { manifest: manifest('3'.repeat(64)), bars: [] }, - { manifest: manifest('4'.repeat(64)), bars: [1], extra: true }, - { manifest: { version: 2 }, bars: [] }, - ]; - for (let index = 0; index < cases.length; index++) { - await f.insert(String(index + 2).repeat(64), cases[index]); - } - const result = await f.routes.request('/api/v2/datasets'); - expect(result.status).toBe(200); - const body = await result.json(); - expect(body.datasets).toHaveLength(8); - expect(body.datasets[0]).toMatchObject({ - hash, - status: 'available', - coverage: 'unknown', - integrity: 'not-verified', - manifest: { barCount: 1 }, - }); - expect(body.datasets.at(-1)).toMatchObject({ - version: 2, - status: 'unsupported', - manifest: null, - }); - expect(body.datasets.at(-1).reason).toContain('R05'); - expect(JSON.stringify(body)).not.toContain('SECRET_BAR_CONTENT'); - expect(JSON.stringify(body)).not.toContain('"bars"'); - for (const item of body.datasets.slice(1, -1)) { - expect(item.status).toBe('invalid'); - } - const queries: string[] = []; - const projected = new DatasetCatalogService({ - async query(text, values) { - queries.push(text); - const rows = await f.pool.query(text, values); - expect(rows.rows[0]).not.toHaveProperty('payload'); - expect(rows.rows[0]).not.toHaveProperty('bars'); - expect(rows.rows[0].bar_count).toBe(1); - return rows; - }, - }); - await projected.get(hash); - expect(queries[0]).not.toContain('SELECT *'); - expect(queries[0]).toContain("payload->'manifest' AS manifest"); - expect((await f.routes.request('/api/v2/datasets?limit=1&offset=1')).status).toBe(200); - expect((await f.routes.request(`/api/v2/datasets/${'f'.repeat(64)}`)).status).toBe(404); - expect((await f.routes.request('/api/v2/datasets/not-a-hash')).status).toBe(400); - }); - - test('select_hash_compatibility validates exact assets, interval, range, policy and explicit source on create and update', async () => { - const f = await fixture(); - await f.insert(hash, { manifest: manifest(), bars: [{}] }); - const saved = await f.api.createBacktest(request(), { autoStart: false }); - for (const changed of [ - { symbols: ['OTHER.TEST'] }, - { startDate: '2024-01-02T00:00:00.000Z' }, - { endDate: '2024-01-04T00:00:00.000Z' }, - { config: { ...request().config, dataFrequency: '1h' } }, - { - config: { - ...request().config, - dataPolicy: { adjustment: 'provider-adjusted', timestamp: 'utc-session-date' }, - }, - }, - { config: { ...request().config, dataSource: 'questdb' } }, - ]) { - await expect( - f.api.createBacktest({ ...request(), ...changed }, { autoStart: false }) - ).rejects.toThrow('does not match'); - await expect(f.api.updateBacktest(saved.id, changed)).rejects.toThrow('does not match'); - } - expect((await f.api.getBacktest(saved.id))!.config).toEqual(request().config!); - expect((await f.pool.query('SELECT count(*)::int AS n FROM backtests')).rows[0].n).toBe(1); - for (const dataSource of ['eod', 'auto']) { - await expect( - f.api.updateBacktest(saved.id, { config: { ...request().config, dataSource } }) - ).resolves.not.toBeNull(); - } - }); - - test('legacy admission refuses missing, inconsistent, malformed and unsupported snapshots before any run/outbox is inserted', async () => { - const f = await fixture(); - const saved = await f.api.createBacktest( - { ...request(), config: { fastPeriod: 2, slowPeriod: 3 } }, - { autoStart: false } - ); - const payloads = [ - { manifest: manifest('f'.repeat(64)), bars: [{}] }, - { manifest: { ...manifest(), barCount: 2 }, bars: [{}] }, - { manifest: { ...manifest(), sources: [] }, bars: [{}] }, - { manifest: { version: 2 }, bars: [] }, - ]; - for (const [index, payload] of payloads.entries()) { - const key = String(index + 1).repeat(64); - const row = structuredClone(payload); - // Preserve each malformed shape while matching the storage key except in the identity-mismatch case. - if (index > 0 && 'hash' in row.manifest) { - row.manifest.hash = key; - } - await f.insert(key, row); - await f.pool.query('UPDATE backtests SET config=$2 WHERE id=$1', [ - saved.id, - JSON.stringify({ ...request().config, datasetHash: key }), - ]); - await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow(); - } - await f.pool.query('UPDATE backtests SET config=$2 WHERE id=$1', [ - saved.id, - { ...request().config, datasetHash: 'e'.repeat(64) }, - ]); - await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow( - 'Legacy backtest execution is retired' - ); - expect((await f.pool.query('SELECT count(*)::int AS n FROM runs')).rows[0].n).toBe(0); - expect((await f.pool.query('SELECT count(*)::int AS n FROM backtest_dispatch')).rows[0].n).toBe( - 0 - ); - }); - - test('concurrent partial definition edits lock, merge and validate one committed definition', async () => { - const f = await fixture(); - await f.insert(hash, { manifest: manifest(), bars: [{}] }); - const saved = await f.api.createBacktest({ ...request(), config: {} }, { autoStart: false }); - const blocker = await f.pool.connect(); - await blocker.query('BEGIN'); - await blocker.query('LOCK TABLE backtest_datasets IN ACCESS EXCLUSIVE MODE'); - const selected = f.api.updateBacktest(saved.id, { config: request().config }).then( - value => ({ value, error: null }), - error => ({ value: null, error }) - ); - const isWaiting = async (pattern: string) => { - for (let attempt = 0; attempt < 100; attempt++) { - const result = await f.pool.query( - "SELECT 1 FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock' AND query LIKE $2", - [f.schema, pattern] - ); - if (result.rowCount) { - return true; - } - await new Promise(resolve => setTimeout(resolve, 5)); - } - return false; - }; - let catalogWait = false; - let definitionWait = false; - let changed: typeof selected | undefined; - try { - catalogWait = await isWaiting('%FROM backtest_datasets%'); - changed = f.api.updateBacktest(saved.id, { endDate: '2024-01-04T00:00:00.000Z' }).then( - value => ({ value, error: null }), - error => ({ value: null, error }) - ); - definitionWait = await isWaiting('SELECT * FROM backtests WHERE id = $1 FOR UPDATE'); - } finally { - await blocker.query('COMMIT'); - blocker.release(); - } - const winner = await selected; - if (!changed) { - throw new Error('Concurrent edit was not started'); - } - const loser = await changed; - expect(catalogWait).toBe(true); - expect(definitionWait).toBe(true); - expect(winner.error).toBeNull(); - expect(loser.error).toBeInstanceOf(Error); - expect(loser.error!.message).toContain('does not match'); - const retained = await f.api.getBacktest(saved.id); - expect(retained!.endDate.toISOString()).toBe(manifest().endDate); - expect(retained!.config.datasetHash).toBe(hash); - expect( - (await seedHistoricalRun(f.pool, f.api, { backtestId: saved.id })).dataset.requestedHash - ).toBe(hash); - await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow( - 'Legacy backtest execution is retired' - ); - }); - - test('historical selected snapshots and original receipts survive retired admission and later definition edits', async () => { - const f = await fixture(); - await f.insert(hash, { manifest: manifest(), bars: [{}] }); - const saved = await f.api.createBacktest(request(), { autoStart: false }); - const submission = { principal: 'operator' as const, key: 'dataset-retry' }; - const first = await seedHistoricalRun(f.pool, f.api, { backtestId: saved.id }, submission); - expect(first.dataset).toEqual({ - requestedHash: hash, - pinnedHash: null, - source: 'auto', - state: 'requested', - }); - await f.pool.query( - 'UPDATE backtests SET symbols=\'["OTHER.TEST"]\',config=\'{"datasetHash":"bad"}\' WHERE id=$1', - [saved.id] - ); - await expect(f.pool.query('DELETE FROM backtest_datasets')).rejects.toThrow(); - const retried = await f.api.createRun({ backtestId: saved.id }, submission); - expect(retried.id).toBe(first.id); - expect(retried.dataset).toEqual(first.dataset); - expect((await f.pool.query('SELECT count(*)::int AS n FROM backtest_dispatch')).rows[0].n).toBe( - 1 - ); - await expect( - f.api.createRun({ backtestId: saved.id }, { ...submission, key: 'different' }) - ).rejects.toThrow(); - }); - - test('source_request_freeze_status exposes immutable request and binding independently of run success or later template edits', async () => { - const f = await fixture(); - await f.insert(hash, { manifest: manifest(), bars: [{}] }); - const saved = await f.api.createBacktest( - { ...request(), config: { dataSource: 'eod' } }, - { autoStart: false } - ); - const run = await seedHistoricalRun(f.pool, f.api, { backtestId: saved.id }); - expect(run.dataset).toEqual({ - requestedHash: null, - pinnedHash: null, - source: 'eod', - state: 'requested', - }); - await f.pool.query("UPDATE runs SET status='running' WHERE id=$1", [run.id]); - expect((await f.api.getRun(run.id))!.dataset.state).toBe('preparing'); - await f.pool.query("UPDATE runs SET status='failed' WHERE id=$1", [run.id]); - expect((await f.api.getRun(run.id))!.dataset.state).toBe('unavailable'); - await f.pool.query('UPDATE runs SET dataset_hash=$2 WHERE id=$1', [run.id, hash]); - await f.pool.query('UPDATE backtests SET config=\'{"dataSource":"questdb"}\' WHERE id=$1', [ - saved.id, - ]); - expect(await f.api.getRun(run.id)).toMatchObject({ - status: 'failed', - dataset: { requestedHash: null, pinnedHash: hash, source: 'eod', state: 'pinned' }, - }); - const legacyRunId = randomUUID(); - await f.pool.query( - "INSERT INTO runs(id,backtest_id,run_number,status,dataset_hash) VALUES ($1,$2,2,'completed',$3)", - [legacyRunId, saved.id, hash] - ); - expect((await f.api.getRun(legacyRunId))!.dataset).toEqual({ - requestedHash: null, - pinnedHash: hash, - source: null, - state: 'unknown', - }); - }); -}); diff --git a/test/postgres/dataset-source-preparation.test.ts b/test/postgres/dataset-source-preparation.test.ts deleted file mode 100644 index 97c83662..00000000 --- a/test/postgres/dataset-source-preparation.test.ts +++ /dev/null @@ -1,332 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { readFileSync } from 'node:fs'; -import { mkdtemp, rm, writeFile } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { afterEach, describe, expect, test } from 'bun:test'; -import { Hono } from 'hono'; -import { Pool } from 'pg'; -import { getLogger, setLoggerConfig } from '@stock-bot/logger'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import { - createDatasetV2, - validateDatasetV2, -} from '../../apps/stock/orchestrator/src/data/historical-dataset-v2'; -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 } from '../../apps/stock/web-api/src/services/dataset-preparation.service'; -import { datasetInput } from '../fixtures/historical-v2/dataset'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('source-preparation-postgres'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const cleanup: Array<() => Promise> = []; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); -function at(values: readonly T[], index = 0): T { - const value = values[index]; - if (value === undefined) { - throw new Error('Missing fixture item'); - } - return value; -} -async function fixture() { - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Dedicated stock_bot_safety database required'); - } - const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; - const admin = new Pool({ connectionString: url }); - await admin.query(`CREATE SCHEMA ${schema}`); - const pool = new Pool({ - connectionString: url, - max: 4, - application_name: schema, - options: `-c search_path=${schema} -c statement_timeout=10000`, - }); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - for (const name of [ - '06-create-backtest-tables.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', - '20-research-workspace.sql', - '21-run-reproduction.sql', - '22-experiments.sql', - '23-experiment-retries.sql', - '24-chronological-validation.sql', - '25-walk-forward.sql', - '26-cost-sensitivity.sql', - '27-research-evidence-sources.sql', - ]) { - await pool.query( - readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') - ); - } - await pool.query(`INSERT INTO backtests(name,strategy,symbols,start_date,end_date,initial_capital,config) - VALUES('untouched legacy draft','sma-crossover','["A.US"]','2024-03-01','2024-04-01',1000,'{"fastPeriod":2,"slowPeriod":3}')`); - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, - logger - ); - let queryCount = 0; - Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); - Object.defineProperty(postgres, 'query', { - value: async (sql: string, values?: unknown[]) => { - queryCount++; - return pool.query(sql, values); - }, - }); - const routes = new Hono().route('/', createDatasetRoutes({ postgres, logger })); - const post = (operation: 'preview' | 'retain', body: unknown) => - routes.request(`/api/v2/datasets/canonical/${operation}`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(body), - }); - const snapshot = async (includeDatasets = true) => { - const tables = ( - await pool.query<{ tablename: string }>( - 'SELECT tablename FROM pg_tables WHERE schemaname=$1 ORDER BY tablename', - [schema] - ) - ).rows; - const rows: Record = {}; - for (const { tablename } of tables) { - if (includeDatasets || tablename !== 'backtest_datasets') { - rows[tablename] = ( - await pool.query( - `SELECT to_jsonb(t) AS row FROM "${tablename}" t ORDER BY to_jsonb(t)::text` - ) - ).rows; - } - } - return rows; - }; - const defaults = async () => - ( - await pool.query( - `SELECT table_name,column_name,column_default FROM information_schema.columns WHERE table_schema=$1 ORDER BY table_name,column_name`, - [schema] - ) - ).rows; - return { - pool, - schema, - post, - routes, - snapshot, - defaults, - get queryCount() { - return queryCount; - }, - }; -} - -describe.skipIf(!url)('source-export preparation with retained PostgreSQL custody', () => { - test('preview, invalid input and drift write nothing; retain only adds exact normalized dataset, leaving runs/outbox/templates/schema defaults untouched', async () => { - const f = await fixture(), - input = datasetInput(); - const before = await f.snapshot(), - defaults = await f.defaults(); - const preview = await f.post('preview', { input }); - expect(preview.status).toBe(200); - expect(f.queryCount).toBe(0); - const prepared = previewDatasetPreparation({ input }); - expect(await preview.json()).toEqual({ preparation: prepared }); - expect((await f.post('retain', { input, expectedHash: '0'.repeat(64) })).status).toBe(409); - expect((await f.post('retain', { input: {}, expectedHash: prepared.hash })).status).toBe(400); - expect(f.queryCount).toBe(0); - expect(await f.snapshot()).toEqual(before); - const retained = await f.post('retain', { input, expectedHash: prepared.hash }); - expect(retained.status).toBe(200); - expect(await retained.json()).toEqual({ preparation: prepared }); - const stored = at((await f.pool.query('SELECT hash,payload FROM backtest_datasets')).rows); - expect(stored.hash).toBe(prepared.hash); - expect(stored.payload).toEqual(createDatasetV2(input)); - expect(validateDatasetV2(stored.payload).bars.map(bar => bar.vwap)).toEqual([null, 101, null]); - const { backtest_datasets: _datasets, ...unchanged } = before; - expect(await f.snapshot(false)).toEqual(unchanged); - expect(await f.defaults()).toEqual(defaults); - expect((await f.pool.query('SELECT count(*) AS n FROM runs')).rows).toEqual([{ n: '0' }]); - expect((await f.pool.query('SELECT count(*) AS n FROM backtest_dispatch')).rows).toEqual([ - { n: '0' }, - ]); - const found = await f.routes.request(`/api/v2/datasets/canonical/${prepared.hash}`); - expect(found.status).toBe(200); - expect((await found.json()).dataset).toMatchObject({ - hash: prepared.hash, - manifest: prepared.manifest, - available: true, - reason: null, - }); - }); - - test('concurrent and repeated exact retention is content idempotent with one frozen row and unchanged created_at', async () => { - const f = await fixture(), - input = datasetInput(); - const expected = previewDatasetPreparation({ input }); - const body = { input, expectedHash: expected.hash }; - const replies = await Promise.all(Array.from({ length: 6 }, () => f.post('retain', body))); - for (const reply of replies) { - expect(reply.status).toBe(200); - expect(await reply.json()).toEqual({ preparation: expected }); - } - const before = (await f.pool.query('SELECT * FROM backtest_datasets')).rows; - expect(before).toHaveLength(1); - const repeat = await f.post('retain', body); - expect(repeat.status).toBe(200); - expect(await repeat.json()).toEqual({ preparation: expected }); - const permuted = { ...input, bars: [...input.bars].reverse() }; - expect((await f.post('retain', { input: permuted, expectedHash: expected.hash })).status).toBe( - 200 - ); - expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toEqual(before); - await expect( - f.pool.query('UPDATE backtest_datasets SET payload=$1 WHERE hash=$2', [ - { corrupt: true }, - expected.hash, - ]) - ).rejects.toThrow(); - expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toEqual(before); - }); - - test('valid unavailable source evidence may be retained but remains rejected by the existing picker and execution gate', async () => { - const f = await fixture(), - original = datasetInput(); - const input = { - ...original, - metadata: { - ...original.metadata, - universe: { ...original.metadata.universe, selection: 'unknown' as const, asOf: null }, - }, - }; - const prepared = previewDatasetPreparation({ input }); - expect(prepared.available).toBe(false); - expect(prepared.manifest.eligibility).toBe('exploratory'); - expect((await f.post('retain', { input, expectedHash: prepared.hash })).status).toBe(200); - expect( - validateDatasetV2( - at((await f.pool.query('SELECT payload FROM backtest_datasets')).rows).payload - ).manifest - ).toEqual(prepared.manifest); - const lookup = await f.routes.request(`/api/v2/datasets/canonical/${prepared.hash}`); - expect((await lookup.json()).dataset).toMatchObject({ - available: false, - reason: prepared.reason, - }); - await expect(readCanonicalDataset(f.pool, prepared.hash)).rejects.toThrow( - prepared.reason ?? 'missing reason' - ); - const exported = await f.routes.request(`/api/v2/datasets/canonical/${prepared.hash}/export`); - expect(exported.status).toBe(422); - expect(exported.headers.get('Content-Disposition')).toBeNull(); - expect((await f.pool.query('SELECT count(*) AS n FROM runs')).rows).toEqual([{ n: '0' }]); - }); - - test('a conflicting retained row with structurally valid but hash-corrupted bars fails full readback as sanitized500 and is never overwritten', async () => { - const f = await fixture(), - input = datasetInput(), - dataset = createDatasetV2(input); - const corrupt = { - ...dataset, - bars: dataset.bars.map((bar, index) => (index === 0 ? { ...bar, close: 106 } : bar)), - }; - expect(corrupt).not.toEqual(dataset); - await f.pool.query('INSERT INTO backtest_datasets(hash,payload) VALUES($1,$2)', [ - dataset.manifest.hash, - corrupt, - ]); - const before = await f.snapshot(); - const response = await f.post('retain', { input, expectedHash: dataset.manifest.hash }); - expect(response.status).toBe(500); - expect(response.headers.get('Cache-Control')).toBe('no-store'); - expect(await response.json()).toEqual({ error: 'Source dataset retention unavailable' }); - expect(await f.snapshot()).toEqual(before); - await expect(readCanonicalDataset(f.pool, dataset.manifest.hash)).rejects.toThrow( - 'content validation' - ); - const exported = await f.routes.request( - `/api/v2/datasets/canonical/${dataset.manifest.hash}/export` - ); - expect(exported.status).toBe(409); - expect(exported.headers.get('Content-Disposition')).toBeNull(); - expect(await f.snapshot()).toEqual(before); - }); - - test('validated export feeds the existing --file CLI with identical retained identity and no custody writes', async () => { - const f = await fixture(), - input = datasetInput(), - dataset = createDatasetV2(input); - const directory = await mkdtemp(join(tmpdir(), 'source-preparation-cli-')); - cleanup.push(() => rm(directory, { recursive: true, force: true })); - const file = join(directory, 'dataset.json'); - const connection = new URL(url ?? ''); - connection.searchParams.set('options', `-c search_path=${f.schema}`); - const execute = async (args: string[]) => { - const child = Bun.spawn( - [process.execPath, 'run', 'scripts/import-research-dataset.ts', ...args], - { - cwd: new URL('../../', import.meta.url).pathname, - env: { ...process.env, RESEARCH_DATASET_DATABASE_URL: connection.toString() }, - stdout: 'pipe', - stderr: 'pipe', - } - ); - const [code, out, err] = await Promise.all([ - child.exited, - new Response(child.stdout).text(), - new Response(child.stderr).text(), - ]); - return { code, out, err }; - }; - expect((await f.post('retain', { input, expectedHash: dataset.manifest.hash })).status).toBe( - 200 - ); - const before = await f.snapshot(); - const reads = f.queryCount; - const exported = await f.routes.request( - `/api/v2/datasets/canonical/${dataset.manifest.hash}/export` - ); - expect(exported.status).toBe(200); - expect(exported.headers.get('Content-Type')).toContain('application/json'); - expect(exported.headers.get('Cache-Control')).toBe('no-store'); - expect(exported.headers.get('X-Content-Type-Options')).toBe('nosniff'); - expect(exported.headers.get('Content-Disposition')).toBe( - `attachment; filename="dataset-${dataset.manifest.hash}.json"` - ); - const exportedText = await exported.text(); - expect(validateDatasetV2(JSON.parse(exportedText))).toEqual(dataset); - expect(f.queryCount).toBe(reads + 1); - expect(await f.snapshot()).toEqual(before); - await writeFile(file, exportedText); - const cli = await execute(['--file', file]); - expect(cli.code).toBe(0); - expect(JSON.parse(cli.out)).toEqual({ - hash: dataset.manifest.hash, - barCount: dataset.manifest.barCount, - eligibility: dataset.manifest.eligibility, - limitations: dataset.manifest.limitations, - }); - expect((await execute(['--file', file])).code).toBe(0); - expect(await f.snapshot()).toEqual(before); - const flags = await execute(['--source-hash', dataset.manifest.hash]); - expect(flags.code).toBe(1); - expect(flags.err).toContain('Usage:'); - await writeFile(file, JSON.stringify(input)); - expect((await execute(['--file', file])).code).toBe(1); - expect(await f.snapshot()).toEqual(before); - }); -}); diff --git a/test/postgres/durable-backtest.test.ts b/test/postgres/durable-backtest.test.ts deleted file mode 100644 index 61cba00b..00000000 --- a/test/postgres/durable-backtest.test.ts +++ /dev/null @@ -1,1024 +0,0 @@ -import { fork } from 'node:child_process'; -import { randomUUID } from 'node:crypto'; -import { readFileSync } from 'node:fs'; -import { fileURLToPath } from 'node:url'; -import { afterEach, describe, expect, test } from 'bun:test'; -import { Hono } from 'hono'; -import { Pool } from 'pg'; -import { createHttpSecurity } from '@stock-bot/di'; -import { HandlerRegistry } from '@stock-bot/handler-registry'; -import { getLogger, setLoggerConfig } from '@stock-bot/logger'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import { Queue } from '@stock-bot/queue'; -import { backtestRequestFromDefinition } from '@stock-bot/stock-config/backtest'; -import { - canonicalRunRequestSchema, - type CanonicalRunRequest, - type CanonicalRunResult, -} from '@stock-bot/stock-config/canonical-research'; -import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner'; -import { LegacyBacktestRunWriter } from '../../apps/stock/orchestrator/src/backtest/compatibility/LegacyBacktestRunWriter'; -import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine'; -import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository'; -import { BacktestLeaseLostError } from '../../apps/stock/orchestrator/src/backtest/run-repository'; -import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter'; -import { loadDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset'; -import { StorageService } from '@stock-bot/trading-runtime/historical-storage'; -import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types'; -import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes'; -import { - BacktestServiceV2, - RunSubmissionConflictError, -} from '../../apps/stock/web-api/src/services/backtest-v2.service'; -import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher'; -import { canonicalAdmissionFixture } from '../fixtures/canonical-admission'; -import { canonicalSettings } from '../fixtures/canonical-research'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('durable-backtest-test'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const redisUrl = process.env.BACKTEST_TEST_REDIS_URL; -const cleanup: (() => Promise)[] = []; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); -const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); -async function until(check: () => Promise, timeoutMs = 3_000) { - const deadline = Date.now() + timeoutMs; - while (Date.now() < deadline) { - if (await check()) { - return; - } - await sleep(20); - } - throw new Error('Timed out waiting for durable workflow'); -} - -async function fixture(historical = false) { - if ( - !url || - !new URL(url).pathname.startsWith('/stock_bot_safety') || - !redisUrl || - new URL(redisUrl).pathname !== '/15' - ) { - throw new Error('Dedicated stock_bot_safety database and Redis database 15 required'); - } - const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; - const admin = new Pool({ connectionString: url }); - await admin.query(`CREATE SCHEMA ${schema}`); - const pool = new Pool({ - connectionString: url, - application_name: schema, - options: `-c search_path=${schema}`, - }); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - await pool.query(`CREATE TYPE run_status AS ENUM ('pending','running','completed','failed','cancelled','paused'); - CREATE TABLE backtests (id uuid PRIMARY KEY, name text NOT NULL, strategy text NOT NULL, symbols jsonb NOT NULL, - start_date timestamptz NOT NULL, end_date timestamptz NOT NULL, initial_capital numeric NOT NULL, config jsonb, - created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW()); - CREATE TABLE runs (id uuid PRIMARY KEY, backtest_id uuid REFERENCES backtests(id) ON DELETE CASCADE, run_number integer, - status run_status DEFAULT 'pending', speed_multiplier numeric, progress numeric DEFAULT 0, error text, - started_at timestamptz, completed_at timestamptz, paused_at timestamptz, current_simulation_date timestamptz, - created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW(), UNIQUE(backtest_id, run_number)); - CREATE TABLE backtest_results (run_id uuid REFERENCES runs(id) ON DELETE CASCADE, completed_at timestamptz, - metrics jsonb, equity_curve jsonb, ohlc_data jsonb, trades jsonb, positions jsonb, analytics jsonb, execution_time numeric);`); - for (const filename of [ - '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/${filename}`, import.meta.url), 'utf8') - ); - } - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, - logger - ); - Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); - Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); - const endpoint = new URL(redisUrl); - const redis = { - host: endpoint.hostname, - port: Number(endpoint.port || 6379), - db: 15, - ...(endpoint.password ? { password: decodeURIComponent(endpoint.password) } : {}), - }; - const queueName = `stock-bot-safety-${randomUUID()}`; - const queue = new Queue(queueName, redis, {}, { workers: 0 }, logger); - await queue.getBullQueue().waitUntilReady(); - cleanup.push(async () => { - await queue.getBullQueue().obliterate({ force: true }); - await queue.close(); - }); - const dispatcher = new BacktestDispatcher(postgres, queue, logger, { - intervalMs: 20, - republishMs: 50, - maxAttempts: 3, - }); - cleanup.push(() => dispatcher.shutdown()); - const api = new BacktestServiceV2({ postgres, logger }, async () => { - throw new Error('No HTTP execution dispatch allowed'); - }); - const legacyDefinition = historical - ? await api.createBacktest( - { - name: 'Durable fixture', - strategy: 'sma-crossover', - symbols: ['FIXTURE.TEST'], - startDate: '2024-01-01T00:00:00.000Z', - endDate: '2024-03-15T00:00:00.000Z', - initialCapital: 100000, - config: { fastPeriod: 3, slowPeriod: 7, commission: 0, slippage: 0 }, - }, - { autoStart: false } - ) - : undefined; - const canonical = historical ? undefined : await canonicalAdmissionFixture(pool, postgres, false); - const definition = canonical?.draft ?? legacyDefinition!; - const definitionInput = canonical?.definition ?? { - name: definition.name, - strategy: definition.strategy, - symbols: definition.symbols, - startDate: definition.startDate.toISOString(), - endDate: definition.endDate.toISOString(), - initialCapital: definition.initialCapital, - config: definition.config, - }; - // This raw insertion represents already accepted pre-cutover history. It is - // deliberately not exposed through a service or production admission switch. - const historicalRun = async (_request: { backtestId: string }) => { - if (!historical) { - throw new Error('Historical fixture only'); - } - const runId = randomUUID(); - const snapshot = backtestRequestFromDefinition(definitionInput, { - runId, - backtestId: definition.id, - }); - await pool.query( - `INSERT INTO runs(id,backtest_id,run_number,request_snapshot) - SELECT $1,$2,COALESCE(MAX(run_number),0)+1,$3 FROM runs WHERE backtest_id=$2`, - [runId, definition.id, snapshot] - ); - await pool.query('INSERT INTO backtest_dispatch(run_id) VALUES($1)', [runId]); - return { id: runId }; - }; - const repository = new PostgresBacktestRunRepository(postgres, 2_000); - const legacyWriter = new LegacyBacktestRunWriter(postgres, 2_000); - const history = { reads: 0, unavailable: false }; - const storage = { - async getHistoricalBars() { - history.reads++; - if (history.unavailable) { - throw new Error('Provider history unavailable'); - } - return Array.from({ length: 70 }, (_, i) => { - const close = 100 + Math.sin((i * Math.PI) / 6) * 8; - return { - symbol: 'FIXTURE.TEST', - source: 'eod', - timestamp: new Date(Date.parse(definition.startDate.toISOString()) + i * 86400000), - open: close, - high: close + 1, - low: close - 1, - close, - volume: 1000000, - }; - }); - }, - } as unknown as StorageService; - const engine = new RustBacktestAdapter({ logger }, { timeoutMs: 5_000 }); - const runner = new BacktestRunner({ - engine, - repository, - logger, - heartbeatMs: 50, - }); - cleanup.push(() => runner.shutdown()); - const enqueueWorker = () => { - const registry = new HandlerRegistry(); - registry.registerConfiguration({ - name: 'orchestrator', - operations: { - 'run-backtest': async payload => runner.runQueued((payload as { runId: string }).runId), - }, - }); - const worker = new Queue( - queueName, - redis, - {}, - { workers: 1, concurrency: 1, handlerRegistry: registry }, - logger - ); - cleanup.push(async () => { - await runner.shutdown(); - await worker.close(); - }); - return worker; - }; - const snapshot = async (runId: string) => - canonicalRunRequestSchema.parse( - (await pool.query('SELECT request_snapshot FROM runs WHERE id = $1', [runId])).rows[0] - .request_snapshot - ); - const legacySnapshot = async (runId: string) => - BacktestConfigSchema.parse( - (await pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])).rows[0] - .request_snapshot - ); - const report = async (request: CanonicalRunRequest): Promise => ({ - kind: 'canonical-result/v1', - runId: request.runId, - backtestId: request.backtestId, - status: 'completed', - completedAt: new Date().toISOString(), - executionTime: 1, - financialEngine: 'rust', - strategyExecution: 'typescript-retained-builtin/v1', - request, - ...(await engine.runCanonical(request, async () => canonical!.dataset)), - }); - const expire = async (runId: string) => { - await pool.query( - "UPDATE runs SET lease_expires_at = NOW() - INTERVAL '1 second' WHERE id = $1", - [runId] - ); - }; - return { - schema, - pool, - postgres, - api, - definition, - definitionInput, - repository, - legacyWriter, - runner, - engine, - queue, - dispatcher, - enqueueWorker, - snapshot, - legacySnapshot, - historicalRun, - report, - canonical, - expire, - history, - storage, - }; -} - -describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Redis', () => { - test('idempotent_submission_postgres_race: one snapshot/outbox, canonical null speed and stable original intent after edits', async () => { - const f = await fixture(); - const submission = { principal: 'operator' as const, key: 'same-intent' }; - const runs = await Promise.all( - Array.from({ length: 8 }, (_, i) => - f.api.createRun( - { backtestId: f.definition.id, ...(i % 2 ? { speedMultiplier: null } : {}) }, - submission - ) - ) - ); - expect(new Set(runs.map(run => run.id)).size).toBe(1); - const original = await f.snapshot(runs[0]!.id); - await f.api.updateBacktest(f.definition.id, { - initialCapital: 12345, - strategyParameters: { fastPeriod: 3, slowPeriod: 4 }, - }); - expect((await f.api.createRun({ backtestId: f.definition.id }, submission)).id).toBe( - runs[0]!.id - ); - expect(await f.snapshot(runs[0]!.id)).toEqual(original); - expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(1); - expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1); - await expect( - f.api.createRun({ backtestId: f.definition.id, speedMultiplier: 2 }, submission) - ).rejects.toBeInstanceOf(RunSubmissionConflictError); - }); - - test('submission_key_conflict: different definitions racing for one principal/key cannot both commit', async () => { - const f = await fixture(); - const second = await f.api.createBacktest( - { - ...f.definitionInput, - startDate: f.definition.startDate.toISOString(), - endDate: f.definition.endDate.toISOString(), - name: 'Second', - }, - { autoStart: false } - ); - const barrierKey = parseInt(randomUUID().slice(0, 7), 16); - await f.pool - .query(`CREATE FUNCTION delay_submission() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN - PERFORM pg_advisory_xact_lock_shared(40303, ${barrierKey}); RETURN NEW; END $$; - CREATE TRIGGER delay_submission BEFORE INSERT ON runs FOR EACH ROW EXECUTE FUNCTION delay_submission()`); - const submission = { principal: 'operator' as const, key: 'cross-definition' }; - const barrier = await f.pool.connect(); - await barrier.query('SELECT pg_advisory_lock(40303, $1)', [barrierKey]); - const submissions = Promise.allSettled( - [f.definition.id, second.id].map(backtestId => f.api.createRun({ backtestId }, submission)) - ); - try { - // Both requests passed their initial receipt lookup and hold distinct parent - // locks. One waits inside INSERT; the other waits on the shared strategy - // family lock. The stale second receipt lookup must still conflict after - // the first transaction commits, rather than returning its unrelated run. - await until( - async () => - ( - await f.pool.query( - "SELECT count(*)::int AS count FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock'", - [f.schema] - ) - ).rows[0].count === 2 - ); - expect( - ( - await f.pool.query( - "SELECT count(*)::int AS count FROM pg_locks WHERE locktype='advisory' AND classid=40303 AND objid=$1 AND NOT granted", - [barrierKey] - ) - ).rows[0].count - ).toBe(1); - expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0); - } finally { - await barrier.query('SELECT pg_advisory_unlock(40303, $1)', [barrierKey]); - barrier.release(); - } - const outcomes = await submissions; - expect(outcomes.filter(outcome => outcome.status === 'fulfilled')).toHaveLength(1); - const rejection = outcomes.find(outcome => outcome.status === 'rejected'); - expect(rejection?.status === 'rejected' && rejection.reason).toBeInstanceOf( - RunSubmissionConflictError - ); - const committed = (await f.pool.query('SELECT * FROM runs')).rows; - expect(committed).toHaveLength(1); - expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1); - const otherId = committed[0].backtest_id === f.definition.id ? second.id : f.definition.id; - await expect(f.api.createRun({ backtestId: otherId }, submission)).rejects.toBeInstanceOf( - RunSubmissionConflictError - ); - }); - - test('different principals can reuse keys; concurrent distinct and unkeyed submissions preserve run numbering', async () => { - const f = await fixture(); - const runs = await Promise.all([ - f.api.createRun({ backtestId: f.definition.id }, { principal: 'operator', key: 'shared' }), - f.api.createRun({ backtestId: f.definition.id }, { principal: 'service', key: 'shared' }), - ...Array.from({ length: 4 }, (_, i) => - f.api.createRun( - { backtestId: f.definition.id }, - { principal: 'operator', key: `intent-${i}` } - ) - ), - f.api.createRun({ backtestId: f.definition.id }), - f.api.createRun({ backtestId: f.definition.id }), - ]); - expect(new Set(runs.map(run => run.id)).size).toBe(8); - expect(runs.map(run => run.runNumber).sort((a, b) => a - b)).toEqual([1, 2, 3, 4, 5, 6, 7, 8]); - expect( - (await f.pool.query('SELECT * FROM runs WHERE submission_key IS NULL')).rows - ).toHaveLength(2); - expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(8); - }); - - test('outbox failure rolls back the submission claim and retry creates exactly one run', async () => { - const f = await fixture(); - await f.pool - .query(`CREATE FUNCTION reject_submission_outbox() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN - RAISE EXCEPTION 'injected submission outbox failure'; END $$; - CREATE TRIGGER reject_submission_outbox BEFORE INSERT ON backtest_dispatch FOR EACH ROW EXECUTE FUNCTION reject_submission_outbox()`); - const submission = { principal: 'operator' as const, key: 'retry-after-rollback' }; - await expect(f.api.createRun({ backtestId: f.definition.id }, submission)).rejects.toThrow( - 'injected submission' - ); - expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0); - await f.pool.query('DROP TRIGGER reject_submission_outbox ON backtest_dispatch'); - const created = await f.api.createRun({ backtestId: f.definition.id }, submission); - expect((await f.api.createRun({ backtestId: f.definition.id }, submission)).id).toBe( - created.id - ); - expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1); - }); - - test('save_only catalog route requires explicit false; authenticated keyed submissions return202/Location or409', async () => { - const f = await fixture(); - const app = new Hono(); - createHttpSecurity({ disabled: true, environment: 'test' }).mount(app); - app.route('/', createBacktestV2Routes({ postgres: f.postgres, logger })); - const body = { ...f.definitionInput, autoStart: false }; - expect( - ( - await app.request('/api/v2/backtests', { - method: 'POST', - body: JSON.stringify({ ...body, autoStart: 'false' }), - }) - ).status - ).toBe(400); - const saved = await app.request('/api/v2/backtests', { - method: 'POST', - body: JSON.stringify(body), - }); - expect(saved.status).toBe(201); - const definition = await saved.json(); - expect(await f.api.listRuns(definition.id)).toHaveLength(0); - const post = (payload: object) => - app.request(`/api/v2/backtests/${definition.id}/runs`, { - method: 'POST', - headers: { 'Idempotency-Key': 'route-retry' }, - body: JSON.stringify(payload), - }); - const response = await post({}); - expect(response.status).toBe(202); - const run = await response.json(); - expect(response.headers.get('Location')).toBe(`/api/v2/runs/${run.id}`); - expect((await (await post({ speedMultiplier: null })).json()).id).toBe(run.id); - expect((await post({ speedMultiplier: 2 })).status).toBe(409); - const saveOnly = await app.request('/api/v2/backtests', { - method: 'POST', - body: JSON.stringify({ ...body, autoStart: undefined }), - }); - expect(saveOnly.status).toBe(400); - expect((await f.pool.query('SELECT count(*)::int AS count FROM backtests')).rows[0].count).toBe( - 2 - ); - }); - - test('cookie renewal and admin bearer replay the same operator submission while service keys are separate', async () => { - const f = await fixture(); - const adminToken = 'submission-fixture-admin-not-a-secret-123456'; - const serviceToken = 'submission-fixture-service-not-a-secret-123456'; - const app = new Hono(); - createHttpSecurity({ - adminToken, - serviceToken, - browserSessions: true, - origins: ['http://ui.test'], - }).mount(app); - app.route('/', createBacktestV2Routes({ postgres: f.postgres, logger })); - const submit = async (headers: Record) => { - const response = await app.request(`/api/v2/backtests/${f.definition.id}/runs`, { - method: 'POST', - headers: { - 'Idempotency-Key': 'authenticated-intent', - 'X-Principal': 'spoofed', - ...headers, - }, - body: '{}', - }); - expect(response.status).toBe(202); - return (await response.json()).id as string; - }; - const original = await submit({ Authorization: `Bearer ${adminToken}` }); - for (let i = 0; i < 2; i++) { - const login = await app.request('/api/auth/session', { - method: 'POST', - headers: { 'Content-Type': 'application/json', Origin: 'http://ui.test' }, - body: JSON.stringify({ token: adminToken }), - }); - expect(login.status).toBe(200); - expect( - await submit({ - Cookie: login.headers.get('Set-Cookie')!.split(';')[0]!, - Origin: 'http://ui.test', - }) - ).toBe(original); - } - expect(await submit({ Authorization: `Bearer ${serviceToken}` })).not.toBe(original); - expect( - (await f.pool.query('SELECT submission_principal FROM runs ORDER BY run_number')).rows - ).toEqual([{ submission_principal: 'operator' }, { submission_principal: 'service' }]); - expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(2); - }); - - test('a lease expiring during snapshot insertion cannot pin or leave an orphan snapshot', async () => { - const f = await fixture(true); - const run = await f.historicalRun({ backtestId: f.definition.id }); - const config = await f.legacySnapshot(run.id); - const dataset = await loadDataset(f.storage, config); - await f.pool - .query(`CREATE FUNCTION delay_snapshot() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN - PERFORM pg_sleep(0.35); RETURN NEW; END $$; - CREATE TRIGGER delay_snapshot BEFORE INSERT ON backtest_datasets FOR EACH ROW EXECUTE FUNCTION delay_snapshot()`); - const short = new LegacyBacktestRunWriter(f.postgres, 250); - const claim = await short.start(config); - await expect(short.freezeDataset(run.id, claim.attemptId, dataset)).rejects.toBeInstanceOf( - BacktestLeaseLostError - ); - expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(0); - expect( - (await f.pool.query('SELECT dataset_hash FROM runs WHERE id = $1', [run.id])).rows[0] - .dataset_hash - ).toBeNull(); - }); - test('retained canonical inputs survive owner loss and replay without provider reads', async () => { - const f = await fixture(); - const first = await f.api.createRun({ backtestId: f.definition.id }); - await f.runner.runQueued(first.id); - const baseline = await f.api.getRunResults(first.id); - const run = await f.api.createRun({ backtestId: f.definition.id }); - const old = await f.repository.startCanonical(await f.snapshot(run.id)); - const frozen = await f.repository.loadCanonicalDataset( - run.id, - old.attemptId, - f.canonical!.dataset.manifest.hash - ); - await f.expire(run.id); - await expect( - f.repository.loadCanonicalDataset(run.id, old.attemptId, frozen.manifest.hash) - ).rejects.toBeInstanceOf(BacktestLeaseLostError); - f.history.unavailable = true; - await f.dispatcher.tick(); - await f.runner.runQueued(run.id); - const replay = await f.api.getRunResults(run.id); - if (!baseline || !replay || !('financial' in baseline) || !('financial' in replay)) { - throw new Error('Canonical results required'); - } - expect(f.history.reads).toBe(0); - expect(replay.financial.projection.valuation).toEqual(baseline.financial.projection.valuation); - expect(replay.financial.projection.fills).toEqual(baseline.financial.projection.fills); - expect(replay.analytics).toEqual(baseline.analytics); - expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(1); - }); - - test('snapshot insertion and the run pointer roll back together; frozen inputs cannot be replaced', async () => { - const f = await fixture(true); - const run = await f.historicalRun({ backtestId: f.definition.id }); - const config = await f.legacySnapshot(run.id); - const claim = await f.legacyWriter.start(config); - const dataset = await loadDataset(f.storage, config); - await f.pool - .query(`CREATE FUNCTION reject_dataset_pointer() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN - IF NEW.dataset_hash IS NOT NULL THEN RAISE EXCEPTION 'injected snapshot pointer failure'; END IF; RETURN NEW; END $$; - CREATE TRIGGER reject_dataset_pointer BEFORE UPDATE ON runs FOR EACH ROW EXECUTE FUNCTION reject_dataset_pointer()`); - await expect(f.legacyWriter.freezeDataset(run.id, claim.attemptId, dataset)).rejects.toThrow( - 'injected' - ); - expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(0); - expect( - (await f.pool.query('SELECT dataset_hash FROM runs WHERE id = $1', [run.id])).rows[0] - .dataset_hash - ).toBeNull(); - await f.pool.query('DROP TRIGGER reject_dataset_pointer ON runs'); - await f.legacyWriter.freezeDataset(run.id, claim.attemptId, dataset); - const different = await loadDataset(f.storage, { - ...config, - dataPolicy: { adjustment: 'raw', timestamp: 'utc-session-date' }, - endDate: '2024-03-16T00:00:00.000Z', - }); - await expect(f.legacyWriter.freezeDataset(run.id, claim.attemptId, different)).rejects.toThrow( - 'already frozen' - ); - expect((await f.legacyWriter.loadDataset(run.id, claim.attemptId))?.manifest.hash).toBe( - dataset.manifest.hash - ); - }); - - test('cancellation after snapshot insertion aborts preparation and rolls back the run pointer and payload', async () => { - const f = await fixture(true); - const run = await f.historicalRun({ backtestId: f.definition.id }); - const config = await f.legacySnapshot(run.id); - const claim = await f.legacyWriter.start(config); - const dataset = await loadDataset(f.storage, config); - const controller = new AbortController(); - const reason = new BacktestCancelledError(); - const repository = new LegacyBacktestRunWriter({ - transaction: work => - f.postgres.transaction(client => - work( - new Proxy(client, { - get(target, key) { - if (key !== 'query') { - return Reflect.get(target, key); - } - return async (sql: string, params?: unknown[]) => { - const result = await target.query(sql, params); - if (sql.startsWith('INSERT INTO backtest_datasets')) { - controller.abort(reason); - } - return result; - }; - }, - }) - ) - ), - }); - await expect( - repository.freezeDataset(run.id, claim.attemptId, dataset, controller.signal) - ).rejects.toBe(reason); - expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(0); - expect( - (await f.pool.query('SELECT dataset_hash FROM runs WHERE id = $1', [run.id])).rows[0] - .dataset_hash - ).toBeNull(); - await expect( - repository.loadDataset(run.id, claim.attemptId, undefined, controller.signal) - ).rejects.toBe(reason); - }); - - test('restored snapshots are revalidated rather than trusted by their content-addressed key', async () => { - const f = await fixture(true); - const run = await f.historicalRun({ backtestId: f.definition.id }); - const config = await f.legacySnapshot(run.id); - const claim = await f.legacyWriter.start(config); - const dataset = await loadDataset(f.storage, config); - // Model corrupt historical storage at initial insertion; retained evidence cannot be edited. - const corrupt = structuredClone(dataset); - corrupt.bars[0]!.volume = 0; - await f.pool.query('INSERT INTO backtest_datasets(hash,payload) VALUES ($1,$2)', [ - dataset.manifest.hash, - corrupt, - ]); - await f.pool.query('UPDATE runs SET dataset_hash=$2 WHERE id=$1', [ - run.id, - dataset.manifest.hash, - ]); - const reads = f.history.reads; - f.history.unavailable = true; - await expect(f.legacyWriter.loadDataset(run.id, claim.attemptId)).rejects.toThrow( - 'hash/content' - ); - await f.expire(run.id); - await f.dispatcher.tick(); - expect((await f.runner.runQueued(run.id)).status).toBe('failed'); - expect((await f.api.getRun(run.id))?.error).toContain('Legacy backtest execution is retired'); - expect((await f.api.getRun(run.id))?.status).toBe('failed'); - expect(await f.api.getRunResults(run.id)).toBeNull(); - expect(f.history.reads).toBe(reads); - }); - - test('a missing retained dataset fails a historical request without provider fallback', async () => { - const f = await fixture(true); - const runId = randomUUID(); - const snapshot = backtestRequestFromDefinition( - { ...f.definitionInput, config: { ...f.definition.config, datasetHash: 'f'.repeat(64) } }, - { runId, backtestId: f.definition.id } - ); - // Imported history can reference unavailable storage; retain its request and report the loss. - await f.pool.query( - 'INSERT INTO runs(id,backtest_id,run_number,request_snapshot) VALUES ($1,$2,1,$3)', - [runId, f.definition.id, snapshot] - ); - await f.pool.query('INSERT INTO backtest_dispatch(run_id) VALUES ($1)', [runId]); - f.history.unavailable = true; - expect((await f.runner.runQueued(runId)).status).toBe('failed'); - expect((await f.api.getRun(runId))?.error).toContain('Legacy backtest execution is retired'); - expect(f.history.reads).toBe(0); - expect((await f.api.getRun(runId))?.status).toBe('failed'); - expect(await f.api.getRunResults(runId)).toBeNull(); - }); - - test('canonical admission rejects template ranges inconsistent with its retained dataset', async () => { - const f = await fixture(); - await expect( - f.api.updateBacktest(f.definition.id, { endDate: '2025-01-01T00:00:00.000Z' }) - ).rejects.toThrow('trade bounds'); - await f.pool.query('UPDATE backtests SET end_date=$2 WHERE id=$1', [ - f.definition.id, - '2025-01-01T00:00:00.000Z', - ]); - await expect(f.api.createRun({ backtestId: f.definition.id })).rejects.toThrow(); - expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0); - expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(0); - }); - test('canonical admission rejects malformed policy and legacy pacing before run/outbox writes', async () => { - const f = await fixture(); - await expect( - f.api.createRun({ backtestId: f.definition.id, speedMultiplier: 7 }) - ).rejects.toThrow('maximum speed'); - await f.pool.query('UPDATE backtests SET config=$2 WHERE id=$1', [ - f.definition.id, - { ...f.definition.config, canonical: { ...canonicalSettings, feeRate: '-1' } }, - ]); - await expect(f.api.createRun({ backtestId: f.definition.id })).rejects.toThrow(); - expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0); - expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(0); - }); - - test('acceptance commits run + immutable snapshot + intent atomically, with no Redis/HTTP dependency', async () => { - const f = await fixture(); - await f.pool - .query(`CREATE FUNCTION reject_dispatch() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN - RAISE EXCEPTION 'injected outbox failure'; END $$; - CREATE TRIGGER reject_dispatch BEFORE INSERT ON backtest_dispatch FOR EACH ROW EXECUTE FUNCTION reject_dispatch();`); - await expect(f.api.createRun({ backtestId: f.definition.id })).rejects.toThrow( - 'injected outbox' - ); - expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0); - await f.pool.query('DROP TRIGGER reject_dispatch ON backtest_dispatch'); - const response = await createBacktestV2Routes({ postgres: f.postgres, logger }).request( - `/api/v2/backtests/${f.definition.id}/runs`, - { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' } - ); - expect(response.status).toBe(202); - const run = (await response.json()) as { id: string; status: string }; - expect(response.headers.get('location')).toBe(`/api/v2/runs/${run.id}`); - expect(f.queue.getWorkerCount()).toBe(0); - expect(run.status).toBe('pending'); - expect( - (await f.pool.query('SELECT * FROM backtest_dispatch WHERE run_id = $1', [run.id])).rows - ).toHaveLength(1); - await f.api.updateBacktest(f.definition.id, { - strategyParameters: { fastPeriod: 3, slowPeriod: 4 }, - name: 'Mutated after admission', - }); - // A fresh dispatcher models an API restart after SQL commit but before the first publish. - const restarted = new BacktestDispatcher(f.postgres, f.queue, logger); - await restarted.tick(); - await restarted.shutdown(); - f.enqueueWorker(); - await until(async () => (await f.api.getRun(run.id))?.status === 'completed'); - const result = await f.api.getRunResults(run.id); - expect(result).toHaveProperty('kind', 'canonical-result/v1'); - if (!result || !('request' in result)) { - throw new Error('Canonical result required'); - } - expect(result.request.strategy.selection.instrumentId).toBe(f.definition.symbols[0]!); - expect(result.request.strategy.selection.parameters).toMatchObject({ fastPeriod: 2 }); - expect((await f.api.getRun(run.id))?.attemptNumber).toBe(1); - }); - - test('duplicate deliveries and competing claims execute once and persist exactly one result', async () => { - const f = await fixture(); - const run = await f.api.createRun({ backtestId: f.definition.id }); - const config = await f.snapshot(run.id); - const claims = await Promise.allSettled([ - f.repository.startCanonical(config), - f.repository.startCanonical(config), - ]); - expect(claims.filter(result => result.status === 'fulfilled')).toHaveLength(1); - expect(claims.filter(result => result.status === 'rejected')).toHaveLength(1); - await f.expire(run.id); - await f.dispatcher.tick(); - f.enqueueWorker(); - await until(async () => (await f.api.getRun(run.id))?.status === 'completed'); - await f.runner.runQueued(run.id); - await f.runner.runQueued(run.id); - await f.queue.add('duplicate', { - handler: 'orchestrator', - operation: 'run-backtest', - payload: { runId: run.id }, - }); - await until(async () => (await f.queue.getStats()).completed > 0); - expect( - (await f.pool.query('SELECT * FROM backtest_results WHERE run_id = $1', [run.id])).rows - ).toHaveLength(1); - expect((await f.api.getRun(run.id))?.attemptNumber).toBe(2); - }); - - test('expired owners cannot heartbeat, write progress/control/failure/cancellation, or commit a stale result', async () => { - const f = await fixture(); - const run = await f.api.createRun({ backtestId: f.definition.id }); - const request = await f.snapshot(run.id); - const old = await f.repository.startCanonical(request); - const result = await f.report(request); - await f.expire(run.id); - await f.dispatcher.tick(); - const replacement = await f.repository.startCanonical(await f.snapshot(run.id)); - await expect(f.repository.heartbeat(run.id, old.attemptId)).rejects.toBeInstanceOf( - BacktestLeaseLostError - ); - await expect( - f.repository.updateProgress(run.id, 99, undefined, old.attemptId) - ).rejects.toBeInstanceOf(BacktestLeaseLostError); - await expect( - f.legacyWriter.updateControl(run.id, { status: 'paused' }, old.attemptId) - ).rejects.toBeInstanceOf(BacktestLeaseLostError); - await expect(f.repository.cancel(run.id, old.attemptId)).rejects.toBeInstanceOf( - BacktestLeaseLostError - ); - await f.repository.fail(run.id, 'stale failure', old.attemptId); - await expect(f.repository.completeCanonical(result, old.attemptId)).rejects.toBeInstanceOf( - BacktestLeaseLostError - ); - expect((await f.api.getRun(run.id))?.status).toBe('running'); - await f.repository.loadCanonicalDataset(run.id, replacement.attemptId, request.datasetHash); - await f.repository.completeCanonical(result, replacement.attemptId); - expect( - (await f.pool.query('SELECT * FROM backtest_results WHERE run_id = $1', [run.id])).rows - ).toHaveLength(1); - }); - - test('healthy heartbeats prevent reclamation; cancellation before claim never executes', async () => { - const f = await fixture(); - const run = await f.api.createRun({ backtestId: f.definition.id }); - const shortLease = new PostgresBacktestRunRepository(f.postgres, 300); - const claim = await shortLease.startCanonical(await f.snapshot(run.id)); - await sleep(200); - await shortLease.heartbeat(run.id, claim.attemptId); - await sleep(150); - await f.dispatcher.tick(); - expect((await f.api.getRun(run.id))?.attemptNumber).toBe(1); - expect((await f.api.getRun(run.id))?.status).toBe('running'); - const queued = await f.api.createRun({ backtestId: f.definition.id }); - await f.api.cancelRun(queued.id); - await f.api.cancelRun(queued.id); - expect((await f.runner.runQueued(queued.id)).status).toBe('cancelled'); - expect((await f.api.getRun(queued.id))?.attemptNumber).toBe(0); - expect(await f.api.getRunResults(queued.id)).toBeNull(); - }); - - test('a heartbeat blocked behind a row lock cannot resurrect an expired lease using transaction-start time', async () => { - const f = await fixture(); - const run = await f.api.createRun({ backtestId: f.definition.id }); - const shortLease = new PostgresBacktestRunRepository(f.postgres, 300); - const claim = await shortLease.startCanonical(await f.snapshot(run.id)); - const lock = await f.pool.connect(); - let renewal: Promise | undefined; - try { - await lock.query('BEGIN'); - await lock.query('SELECT id FROM runs WHERE id = $1 FOR UPDATE', [run.id]); - renewal = shortLease.heartbeat(run.id, claim.attemptId).catch(error => error); - await sleep(400); - await lock.query('COMMIT'); - expect(await renewal).toBeInstanceOf(BacktestLeaseLostError); - } finally { - await lock.query('ROLLBACK'); - lock.release(); - } - await f.dispatcher.tick(); - expect((await f.api.getRun(run.id))?.status).toBe('pending'); - }); - - test('cancellation wins against late completion and expires an abandoned cancelled owner truthfully', async () => { - const f = await fixture(); - const run = await f.api.createRun({ backtestId: f.definition.id }); - const claim = await f.repository.startCanonical(await f.snapshot(run.id)); - const result = await f.report(await f.snapshot(run.id)); - await f.api.cancelRun(run.id); - expect((await f.repository.heartbeat(run.id, claim.attemptId)).cancelRequested).toBe(true); - await expect(f.repository.completeCanonical(result, claim.attemptId)).rejects.toBeInstanceOf( - BacktestCancelledError - ); - await f.expire(run.id); - await f.dispatcher.tick(); - expect((await f.api.getRun(run.id))?.status).toBe('cancelled'); - expect(await f.api.getRunResults(run.id)).toBeNull(); - }); - - test('expired attempts retry at most three times, then become failed without a result', async () => { - const f = await fixture(); - const run = await f.api.createRun({ backtestId: f.definition.id }); - for (let attempt = 1; attempt <= 3; attempt++) { - await f.repository.startCanonical(await f.snapshot(run.id)); - await f.expire(run.id); - await f.dispatcher.tick(); - expect((await f.api.getRun(run.id))?.status).toBe(attempt === 3 ? 'failed' : 'pending'); - } - expect((await f.api.getRun(run.id))?.error).toContain('retry limit'); - expect((await f.runner.runQueued(run.id)).status).toBe('failed'); - expect(await f.api.getRunResults(run.id)).toBeNull(); - }); - - test('a hard-killed execution process is recovered by a fresh dispatcher and owner', async () => { - const f = await fixture(); - const run = await f.api.createRun({ backtestId: f.definition.id }); - const child = fork( - fileURLToPath(new URL('../fixtures/backtest-crash-owner.ts', import.meta.url)), - [], - { - execPath: process.execPath, - execArgv: [], - stdio: ['ignore', 'ignore', 'pipe', 'ipc'], - env: { ...process.env, BACKTEST_FIXTURE_SCHEMA: f.schema, BACKTEST_FIXTURE_RUN_ID: run.id }, - } - ); - const closed = new Promise(resolve => child.once('close', () => resolve())); - cleanup.push(async () => { - child.kill('SIGKILL'); - await closed; - }); - await new Promise((resolve, reject) => { - const timeout = setTimeout(() => reject(new Error('Crash owner did not claim')), 3_000); - child.once('message', () => { - clearTimeout(timeout); - resolve(); - }); - child.once('error', reject); - child.once('exit', code => { - clearTimeout(timeout); - if (code) { - reject(new Error(`Crash owner exited: ${code}`)); - } - }); - }); - expect((await f.api.getRun(run.id))?.status).toBe('running'); - child.kill('SIGKILL'); - await closed; - // Wait for the real lease; do not alter the crashed owner's SQL state. - await sleep(550); - await f.dispatcher.tick(); - f.enqueueWorker(); - await until(async () => (await f.api.getRun(run.id))?.status === 'completed'); - expect((await f.api.getRun(run.id))?.attemptNumber).toBe(2); - expect( - (await f.pool.query('SELECT * FROM backtest_results WHERE run_id = $1', [run.id])).rows - ).toHaveLength(1); - }); - - test('publication failure retains intent; a restarted publisher recovers the same accepted run', async () => { - const f = await fixture(); - const run = await f.api.createRun({ backtestId: f.definition.id }); - const connection = await f.queue.getBullQueue().client; - connection.disconnect(); - await expect(f.dispatcher.tick()).rejects.toThrow(); - // Only this fixture producer's socket is disconnected; no shared Redis data is touched. - await connection.connect(); - expect((await f.api.getRun(run.id))?.status).toBe('pending'); - await sleep(60); - await f.dispatcher.tick(); - f.enqueueWorker(); - await until(async () => (await f.api.getRun(run.id))?.status === 'completed'); - expect((await f.api.getRun(run.id))?.attemptNumber).toBe(1); - }); - - test('lost Redis notifications are republished; concurrent publishers reserve each SQL intent once', async () => { - const f = await fixture(); - const run = await f.api.createRun({ backtestId: f.definition.id }); - const second = new BacktestDispatcher(f.postgres, f.queue, logger, { - intervalMs: 20, - republishMs: 50, - maxAttempts: 3, - }); - await Promise.all([f.dispatcher.tick(), second.tick()]); - expect( - ( - await f.pool.query('SELECT publish_count FROM backtest_dispatch WHERE run_id = $1', [ - run.id, - ]) - ).rows[0].publish_count - ).toBe(1); - const notification = await f.queue.getJob(`backtest-${run.id}`); - await notification!.remove(); - await sleep(60); - await second.tick(); - await second.shutdown(); - f.enqueueWorker(); - await until(async () => (await f.api.getRun(run.id))?.status === 'completed'); - expect((await f.api.getRun(run.id))?.attemptNumber).toBe(1); - }); - - test('invalid persisted snapshots become failed instead of remaining stranded pending', async () => { - const f = await fixture(true); - const run = { id: randomUUID() }; - // A legacy malformed snapshot is inserted as found, not fabricated by editing retained evidence. - await f.pool.query( - "INSERT INTO runs(id,backtest_id,run_number,request_snapshot) VALUES ($1,$2,1,'{}')", - [run.id, f.definition.id] - ); - await f.pool.query('INSERT INTO backtest_dispatch(run_id) VALUES ($1)', [run.id]); - await expect(f.runner.runQueued(run.id)).rejects.toThrow(); - expect((await f.api.getRun(run.id))?.status).toBe('failed'); - expect((await f.api.getRun(run.id))?.attemptNumber).toBe(0); - }); - - test('migration replay preserves leased owners, backfills legacy pending snapshots, and fails ownerless legacy runs', async () => { - const f = await fixture(true); - const pending = { id: randomUUID() }; - await f.pool.query('INSERT INTO runs(id,backtest_id,run_number) VALUES ($1,$2,1)', [ - pending.id, - f.definition.id, - ]); - const active = await f.historicalRun({ backtestId: f.definition.id }); - const oldActive = await f.historicalRun({ backtestId: f.definition.id }); - const claim = await f.legacyWriter.start(await f.legacySnapshot(active.id)); - await f.pool.query("UPDATE runs SET status = 'running' WHERE id = $1", [oldActive.id]); - const migration = readFileSync( - new URL('../../database/postgres/init/10-durable-backtest-dispatch.sql', import.meta.url), - 'utf8' - ); - await f.pool.query(migration); - await f.pool.query(migration); - expect((await f.legacySnapshot(pending.id)).startDate).toBe('2024-01-01T00:00:00.000Z'); - expect( - (await f.pool.query('SELECT * FROM backtest_dispatch WHERE run_id = $1', [pending.id])).rows - ).toHaveLength(1); - expect((await f.api.getRun(oldActive.id))?.status).toBe('failed'); - expect((await f.repository.heartbeat(active.id, claim.attemptId)).cancelRequested).toBe(false); - await f.runner.runQueued(pending.id); - expect((await f.api.getRun(pending.id))?.status).toBe('failed'); - expect((await f.api.getRun(pending.id))?.error).toContain( - 'Legacy backtest execution is retired' - ); - }); -}); diff --git a/test/postgres/experiment-comparison.test.ts b/test/postgres/experiment-comparison.test.ts deleted file mode 100644 index b8924b78..00000000 --- a/test/postgres/experiment-comparison.test.ts +++ /dev/null @@ -1,429 +0,0 @@ -import { 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 type { PoolClient } from 'pg'; -import { createHttpSecurity } from '@stock-bot/di'; -import { getLogger, setLoggerConfig } from '@stock-bot/logger'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import type { CostSensitivityInput } from '@stock-bot/stock-config/cost-sensitivity'; -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 { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service'; -import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service'; -import { createResearchServices } from '../../apps/stock/web-api/src/services/research-services'; -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 '../fixtures/canonical-research'; -import { canonicalSmaFixture } from '../fixtures/canonical-sma'; -import { chronologicalDataset } from '../fixtures/chronological-validation'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('chronological-validation'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const cleanup: (() => Promise)[] = []; -let packages: ReturnType | undefined; -const tokens = { - read: 'comparison-read-fixture-not-a-real-secret-1234', - operator: 'chronological-operator-fixture-not-a-real-secret-1234', - service: 'chronological-service-fixture-not-a-real-secret-1234', -}; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); -async function fixture(poolMax = 1, withCosts = true, capital = 10000) { - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Disposable safety database required'); - } - const schema = 'stock_bot_safety_validation_' + randomUUID().replaceAll('-', ''); - const admin = new Pool({ connectionString: url }); - await admin.query(`CREATE SCHEMA ${schema}`); - // A single connection detects accidental nested pool reads while the admission lock is held. - const pool = new Pool({ - connectionString: url, - application_name: schema, - max: poolMax, - options: `-c search_path=${schema} -c statement_timeout=10000`, - }); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - for (const name of [ - '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', - ...(withCosts ? ['26-cost-sensitivity.sql'] : []), - ]) { - await pool.query( - readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') - ); - } - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, - logger - ); - Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); - Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); - const container = { postgres, logger }, - api = new BacktestServiceV2(container), - experiments = new ExperimentsService(container), - catalog = new StrategyCatalogService(container); - const version = await catalog.seedBuiltin( - 'Validation SMA', - (await (packages ??= packageBuiltinStrategies()))[0]!, - 'seed' - ); - const data = canonicalSmaFixture(), - dataset = data.dataset; - await retainResearchDataset(pool, dataset); - const draft = await api.createBacktest( - { - name: 'Validation template', - strategy: 'catalog', - strategyVersionId: version.id, - strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, - symbols: ['X0.US'], - startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(), - endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(), - initialCapital: capital, - config: { - datasetHash: dataset.manifest.hash, - dataFrequency: '1m', - canonical: canonicalSettings, - }, - }, - { autoStart: false } - ); - const input: CostSensitivityInput = { - backtestId: draft.id, - name: 'Explicit cost diagnostics', - scenarios: [ - { feeRate: '0.001', slippageRate: '0' }, - { feeRate: '0', slippageRate: '0.01' }, - ], - }; - const app = new Hono(); - createHttpSecurity({ - adminToken: tokens.operator, - readToken: tokens.read, - serviceToken: tokens.service, - environment: 'test', - hostname: '127.0.0.1', - }).mount(app); - app.route('/', createExperimentRoutes(container)); - const request = (raw: unknown = input, role: keyof typeof tokens = 'operator') => - app.request('/api/v2/experiments/cost-sensitivity/preview', { - method: 'POST', - headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${tokens[role]}` }, - body: JSON.stringify(raw), - }); - const review = async (decision: 'approve' | 'revoke' = 'approve') => { - await catalog.reviewVersion( - version.id, - { decision, reason: 'Disposable validation proof' }, - 'operator' - ); - return (await catalog.getVersionReviews(version.id)).at(-1)!; - }; - const snapshot = async () => { - const tables = ( - await pool.query('SELECT tablename FROM pg_tables WHERE schemaname=$1 ORDER BY tablename', [ - schema, - ]) - ).rows; - const rows: Record = {}; - for (const { tablename } of tables) { - const quoted = '"' + String(tablename).replaceAll('"', '""') + '"'; - rows[String(tablename)] = ( - await pool.query( - `SELECT COALESCE(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text),'[]'::jsonb) AS rows FROM ${quoted} t` - ) - ).rows[0].rows; - } - return rows; - }; - const validations = createResearchServices(container).validations; - const repository = new PostgresBacktestRunRepository(postgres); - const execute = async (id: string) => { - const engine = new RustBacktestAdapter({ - logger, - }); - const runner = new BacktestRunner({ engine, repository, logger }); - try { - await runner.runQueued(id); - } finally { - await runner.shutdown(); - } - }; - return { - cloneTemplate: async (sourceDataset = dataset) => - api.createBacktest( - { - name: 'Other validation template', - strategy: 'catalog', - strategyVersionId: version.id, - strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, - symbols: ['X0.US'], - startDate: new Date(sourceDataset.manifest.bounds.tradeStart).toISOString(), - endDate: new Date(sourceDataset.manifest.bounds.tradeEnd).toISOString(), - initialCapital: capital, - config: { - datasetHash: sourceDataset.manifest.hash, - dataFrequency: '1m', - canonical: canonicalSettings, - }, - }, - { autoStart: false } - ), - app, - validations, - repository, - execute, - api, - pool, - postgres, - experiments, - catalog, - version, - draft, - dataset, - input, - request, - review, - snapshot, - }; -} - -const actor = (key = randomUUID()) => ({ principal: 'operator' as const, key }); -type Fixture = Awaited>; -async function pair(f: Fixture) { - await f.review(); - const costPreview = await f.experiments.previewCosts(f.input), - left = await f.experiments.submitCosts( - { ...f.input, previewHash: costPreview.previewHash }, - actor() - ); - const input = { - backtestId: f.draft.id, - name: 'Other parameters', - grid: { fastPeriod: [1, 2], slowPeriod: [3] }, - }, - preview = await f.experiments.preview(input), - right = await f.experiments.submit({ ...input, previewHash: preview.previewHash }, actor()); - return { left, right, input: { leftId: left.id, rightId: right.id } }; -} -const request = (f: Fixture, query: Record) => - f.app.request('/api/v2/experiments/compare?' + new URLSearchParams(query), { - headers: { Authorization: `Bearer ${tokens.read}` }, - }); -describe.skipIf(!url)('saved experiment comparison snapshot', () => { - test('pool1 native pair returns all compact summaries and actual scenario costs without writes; archive and template edits do not gate historical reopen', async () => { - const f = await fixture(), - p = await pair(f); - for (const trial of [...p.left.trials, ...p.right.trials]) { - await f.execute(trial.runId!); - } - const before = await f.snapshot(); - const compared = await f.experiments.compare(p.input); - expect(await f.snapshot()).toEqual(before); - expect(compared.experiments.map(e => e.id)).toEqual([p.left.id, p.right.id]); - expect(compared.rows).toHaveLength(5); - expect(compared.rows.map(r => r.inputCompatibility)).toEqual([ - 'match', - 'mismatch', - 'mismatch', - 'match', - 'match', - ]); - expect(compared.rows.map(r => r.ready)).toEqual([true, false, false, true, true]); - expect(compared.experiments[0].trials[0]!.metrics!.totalReturn).toBeCloseTo(-0.00307, 10); - expect(compared.experiments[0].trials[0]!.metrics!.sharpeRatio).toBeNull(); - expect(compared.experiments[0].trials[0]!.unavailable!.sharpeRatio).toBeDefined(); - expect( - compared.experiments[0].trials.every( - t => !('financial' in t) && !('trades' in t) && !('sessionReturns' in t) - ) - ).toBe(true); - const selected = await f.experiments.compare({ - ...p.input, - referenceTrialKey: p.left.trials[1]!.trialKey, - }); - expect(selected.reference.index).toBe(1); - expect(selected.rows[1]!.ready).toBe(true); - expect(selected.rows[3]!.differences).toEqual(['costs']); - await f.api.updateBacktest(f.draft.id, { - name: 'Mutable presentation', - initialCapital: 12000, - config: { - datasetHash: f.dataset.manifest.hash, - dataFrequency: '1m', - canonical: { ...canonicalSettings, feeRate: '0.5' }, - }, - }); - await f.review('revoke'); - await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]); - await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [ - f.version.strategyId, - ]); - const saved = await f.snapshot(); - expect(await f.experiments.compare(p.input)).toEqual(compared); - expect(await f.snapshot()).toEqual(saved); - const response = await request(f, p.input); - expect(response.status).toBe(200); - expect(response.headers.get('Cache-Control')).toBe('no-store'); - expect(await response.json()).toEqual({ comparison: compared }); - const upperCaseResponse = await request(f, { - leftId: p.left.id.toUpperCase(), - rightId: p.right.id.toUpperCase(), - }); - expect(upperCaseResponse.status).toBe(200); - expect(await upperCaseResponse.json()).toEqual({ comparison: compared }); - }, 60000); - test('failed/missing/cancelled/inconsistent outcomes remain visible and never replace the unavailable default reference', async () => { - const f = await fixture(), - p = await pair(f); - await f.execute(p.left.trials[1]!.runId!); - await f.execute(p.right.trials[0]!.runId!); - await f.pool.query( - "UPDATE runs SET status='failed',error='Retained fixture failure',completed_at=NOW() WHERE id=$1", - [p.left.trials[0]!.runId] - ); - await f.experiments.cancel(p.left.id); - let compared = await f.experiments.compare(p.input); - expect(compared.reference.index).toBe(0); - expect(compared.reference.diagnostic).toBe('Retained fixture failure'); - expect(compared.rows.every(r => !r.ready)).toBe(true); - expect(compared.experiments[0].trials.map(t => t.status)).toEqual([ - 'failed', - 'completed', - 'cancelled', - ]); - expect(compared.rows[1]!.summaryAvailable).toBe(true); - expect(compared.experiments[0].cancelRequested).toBe(true); - await f.pool.query('ALTER TABLE runs DISABLE TRIGGER USER'); - await f.pool.query( - 'UPDATE runs SET experiment_id=NULL,trial_key=NULL,trial_index=NULL WHERE id=$1', - [p.left.trials[0]!.runId] - ); - await f.pool.query('ALTER TABLE runs ENABLE TRIGGER USER'); - compared = await f.experiments.compare(p.input); - expect(compared.reference.runId).toBeNull(); - expect(compared.experiments[0].trials[0]!.status).toBe('missing'); - expect(compared.rows).toHaveLength(5); - await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER'); - await f.pool.query( - "UPDATE backtest_results SET canonical_result=jsonb_set(canonical_result,'{financial,policy,matching,slippageRate}',$2::jsonb) WHERE run_id=$1", - [p.right.trials[0]!.runId, JSON.stringify('0.50000000')] - ); - await f.pool.query('ALTER TABLE backtest_results ENABLE TRIGGER USER'); - compared = await f.experiments.compare(p.input); - expect(compared.rows[3]!.summaryAvailable).toBe(false); - expect(compared.rows[3]!.inputCompatibility).toBe('match'); - expect(compared.experiments[1].trials[0]!.diagnostic).toContain('inconsistent'); - await expect( - f.experiments.compare({ ...p.input, referenceTrialKey: 'f'.repeat(64) }) - ).rejects.toMatchObject({ status: 409 }); - }, 60000); - test('read-only repeatable snapshot captures both sides before a controlled committed concurrent status change', async () => { - const f = await fixture(4), - p = await pair(f), - trace: string[] = []; - const transaction = f.postgres.transaction.bind(f.postgres); - let changed = false, - mode: unknown; - Object.defineProperty(f.postgres, 'transaction', { - value: (work: (client: PoolClient) => Promise) => - transaction(async client => { - const query = client.query.bind(client); - const proxy = Object.create(client) as PoolClient; - Object.defineProperty(proxy, 'query', { - value: async (sql: string, values?: unknown[]) => { - trace.push(sql); - const result = await query(sql, values); - if (sql.startsWith('SET TRANSACTION')) { - mode = ( - await query( - "SELECT current_setting('transaction_isolation') AS isolation,current_setting('transaction_read_only') AS readonly" - ) - ).rows[0]; - } - if (sql.startsWith('SELECT id,validation_phase') && !changed) { - changed = true; - await f.pool.query( - "UPDATE runs SET status='failed',error='Committed after snapshot',completed_at=NOW() WHERE id=$1", - [p.right.trials[0]!.runId] - ); - } - return result; - }, - }); - return work(proxy); - }), - }); - const compared = await f.experiments.compare(p.input); - expect(mode).toEqual({ isolation: 'repeatable read', readonly: 'on' }); - expect(changed).toBe(true); - expect(trace[0]).toBe('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY'); - expect(compared.experiments[1].counts.pending).toBe(2); - expect(compared.experiments[1].counts.failed).toBe(0); - expect(compared.experiments[1].trials.map(t => t.status)).toEqual(['pending', 'pending']); - expect(compared.rows.every(r => !r.summaryAvailable)).toBe(true); - const fresh = await f.experiments.get(p.right.id); - expect(fresh.counts.failed).toBe(1); - expect(fresh.trials[0]!.error).toBe('Committed after snapshot'); - expect(trace.filter(sql => /^(INSERT|UPDATE|DELETE|SELECT .*FOR UPDATE)/i.test(sql))).toEqual( - [] - ); - expect(trace.some(sql => /SELECT .*canonical_result\s*(,|FROM)/i.test(sql))).toBe(false); - }, 60000); - test('standalone role, missing identity and retained corruption produce explicit409/404/sanitized500', async () => { - const f = await fixture(), - p = await pair(f), - data = chronologicalDataset(); - await retainResearchDataset(f.pool, data.dataset); - const template = await f.cloneTemplate(data.dataset); - const input = { - backtestId: template.id, - name: 'Actual chronological phase', - grid: { fastPeriod: [1, 2], slowPeriod: [3] }, - recipe: data.recipe, - }, - preview = await f.experiments.previewValidation(input), - validation = await f.validations.submit( - { ...input, previewHash: preview.previewHash }, - actor() - ); - expect((await request(f, { leftId: validation.id, rightId: p.right.id })).status).toBe(409); - expect((await request(f, { leftId: randomUUID(), rightId: p.right.id })).status).toBe(404); - await f.pool.query('ALTER TABLE research_experiments DISABLE TRIGGER USER'); - await f.pool.query( - "UPDATE research_experiments SET preview=jsonb_set(preview,'{previewHash}',to_jsonb(repeat('f',64))) WHERE id=$1", - [p.left.id] - ); - await f.pool.query('ALTER TABLE research_experiments ENABLE TRIGGER USER'); - const response = await request(f, p.input); - expect(response.status).toBe(500); - expect(await response.json()).toEqual({ error: 'Experiment operation unavailable' }); - }, 60000); -}); diff --git a/test/postgres/experiment-retries.test.ts b/test/postgres/experiment-retries.test.ts deleted file mode 100644 index 34633f9e..00000000 --- a/test/postgres/experiment-retries.test.ts +++ /dev/null @@ -1,840 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { readFileSync } from 'node:fs'; -import { afterEach, describe, expect, test } from 'bun:test'; -import { Pool } from 'pg'; -import { HandlerRegistry } from '@stock-bot/handler-registry'; -import { getLogger, setLoggerConfig } from '@stock-bot/logger'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import { Queue } from '@stock-bot/queue'; -import type { - CanonicalRunRequest, - CanonicalRunResult, -} from '@stock-bot/stock-config/canonical-research'; -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 { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service'; -import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher'; -import { - experimentHash, - experimentTrialRequest, -} from '../../apps/stock/web-api/src/services/experiment-input'; -import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.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 '../fixtures/canonical-research'; -import { canonicalSmaFixture } from '../fixtures/canonical-sma'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('experiment-retries'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const cleanup: (() => Promise)[] = []; -let packages: ReturnType | undefined; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); -async function fixture(poolMax = 4, withRetries = true) { - const dataset = canonicalSmaFixture().dataset; - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Disposable safety database required'); - } - const schema = 'stock_bot_safety_retries_' + randomUUID().replaceAll('-', ''); - const admin = new Pool({ connectionString: url }); - await admin.query(`CREATE SCHEMA ${schema}`); - const pool = new Pool({ - connectionString: url, - application_name: schema, - max: poolMax, - options: `-c search_path=${schema} -c statement_timeout=10000`, - }); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - for (const name of [ - '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', - ...(withRetries - ? [ - '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') - ); - } - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, - logger - ); - Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); - Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); - const container = { postgres, logger }; - const api = new BacktestServiceV2(container); - const experiments = new ExperimentsService(container); - const repository = new PostgresBacktestRunRepository(postgres); - const catalog = new StrategyCatalogService(container); - const pkg = (await (packages ??= packageBuiltinStrategies()))[0]!; - const version = await catalog.seedBuiltin('Retained SMA', pkg, 'seed'); - await retainResearchDataset(pool, dataset); - const definition = { - name: 'Canonical API', - strategy: 'catalog', - strategyVersionId: version.id, - strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, - symbols: dataset.manifest.executionSeries.map(s => s.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 }); - const approve = async () => { - await catalog.reviewVersion( - version.id, - { decision: 'approve', reason: 'Reviewed retained builtin' }, - 'operator' - ); - return (await catalog.getVersionReviews(version.id)).at(-1)!; - }; - const execute = async (id: string) => { - const engine = new RustBacktestAdapter({ - logger, - }); - const runner = new BacktestRunner({ - engine, - repository: new PostgresBacktestRunRepository(postgres), - logger, - }); - try { - await runner.runQueued(id); - } finally { - await runner.shutdown(); - } - }; - return { - pool, - postgres, - schema, - api, - experiments, - repository, - catalog, - pkg, - version, - draft, - definition, - dataset, - approve, - execute, - }; -} - -const receipt = (key: string = randomUUID()) => ({ principal: 'operator' as const, key }); -type Fixture = Awaited>; -async function prepare(f: Fixture) { - await f.approve(); - const input = { backtestId: f.draft.id, name: 'Retry fixture', grid: {} }; - const preview = await f.experiments.preview(input); - const experiment = await f.experiments.submit( - { ...input, previewHash: preview.previewHash }, - receipt() - ); - const runId = experiment.trials[0]!.runId!; - const request = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])) - .rows[0].request_snapshot as CanonicalRunRequest; - return { experiment, runId, request }; -} -async function row(f: Fixture, id: string) { - return (await f.pool.query('SELECT to_jsonb(r) AS value FROM runs r WHERE id=$1', [id])).rows[0] - .value; -} -async function failBeforeClaim( - f: Fixture, - id: string, - error: string | null = 'Preclaim diagnostic' -) { - await f.pool.query( - "UPDATE runs SET status='failed',error=$2,completed_at=clock_timestamp() WHERE id=$1", - [id, error] - ); -} -async function nativeResult(f: Fixture, request: CanonicalRunRequest): Promise { - const engine = new RustBacktestAdapter({ - logger, - }); - try { - return { - kind: 'canonical-result/v1', - runId: request.runId, - backtestId: request.backtestId, - status: 'completed', - completedAt: new Date().toISOString(), - executionTime: 0, - financialEngine: 'rust', - strategyExecution: 'typescript-retained-builtin/v1', - request, - ...(await engine.runCanonical(request, async () => f.dataset)), - }; - } finally { - await engine.shutdown(); - } -} -async function snapshotCounts(f: Fixture) { - return ( - await f.pool.query(`SELECT (SELECT count(*)::int FROM experiment_trial_retries) AS retries, - (SELECT count(*)::int FROM runs) AS runs,(SELECT count(*)::int FROM backtest_results) AS results,(SELECT count(*)::int FROM backtest_dispatch) AS dispatch`) - ).rows[0]; -} -const observed = (attempt = 0, retry = 0) => ({ - expectedAttemptNumber: attempt, - expectedRetryCount: retry, -}); -async function rawReceipt( - f: Fixture, - runId: string, - reviewId: string, - changes: Record = {} -) { - const retryId = randomUUID(); - return f.pool.query( - `INSERT INTO experiment_trial_retries(id,experiment_id,run_id,trial_key,retry_number,previous_attempt_number,previous_attempt_id, - error,progress,current_simulation_date,started_at,completed_at,paused_at,failure_updated_at,principal,review_id,submission_key,submission_hash) - SELECT $1,COALESCE($4::uuid,experiment_id),id,trial_key,COALESCE($5::int,manual_retry_count+1),attempt_number,attempt_id, - CASE WHEN $6::text IS NULL THEN error ELSE $6::text END,progress,current_simulation_date,started_at,completed_at,paused_at, - ${changes.roundTime ? "date_trunc('milliseconds',updated_at)" : 'updated_at'},'operator',$3,$7,$8 - FROM runs WHERE id=$2 RETURNING id`, - [ - retryId, - runId, - reviewId, - changes.experiment ?? null, - changes.retryNumber ?? null, - changes.error ?? null, - randomUUID(), - 'a'.repeat(64), - ] - ); -} - -describe.skipIf(!url)('guarded failed experiment trial retry', () => { - test('failed worker retry retains exact failure timestamps and frozen identity, fences every stale callback, and completes once in real Rust', async () => { - const f = await fixture(1), - { experiment, runId, request } = await prepare(f); - const claim = await f.repository.startCanonical(request); - await f.repository.updateProgress(runId, 37.25, '2024-01-01T09:03:00.123Z', claim.attemptId); - await f.pool.query( - "UPDATE runs SET started_at='2026-10-24T10:00:00.123456Z',paused_at='2026-10-24T10:01:00.654321Z' WHERE id=$1", - [runId] - ); - const result = await nativeResult(f, request); - await f.repository.fail(runId, 'Observed failure after computation', claim.attemptId); - await expect( - f.pool.query('UPDATE runs SET attempt_number=0 WHERE id=$1', [runId]) - ).rejects.toMatchObject({ code: '23514' }); - const before = await row(f, runId), - key = receipt(); - const latest = await f.approve(); - expect(latest.id).not.toBe(request.strategy.reviewId); - const retried = await f.experiments.retryTrial(experiment.id, runId, observed(1), key); - expect(retried.retry).toMatchObject({ - runId, - experimentId: experiment.id, - retryNumber: 1, - previousAttemptNumber: 1, - previousAttemptId: claim.attemptId, - error: before.error, - progress: 37.25, - reviewId: latest.id, - }); - expect(retried.retry.startedAt).toBe('2026-10-24T10:00:00.123456Z'); - expect(retried.retry.pausedAt).toBe('2026-10-24T10:01:00.654321Z'); - const exact = ( - await f.pool.query( - `SELECT h.started_at=($2::jsonb->>'started_at')::timestamptz AND h.paused_at=($2::jsonb->>'paused_at')::timestamptz - AND h.completed_at=($2::jsonb->>'completed_at')::timestamptz AND h.failure_updated_at=($2::jsonb->>'updated_at')::timestamptz AS exact - FROM experiment_trial_retries h WHERE run_id=$1`, - [runId, before] - ) - ).rows[0]; - expect(exact.exact).toBe(true); - const pending = await row(f, runId); - expect(pending).toMatchObject({ - status: 'pending', - attempt_number: 1, - manual_retry_count: 1, - attempt_id: null, - lease_expires_at: null, - progress: 0, - error: null, - current_simulation_date: null, - started_at: null, - completed_at: null, - paused_at: null, - request_snapshot: request, - dataset_hash: request.datasetHash, - }); - expect(pending.request_snapshot.strategy.reviewId).toBe(request.strategy.reviewId); - const assertStale = async () => { - const current = await row(f, runId); - await expect(f.repository.heartbeat(runId, claim.attemptId)).rejects.toThrow(); - await expect( - f.repository.updateProgress(runId, 99, undefined, claim.attemptId) - ).rejects.toThrow(); - await f.repository.fail(runId, 'Stale overwrite', claim.attemptId); - await expect(f.repository.cancel(runId, claim.attemptId)).rejects.toThrow(); - await expect(f.repository.completeCanonical(result, claim.attemptId)).rejects.toThrow(); - expect(await row(f, runId)).toEqual(current); - }; - await assertStale(); - const next = await f.repository.startCanonical(request); - expect(next.attemptId).not.toBe(claim.attemptId); - await assertStale(); - await f.repository.completeCanonical(result, next.attemptId); - expect((await f.api.getRunResults(runId))!.runId).toBe(runId); - expect(await snapshotCounts(f)).toEqual({ runs: 1, results: 1, retries: 1, dispatch: 1 }); - expect((await f.experiments.get(experiment.id)).trials[0]).toMatchObject({ - attemptNumber: 2, - retryCount: 1, - status: 'completed', - comparable: true, - }); - expect((await f.experiments.retryTrial(experiment.id, runId, observed(1), key)).retry).toEqual( - retried.retry - ); - await expect( - f.experiments.retryTrial(experiment.id, runId, observed(2, 1), receipt()) - ).rejects.toMatchObject({ status: 409 }); - expect(await f.experiments.listTrialRetries(experiment.id, runId)).toEqual([retried.retry]); - }); - - test('preclaim failure0 can recur; both counters prevent stale intent and null prior identifiers stay honest', async () => { - const f = await fixture(), - { experiment, runId } = await prepare(f); - await failBeforeClaim(f, runId, null); - const key = receipt(), - first = await f.experiments.retryTrial(experiment.id, runId, observed(), key); - expect(first.retry).toMatchObject({ - previousAttemptNumber: 0, - previousAttemptId: null, - error: null, - retryNumber: 1, - startedAt: null, - pausedAt: null, - currentDate: null, - }); - await failBeforeClaim(f, runId, 'second preclaim failure'); - await expect( - f.experiments.retryTrial(experiment.id, runId, observed(), receipt()) - ).rejects.toMatchObject({ status: 409 }); - expect((await f.experiments.retryTrial(experiment.id, runId, observed(), key)).retry).toEqual( - first.retry - ); - const second = await f.experiments.retryTrial(experiment.id, runId, observed(0, 1), receipt()); - expect(second.retry).toMatchObject({ - retryNumber: 2, - previousAttemptNumber: 0, - previousAttemptId: null, - error: 'second preclaim failure', - }); - expect( - (await f.experiments.listTrialRetries(experiment.id, runId)).map(h => h.retryNumber) - ).toEqual([1, 2]); - expect((await row(f, runId)).attempt_number).toBe(0); - }); - - test('same-key race replays one receipt; different keys or cross-experiment reuse cannot reset twice', async () => { - const f = await fixture(), - { experiment, runId } = await prepare(f); - await failBeforeClaim(f, runId); - const key = receipt(); - const [a, b] = await Promise.all([ - f.experiments.retryTrial(experiment.id, runId, observed(), key), - f.experiments.retryTrial(experiment.id, runId, observed(), key), - ]); - expect(a.retry.id).toBe(b.retry.id); - await failBeforeClaim(f, runId); - const race = await Promise.allSettled([ - f.experiments.retryTrial(experiment.id, runId, observed(0, 1), receipt()), - f.experiments.retryTrial(experiment.id, runId, observed(0, 1), receipt()), - ]); - expect(race.filter(r => r.status === 'fulfilled')).toHaveLength(1); - expect( - race.filter(r => r.status === 'rejected').map(r => (r as PromiseRejectedResult).reason.status) - ).toEqual([409]); - await expect( - f.experiments.retryTrial(randomUUID(), runId, observed(), key) - ).rejects.toMatchObject({ status: 409 }); - expect(await snapshotCounts(f)).toEqual({ runs: 1, results: 0, retries: 2, dispatch: 1 }); - const secondParent = await f.api.createBacktest( - { ...f.definition, name: 'Second retry parent' }, - { autoStart: false } - ); - const secondInput = { backtestId: secondParent.id, name: 'Other parent experiment', grid: {} }; - const secondPreview = await f.experiments.preview(secondInput); - const secondExperiment = await f.experiments.submit( - { ...secondInput, previewHash: secondPreview.previewHash }, - receipt() - ); - const secondRunId = secondExperiment.trials[0]!.runId!; - await failBeforeClaim(f, runId); - await failBeforeClaim(f, secondRunId); - const crossKey = receipt(); - const cross = await Promise.allSettled([ - f.experiments.retryTrial(experiment.id, runId, observed(0, 2), crossKey), - f.experiments.retryTrial(secondExperiment.id, secondRunId, observed(), crossKey), - ]); - expect(cross.filter(item => item.status === 'fulfilled')).toHaveLength(1); - expect( - cross - .filter(item => item.status === 'rejected') - .map(item => (item as PromiseRejectedResult).reason.status) - ).toEqual([409]); - expect(await snapshotCounts(f)).toEqual({ runs: 2, results: 0, retries: 3, dispatch: 2 }); - }); - - test('latest original-version approval governs retries despite template edits; accepted receipts survive revocation/archive/cancellation', async () => { - const f = await fixture(), - { experiment, runId, request } = await prepare(f); - await failBeforeClaim(f, runId); - const other = (await (packages ??= packageBuiltinStrategies()))[1]!; - const version = await f.catalog.seedBuiltin('Different template version', other, 'seed-other'); - await f.api.updateBacktest(f.draft.id, { - name: 'Different template', - strategyVersionId: version.id, - strategyParameters: { - lookbackPeriod: 2, - trendPeriod: 3, - momentumPeriod: 1, - volatilityPeriod: 2, - entryZScore: 1, - exitZScore: 0.1, - minTrendReturn: -0.5, - minMomentumReturn: -0.5, - maxVolatility: 1, - minNotionalVolume: '0', - regimeFilter: 'none', - }, - initialCapital: 20000, - }); - await f.catalog.reviewVersion( - f.version.id, - { decision: 'revoke', reason: 'No new execution' }, - 'operator' - ); - const before = await row(f, runId); - await expect( - f.experiments.retryTrial(experiment.id, runId, observed(), receipt()) - ).rejects.toMatchObject({ status: 409 }); - expect(await row(f, runId)).toEqual(before); - const latest = await f.approve(), - key = receipt(); - const accepted = await f.experiments.retryTrial(experiment.id, runId, observed(), key); - expect(accepted.retry.reviewId).toBe(latest.id); - expect((await row(f, runId)).request_snapshot).toEqual(request); - await f.catalog.reviewVersion( - f.version.id, - { decision: 'revoke', reason: 'Pause' }, - 'operator' - ); - await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]); - await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [ - f.version.strategyId, - ]); - await f.experiments.cancel(experiment.id); - expect((await f.experiments.retryTrial(experiment.id, runId, observed(), key)).retry).toEqual( - accepted.retry - ); - await expect( - f.experiments.retryTrial(experiment.id, runId, observed(0, 1), receipt()) - ).rejects.toMatchObject({ status: 409 }); - }); - - test('outbox fault rolls back history and reset; due redispatch survives publication outage without resetting lifetime attempt budget', async () => { - const f = await fixture(), - { experiment, runId, request } = await prepare(f); - const claim = await f.repository.startCanonical(request); - await f.repository.fail(runId, 'worker failure', claim.attemptId); - await f.pool.query( - "UPDATE backtest_dispatch SET publish_count=9,last_published_at='2026-10-24T10:00:00.123456Z',next_publish_at=NOW()+interval '1 day' WHERE run_id=$1", - [runId] - ); - await f.pool - .query(`CREATE FUNCTION reject_retry_dispatch() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'fixture outage'; END $$; - CREATE TRIGGER fixture_dispatch_outage BEFORE UPDATE ON backtest_dispatch FOR EACH ROW EXECUTE FUNCTION reject_retry_dispatch()`); - const before = await row(f, runId), - key = receipt(); - await expect(f.experiments.retryTrial(experiment.id, runId, observed(1), key)).rejects.toThrow( - 'fixture outage' - ); - expect(await row(f, runId)).toEqual(before); - expect((await snapshotCounts(f)).retries).toBe(0); - await f.pool.query('DROP TRIGGER fixture_dispatch_outage ON backtest_dispatch'); - await f.experiments.retryTrial(experiment.id, runId, observed(1), key); - const dispatch = ( - await f.pool.query('SELECT * FROM backtest_dispatch WHERE run_id=$1', [runId]) - ).rows[0]; - expect(dispatch.publish_count).toBe(9); - expect(dispatch.last_published_at.toISOString()).toBe('2026-10-24T10:00:00.123Z'); - let failed = true; - const delivered: string[] = []; - const dispatcher = new BacktestDispatcher( - f.postgres, - { - async add(_name: string, data: unknown) { - if (failed) { - throw new Error('Redis unavailable'); - } - delivered.push((data as { payload: { runId: string } }).payload.runId); - return {}; - }, - } as never, - logger, - { intervalMs: 20, republishMs: 5, maxAttempts: 1 } - ); - await expect(dispatcher.tick()).rejects.toThrow('Redis unavailable'); - expect((await row(f, runId)).status).toBe('pending'); - failed = false; - await new Promise(resolve => setTimeout(resolve, 10)); - await dispatcher.tick(); - expect(delivered).toEqual([runId]); - const next = await f.repository.startCanonical(request); - expect((await row(f, runId)).attempt_number).toBe(2); - await f.pool.query("UPDATE runs SET lease_expires_at=NOW()-interval '1 second' WHERE id=$1", [ - runId, - ]); - await dispatcher.tick(); - expect(await row(f, runId)).toMatchObject({ - status: 'failed', - attempt_number: 2, - manual_retry_count: 1, - attempt_id: null, - error: 'Execution lease expired; retry limit reached', - }); - await expect(f.repository.heartbeat(runId, next.attemptId)).rejects.toThrow(); - await dispatcher.shutdown(); - }); - - test('SQL rejects missing receipts, altered or rounded snapshots, history tampering, count changes and incomplete resets', async () => { - const f = await fixture(), - { experiment, runId } = await prepare(f); - await failBeforeClaim(f, runId); - const review = (await f.catalog.getVersionReviews(f.version.id)).at(-1)!; - const original = await row(f, runId); - for (const patch of ["status='pending'", "status='running'", 'manual_retry_count=1']) { - await expect( - f.pool.query(`UPDATE runs SET ${patch} WHERE id=$1`, [runId]) - ).rejects.toMatchObject({ code: '23514' }); - } - for (const changes of [ - { error: 'invented failure' }, - { retryNumber: 2 }, - { experiment: randomUUID() }, - { roundTime: true }, - {}, - ]) { - await expect(rawReceipt(f, runId, review.id, changes)).rejects.toMatchObject({ - code: '23514', - }); - } - expect(await row(f, runId)).toEqual(original); - const client = await f.pool.connect(); - try { - await client.query('BEGIN'); - // Use the SQL capture itself, then prove a partial reset cannot consume the receipt. - await client.query( - `INSERT INTO experiment_trial_retries(id,experiment_id,run_id,trial_key,retry_number,previous_attempt_number,previous_attempt_id,error,progress,current_simulation_date,started_at,completed_at,paused_at,failure_updated_at,principal,review_id,submission_key,submission_hash) - SELECT $1,experiment_id,id,trial_key,1,attempt_number,attempt_id,error,progress,current_simulation_date,started_at,completed_at,paused_at,updated_at,'operator',$3,$4,$5 FROM runs WHERE id=$2`, - [randomUUID(), runId, review.id, randomUUID(), 'a'.repeat(64)] - ); - await expect( - client.query("UPDATE runs SET status='pending',manual_retry_count=1 WHERE id=$1", [runId]) - ).rejects.toMatchObject({ code: '23514' }); - } finally { - await client.query('ROLLBACK'); - client.release(); - } - const retry = await f.experiments.retryTrial(experiment.id, runId, observed(), receipt()); - for (const sql of [ - "UPDATE experiment_trial_retries SET error='changed' WHERE id=$1", - 'DELETE FROM experiment_trial_retries WHERE id=$1', - ]) { - await expect(f.pool.query(sql, [retry.retry.id])).rejects.toMatchObject({ code: '23514' }); - } - await expect(f.pool.query('TRUNCATE experiment_trial_retries')).rejects.toMatchObject({ - code: '23514', - }); - await expect( - f.pool.query('UPDATE runs SET manual_retry_count=0 WHERE id=$1', [runId]) - ).rejects.toMatchObject({ code: '23514' }); - expect((await snapshotCounts(f)).retries).toBe(1); - }); - - test('cancellation race either rejects retry or cancels its reset run; wrong membership/results/current terminal states reject', async () => { - const f = await fixture(), - { experiment, runId } = await prepare(f); - await expect( - f.experiments.retryTrial(experiment.id, runId, observed(), receipt()) - ).rejects.toMatchObject({ status: 409 }); - await expect( - f.experiments.retryTrial(experiment.id, randomUUID(), observed(), receipt()) - ).rejects.toMatchObject({ status: 404 }); - const ordinary = await f.api.createRun({ backtestId: f.draft.id }); - await expect( - f.experiments.retryTrial(experiment.id, ordinary.id, observed(), receipt()) - ).rejects.toMatchObject({ status: 409 }); - await expect(f.experiments.listTrialRetries(experiment.id, ordinary.id)).rejects.toMatchObject({ - status: 409, - }); - await failBeforeClaim(f, runId); - await Promise.allSettled([ - f.experiments.retryTrial(experiment.id, runId, observed(), receipt()), - f.experiments.cancel(experiment.id), - ]); - const current = await row(f, runId); - expect(current.status === 'failed' || current.status === 'cancelled').toBe(true); - expect((await f.experiments.get(experiment.id)).cancelRequested).toBe(true); - await expect( - f.experiments.retryTrial( - experiment.id, - runId, - observed(0, current.manual_retry_count), - receipt() - ) - ).rejects.toMatchObject({ status: 409 }); - const completed = await prepare(f); - await f.execute(completed.runId); - // Deliberate corruption in this disposable schema proves retained results still forbid retry. - await f.pool.query('ALTER TABLE runs DISABLE TRIGGER USER'); - await f.pool.query("UPDATE runs SET status='failed' WHERE id=$1", [completed.runId]); - await f.pool.query('ALTER TABLE runs ENABLE TRIGGER USER'); - const evidence = await row(f, completed.runId); - await expect( - f.experiments.retryTrial(completed.experiment.id, completed.runId, observed(1), receipt()) - ).rejects.toMatchObject({ status: 409 }); - expect(await row(f, completed.runId)).toEqual(evidence); - await expect( - f.pool.query("UPDATE runs SET status='pending' WHERE id=$1", [completed.runId]) - ).rejects.toMatchObject({ code: '23514' }); - }); - test('real Redis publication outage recovers the same retried run and real Rust result once', async () => { - const redisUrl = process.env.BACKTEST_TEST_REDIS_URL; - if (!redisUrl || new URL(redisUrl).pathname !== '/15') { - throw new Error('Dedicated Redis database15 required'); - } - const f = await fixture(), - { experiment, runId } = await prepare(f); - await failBeforeClaim(f, runId); - await f.experiments.retryTrial(experiment.id, runId, observed(), receipt()); - const endpoint = new URL(redisUrl), - redis = { host: endpoint.hostname, port: Number(endpoint.port), db: 15 }; - const name = `stock-bot-safety-retry-${randomUUID()}`; - const producer = new Queue(name, redis, {}, { workers: 0 }, logger); - await producer.getBullQueue().waitUntilReady(); - cleanup.push(async () => { - await producer.getBullQueue().obliterate({ force: true }); - await producer.close(); - }); - const dispatcher = new BacktestDispatcher(f.postgres, producer, logger, { - intervalMs: 20, - republishMs: 30, - maxAttempts: 3, - }); - cleanup.push(() => dispatcher.shutdown()); - const connection = await producer.getBullQueue().client; - connection.disconnect(); - await expect(dispatcher.tick()).rejects.toThrow(); - expect((await row(f, runId)).status).toBe('pending'); - await connection.connect(); - await new Promise(resolve => setTimeout(resolve, 40)); - await dispatcher.tick(); - const registry = new HandlerRegistry(); - registry.registerConfiguration({ - name: 'orchestrator', - operations: { - 'run-backtest': async payload => f.execute((payload as { runId: string }).runId), - }, - }); - const worker = new Queue( - name, - redis, - {}, - { workers: 1, concurrency: 1, handlerRegistry: registry }, - logger - ); - cleanup.push(() => worker.close()); - let done = false; - for (let i = 0; i < 150; i++) { - if ((await row(f, runId)).status === 'completed') { - done = true; - break; - } - await new Promise(resolve => setTimeout(resolve, 20)); - } - expect(done).toBe(true); - expect(await snapshotCounts(f)).toEqual({ runs: 1, results: 1, retries: 1, dispatch: 1 }); - await f.execute(runId); // Repeat delivery is harmless after completion. - expect((await snapshotCounts(f)).results).toBe(1); - expect((await row(f, runId)).attempt_number).toBe(1); - }); - - test('first SQL23 upgrade preserves old failed experiment evidence with count0 and no invented history; reapplication preserves accepted retry', async () => { - const f = await fixture(4, false); - await f.approve(); - const input = { backtestId: f.draft.id, name: 'Pre-migration experiment', grid: {} }; - const preview = await f.experiments.preview(input), - experimentId = randomUUID(), - runId = randomUUID(); - const candidate = preview.candidates[0]!, - request = experimentTrialRequest(preview, candidate, runId); - await f.pool.query( - `INSERT INTO research_experiments(id,backtest_id,name,preview,preview_hash,submission_principal,submission_key,submission_hash) - VALUES($1,$2,$3,$4,$5,'operator',$6,$7)`, - [ - experimentId, - f.draft.id, - input.name, - preview, - preview.previewHash, - randomUUID(), - 'a'.repeat(64), - ] - ); - await f.pool.query( - `INSERT INTO runs(id,backtest_id,run_number,status,speed_multiplier,request_snapshot,dataset_hash,experiment_id,trial_key,trial_index) - VALUES($1,$2,1,'pending',NULL,$3,$4,$5,$6,0)`, - [runId, f.draft.id, request, request.datasetHash, experimentId, candidate.trialKey] - ); - await f.pool.query('INSERT INTO backtest_dispatch(run_id) VALUES($1)', [runId]); - await failBeforeClaim(f, runId); - const before = await row(f, runId), - outbox = (await f.pool.query('SELECT to_jsonb(d) AS value FROM backtest_dispatch d')).rows; - const sql = readFileSync( - new URL('../../database/postgres/init/23-experiment-retries.sql', import.meta.url), - 'utf8' - ); - await f.pool.query(sql); - expect(await row(f, runId)).toEqual({ ...before, manual_retry_count: 0 }); - expect( - (await f.pool.query('SELECT to_jsonb(d) AS value FROM backtest_dispatch d')).rows - ).toEqual(outbox); - // Current services require the later validation columns; verify SQL23 evidence first. - await f.pool.query( - readFileSync( - new URL('../../database/postgres/init/24-chronological-validation.sql', import.meta.url), - 'utf8' - ) - ); - expect(await f.experiments.listTrialRetries(experimentId, runId)).toEqual([]); - const accepted = await f.experiments.retryTrial(experimentId, runId, observed(), receipt()); - const after = await row(f, runId); - await f.pool.query(sql); - expect(await row(f, runId)).toEqual(after); - expect(await f.experiments.listTrialRetries(experimentId, runId)).toEqual([accepted.retry]); - await f.execute(runId); - expect((await f.experiments.get(experimentId)).trials[0]).toMatchObject({ - status: 'completed', - attemptNumber: 1, - retryCount: 1, - }); - }); - test('current-family archive serializes fresh retry and leaves the prior failure intact', async () => { - const f = await fixture(), - { experiment, runId } = await prepare(f); - await failBeforeClaim(f, runId); - const before = await row(f, runId); - const blocker = await f.pool.connect(); - let pending: Promise | undefined; - try { - await blocker.query('BEGIN'); - await blocker.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [ - f.version.strategyId, - ]); - pending = f.experiments.retryTrial(experiment.id, runId, observed(), receipt()).then( - value => ({ value }), - error => ({ error }) - ); - let waiting = false; - for (let i = 0; i < 100; i++) { - if ( - ( - await f.pool.query( - "SELECT 1 FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock'", - [f.schema] - ) - ).rows.length - ) { - waiting = true; - break; - } - await new Promise(resolve => setTimeout(resolve, 10)); - } - expect(waiting).toBe(true); - await blocker.query('COMMIT'); - expect(await pending).toMatchObject({ error: { status: 409 } }); - } finally { - await blocker.query('ROLLBACK'); - blocker.release(); - await pending; - } - expect(await row(f, runId)).toEqual(before); - expect((await snapshotCounts(f)).retries).toBe(0); - }); - - test('unsupported retained build rejects fresh retry while accepted receipt replays before current build eligibility', async () => { - const f = await fixture(), - { experiment, runId } = await prepare(f); - await failBeforeClaim(f, runId); - const key = receipt(); - const accepted = await f.experiments.retryTrial(experiment.id, runId, observed(), key); - await failBeforeClaim(f, runId, 'Later failure'); - // Alter retained evidence only in this disposable schema to model a no-longer-installed historical build. - const altered = structuredClone(experiment.preview); - altered.request.build.runtimeVersion = 'unavailable-historical-build'; - const { previewHash: _oldHash, ...manifest } = altered; - altered.previewHash = experimentHash(manifest); - const request = experimentTrialRequest(altered, altered.candidates[0]!, runId); - await f.pool.query('ALTER TABLE research_experiments DISABLE TRIGGER USER'); - await f.pool.query('ALTER TABLE runs DISABLE TRIGGER USER'); - await f.pool.query('UPDATE research_experiments SET preview=$2,preview_hash=$3 WHERE id=$1', [ - experiment.id, - altered, - altered.previewHash, - ]); - await f.pool.query('UPDATE runs SET request_snapshot=$2 WHERE id=$1', [runId, request]); - await f.pool.query('ALTER TABLE research_experiments ENABLE TRIGGER USER'); - await f.pool.query('ALTER TABLE runs ENABLE TRIGGER USER'); - const before = await row(f, runId); - await expect( - f.experiments.retryTrial(experiment.id, runId, observed(0, 1), receipt()) - ).rejects.toMatchObject({ status: 409 }); - expect(await row(f, runId)).toEqual(before); - expect((await f.experiments.retryTrial(experiment.id, runId, observed(), key)).retry).toEqual( - accepted.retry - ); - expect((await snapshotCounts(f)).retries).toBe(1); - }); -}); diff --git a/test/postgres/experiments.test.ts b/test/postgres/experiments.test.ts deleted file mode 100644 index d4fbfc09..00000000 --- a/test/postgres/experiments.test.ts +++ /dev/null @@ -1,722 +0,0 @@ -import { 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 { getLogger, setLoggerConfig } from '@stock-bot/logger'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import type { - CanonicalRunRequest, - CanonicalRunResult, -} from '@stock-bot/stock-config/canonical-research'; -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 { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service'; -import { experimentTrialRequest } from '../../apps/stock/web-api/src/services/experiment-input'; -import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.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 '../fixtures/canonical-research'; -import { canonicalSmaFixture } from '../fixtures/canonical-sma'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('experiments'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const cleanup: (() => Promise)[] = []; -let packages: ReturnType | undefined; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); -async function fixture(poolMax = 4, withExperiments = true) { - const dataset = canonicalSmaFixture().dataset; - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Disposable safety database required'); - } - const schema = 'stock_bot_safety_experiments_' + randomUUID().replaceAll('-', ''); - const admin = new Pool({ connectionString: url }); - await admin.query(`CREATE SCHEMA ${schema}`); - const pool = new Pool({ - connectionString: url, - application_name: schema, - max: poolMax, - options: `-c search_path=${schema} -c statement_timeout=10000`, - }); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - for (const name of [ - '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', - ...(withExperiments - ? [ - '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') - ); - } - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, - logger - ); - Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); - Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); - const container = { postgres, logger }; - const api = new BacktestServiceV2(container); - const experiments = new ExperimentsService(container); - const repository = new PostgresBacktestRunRepository(postgres); - const catalog = new StrategyCatalogService(container); - const pkg = (await (packages ??= packageBuiltinStrategies()))[0]!; - const version = await catalog.seedBuiltin('Retained SMA', pkg, 'seed'); - await retainResearchDataset(pool, dataset); - const definition = { - name: 'Canonical API', - strategy: 'catalog', - strategyVersionId: version.id, - strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, - symbols: dataset.manifest.executionSeries.map(s => s.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 }); - const approve = async () => { - await catalog.reviewVersion( - version.id, - { decision: 'approve', reason: 'Reviewed retained builtin' }, - 'operator' - ); - return (await catalog.getVersionReviews(version.id)).at(-1)!; - }; - const execute = async (id: string) => { - const engine = new RustBacktestAdapter({ - logger, - }); - const runner = new BacktestRunner({ - engine, - repository: new PostgresBacktestRunRepository(postgres), - logger, - }); - try { - await runner.runQueued(id); - } finally { - await runner.shutdown(); - } - }; - return { - pool, - schema, - api, - experiments, - repository, - catalog, - pkg, - version, - draft, - definition, - dataset, - approve, - execute, - app: new Hono().route('/', createExperimentRoutes(container)), - }; -} - -const receipt = (key: string = randomUUID()) => ({ principal: 'operator' as const, key }); -async function prepare( - f: Awaited>, - grid: Record = { fastPeriod: [1, 2] } -) { - await f.approve(); - const input = { backtestId: f.draft.id, name: 'Retained SMA search', grid }; - const preview = await f.experiments.preview(input); - const submission = { ...input, previewHash: preview.previewHash }; - return { input, preview, submission }; -} -async function totals(f: Awaited>) { - return ( - await f.pool.query(`SELECT (SELECT count(*)::int FROM research_experiments) AS experiments, - (SELECT count(*)::int FROM runs) AS runs,(SELECT count(*)::int FROM backtest_dispatch) AS dispatch`) - ).rows[0]; -} -async function rawTrial( - f: Awaited>, - experiment: Awaited>, - changes: Record = {} -) { - const id = randomUUID(); - const candidate = experiment.preview.candidates[0]!; - const request = experimentTrialRequest(experiment.preview, candidate, id); - const row = { - id, - backtest: f.draft.id, - request, - dataset: request.datasetHash, - experiment: experiment.id, - key: candidate.trialKey, - index: candidate.index, - original: null, - principal: null, - receiptKey: null, - hash: null, - ...changes, - }; - return f.pool.query( - `INSERT INTO runs(id,backtest_id,run_number,status,speed_multiplier,request_snapshot,dataset_hash,experiment_id,trial_key,trial_index,original_run_id,submission_principal,submission_key,submission_hash) - SELECT $1,$2,COALESCE(MAX(run_number),0)+1,'pending',NULL,$3,$4,$5,$6,$7,$8,$9,$10,$11 FROM runs WHERE backtest_id=$2`, - [ - row.id, - row.backtest, - row.request, - row.dataset, - row.experiment, - row.key, - row.index, - row.original, - row.principal, - row.receiptKey, - row.hash, - ] - ); -} - -describe.skipIf(!url)('retained-input experiments', () => { - test('deterministic_grid validates every combination, duplicates, unknown/reserved axes and bounded expansion', async () => { - const f = await fixture(1); - const { preview } = await prepare(f, { slowPeriod: [4, 3], fastPeriod: [1, 2] }); - const reordered = await f.experiments.preview({ - ...preview.input, - grid: { fastPeriod: [1, 2], slowPeriod: [4, 3] }, - }); - expect(reordered).toEqual(preview); - expect(preview.candidates.map(c => c.parameters)).toEqual([ - { fastPeriod: 1, slowPeriod: 4 }, - { fastPeriod: 1, slowPeriod: 3 }, - { fastPeriod: 2, slowPeriod: 4 }, - { fastPeriod: 2, slowPeriod: 3 }, - ]); - expect(preview.candidates.map(c => c.index)).toEqual([0, 1, 2, 3]); - expect(preview.dataset).toEqual(f.dataset.manifest); - expect((await f.experiments.preview({ ...preview.input, grid: {} })).candidates).toHaveLength( - 1 - ); - for (const grid of [ - { fastPeriod: [1, 1] }, - { fastPeriod: [2, 3] }, - { unknown: [1] }, - { fastPeriod: [] }, - { - fastPeriod: Array.from({ length: 10 }, (_, i) => i + 1), - slowPeriod: Array.from({ length: 11 }, (_, i) => i + 20), - }, - JSON.parse('{"__proto__":[1]}'), - { constructor: [1] }, - ]) { - await expect(f.experiments.preview({ ...preview.input, grid })).rejects.toMatchObject({ - status: 400, - }); - } - expect(await totals(f)).toEqual({ experiments: 0, runs: 0, dispatch: 0 }); - }); - - test('frozen trials execute real Rust with distinct parameters and exact template/data/policy/build; compact saved summaries reopen', async () => { - const f = await fixture(1); - const before = await f.api.getBacktest(f.draft.id); - const { preview, submission } = await prepare(f, { fastPeriod: [1], slowPeriod: [3, 10] }); - const experiment = await f.experiments.submit(submission, receipt()); - expect(experiment.trialCount).toBe(2); - expect(experiment.counts.pending).toBe(2); - expect(experiment.trials.every(t => !t.comparable && t.metrics === null)).toBe(true); - const rows = (await f.pool.query('SELECT * FROM runs ORDER BY trial_index')).rows; - for (const row of rows) { - expect(row.submission_key).toBeNull(); - expect(row.original_run_id).toBeNull(); - expect(row.request_snapshot).toEqual( - experimentTrialRequest(preview, preview.candidates[row.trial_index]!, row.id) - ); - await f.execute(row.id); - } - const detail = await f.experiments.get(experiment.id); - expect(detail.counts).toEqual({ - pending: 0, - running: 0, - paused: 0, - completed: 2, - failed: 0, - cancelled: 0, - }); - expect(detail.trials.every(t => t.comparable)).toBe(true); - for (const trial of detail.trials) { - const result = await f.api.getRunResults(trial.runId!); - expect(result && 'kind' in result && result.financialEngine).toBe('rust'); - if (!result || !('kind' in result)) { - throw new Error('Canonical result expected'); - } - expect(trial.metrics).toEqual(result.analytics.metrics); - expect(trial.unavailable).toEqual(result.analytics.unavailable); - expect(trial.metrics!.alpha).toBeNull(); - expect(trial.limitations).toEqual([ - ...result.financial.limitations, - ...result.financial.modelLimitations, - ]); - } - expect(detail.trials[0]!.metrics!.totalReturn).not.toEqual( - detail.trials[1]!.metrics!.totalReturn - ); - expect(detail.trials[1]!.metrics!.totalReturn).toBe(0); - expect(detail.trials[1]!.unavailable!.totalReturn).toBeUndefined(); - expect(await f.api.getBacktest(f.draft.id)).toEqual(before); - expect(await totals(f)).toEqual({ experiments: 1, runs: 2, dispatch: 2 }); - expect((await f.experiments.list(f.draft.id))[0]).toMatchObject({ - id: experiment.id, - trialCount: 2, - counts: { completed: 2 }, - }); - expect(await f.experiments.list(randomUUID())).toEqual([]); - expect(JSON.stringify(detail.trials)).not.toContain('sessionReturns'); - expect(JSON.stringify(detail.trials)).not.toContain('equity_curve'); - }); - - test('stale preview refuses edits/reviews and accepted receipt survives archive and review changes', async () => { - const f = await fixture(); - const { input, submission } = await prepare(f); - await f.api.updateBacktest(f.draft.id, { name: 'Changed template' }); - await expect(f.experiments.submit(submission, receipt())).rejects.toMatchObject({ - status: 409, - }); - expect(await totals(f)).toEqual({ experiments: 0, runs: 0, dispatch: 0 }); - const next = await f.experiments.preview(input); - await f.approve(); - await expect( - f.experiments.submit({ ...input, previewHash: next.previewHash }, receipt()) - ).rejects.toMatchObject({ status: 409 }); - const current = { ...input, previewHash: (await f.experiments.preview(input)).previewHash }; - const key = receipt(); - const accepted = await f.experiments.submit(current, key); - await f.catalog.reviewVersion( - f.version.id, - { decision: 'revoke', reason: 'No new admissions' }, - 'operator' - ); - await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]); - await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [ - f.version.strategyId, - ]); - expect((await f.experiments.submit(current, key)).id).toBe(accepted.id); - await expect(f.experiments.submit(current, receipt())).rejects.toMatchObject({ status: 409 }); - await expect( - f.experiments.submit({ ...current, name: 'Different' }, key) - ).rejects.toMatchObject({ status: 409 }); - expect(await totals(f)).toEqual({ experiments: 1, runs: 2, dispatch: 2 }); - }); - - test('duplicate_expand_race and cross-parent global receipt conflict admit exactly one atomic batch', async () => { - const f = await fixture(); - const { submission } = await prepare(f); - const key = receipt(); - const [a, b] = await Promise.all([ - f.experiments.submit(submission, key), - f.experiments.submit(submission, key), - ]); - expect(a.id).toBe(b.id); - expect(await totals(f)).toEqual({ experiments: 1, runs: 2, dispatch: 2 }); - const other = await f.api.createBacktest( - { ...f.definition, name: 'Other parent' }, - { autoStart: false } - ); - const input = { ...submission, backtestId: other.id }; - const otherPreview = await f.experiments.preview({ - backtestId: other.id, - name: submission.name, - grid: submission.grid, - }); - input.previewHash = otherPreview.previewHash; - const raceKey = receipt(); - const result = await Promise.allSettled([ - f.experiments.submit(submission, raceKey), - f.experiments.submit(input, raceKey), - ]); - expect(result.filter(r => r.status === 'fulfilled')).toHaveLength(1); - expect( - result - .filter(r => r.status === 'rejected') - .map(r => (r as PromiseRejectedResult).reason.status) - ).toEqual([409]); - expect(await totals(f)).toEqual({ experiments: 2, runs: 4, dispatch: 4 }); - }); - - test('dispatch insertion failure rolls the manifest, every trial and every outbox entry back', async () => { - const f = await fixture(); - const { submission } = await prepare(f); - await f.pool - .query(`CREATE FUNCTION fail_second_dispatch() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN - IF (SELECT trial_index FROM runs WHERE id=NEW.run_id)=1 THEN RAISE EXCEPTION 'fixture dispatch failure'; END IF; RETURN NEW; END $$; - CREATE TRIGGER fixture_dispatch_failure BEFORE INSERT ON backtest_dispatch FOR EACH ROW EXECUTE FUNCTION fail_second_dispatch()`); - const key = receipt(); - await expect(f.experiments.submit(submission, key)).rejects.toThrow('fixture dispatch failure'); - expect(await totals(f)).toEqual({ experiments: 0, runs: 0, dispatch: 0 }); - await f.pool.query('DROP TRIGGER fixture_dispatch_failure ON backtest_dispatch'); - expect((await f.experiments.submit(submission, key)).trialCount).toBe(2); - }); - - test('SQL guards reject manifest/receipt/linkage mutation, direct altered requests and missing identity', async () => { - const f = await fixture(); - const { preview, submission } = await prepare(f); - const experiment = await f.experiments.submit(submission, receipt()); - const id = experiment.trials[0]!.runId!; - for (const sql of [ - "UPDATE research_experiments SET name='changed' WHERE id=$1", - "UPDATE research_experiments SET preview_hash=repeat('a',64) WHERE id=$1", - "UPDATE research_experiments SET submission_key='other' WHERE id=$1", - "UPDATE research_experiments SET preview=preview-'candidates' WHERE id=$1", - 'DELETE FROM research_experiments WHERE id=$1', - ]) { - await expect(f.pool.query(sql, [experiment.id])).rejects.toMatchObject({ code: '23514' }); - } - await expect(f.pool.query('TRUNCATE research_experiments CASCADE')).rejects.toMatchObject({ - code: '23514', - }); - for (const assignment of [ - 'experiment_id=NULL', - 'trial_index=4', - "trial_key=repeat('a',64)", - "request_snapshot=request_snapshot-'policy'", - ]) { - await expect( - f.pool.query(`UPDATE runs SET ${assignment} WHERE id=$1`, [id]) - ).rejects.toMatchObject({ code: '23514' }); - } - for (const changes of [ - { index: 99 }, - { key: 'a'.repeat(64) }, - { dataset: 'a'.repeat(64) }, - { original: id }, - { principal: 'operator', receiptKey: 'key', hash: 'a'.repeat(64) }, - { request: { ...preview.request, name: 'changed' } }, - { request: null }, - { backtest: randomUUID() }, - { experiment: null }, - ]) { - await expect(rawTrial(f, experiment, changes)).rejects.toBeDefined(); - } - for (const mutate of [ - (p: typeof preview) => { - delete (p.request as unknown as Record).build; - }, - (p: typeof preview) => { - p.candidates[0]!.parameters = {}; - }, - (p: typeof preview) => { - p.request.policy.matching.risk.feeRate = - '0.00000000' as typeof p.request.policy.matching.risk.feeRate; - }, - ]) { - const altered = structuredClone(preview); - mutate(altered); - await expect( - f.pool.query( - `INSERT INTO research_experiments(id,backtest_id,name,preview,preview_hash,submission_principal,submission_key,submission_hash) - VALUES($1,$2,$3,$4,$5,'operator',$6,$7)`, - [ - randomUUID(), - f.draft.id, - preview.input.name, - altered, - preview.previewHash, - randomUUID(), - 'a'.repeat(64), - ] - ) - ).rejects.toBeDefined(); - } - await f.pool.query( - readFileSync( - new URL('../../database/postgres/init/22-experiments.sql', import.meta.url), - 'utf8' - ) - ); - expect((await f.experiments.get(experiment.id)).preview).toEqual(preview); - }); - - test('cancel_batch is idempotent, preserves completed results and fences running/paused completion and pending claims', async () => { - const f = await fixture(); - const { submission } = await prepare(f, { fastPeriod: [1, 2], slowPeriod: [3, 4] }); - const experiment = await f.experiments.submit(submission, receipt()); - await f.execute(experiment.trials[0]!.runId!); - const completedBefore = await f.api.getRunResults(experiment.trials[0]!.runId!); - const requests = ( - await f.pool.query( - 'SELECT request_snapshot FROM runs WHERE experiment_id=$1 ORDER BY trial_index', - [experiment.id] - ) - ).rows.map(r => r.request_snapshot as CanonicalRunRequest); - const active = await f.repository.startCanonical(requests[1]!); - await f.repository.startCanonical(requests[2]!); - await f.pool.query("UPDATE runs SET status='paused' WHERE id=$1", [requests[2]!.runId]); - const engine = new RustBacktestAdapter({ - logger, - }); - let computed; - try { - computed = await engine.runCanonical(requests[1]!, async () => f.dataset); - } finally { - await engine.shutdown(); - } - const result: CanonicalRunResult = { - kind: 'canonical-result/v1', - runId: active.runId, - backtestId: f.draft.id, - status: 'completed', - completedAt: new Date().toISOString(), - executionTime: 0, - financialEngine: 'rust', - strategyExecution: 'typescript-retained-builtin/v1', - request: requests[1]!, - ...computed, - }; - const cancelled = await f.experiments.cancel(experiment.id); - expect(cancelled.counts).toEqual({ - pending: 0, - running: 1, - paused: 1, - completed: 1, - failed: 0, - cancelled: 1, - }); - expect(cancelled.trials.map(t => t.cancelRequested)).toEqual([false, true, true, true]); - expect(await f.experiments.cancel(experiment.id)).toEqual(cancelled); - await expect(f.repository.completeCanonical(result, active.attemptId)).rejects.toThrow( - 'Backtest cancelled' - ); - expect( - (await f.pool.query('SELECT 1 FROM backtest_results WHERE run_id=$1', [active.runId])).rows - ).toHaveLength(0); - await f.repository.cancel(active.runId, active.attemptId); - expect((await f.experiments.get(experiment.id)).trials[1]!.status).toBe('cancelled'); - await expect(f.repository.startCanonical(requests[3]!)).rejects.toThrow(); - await expect( - f.repository.loadCanonicalDataset(active.runId, active.attemptId, requests[1]!.datasetHash) - ).rejects.toThrow(); - await expect( - f.pool.query('UPDATE research_experiments SET cancel_requested=FALSE WHERE id=$1', [ - experiment.id, - ]) - ).rejects.toMatchObject({ code: '23514' }); - await expect(rawTrial(f, experiment)).rejects.toMatchObject({ code: '23514' }); - expect(await f.api.getRunResults(experiment.trials[0]!.runId!)).toEqual(completedBefore); - // A claim racing cancellation either loses admission or becomes a cancel-requested active run. - const fresh = await f.experiments.submit(submission, receipt()); - const request = ( - await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [fresh.trials[0]!.runId]) - ).rows[0].request_snapshot; - await Promise.allSettled([ - f.repository.startCanonical(request), - f.experiments.cancel(fresh.id), - ]); - const raced = (await f.experiments.get(fresh.id)).trials[0]!; - expect(['running', 'cancelled']).toContain(raced.status); - expect(raced.cancelRequested).toBe(true); - }); - - test('missing/null/failed/incomparable outcomes remain visible and summaries select no full result or financial arrays', async () => { - const f = await fixture(); - const { submission } = await prepare(f, { fastPeriod: [1, 2], slowPeriod: [3, 4] }); - const experiment = await f.experiments.submit(submission, receipt()); - await f.execute(experiment.trials[0]!.runId!); - await f.pool.query("UPDATE runs SET status='failed',error='fixture failure' WHERE id=$1", [ - experiment.trials[1]!.runId, - ]); - // Deliberate corruption is restricted to this disposable schema and verifies fail-closed reads. - await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER'); - const originalResult = ( - await f.pool.query('SELECT canonical_result FROM backtest_results WHERE run_id=$1', [ - experiment.trials[0]!.runId, - ]) - ).rows[0].canonical_result; - for (const [path, value] of [ - ['{analytics,version}', 2], - ['{analytics,policy,sampling}', 'unsupported'], - ['{analytics,policy,variance}', 'population'], - ['{financial,policy,matching,risk,feeRate}', '0.00000000'], - ['{financial,identity,datasetHash}', 'a'.repeat(64)], - ['{analytics,metrics,totalReturn}', null], - ]) { - await f.pool.query( - 'UPDATE backtest_results SET canonical_result=jsonb_set($1::jsonb,$2::text[],$3::jsonb) WHERE run_id=$4', - [originalResult, path, JSON.stringify(value), experiment.trials[0]!.runId] - ); - const trial = (await f.experiments.get(experiment.id)).trials[0]!; - expect(trial.comparable).toBe(false); - expect(trial.metrics).toBeNull(); - expect(trial.diagnostic).not.toBeNull(); - } - await f.pool.query('UPDATE backtest_results SET canonical_result=$1 WHERE run_id=$2', [ - originalResult, - experiment.trials[0]!.runId, - ]); - await f.pool.query( - `UPDATE backtest_results SET canonical_result=jsonb_set(canonical_result,'{analytics,policy,periodsPerYear}','1') WHERE run_id=$1`, - [experiment.trials[0]!.runId] - ); - await f.pool.query('ALTER TABLE backtest_results ENABLE TRIGGER USER'); - await f.pool.query('ALTER TABLE runs DISABLE TRIGGER ALL'); - await f.pool.query('ALTER TABLE backtest_dispatch DISABLE TRIGGER ALL'); - await f.pool.query('DELETE FROM backtest_dispatch WHERE run_id=$1', [ - experiment.trials[3]!.runId, - ]); - await f.pool.query('DELETE FROM runs WHERE id=$1', [experiment.trials[3]!.runId]); - await f.pool.query('ALTER TABLE runs ENABLE TRIGGER ALL'); - await f.pool.query('ALTER TABLE backtest_dispatch ENABLE TRIGGER ALL'); - const detail = await f.experiments.get(experiment.id); - expect(detail.trialCount).toBe(4); - expect(detail.trials.map(t => t.status)).toEqual(['completed', 'failed', 'pending', 'missing']); - expect(detail.trials.every(t => t.metrics === null && !t.comparable)).toBe(true); - expect(detail.trials[1]!.error).toBe('fixture failure'); - expect(detail.trials[3]!.runId).toBeNull(); - const source = readFileSync( - new URL('../../apps/stock/web-api/src/services/experiments.service.ts', import.meta.url), - 'utf8' - ); - const projection = source.slice( - source.indexOf('SELECT r.id'), - source.indexOf('ORDER BY r.trial_index') - ); - expect(projection).not.toMatch(/canonical_result\s*(?:,|AS\s+\w+)/i); - expect(projection).not.toContain("->'financial'"); - expect(projection).not.toContain('sessionReturns'); - }); - - test('current original-family archive lock serializes preview and new admission without rewriting accepted receipts', async () => { - const f = await fixture(); - const { input, submission } = await prepare(f); - const key = receipt(); - const accepted = await f.experiments.submit(submission, key); - const blocker = await f.pool.connect(); - let pending: Promise | undefined; - try { - await blocker.query('BEGIN'); - await blocker.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [ - f.version.strategyId, - ]); - pending = f.experiments.preview(input).then( - value => ({ value }), - error => ({ error }) - ); - let waiting = false; - for (let attempt = 0; attempt < 100; attempt++) { - const rows = ( - await f.pool.query( - "SELECT 1 FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock'", - [f.schema] - ) - ).rows; - if (rows.length) { - waiting = true; - break; - } - await new Promise(resolve => setTimeout(resolve, 10)); - } - expect(waiting).toBe(true); - await blocker.query('COMMIT'); - expect(await pending).toMatchObject({ error: { status: 409 } }); - } finally { - await blocker.query('ROLLBACK'); - blocker.release(); - await pending; - } - await expect(f.experiments.submit(submission, receipt())).rejects.toMatchObject({ - status: 409, - }); - expect((await f.experiments.submit(submission, key)).id).toBe(accepted.id); - expect(await totals(f)).toEqual({ experiments: 1, runs: 2, dispatch: 2 }); - }); - - test('first SQL22 upgrade preserves ordinary and reproduction snapshots, receipts, leases and results', async () => { - const f = await fixture(4, false); - await f.approve(); - const original = await f.api.createRun({ backtestId: f.draft.id }, receipt()); - await f.execute(original.id); - const reproduction = await f.api.reproduceRun(original.id, receipt()); - const leased = await f.api.createRun({ backtestId: f.draft.id }, receipt()); - await f.repository.startCanonical( - (await f.repository.load(leased.id))!.config as CanonicalRunRequest - ); - const before = (await f.pool.query('SELECT * FROM runs ORDER BY run_number')).rows; - const results = (await f.pool.query('SELECT * FROM backtest_results')).rows; - const outbox = (await f.pool.query('SELECT * FROM backtest_dispatch ORDER BY run_id')).rows; - await f.pool.query( - readFileSync( - new URL('../../database/postgres/init/22-experiments.sql', import.meta.url), - 'utf8' - ) - ); - const after = (await f.pool.query('SELECT * FROM runs ORDER BY run_number')).rows; - expect( - after.map( - ({ - experiment_id: _experimentId, - trial_key: _trialKey, - trial_index: _trialIndex, - ...row - }) => row - ) - ).toEqual(before); - expect( - after.every(r => r.experiment_id === null && r.trial_key === null && r.trial_index === null) - ).toBe(true); - expect((await f.pool.query('SELECT * FROM backtest_results')).rows).toEqual(results); - expect((await f.pool.query('SELECT * FROM backtest_dispatch ORDER BY run_id')).rows).toEqual( - outbox - ); - await f.execute(reproduction.id); - expect((await f.api.getReproductionComparison(reproduction.id)).status).toBe('match'); - const ordinary = await f.api.createRun({ backtestId: f.draft.id }, receipt()); - expect(ordinary.status).toBe('pending'); - // The current experiment reader includes retry counters introduced after SQL22. - await f.pool.query( - readFileSync( - new URL('../../database/postgres/init/23-experiment-retries.sql', import.meta.url), - 'utf8' - ) - ); - await f.pool.query( - readFileSync( - new URL('../../database/postgres/init/24-chronological-validation.sql', import.meta.url), - 'utf8' - ) - ); - const input = { backtestId: f.draft.id, name: 'After upgrade', grid: {} }; - const preview = await f.experiments.preview(input); - expect( - (await f.experiments.submit({ ...input, previewHash: preview.previewHash }, receipt())) - .trialCount - ).toBe(1); - }); -}); diff --git a/test/postgres/isolated-candidates.test.ts b/test/postgres/isolated-candidates.test.ts deleted file mode 100644 index 7e984f82..00000000 --- a/test/postgres/isolated-candidates.test.ts +++ /dev/null @@ -1,533 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { readFileSync } from 'node:fs'; -import { afterEach, describe, expect, test } from 'bun:test'; -import { Pool } from 'pg'; -import { getLogger, setLoggerConfig } from '@stock-bot/logger'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import { isResearchAgent, type ResearchActor } from '@stock-bot/types'; -import { canonicalRunRequestSchema } from '../../apps/stock/config/src/contracts/canonical-research'; -import { builtinStrategySelectionSchema } from '../../apps/stock/config/src/contracts/strategy'; -import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner'; -import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay'; -import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository'; -import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter'; -import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime'; -import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins'; -import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service'; -import { researchGrantPolicy } from '../../apps/stock/web-api/src/services/research-agent-budget'; -import { ResearchAgentsService } from '../../apps/stock/web-api/src/services/research-agents.service'; -import { createResearchServices } from '../../apps/stock/web-api/src/services/research-services'; -import { retainResearchDataset } from '../../scripts/import-research-dataset'; -import { canonicalAdmissionFixture } from '../fixtures/canonical-admission'; -import { walkForwardDataset } from '../fixtures/walk-forward'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('isolated-candidate-test'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const cleanups: (() => Promise)[] = []; -afterEach(async () => { - for (const close of cleanups.splice(0).reverse()) { - await close(); - } -}); -const migrations = [ - '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', - '20-research-workspace.sql', - '21-run-reproduction.sql', - '22-experiments.sql', - '23-experiment-retries.sql', - '24-chronological-validation.sql', - '25-walk-forward.sql', - '26-cost-sensitivity.sql', - '27-research-evidence-sources.sql', - '28-research-agents.sql', -]; -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_candidate_' + 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(); - }); - for (const file of migrations) { - await pool.query( - readFileSync(new URL(`../../database/postgres/init/${file}`, import.meta.url), 'utf8') - ); - } - 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, false); - const container = { postgres, logger }, - experiments = new ExperimentsService(container), - agents = new ResearchAgentsService(container); - const apply = () => - pool.query( - readFileSync( - new URL('../../database/postgres/init/29-isolated-candidates.sql', import.meta.url), - 'utf8' - ) - ); - const candidate = async (principal: ResearchActor = 'operator', warmupBars = 0) => { - const family = await base.catalog.createStrategy( - { name: 'Isolated SMA', description: 'Controlled parity fixture' }, - principal - ); - const pkg = { - ...(await base.catalog.getVersionArtifact(base.version.id)), - execution: { kind: 'isolated-candidate/v1' as const, warmupBars }, - }; - return base.catalog.publishVersion(family.id, pkg, null, principal, randomUUID()); - }; - const execute = async (runId: string) => { - const engine = new RustBacktestAdapter({ - logger, - }); - const runner = new BacktestRunner({ - engine, - repository: new PostgresBacktestRunRepository(postgres), - logger, - }); - try { - await runner.runQueued(runId); - } finally { - await runner.shutdown(); - await engine.shutdown(); - } - return base.api.getRunResults(runId); - }; - return { ...base, pool, postgres, container, experiments, agents, apply, candidate, execute }; -} -const suite = url ? describe : describe.skip; -suite('isolated candidate durable research', () => { - test('SQL29 first upgrade/reapply preserves existing evidence and authoritative SQL28 resource guards', async () => { - const f = await fixture(); - const before = ( - await f.pool.query( - "SELECT pg_get_functiondef('guard_agent_run_budget()'::regprocedure) AS budget,pg_get_functiondef('require_agent_result_deadline()'::regprocedure) AS deadline" - ) - ).rows; - const old = await f.experiments.preview({ - name: 'Old builtin', - backtestId: f.draft.id, - grid: {}, - }); - const admitted = await f.experiments.submit( - { ...old.input, previewHash: old.previewHash }, - { principal: 'operator', key: 'before-upgrade' } - ); - const pending = ( - await f.pool.query('SELECT request_snapshot FROM runs WHERE experiment_id=$1', [admitted.id]) - ).rows[0]; - await new PostgresBacktestRunRepository(f.postgres).startCanonical( - canonicalRunRequestSchema.parse(pending.request_snapshot) - ); - const bytes = ( - await f.pool.query('SELECT to_jsonb(r) AS row FROM runs r WHERE experiment_id=$1', [ - admitted.id, - ]) - ).rows; - expect(bytes[0].row.status).toBe('running'); - expect(bytes[0].row.attempt_id).not.toBeNull(); - await f.apply(); - await f.apply(); - expect( - ( - await f.pool.query( - "SELECT pg_get_functiondef('guard_agent_run_budget()'::regprocedure) AS budget,pg_get_functiondef('require_agent_result_deadline()'::regprocedure) AS deadline" - ) - ).rows - ).toEqual(before); - expect( - ( - await f.pool.query('SELECT to_jsonb(r) AS row FROM runs r WHERE experiment_id=$1', [ - admitted.id, - ]) - ).rows - ).toEqual(bytes); - expect( - ( - await f.experiments.submit( - { ...old.input, previewHash: old.previewHash }, - { principal: 'operator', key: 'before-upgrade' } - ) - ).id - ).toBe(admitted.id); - }); - test('unreviewed candidate admission runs the same Rust economics as the trusted controlled program', async () => { - const f = await fixture(); - await f.apply(); - const candidate = await f.candidate(); - const input = { - name: 'Candidate parity', - backtestId: f.draft.id, - grid: {}, - candidate: { versionId: candidate.id, parameters: { fastPeriod: 2, slowPeriod: 3 } }, - }; - const preview = await f.experiments.preview(input); - expect(preview.request.strategy.origin).toBe('candidate'); - expect(preview.request.strategy.reviewId).toBeNull(); - const experiment = await f.experiments.submit( - { ...input, previewHash: preview.previewHash }, - { principal: 'operator', key: 'candidate-once' } - ); - const runId = experiment.trials[0]?.runId; - if (!runId) { - throw new Error('Missing candidate trial'); - } - const result = await f.execute(runId); - if (!result || !('kind' in result) || result.kind !== 'canonical-result/v1') { - throw new Error('Missing canonical candidate result'); - } - expect(result.strategyExecution).toBe('typescript-isolated-candidate/v1'); - const trusted = runStrategyReplay( - prepareReplayLoad(f.dataset, result.request.policy), - [ - createBuiltinStrategy( - builtinStrategySelectionSchema.parse(result.request.strategy.selection) - ), - ], - { resultFormat: 'report' } - ); - expect(result.financial).toEqual(trusted.result); - expect(String(result.financial.view.equity)).toBe('9969.30000000'); - expect((await f.experiments.get(experiment.id)).trials[0]?.comparable).toBeTrue(); - expect( - ( - await f.experiments.submit( - { ...input, previewHash: preview.previewHash }, - { principal: 'operator', key: 'candidate-once' } - ) - ).id - ).toBe(experiment.id); - }, 30000); - test('agent own-candidate opt-in maps exactly to its frozen grant and rejects another principal/version or financial drift', async () => { - const f = await fixture(); - await f.apply(); - const created = await f.agents.create({ - name: 'Candidate researcher', - allowedProjectIds: [], - allowedBacktestIds: [f.draft.id], - limits: { - maxActiveTrials: 2, - maxTrialsPerExperiment: 10, - maxBarEvaluationsPerExperiment: 10000, - maxAttemptWallMs: 60000, - maxAttempts: 2, - }, - }); - const principal = created.agent.id; - if (!isResearchAgent(principal)) { - throw new Error('Expected agent identity'); - } - const candidate = await f.candidate(principal); - const input = { - name: 'Own candidate', - backtestId: f.draft.id, - grid: {}, - candidate: { versionId: candidate.id, parameters: { fastPeriod: 2, slowPeriod: 3 } }, - }; - await expect(f.experiments.preview(input, principal)).rejects.toThrow('candidate permission'); - const before = ( - await f.pool.query('SELECT policy FROM research_agents WHERE id=$1', [principal]) - ).rows[0].policy; - await f.agents.update(principal, { - expectedRevision: 1, - allowOwnCandidateBacktestIds: [f.draft.id], - }); - const preview = await f.experiments.preview(input, principal); - expect(researchGrantPolicy(preview.request)).toEqual(before.grants[0].policy); - expect( - (await f.pool.query('SELECT research_grant_policy($1::jsonb) AS policy', [preview.request])) - .rows[0].policy - ).toEqual(researchGrantPolicy(preview.request)); - const foreign = await f.candidate('operator'); - await expect( - f.experiments.preview( - { ...input, candidate: { ...input.candidate, versionId: foreign.id } }, - principal - ) - ).rejects.toThrow('belong'); - const [experiment, duplicate] = await Promise.all([ - f.experiments.submit( - { ...input, previewHash: preview.previewHash }, - { principal, key: 'agent-candidate' } - ), - f.experiments.submit( - { ...input, previewHash: preview.previewHash }, - { principal, key: 'agent-candidate' } - ), - ]); - expect(duplicate.id).toBe(experiment.id); - expect(experiment.trialCount).toBe(1); - const after = ( - await f.pool.query('SELECT policy FROM research_agents WHERE id=$1', [principal]) - ).rows[0].policy; - expect(after.grants[0].policy).toEqual(before.grants[0].policy); - expect(after.grants[0].policyHash).toBe(before.grants[0].policyHash); - }, 30000); - test('candidate retry and reproduction preserve the original package, null review, runtime and baseline after template edits', async () => { - const f = await fixture(); - await f.apply(); - const candidate = await f.candidate(); - const input = { - name: 'Retry candidate', - backtestId: f.draft.id, - grid: {}, - candidate: { versionId: candidate.id, parameters: { fastPeriod: 2, slowPeriod: 3 } }, - }; - const preview = await f.experiments.preview(input); - const experiment = await f.experiments.submit( - { ...input, previewHash: preview.previewHash }, - { principal: 'operator', key: 'create' } - ); - const runId = experiment.trials[0]!.runId!; - const repository = new PostgresBacktestRunRepository(f.postgres); - await repository.rejectPending(runId, 'controlled preclaim failure'); - const original = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])) - .rows[0].request_snapshot; - await f.api.updateBacktest(f.draft.id, { - strategyParameters: { fastPeriod: 1, slowPeriod: 4 }, - }); - const retryBody = { expectedAttemptNumber: 0, expectedRetryCount: 0 }, - actor = { principal: 'operator', key: 'retry' }; - const retry = await f.experiments.retryTrial(experiment.id, runId, retryBody, actor); - expect(retry.retry.reviewId).toBeNull(); - expect( - (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])).rows[0] - .request_snapshot - ).toEqual(original); - await f.execute(runId); - expect((await f.experiments.retryTrial(experiment.id, runId, retryBody, actor)).retry.id).toBe( - retry.retry.id - ); - expect(await f.api.getReproductionPreview(runId)).toMatchObject({ - available: true, - currentReviewId: null, - request: { strategy: { origin: 'candidate', reviewId: null } }, - }); - const reproduced = await f.api.reproduceRun(runId, { - principal: 'operator', - key: 'reproduction', - }); - await f.execute(reproduced.id); - expect((await f.api.getReproductionComparison(reproduced.id)).status).toBe('match'); - await f.catalog.reviewVersion( - candidate.id, - { decision: 'revoke', reason: 'deny later admission' }, - 'operator' - ); - expect((await f.api.getReproductionPreview(runId)).available).toBeFalse(); - expect( - (await f.api.reproduceRun(runId, { principal: 'operator', key: 'reproduction' })).id - ).toBe(reproduced.id); - await expect( - f.api.reproduceRun(runId, { principal: 'operator', key: 'after-revoke' }) - ).rejects.toThrow(); - }, 30000); - test('candidate declared warmup and original baseline propagate through two native walk-forward windows and sealed reports', async () => { - const f = await fixture(); - await f.apply(); - const candidate = await f.candidate('operator', 4); - const data = walkForwardDataset(); - await retainResearchDataset(f.pool, data.dataset); - await f.api.updateBacktest(f.draft.id, { - startDate: new Date(data.dataset.manifest.bounds.tradeStart).toISOString(), - endDate: new Date(data.dataset.manifest.bounds.tradeEnd).toISOString(), - config: { ...f.definition.config, datasetHash: data.dataset.manifest.hash }, - }); - const { walkForwards: walks, validations } = createResearchServices(f.container); - const input = { - name: 'Candidate rolling windows', - backtestId: f.draft.id, - grid: {}, - windows: data.windows, - candidate: { versionId: candidate.id, parameters: { fastPeriod: 2, slowPeriod: 3 } }, - }; - const preview = await walks.preview(input); - const walk = await walks.submit( - { ...input, previewHash: preview.previewHash }, - { principal: 'operator', key: 'rolling' } - ); - for (const member of walk.windows) { - const initial = await validations.get(member.validationId); - expect(initial.preview.policy.model).toBe('unverified-candidate'); - for (const trial of initial.phases[0]!.experiment!.trials) { - await f.execute(trial.runId!); - } - const selected = await validations.select( - initial.id, - { previewHash: initial.previewHash }, - { principal: 'operator', key: randomUUID() } - ); - expect(selected.validation.selection!.reviewId).toBeNull(); - const heldout = selected.validation.phases[1]!.experiment!.preview; - for (const field of ['baselineVersionId', 'execution'] as const) { - const forged = structuredClone(heldout); - if (forged.request.strategy.origin !== 'candidate') { - throw Error('candidate fixture'); - } - if (field === 'baselineVersionId') { - forged.request.strategy.baselineVersionId = randomUUID(); - } else { - forged.request.strategy.execution.imageId = `sha256:${'0'.repeat(64)}`; - } - await expect( - f.pool.query("SELECT assert_validation_phase_preview($1,$2,'validation',$3,NULL)", [ - forged, - initial.preview, - selected.validation.selection!.winner, - ]) - ).rejects.toThrow(); - } - for (const phase of selected.validation.phases.slice(1)) { - expect(phase.experiment!.preview.request.strategy.origin).toBe('candidate'); - for (const trial of phase.experiment!.trials) { - await f.execute(trial.runId!); - } - } - await validations.finalize( - initial.id, - { - previewHash: initial.previewHash, - selectionHash: selected.validation.selection!.selectionHash, - }, - { principal: 'operator', key: randomUUID() } - ); - } - const sealed = await walks.finalize( - walk.id, - { previewHash: preview.previewHash }, - { principal: 'operator', key: 'seal' } - ); - expect(sealed.walkForward.report!.segments).toHaveLength(2); - const stored = ( - await f.pool.query( - "SELECT request_snapshot#>>'{strategy,baselineVersionId}' AS baseline, request_snapshot#>'{strategy,reviewId}' AS review FROM runs" - ) - ).rows; - expect(stored).toHaveLength(6); - expect(stored.every(row => row.baseline === f.version.id && row.review === null)).toBeTrue(); - }, 60000); - test('direct SQL refuses forged candidate ownership, baseline, execution profile and financial grant drift', async () => { - const f = await fixture(); - await f.apply(); - const created = await f.agents.create({ - name: 'Direct guard', - allowedProjectIds: [], - allowedBacktestIds: [f.draft.id], - allowOwnCandidateBacktestIds: [f.draft.id], - limits: { - maxActiveTrials: 2, - maxTrialsPerExperiment: 10, - maxBarEvaluationsPerExperiment: 10000, - maxAttemptWallMs: 60000, - maxAttempts: 2, - }, - }); - const principal = created.agent.id; - if (!isResearchAgent(principal)) { - throw Error('agent identity'); - } - const candidate = await f.candidate(principal); - const input = { - name: 'Guard candidate', - backtestId: f.draft.id, - grid: {}, - candidate: { versionId: candidate.id, parameters: { fastPeriod: 2, slowPeriod: 3 } }, - }; - const preview = await f.experiments.preview(input, principal); - const admitted = await f.experiments.submit( - { ...input, previewHash: preview.previewHash }, - { principal, key: 'admit' } - ); - const row = ( - await f.pool.query('SELECT to_jsonb(e) AS value FROM research_experiments e WHERE id=$1', [ - admitted.id, - ]) - ).rows[0].value; - await f.pool.query( - 'SELECT validate_experiment_manifest(jsonb_populate_record(NULL::research_experiments,$1))', - [row] - ); - for (const [path, value] of [ - [['strategy', 'baselineVersionId'], randomUUID()], - [['strategy', 'selection', 'ownerId'], 'strategy:' + randomUUID()], - [['strategy', 'origin'], 'builtin'], - [['strategy', 'execution', 'kind'], 'typescript-retained-builtin/v1'], - [['strategy', 'execution', 'profile', 'limits', 'memoryBytes'], 1073741824], - [['policy', 'matching', 'risk', 'maxGrossExposure'], '999999999'], - ] as const) { - const forged = structuredClone(row); - let parent = forged.preview.request; - for (const key of path.slice(0, -1)) { - parent = parent[key]; - } - parent[path.at(-1)!] = value; - await expect( - f.pool.query( - 'SELECT validate_experiment_manifest(jsonb_populate_record(NULL::research_experiments,$1))', - [forged] - ) - ).rejects.toThrow(); - } - const drift = structuredClone(preview.request); - drift.policy.matching.risk.maxGrossExposure = - '999999999' as typeof drift.policy.matching.risk.maxGrossExposure; - await expect( - f.pool.query( - 'SELECT assert_research_agent_grant(a,$2,$3) FROM research_agents a WHERE id=$1', - [principal, f.draft.id, drift] - ) - ).rejects.toThrow(); - const foreign = await f.candidate('operator'); - const foreignPreview = await f.experiments.preview({ - ...input, - candidate: { ...input.candidate, versionId: foreign.id }, - }); - await expect( - f.pool.query( - 'SELECT assert_research_agent_grant(a,$2,$3) FROM research_agents a WHERE id=$1', - [principal, f.draft.id, foreignPreview.request] - ) - ).rejects.toThrow(); - await f.agents.update(principal, { expectedRevision: 1, allowOwnCandidateBacktestIds: [] }); - await expect( - f.pool.query( - 'SELECT assert_research_agent_grant(a,$2,$3) FROM research_agents a WHERE id=$1', - [principal, f.draft.id, preview.request] - ) - ).rejects.toThrow(); - expect( - ( - await f.experiments.submit( - { ...input, previewHash: preview.previewHash }, - { principal, key: 'admit' } - ) - ).id - ).toBe(admitted.id); - expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(1); - }, 30000); -}); diff --git a/test/postgres/paper-deployments.test.ts b/test/postgres/paper-deployments.test.ts deleted file mode 100644 index 9c5b4cf1..00000000 --- a/test/postgres/paper-deployments.test.ts +++ /dev/null @@ -1,572 +0,0 @@ -import { createHash, randomUUID } from 'node:crypto'; -import { readdirSync, readFileSync } from 'node:fs'; -import { afterEach, describe, expect, test } from 'bun:test'; -import { Pool } from 'pg'; -import { getLogger, setLoggerConfig } from '@stock-bot/logger'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import type { PaperPromotionInput } from '@stock-bot/stock-config/paper-deployments'; -import { parseFinancialDecimal } 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 { PostgresCanonicalExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository'; -import { - readPaperDeployment, - verifyPaperEvidenceCustody, -} from '@stock-bot/trading-runtime/paper-deployment-custody'; -import { readPaperHostIdentity } from '@stock-bot/trading-runtime/paper-host-identity'; -import { PaperDeploymentHost } from '../../apps/stock/orchestrator/src/paper/PaperDeploymentHost'; -import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service'; -import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service'; -import { createResearchServices } from '../../apps/stock/web-api/src/services/research-services'; -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 '../fixtures/canonical-research'; -import { chronologicalDataset } from '../fixtures/chronological-validation'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('paper-promotion'), - url = process.env.PIPELINE_TEST_DATABASE_URL; -const closes: Array<() => Promise> = []; -afterEach(async () => { - for (const close of closes.splice(0).reverse()) { - await close(); - } -}); -const actor = () => ({ principal: 'operator' as const, key: randomUUID() }); -async function fixture(max = 1, withPromotion = true, candidate = false) { - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Disposable database required'); - } - const schema = 'stock_bot_safety_promotion_' + randomUUID().replaceAll('-', ''), - admin = new Pool({ connectionString: url }); - await admin.query(`CREATE SCHEMA ${schema}`); - const pool = new Pool({ - connectionString: url, - max, - options: `-c search_path=${schema} -c statement_timeout=15000`, - }); - closes.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - const directory = new URL('../../database/postgres/init/', import.meta.url); - for (const file of readdirSync(directory) - .filter( - n => - /^\d\d-/.test(n) && - Number(n.slice(0, 2)) >= 6 && - Number(n.slice(0, 2)) <= 30 && - (withPromotion || Number(n.slice(0, 2)) !== 30) - ) - .sort()) { - await pool.query(readFileSync(new URL(file, directory), 'utf8')); - } - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, - logger - ); - Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); - Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); - const container = { postgres, logger }, - researchServices = createResearchServices(container), - api = new BacktestServiceV2(container), - experiments = new ExperimentsService(container), - validations = researchServices.validations, - catalog = new StrategyCatalogService(container), - service = researchServices.paperDeployments; - const pkg = (await packageBuiltinStrategies())[0]; - if (!pkg) { - throw new Error('Missing builtin'); - } - const baseline = await catalog.seedBuiltin('Promotion SMA', pkg, 'seed'); - let version = baseline; - await catalog.reviewVersion( - version.id, - { decision: 'approve', reason: 'Disposable proof' }, - 'operator' - ); - if (candidate) { - const family = await catalog.createStrategy( - { name: 'Generic retained paper candidate' }, - 'operator' - ); - const content = `export function createPaperCandidate(selection) { - return { ownerId: selection.ownerId, strategyId: selection.strategyId, strategyVersion: selection.strategyVersion, - seed: selection.seed, mode: 'target', initialState: {count:0, marker:'retained-candidate'}, - decide(context) { return { nextState:{count:context.state.count+1,marker:'retained-candidate'}, - intent:{mode:'target',targets:[{instrumentId:selection.instrumentId,quantity:'1.00000000'}]} }; } - }; - }`; - version = await catalog.publishVersion( - family.id, - { - ...pkg, - program: { - ...pkg.program, - strategyId: 'paper_fixture_candidate', - strategyVersion: 'candidate/v1', - checkpointVersion: 'candidate-state/v1', - }, - artifact: { - ...pkg.artifact, - entryExport: 'createPaperCandidate', - content, - sha256: createHash('sha256').update(content).digest('hex'), - }, - execution: { kind: 'isolated-candidate/v1', warmupBars: 0 }, - }, - null, - 'operator', - randomUUID() - ); - } - const candidateOverride = candidate - ? { candidate: { versionId: version.id, parameters: { fastPeriod: 2, slowPeriod: 3 } } } - : {}; - const data = chronologicalDataset(), - dataset = data.dataset; - await retainResearchDataset(pool, dataset); - const draft = await api.createBacktest( - { - name: 'Promotion template', - strategy: 'catalog', - strategyVersionId: baseline.id, - strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, - symbols: ['X0.US'], - startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(), - endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(), - initialCapital: 10000, - config: { - datasetHash: dataset.manifest.hash, - dataFrequency: '1m', - canonical: canonicalSettings, - }, - }, - { autoStart: false } - ); - const repository = new PostgresBacktestRunRepository(postgres); - const execute = async (id: string) => { - const engine = new RustBacktestAdapter({ - logger, - }); - const runner = new BacktestRunner({ engine, repository, logger }); - try { - await runner.runQueued(id); - } finally { - await runner.shutdown(); - } - }; - const input = { - backtestId: draft.id, - name: 'Frozen OOS', - grid: {}, - recipe: data.recipe, - ...candidateOverride, - }, - preview = await experiments.previewValidation(input), - validation = await validations.submit({ ...input, previewHash: preview.previewHash }, actor()); - for (const trial of validation.phases[0]!.experiment!.trials) { - await execute(trial.runId!); - } - const selected = await validations.select( - validation.id, - { previewHash: preview.previewHash }, - actor() - ); - for (const phase of selected.validation.phases.slice(1)) { - for (const trial of phase.experiment!.trials) { - await execute(trial.runId!); - } - } - const finished = await validations.finalize( - validation.id, - { - previewHash: preview.previewHash, - selectionHash: selected.validation.selection!.selectionHash, - }, - actor() - ), - report = finished.validation.report!; - const costInput = { - backtestId: draft.id, - name: 'Cost evidence', - ...candidateOverride, - scenarios: [{ feeRate: '0.02', slippageRate: '0.01' }], - }, - costPreview = await experiments.previewCosts(costInput), - cost = await experiments.submitCosts( - { ...costInput, previewHash: costPreview.previewHash }, - actor() - ); - for (const trial of cost.trials) { - await execute(trial.runId!); - } - if (candidate) { - const researchResult = await api.getRunResults(report.test.runId); - expect( - researchResult && 'strategyExecution' in researchResult - ? researchResult.strategyExecution - : null - ).toBe('typescript-isolated-candidate/v1'); - await catalog.reviewVersion( - version.id, - { decision: 'approve', reason: 'Separate human review for trusted paper promotion' }, - 'operator' - ); - } - const start = Date.parse('2030-01-01T14:30:00Z'), - ownerId = `strategy:${version.id}`; - const promotion: PaperPromotionInput = { - name: 'Reviewed paper trial', - outOfSample: { - kind: 'chronological-report/v1', - validationId: validation.id, - reportId: report.id, - reportHash: report.reportHash, - previewHash: report.previewHash, - }, - testRunId: report.test.runId, - costExperimentId: cost.id, - costPreviewHash: cost.previewHash, - costRunId: cost.trials[1]!.runId!, - reason: 'Reviewed held-out results, costs and trusted-code limitations', - acknowledgeTrustedCode: true, - transport: { - accountId: 'paper:' + randomUUID(), - sessionId: 'paper:' + randomUUID(), - quoteSeriesId: 'X0.US:quote', - riskSession: { - calendarId: 'paper-risk', - calendarRevision: 'v1', - sessionId: 'paper-day', - startsAt: start, - }, - policy: { - version: 1, - sourceId: 'disposable-producer', - priceBasis: 'raw', - maxFeedAgeMs: 300000, - observations: [ - { instrumentId: 'X0.US', seriesId: 'X0.US:1m', intervalMs: 60000, staleAfterMs: 300000 }, - ], - cadence: [{ ownerId, seriesIds: ['X0.US:1m'] }], - calendars: [ - { - instrumentId: 'X0.US', - calendarId: 'explicit-venue', - revision: 'v1', - sessions: [{ sessionId: 'paper-day', opensAt: start, closesAt: start + 3600000 }], - }, - ], - riskBoundaries: [], - }, - }, - }; - return { - pool, - postgres, - container, - service, - catalog, - version, - promotion, - report, - cost, - preview, - start, - validation, - api, - draft, - repository, - }; -} -const submit = async ( - f: Awaited>, - input = f.promotion, - key = randomUUID() -) => { - const preview = await f.service.preview(input); - const body = { ...input, previewHash: preview.previewHash }; - return { deployment: await f.service.create(body, key), body, key }; -}; - -describe.skipIf(!url)('human-reviewed paper deployment', () => { - for (const candidate of [false, true]) { - test(`${candidate ? 'generic candidate' : 'builtin'} native OOS/cost promotion binds halted, fills through Rust, and restarts without resetting custody`, async () => { - const f = await fixture(1, true, candidate), - before = (await f.pool.query('SELECT count(*)::int AS n FROM simulation_accounts')).rows[0] - .n; - const saved = await submit(f), - deployment = saved.deployment; - expect( - (await f.pool.query('SELECT count(*)::int AS n FROM simulation_accounts')).rows[0].n - ).toBe(before); - expect(deployment.preview.evidence.test.fillCount).toBeGreaterThan(0); - expect(deployment.preview.evidence.costs.every(e => e.fillCount > 0)).toBe(true); - expect(deployment.preview.configuration.matching.risk.feeRate).toBe( - parseFinancialDecimal('0.02') - ); - let now = f.start + 60000; - const repository = new PostgresCanonicalExecutionRepository(f.postgres), - host = new PaperDeploymentHost({ database: f.postgres, repository, now: () => now }); - closes.push(() => host.shutdown()); - expect((await host.bind(deployment.id.toUpperCase())).readiness.active).toBe(false); - expect((await host.status(deployment.id)).readiness.operatorHalted).toBe(true); - await expect(host.activate(deployment.id)).rejects.toThrow('feed'); - const runtime = host.runtime(), - connection = { sourceId: 'disposable-producer', connectionId: 'one' }; - await runtime.connect(connection); - const send = async (sequence: number, price: number, bars = true) => { - now = f.start + sequence * 60000; - const decimal = parseFinancialDecimal(String(price)); - return runtime.ingest({ - version: 1, - ...connection, - id: 'frame:' + sequence, - sequence, - availableAt: now, - quotes: [ - { - instrumentId: 'X0.US', - seriesId: 'X0.US:quote', - observedAt: now, - sourceSequence: sequence, - bid: decimal, - ask: decimal, - bidSize: parseFinancialDecimal('1000'), - askSize: parseFinancialDecimal('1000'), - }, - ], - observations: bars - ? [ - { - series_id: 'X0.US:1m', - instrument_id: 'X0.US', - interval_start: now - 60000, - interval_end: now, - event_time: now, - available_at: now, - source_sequence: sequence, - open: decimal, - high: decimal, - low: decimal, - close: decimal, - volume: parseFinancialDecimal('1000'), - }, - ] - : [], - }); - }; - await send(1, 3); - await host.activate(deployment.id); - await send(2, 3); - await send(3, 2); - await send(4, 1); - await send(5, 4); - await send(6, 5); - await send(7, 5, false); - const accountId = f.promotion.transport.accountId; - const snapshot = async () => ({ - account: ( - await f.pool.query('SELECT state FROM simulation_accounts WHERE id=$1', [accountId]) - ).rows[0].state, - owners: ( - await f.pool.query( - 'SELECT payload FROM simulation_strategy_checkpoints WHERE account_id=$1 ORDER BY strategy_id', - [accountId] - ) - ).rows, - }); - const filled = await snapshot(); - expect(filled.account.view.portfolio.positions.length).toBeGreaterThan(0); - expect(filled.account.host.deployment.deploymentId).toBe(deployment.id); - expect(deployment.preview.strategy.origin).toBe(candidate ? 'candidate' : 'builtin'); - if (candidate) { - expect(filled.owners[0].payload.definition.strategyId).toBe('paper_fixture_candidate'); - expect(filled.owners[0].payload.diagnostic.state.marker).toBe('retained-candidate'); - expect(filled.owners[0].payload.diagnostic.state.count).toBeGreaterThan(0); - expect(filled.account.view.portfolio.positions[0].quantity).toBe('1.00000000'); - } - - await host.halt(deployment.id, 'Review complete'); - await host.shutdown(); - const restarted = new PaperDeploymentHost({ - database: f.postgres, - repository, - now: () => now, - }); - closes.push(() => restarted.shutdown()); - expect((await restarted.bind(deployment.id)).readiness.active).toBe(false); - const restored = await snapshot(); - expect(restored.account.view).toEqual(filled.account.view); - expect(restored.account.checkpoint).toEqual(filled.account.checkpoint); - expect(restored.owners).toEqual(filled.owners); - expect(restored.account.host.deployment).toEqual(filled.account.host.deployment); - await f.catalog.reviewVersion( - f.version.id, - { decision: 'revoke', reason: 'Stop new activation' }, - 'operator' - ); - await expect(restarted.activate(deployment.id)).rejects.toThrow('current operator approval'); - expect((await restarted.halt(deployment.id, 'Still allowed')).readiness.active).toBe(false); - expect(await f.service.create(saved.body, saved.key)).toEqual(deployment); - }, 60000); - } - test('exact receipts survive review changes; wrong evidence, cost drift, SQL tampering and custody reuse fail closed', async () => { - const f = await fixture(4), - saved = await submit(f); - const race = await Promise.all([ - f.service.create(saved.body, saved.key), - f.service.create(saved.body, saved.key), - ]); - expect(race).toEqual([saved.deployment, saved.deployment]); - await expect(f.service.create({ ...saved.body, name: 'different' }, saved.key)).rejects.toThrow( - 'another request' - ); - await expect( - f.service.preview({ ...f.promotion, testRunId: f.report.validation.runId }) - ).rejects.toThrow('test run'); - await expect( - f.service.preview({ ...f.promotion, costRunId: f.report.test.runId }) - ).rejects.toThrow('cost scenario'); - await expect(f.service.create(saved.body, randomUUID())).rejects.toThrow('already'); - const original = saved.deployment; - for (const mutate of [ - (d: typeof original) => { - d.principal = 'service' as 'operator'; - }, - (d: typeof original) => { - d.preview.configuration.matching.risk.maxGrossExposure = parseFinancialDecimal('999999'); - }, - (d: typeof original) => { - d.preview.input.testRunId = f.report.validation.runId; - }, - (d: typeof original) => { - d.preview.evidence.costs = []; - }, - (d: typeof original) => { - d.preview.evidence.test.metrics.totalReturn = 999; - }, - (d: typeof original) => { - d.preview.host.engineBinarySha256 = 'f'.repeat(64); - }, - ]) { - const d = structuredClone(original); - d.id = randomUUID(); - d.preview.input.transport.accountId = 'other:' + randomUUID(); - d.preview.configuration.matching.risk.ledger.accountId = d.preview.input.transport.accountId; - mutate(d); - await expect( - f.pool.query( - 'INSERT INTO paper_deployments(id,account_id,strategy_version_id,promotion_hash,idempotency_key,request_hash,document) VALUES($1,$2,$3,$4,$5,$6,$7)', - [ - d.id, - d.preview.configuration.matching.risk.ledger.accountId, - d.preview.strategy.versionId, - d.promotionHash, - randomUUID(), - 'a'.repeat(64), - d, - ] - ) - ).rejects.toThrow(); - } - await expect( - f.pool.query( - 'UPDATE paper_deployments SET document=document||\'{"principal":"service"}\' WHERE id=$1', - [original.id] - ) - ).rejects.toThrow('immutable'); - await expect( - f.pool.query('DELETE FROM paper_deployments WHERE id=$1', [original.id]) - ).rejects.toThrow('immutable'); - expect((await f.service.get(original.id)).promotionHash).toBe(original.promotionHash); - await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER'); - await f.pool.query( - "UPDATE backtest_results SET canonical_result=jsonb_set(canonical_result,'{analytics,metrics,totalReturn}','999'::jsonb) WHERE run_id=$1", - [f.promotion.testRunId] - ); - await f.pool.query('ALTER TABLE backtest_results ENABLE TRIGGER USER'); - await expect(f.service.authorizeCommand(original.id)).rejects.toThrow(); - await expect(verifyPaperEvidenceCustody(f.pool, original)).rejects.toThrow('result identity'); - }, 60000); - test('changed installed host and retained artifact cannot initialize or overwrite an account', async () => { - const f = await fixture(), - drifted = createResearchServices(f.container, { - paperIdentity: async () => ({ - ...(await readPaperHostIdentity()), - hostSha256: 'f'.repeat(64), - }), - }).paperDeployments; - const wrongNative = createResearchServices(f.container, { - paperIdentity: async () => ({ - ...(await readPaperHostIdentity()), - engineBinarySha256: 'f'.repeat(64), - }), - }).paperDeployments; - await expect(wrongNative.preview(f.promotion)).rejects.toThrow('same native'); - const preview = await drifted.preview(f.promotion), - saved = await drifted.create( - { ...f.promotion, previewHash: preview.previewHash }, - randomUUID() - ); - const host = new PaperDeploymentHost({ - database: f.postgres, - repository: new PostgresCanonicalExecutionRepository(f.postgres), - }); - closes.push(() => host.shutdown()); - await expect(host.bind(saved.id)).rejects.toThrow('differs'); - expect( - (await f.pool.query('SELECT count(*)::int AS n FROM simulation_accounts')).rows[0].n - ).toBe(0); - await f.postgres.transaction(async tx => { - await tx.query('ALTER TABLE strategy_versions DISABLE TRIGGER USER'); - await tx.query( - "UPDATE strategy_versions SET envelope=jsonb_set(envelope,'{artifact,content}',to_jsonb((envelope#>>'{artifact,content}')||' changed')) WHERE id=$1", - [f.version.id] - ); - await tx.query('ALTER TABLE strategy_versions ENABLE TRIGGER USER'); - }); - await expect(host.bind(saved.id)).rejects.toThrow('hash mismatch'); - await expect(f.service.preview(f.promotion)).rejects.toThrow(); - expect( - (await f.pool.query('SELECT count(*)::int AS n FROM simulation_accounts')).rows[0].n - ).toBe(0); - }, 60000); - test('first migration/reapply preserves accepted research and leases, and archived evidence remains readable', async () => { - const f = await fixture(1, false), - pending = await f.api.createRun({ backtestId: f.draft.id }, actor()), - request = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [pending.id])) - .rows[0].request_snapshot; - await f.repository.startCanonical(request); - const snapshot = async () => - (await f.pool.query('SELECT to_jsonb(r) AS row FROM runs r ORDER BY id')).rows; - const before = await snapshot(); - expect( - before.some( - item => item.row.status === 'running' && item.row.attempt_id && item.row.lease_expires_at - ) - ).toBe(true); - const migration = readFileSync( - new URL('../../database/postgres/init/30-paper-deployments.sql', import.meta.url), - 'utf8' - ); - await f.pool.query(migration); - expect(await snapshot()).toEqual(before); - const saved = await submit(f); - await f.pool.query(migration); - expect(await snapshot()).toEqual(before); - expect(await readPaperDeployment(f.pool, saved.deployment.id)).toEqual(saved.deployment); - await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [ - f.version.strategyId, - ]); - expect(await f.service.get(saved.deployment.id)).toEqual(saved.deployment); - await expect(f.service.authorizeCommand(saved.deployment.id)).rejects.toThrow('active family'); - expect( - (await f.pool.query('SELECT count(*)::int AS n FROM simulation_accounts')).rows[0].n - ).toBe(0); - }, 60000); -}); diff --git a/test/postgres/paper-http.test.ts b/test/postgres/paper-http.test.ts deleted file mode 100644 index 3c1d288f..00000000 --- a/test/postgres/paper-http.test.ts +++ /dev/null @@ -1,170 +0,0 @@ -import { asValue } from 'awilix'; -import { afterEach, describe, expect, test } from 'bun:test'; -import { Hono } from 'hono'; -import { createHttpSecurity, ServiceContainerBuilder } from '@stock-bot/di'; -import { parseFinancialDecimal } from '@stock-bot/types'; -import { createPaperRoutes } from '../../apps/stock/orchestrator/src/api/rest/paper'; -import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container'; -import { builtinStrategySelectionSchema } from '@stock-bot/stock-config/strategy'; -import type { PaperRuntime } from '@stock-bot/stock-config/paper-runtime'; -import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins'; -import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types'; -import { canonicalAdmissionFixture } from '../fixtures/canonical-admission'; -import { logger } from '../fixtures/execution'; -import { paperConfig, paperFixture, paperFrame } from '../fixtures/paper-runtime'; - -const adminToken = 'paper-http-test-admin-token-not-real-123456'; -const serviceToken = 'paper-http-test-service-token-not-real-123456'; -const cleanup: (() => Promise)[] = []; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); -function api(runtime: PaperRuntime) { - const app = new Hono(); - createHttpSecurity({ adminToken, serviceToken }).mount(app); - app.route( - '/api/paper', - createPaperRoutes({ logger, custom: { CanonicalPaperRuntime: runtime } }) - ); - return async (path: string, body: unknown, producer = false) => { - const response = await app.request(`/api/paper/${path}`, { - method: 'POST', - headers: { - Authorization: `Bearer ${producer ? serviceToken : adminToken}`, - 'Content-Type': 'application/json', - }, - body: JSON.stringify(body), - }); - const result = await response.json(); - expect(response.status, JSON.stringify(result)).toBe(200); - return result; - }; -} - -describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)( - 'canonical paper HTTP and composition', - () => { - test('authenticated feed -> actual SMA -> next quote Rust fill -> durable restart without capital reset', async () => { - const config = paperConfig(); - config.matching.risk.ledger.initialCapital = '1234'; - config.strategies[0]!.ownerBudget = '20'; - const program = createBuiltinStrategy( - builtinStrategySelectionSchema.parse(config.strategies[0]) - ); - const f = await paperFixture(config, program); - cleanup.push(f.close); - let post = api(f.runtime); - const connection = { sourceId: 'fixture', connectionId: 'one' }; - await post('feed/connect', connection, true); - await post('feed/frames', paperFrame(1), true); - await post('activate', {}); - const send = async (sequence: number, price: string, bars = true) => { - f.clock(sequence * 10); - const frame = paperFrame(sequence); - frame.quotes[0]!.bid = frame.quotes[0]!.ask = parseFinancialDecimal(price); - frame.observations = bars - ? frame.observations.map(row => ({ - ...row, - open: parseFinancialDecimal(price), - high: parseFinancialDecimal(price), - low: parseFinancialDecimal(price), - close: parseFinancialDecimal(price), - })) - : []; - await post('feed/frames', frame, true); - }; - await send(2, '11'); - await send(3, '9'); - await send(4, '10'); - const decision = await f.snapshot(); - expect(decision.account.view.portfolio.positions).toHaveLength(0); - expect(decision.owners[0]!.diagnostic.nextDecisionSequence).toBe(3); - await send(5, '10', false); - const filled = await f.snapshot(); - expect(filled.account.view.portfolio.positions[0]!.quantity).toBe(parseFinancialDecimal('2')); - expect(filled.account.view.portfolio.cash).toBe(parseFinancialDecimal('1213.8')); - expect(filled.account.view.equity).toBe(parseFinancialDecimal('1233.8')); - expect(filled.journal.filter(row => row.payload.kind === 'effect')).not.toHaveLength(0); - await post('halt', { reason: 'restart fixture' }); - const restored = await f.make(); - post = api(restored); - expect(await restored.status()).toMatchObject({ - operatorHalted: true, - active: false, - connected: false, - }); - expect((await f.snapshot()).account.view).toEqual(filled.account.view); - expect((await f.snapshot()).account.checkpoint).toEqual(filled.account.checkpoint); - expect((await f.snapshot()).journal).toEqual(filled.journal); - expect((await f.snapshot()).owners).toEqual(filled.owners); - await post('feed/connect', { ...connection, connectionId: 'two' }, true); - f.clock(60); - await post('feed/frames', paperFrame(6, 60, 'two'), true); - await post('activate', {}); - expect((await f.snapshot()).account.view).toEqual(filled.account.view); - expect((await f.snapshot()).account.checkpoint).toEqual(filled.account.checkpoint); - expect((await f.snapshot()).journal).toEqual(filled.journal); - }); - - test('opt-in composition exposes canonical custody only and research cannot change its state', async () => { - const config = paperConfig(); - const f = await paperFixture( - config, - createBuiltinStrategy(builtinStrategySelectionSchema.parse(config.strategies[0])) - ); - cleanup.push(f.close); - const container = await new ServiceContainerBuilder() - .withOptions({ - enableCache: false, - enableQueue: false, - enableMongoDB: false, - enablePostgres: false, - enableQuestDB: false, - enableBrowser: false, - enableProxy: false, - }) - .build(); - const services: OrchestratorServices = { logger, postgres: f.postgres }; - container.register({ serviceContainer: asValue(services) }); - await registerOrchestratorServices(container, { - role: 'paper', - canonicalPaper: config, - nativeExecutionTimeoutMs: 10000, - }); - const custom = services.custom!; - cleanup.push(async () => { - await custom.CanonicalPaperRuntime!.shutdown(); - await custom.BacktestRunner!.shutdown(); - await container.dispose(); - }); - expect(custom.CanonicalPaperRuntime).toBeDefined(); - for (const key of [ - 'ExecutionService', - 'ModeManager', - 'StrategyManager', - 'MarketDataService', - 'PaperTradingManager', - ] as const) { - expect(custom[key]).toBeUndefined(); - expect(container.hasRegistration(key)).toBe(false); - } - expect((await custom.CanonicalPaperRuntime!.status()).active).toBe(false); - const before = await f.snapshot(); - const research = await canonicalAdmissionFixture(f.pool, f.postgres); - custom.StorageService!.getHistoricalBars = async () => { - throw new Error('Canonical execution cannot query providers'); - }; - const run = await research.api.createRun({ backtestId: research.draft.id }); - expect((await custom.BacktestRunner!.runQueued(run.id)).status).toBe('completed'); - expect(await f.snapshot()).toEqual(before); - await expect( - registerOrchestratorServices(container, { role: 'paper', canonicalPaper: config }) - ).rejects.toThrow('fresh runtime composition'); - await expect(registerOrchestratorServices(container)).rejects.toThrow( - 'fresh runtime composition' - ); - }); - } -); diff --git a/test/postgres/paper-runtime.test.ts b/test/postgres/paper-runtime.test.ts deleted file mode 100644 index 74864f25..00000000 --- a/test/postgres/paper-runtime.test.ts +++ /dev/null @@ -1,575 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import { parseFinancialDecimal } from '@stock-bot/types'; -import { compareEventKeys } from '../../apps/stock/orchestrator/src/execution/canonical-paper'; -import { CanonicalPaperExecution } from '../../apps/stock/orchestrator/src/execution/CanonicalPaperExecution'; -import { counterProgram, quoteInput } from '../fixtures/canonical-paper'; -import { paperConfig, paperFixture, paperFrame } from '../fixtures/paper-runtime'; - -const connection = { sourceId: 'fixture', connectionId: 'one' }; -test('host event keys preserve Rust UTF-8 instrument ordering for supplementary Unicode', () => { - const key = { at: 1, phase: 'Execution' as const, sourceSequence: 1 }; - expect( - compareEventKeys({ ...key, instrumentId: '\u{10000}' }, { ...key, instrumentId: '\ue000' }) - ).toBeGreaterThan(0); -}); -const cleanup: (() => Promise)[] = []; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); -async function fixture(config = paperConfig(), program = counterProgram()) { - const f = await paperFixture(config, program); - cleanup.push(f.close); - return f; -} -async function start(f: Awaited>) { - await f.runtime.connect(connection); - expect((await f.runtime.ingest(paperFrame(1))).disposition).toBe('health-only'); - await f.runtime.activate({ recoverPending: false }); -} -function deferred() { - let resolve!: () => void; - const promise = new Promise(done => { - resolve = done; - }); - return { promise, resolve }; -} - -describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)( - 'controlled canonical paper on real PostgreSQL', - () => { - test('requires initial activation, retains inactive retry disposition, and freezes active retries after halt', async () => { - const f = await fixture(); - const initial = await f.runtime.status(); - expect(initial).toMatchObject({ - active: false, - ready: false, - connected: false, - operatorHalted: true, - }); - await start(f); - expect(await f.runtime.ingest(paperFrame(1))).toMatchObject({ - duplicate: true, - disposition: 'health-only', - }); - expect((await f.snapshot()).account.inputSequence).toBe(0); - f.clock(20); - const frame = paperFrame(2); - expect((await f.runtime.ingest(frame)).disposition).toBe('admitted'); - const before = await f.snapshot(); - expect(before.owners[0]!.diagnostic.nextDecisionSequence).toBe(1); - await f.runtime.halt('human stop'); - expect(await f.runtime.ingest(frame)).toMatchObject({ - duplicate: true, - disposition: 'admitted', - readiness: { active: false, operatorHalted: true }, - }); - expect((await f.snapshot()).account.checkpoint).toEqual(before.account.checkpoint); - f.clock(30); - expect((await f.runtime.ingest(paperFrame(3))).disposition).toBe('health-only'); - expect((await f.snapshot()).owners).toEqual(before.owners); - }); - - test('persists halt and fences all stale-generation controls, ingestion and shutdown after replacement', async () => { - const f = await fixture(); - await start(f); - await f.runtime.halt('persist me'); - const replacement = await f.make(); - expect(await replacement.status()).toMatchObject({ - active: false, - connected: false, - operatorHalted: true, - }); - f.clock(20); - await expect(f.runtime.ingest(paperFrame(2))).rejects.toThrow('generation'); - await expect(f.runtime.activate({ recoverPending: true })).rejects.toThrow('generation'); - await expect(f.runtime.shutdown()).rejects.toThrow('generation'); - await expect( - (f.runtime as unknown as { execution: CanonicalPaperExecution }).execution.drain() - ).rejects.toThrow('generation'); - await replacement.connect({ ...connection, connectionId: 'two' }); - f.clock(20); - await replacement.ingest(paperFrame(2, 20, 'two')); - await replacement.activate({ recoverPending: false }); - expect(await replacement.status()).toMatchObject({ - active: true, - connected: true, - operatorHalted: false, - }); - await replacement.disconnect(connection); - expect((await replacement.status()).active).toBe(true); - await replacement.connect({ ...connection, connectionId: 'two' }); - expect((await replacement.status()).active).toBe(true); - await replacement.connect({ ...connection, connectionId: 'three' }); - expect(await replacement.status()).toMatchObject({ - active: false, - connected: true, - ready: false, - }); - }); - - test('long idle then a fresh frame revokes activation without a preceding status poll', async () => { - const f = await fixture(); - await start(f); - f.clock(200); - const result = await f.runtime.ingest(paperFrame(2, 200)); - expect(result).toMatchObject({ disposition: 'health-only', readiness: { active: false } }); - expect((await f.snapshot()).account.inputSequence).toBe(0); - await f.runtime.activate({ recoverPending: false }); - expect((await f.runtime.status()).active).toBe(true); - }); - - test('status expiry commits atomically, rolls back on storage failure and never resumes from fresh evidence alone', async () => { - const f = await fixture(); - await start(f); - const before = await f.snapshot(); - f.clock(200); - f.wrap(tx => ({ - ...tx, - async nextInput() { - throw new Error('readiness storage failure'); - }, - })); - await expect(f.runtime.status()).rejects.toThrow('readiness storage failure'); - expect((await f.snapshot()).account).toEqual(before.account); - f.wrap(tx => tx); - const expired = await f.runtime.status(); - expect(expired).toMatchObject({ active: false, ready: false }); - expect(expired.reasons).toContain( - 'Operational readiness expired; fresh feed and operator activation required' - ); - expect((await f.snapshot()).account.host?.active).toBe(false); - expect(await f.runtime.status()).toEqual(expired); - expect(await f.runtime.ingest(paperFrame(2, 200))).toMatchObject({ - disposition: 'health-only', - readiness: { active: false, ready: false }, - }); - expect((await f.snapshot()).account.checkpoint).toEqual(before.account.checkpoint); - expect(await f.runtime.activate({ recoverPending: false })).toMatchObject({ - active: true, - ready: true, - }); - }); - - test('frame inputs, health and receipts commit atomically and conflicting retries cannot alter them', async () => { - const f = await fixture(); - await start(f); - const before = await f.snapshot(); - let writes = 0; - f.wrap(tx => ({ - ...tx, - async putInput(input) { - if (++writes === 2) { - throw new Error('atomic enqueue failure'); - } - await tx.putInput(input); - }, - })); - f.clock(20); - await expect(f.runtime.ingest(paperFrame(2))).rejects.toThrow('atomic enqueue failure'); - expect((await f.snapshot()).account).toEqual(before.account); - f.wrap(tx => tx); - expect(await f.runtime.ingest(paperFrame(2))).toMatchObject({ - duplicate: false, - disposition: 'admitted', - }); - const saved = await f.snapshot(); - const conflict = paperFrame(2); - conflict.quotes[0]!.ask = parseFinancialDecimal('11'); - await expect(f.runtime.ingest(conflict)).rejects.toThrow('conflicting content'); - expect((await f.snapshot()).account).toEqual(saved.account); - }); - - test('new frame IDs cannot turn inactive probe quotes into later tradable liquidity', async () => { - const f = await fixture(); - await start(f); - f.clock(20); - const recycled = paperFrame(2); - recycled.quotes = paperFrame(1).quotes; - await expect(f.runtime.ingest(recycled)).rejects.toThrow('known physical quote'); - recycled.quotes[0]!.bidSize = parseFinancialDecimal('11'); - await expect(f.runtime.ingest(recycled)).rejects.toThrow('conflicting content'); - expect((await f.snapshot()).account.inputSequence).toBe(0); - }); - - test('new quote identities cannot regress a fresh inactive probe or hide stale executable quotes', async () => { - const f = await fixture(); - await start(f); - f.clock(20); - const old = paperFrame(2); - old.quotes[0]!.observedAt = 5; - await expect(f.runtime.ingest(old)).rejects.toThrow('regresses'); - expect((await f.snapshot()).account.inputSequence).toBe(0); - await f.runtime.halt('probe'); - f.clock(200); - await f.runtime.ingest(paperFrame(3, 200)); - await f.runtime.activate({ recoverPending: false }); - f.clock(210); - const stale = paperFrame(4, 210); - stale.quotes[0]!.observedAt = 100; - await expect(f.runtime.ingest(stale)).rejects.toThrow('regresses'); - expect((await f.snapshot()).account.inputSequence).toBe(0); - }); - - test('equal-time quotes require nonregressing physical sequence; a newer sequence remains admissible', async () => { - const f = await fixture(); - await start(f); - f.clock(20); - const newer = paperFrame(2); - newer.quotes[0]!.observedAt = 10; - expect((await f.runtime.ingest(newer)).disposition).toBe('admitted'); - const saved = await f.snapshot(); - f.clock(30); - const older = paperFrame(3); - older.quotes[0]!.observedAt = 10; - older.quotes[0]!.sourceSequence = 0; - await expect(f.runtime.ingest(older)).rejects.toThrow('regresses'); - expect((await f.snapshot()).account.checkpoint).toEqual(saved.account.checkpoint); - }); - - test.each(['reconnect', 'restart'] as const)( - '%s preserves quote highwater while requiring new connection health', - async kind => { - const f = await fixture(); - await f.runtime.connect(connection); - f.clock(30); - await f.runtime.ingest(paperFrame(3)); - const runtime = kind === 'restart' ? await f.make() : f.runtime; - await runtime.connect({ ...connection, connectionId: 'two' }); - expect((await runtime.status()).reasons).toContain('quote-stale:X'); - f.clock(40); - const old = paperFrame(4, 40, 'two'); - old.quotes[0]!.observedAt = 20; - old.quotes[0]!.sourceSequence = 2; - await expect(runtime.ingest(old)).rejects.toThrow('regresses'); - expect((await f.snapshot()).account.inputSequence).toBe(0); - await runtime.ingest(paperFrame(4, 40, 'two')); - expect((await runtime.activate({ recoverPending: false })).active).toBe(true); - } - ); - - test.each(['malformed', 'conflict', 'activation'] as const)( - 'a rejected %s request durably latches stale inactivity without polling or admitting its input', - async kind => { - const f = await fixture(); - await start(f); - const before = await f.snapshot(); - f.clock(200); - if (kind === 'activation') { - await expect(f.runtime.activate({ recoverPending: false })).rejects.toThrow( - 'unavailable' - ); - } else { - const rejected = kind === 'conflict' ? paperFrame(1) : paperFrame(2, 200); - if (kind === 'conflict') { - rejected.quotes[0]!.ask = parseFinancialDecimal('11'); - } else { - rejected.quotes[0]!.ask = parseFinancialDecimal('0'); - } - await expect(f.runtime.ingest(rejected)).rejects.toThrow(); - } - // Read persisted custody directly: status() must not be what latches the halt. - const stopped = await f.snapshot(); - expect(stopped.account.host?.active).toBe(false); - expect(stopped.account.checkpoint).toEqual(before.account.checkpoint); - expect(stopped.account.inputSequence).toBe(0); - expect(stopped.account.host!.frames).toEqual(before.account.host!.frames); - expect(stopped.account.host!.lastAvailableAt).toBe(before.account.host!.lastAvailableAt); - } - ); - - test('fresh transport and asset A cannot certify a stale required asset B or exhausted calendars', async () => { - const config = paperConfig(); - config.matching.series.push({ instrumentId: 'Y', seriesId: 'Y:quote', mode: 'Quote' }); - config.policy.calendars.push({ ...config.policy.calendars[0]!, instrumentId: 'Y' }); - const f = await fixture(config); - await f.runtime.connect(connection); - await f.runtime.ingest(paperFrame(1)); - await expect(f.runtime.activate({ recoverPending: false })).rejects.toThrow('quote-stale:Y'); - f.clock(20); - const frame = paperFrame(2); - frame.quotes.push({ ...frame.quotes[0]!, instrumentId: 'Y', seriesId: 'Y:quote' }); - await f.runtime.ingest(frame); - await f.runtime.activate({ recoverPending: false }); - f.clock(110); - await f.runtime.ingest(paperFrame(3, 110)); - f.clock(121); - expect(await f.runtime.status()).toMatchObject({ active: false, ready: false }); - expect((await f.runtime.status()).reasons).toContain('quote-stale:Y'); - f.clock(10000); - expect((await f.runtime.status()).reasons).toContain('calendar-uncovered:X'); - }); - - test('binds configured capital and policy and refuses uncontrolled reopening or direct enqueue', async () => { - const f = await fixture(); - expect((await f.snapshot()).account.view.portfolio.cash).toBe(parseFinancialDecimal('1000')); - const changed = paperConfig(); - changed.matching.risk.ledger.initialCapital = '2000'; - await expect(f.make(changed)).rejects.toThrow('configuration'); - const plain = new CanonicalPaperExecution({ - repository: f.repository, - programs: [ - { - ...counterProgram(), - strategyId: 'sma_crossover', - strategyVersion: 'sma-crossover-long-only/v1', - }, - ], - }); - await expect(plain.initialize(f.configuration.matching)).rejects.toThrow('configuration'); - const privileged = (f.runtime as unknown as { execution: CanonicalPaperExecution }).execution; - await expect(privileged.enqueue(quoteInput(1))).rejects.toThrow('atomic producer frames'); - expect((await f.snapshot()).account.inputSequence).toBe(0); - }); - - test('requires explicit historical recovery, preserves original times, and retains poisoned decisions', async () => { - let fail = true; - const base = counterProgram(); - const f = await fixture(paperConfig(), { - ...base, - decide: context => { - if (fail) { - throw new Error('poisoned strategy'); - } - return base.decide(context); - }, - }); - await start(f); - f.clock(20); - await expect(f.runtime.ingest(paperFrame(2))).rejects.toThrow('poisoned strategy'); - const pending = await f.runtime.status(); - expect(pending).toMatchObject({ active: false, requiresHistoricalRecovery: true }); - f.clock(200); - await f.runtime.ingest(paperFrame(3, 200)); - await f.repository.transact(f.configuration.matching.risk.ledger.accountId, async tx => { - if (tx.account.host) { - tx.account.host.diagnostic = null; - } - }); - expect(await f.runtime.status()).toMatchObject({ - ready: false, - reasons: ['historical-recovery-required'], - }); - await expect(f.runtime.activate({ recoverPending: false })).rejects.toThrow('recoverPending'); - await expect(f.runtime.activate({ recoverPending: true })).rejects.toThrow( - 'poisoned strategy' - ); - expect(await f.runtime.status()).toMatchObject({ - active: false, - requiresHistoricalRecovery: true, - }); - fail = false; - expect(await f.runtime.activate({ recoverPending: true })).toMatchObject({ - active: true, - ready: true, - requiresHistoricalRecovery: false, - }); - const snapshot = await f.snapshot(); - const decisions = snapshot.journal.filter(row => row.payload.kind === 'decision'); - expect(decisions).toHaveLength(1); - expect(decisions[0]!.payload.kind === 'decision' && decisions[0]!.payload.key.at).toBe(20); - expect(snapshot.owners[0]!.diagnostic.observationCount).toBe(1); - }); - - test('explicit recovery after an hour fills an already admitted quote at its original price/time exactly once', async () => { - const config = paperConfig(); - config.policy.calendars[0]!.sessions[0]!.closesAt = 7_200_000; - const f = await fixture(config); - await start(f); - f.clock(20); - await f.runtime.ingest(paperFrame(2)); - let armed = true; - f.wrap(tx => ({ - ...tx, - async appendJournal(payload) { - if (armed) { - armed = false; - throw new Error('crash before quote commit'); - } - return tx.appendJournal(payload); - }, - })); - f.clock(30); - const admitted = paperFrame(3); - await expect(f.runtime.ingest(admitted)).rejects.toThrow('crash before quote commit'); - expect((await f.snapshot()).account.view.portfolio.positions).toHaveLength(0); - const restored = await f.make(); - await restored.connect({ ...connection, connectionId: 'two' }); - f.clock(3_600_030); - const probe = paperFrame(4, 3_600_030, 'two'); - probe.quotes[0]!.bid = parseFinancialDecimal('99'); - probe.quotes[0]!.ask = parseFinancialDecimal('99'); - expect((await restored.ingest(probe)).disposition).toBe('health-only'); - await expect(restored.activate({ recoverPending: false })).rejects.toThrow('recoverPending'); - expect(await restored.activate({ recoverPending: true })).toMatchObject({ - active: true, - ready: true, - requiresHistoricalRecovery: false, - }); - const recovered = await f.snapshot(); - expect(recovered.account.view.portfolio.cash).toBe(parseFinancialDecimal('979.8')); - expect(recovered.account.view.portfolio.positions[0]!.quantity).toBe( - parseFinancialDecimal('2') - ); - expect(recovered.account.view.portfolio.fees[0]!.amount).toBe(parseFinancialDecimal('0.2')); - const quotes = recovered.journal.filter( - row => - row.payload.kind === 'command' && - row.payload.command.key.at === 30 && - row.payload.command.body.kind === 'execute' - ); - expect(quotes).toHaveLength(1); - const payload = quotes[0]!.payload; - if (payload.kind !== 'command' || payload.command.body.kind !== 'execute') { - throw new Error('Missing quote command'); - } - expect(payload.command.body.observation).toMatchObject({ - kind: 'quote', - observedAt: 30, - ask: parseFinancialDecimal('10'), - }); - expect(await restored.ingest(admitted)).toMatchObject({ - duplicate: true, - disposition: 'admitted', - }); - expect((await f.snapshot()).account.checkpoint).toEqual(recovered.account.checkpoint); - }); - - test('a halt waiting on the real account lock stops the next financial step without discarding work', async () => { - const f = await fixture(); - await start(f); - const reached = deferred(); - const release = deferred(); - let armed = true; - f.wrap(tx => ({ - ...tx, - async appendJournal(payload) { - if (armed && payload.kind === 'decision') { - armed = false; - reached.resolve(); - await release.promise; - } - return tx.appendJournal(payload); - }, - })); - f.clock(20); - const ingest = f.runtime.ingest(paperFrame(2)); - await reached.promise; - const halt = f.runtime.halt('race stop'); - // Verify PostgreSQL sees a lock waiter before allowing the financial step to commit. - let waiting = false; - for (let attempt = 0; attempt < 100; attempt++) { - const rows = await f.pool.query( - "SELECT 1 FROM pg_stat_activity WHERE datname=current_database() AND wait_event_type='Lock' AND query LIKE 'SELECT state FROM simulation_accounts%' " - ); - if (rows.rowCount) { - waiting = true; - break; - } - await new Promise(resolve => setTimeout(resolve, 5)); - } - release.resolve(); - expect(waiting).toBe(true); - expect(await halt).toMatchObject({ active: false, operatorHalted: true }); - await ingest; - const snapshot = await f.snapshot(); - expect(snapshot.account.pendingDecisionSequence).not.toBeNull(); - expect(snapshot.owners[0]!.diagnostic.nextDecisionSequence).toBe(0); - expect(snapshot.account.view.orders).toHaveLength(0); - }); - - test.each(['input', 'batch'] as const)( - 'explicit recovery retains %s work across transient SQL or acknowledgement failures', - async stage => { - const f = await fixture(); - await start(f); - let armed = true; - let lostAcknowledgement = false; - f.wrap(tx => ({ - ...tx, - async appendJournal(payload) { - if (stage === 'input' && armed) { - armed = false; - throw new Error('transient SQL failure'); - } - return tx.appendJournal(payload); - }, - async putBatch(batch) { - await tx.putBatch(batch); - if (stage === 'batch' && armed) { - armed = false; - lostAcknowledgement = true; - } - }, - })); - f.afterCommit(() => { - if (lostAcknowledgement) { - lostAcknowledgement = false; - throw new Error('lost batch acknowledgement'); - } - }); - f.clock(20); - await expect(f.runtime.ingest(paperFrame(2))).rejects.toThrow(); - const stopped = await f.runtime.status(); - expect(stopped.active).toBe(false); - expect(stage === 'input' ? stopped.pendingInput : stopped.pendingBatch).not.toBeNull(); - f.clock(200); - await f.runtime.ingest(paperFrame(3, 200)); - await expect(f.runtime.activate({ recoverPending: false })).rejects.toThrow( - 'recoverPending' - ); - expect(await f.runtime.activate({ recoverPending: true })).toMatchObject({ - active: true, - requiresHistoricalRecovery: false, - }); - expect((await f.snapshot()).owners[0]!.diagnostic.nextDecisionSequence).toBe(1); - } - ); - - test('auxiliary cadence survives restart; known old physical bars dedup while new delayed bars remain visible', async () => { - const config = paperConfig(); - config.policy.observations.push({ - seriesId: 'X:slow', - instrumentId: 'X', - intervalMs: 10, - staleAfterMs: 100, - }); - config.policy.cadence[0]!.seriesIds = ['X:slow']; - config.strategies[0]!.seriesId = 'X:slow'; - const f = await fixture(config); - await start(f); - f.clock(20); - const fast = paperFrame(2); - await f.runtime.ingest(fast); - expect((await f.snapshot()).owners[0]!.pendingObservations).toHaveLength(1); - const restored = await f.make(); - await restored.connect({ ...connection, connectionId: 'two' }); - f.clock(30); - await restored.ingest(paperFrame(3, 30, 'two')); - await restored.activate({ recoverPending: false }); - f.clock(40); - const slow = paperFrame(4, 40, 'two'); - slow.observations = [ - fast.observations[0]!, - { - ...fast.observations[0]!, - series_id: 'X:slow', - event_time: 20, - available_at: 40, - source_sequence: 99, - }, - ]; - await restored.ingest(slow); - const snapshot = await f.snapshot(); - expect(snapshot.owners[0]!.diagnostic.observationCount).toBe(2); - expect(snapshot.owners[0]!.diagnostic.nextDecisionSequence).toBe(1); - expect(snapshot.owners[0]!.diagnostic.state).toMatchObject({ seen: [2, 99] }); - f.clock(50); - const conflict = paperFrame(5, 50, 'two'); - conflict.observations = [{ ...fast.observations[0]!, volume: parseFinancialDecimal('11') }]; - await expect(restored.ingest(conflict)).rejects.toThrow('conflicting content'); - expect((await f.snapshot()).account.checkpoint).toEqual(snapshot.account.checkpoint); - }); - } -); diff --git a/test/postgres/queue-shutdown.test.ts b/test/postgres/queue-shutdown.test.ts deleted file mode 100644 index cb840ff7..00000000 --- a/test/postgres/queue-shutdown.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { Queue as BullQueue } from 'bullmq'; -import { expect, test } from 'bun:test'; -import Redis from 'ioredis'; -import { processBatchJob, processItems } from '../../libs/core/queue/src/batch-processor'; -import { QueueManager } from '../../libs/core/queue/src/queue-manager'; -import type { BatchJobData } from '../../libs/core/queue/src/types'; - -const redisUrl = process.env.BACKTEST_TEST_REDIS_URL; -const logger = { info() {}, debug() {}, trace() {}, warn() {}, error() {} }; - -test.skipIf(!redisUrl)( - 'real Redis retains queued batch payloads across observer and producer shutdown', - async () => { - const url = new URL(redisUrl!); - if (url.pathname !== '/15') { - throw new Error('Dedicated Redis fixture using database 15 required'); - } - const connection = { - host: url.hostname, - port: Number(url.port || 6379), - username: decodeURIComponent(url.username) || undefined, - password: decodeURIComponent(url.password) || undefined, - db: 15, - maxRetriesPerRequest: 1, - }; - const queueName = `cl22_${randomUUID().replaceAll('-', '')}`; - const redis = new Redis({ ...connection, retryStrategy: () => null }); - const admin = new BullQueue(queueName, { connection }); - const managers: QueueManager[] = []; - const manager = () => { - // serviceName intentionally omitted: service routing forces database 0. - const value = new QueueManager( - { redis: connection, defaultQueueOptions: { workers: 0 } }, - undefined, - logger - ); - managers.push(value); - return value; - }; - let payloadKey: string | undefined; - try { - await redis.ping(); - const producer = manager(); - const observer = manager(); - const items = [{ symbol: 'AAPL.US' }, { symbol: 'MSFT.US' }]; - await processItems( - items, - queueName, - { - totalDelayHours: 0, - useBatching: true, - batchSize: 2, - ttl: 120, - handler: queueName, - operation: 'save', - }, - producer - ); - const jobs = await admin.getJobs(['waiting']); - expect(jobs).toHaveLength(1); - const batch = jobs[0]!.data.payload as BatchJobData; - payloadKey = `batch:${queueName}:${batch.payloadKey}`; - observer.getQueue(queueName); - expect(await observer.getCache(queueName).get(batch.payloadKey)).toMatchObject({ items }); - await observer.shutdown(); - expect(await redis.exists(payloadKey)).toBe(1); - await producer.shutdown(); - expect(await redis.exists(payloadKey)).toBe(1); - expect(await redis.ttl(payloadKey)).toBeGreaterThan(0); - expect(await admin.getJob(jobs[0]!.id!)).toBeDefined(); - expect(await admin.getWorkers()).toEqual([]); - - const consumer = manager(); - expect(await processBatchJob(batch, queueName, consumer)).toEqual({ - batchIndex: 0, - itemsProcessed: 2, - jobsCreated: 2, - }); - const itemJobs = (await admin.getJobs(['waiting'])) - .filter(job => job.name === 'process-item') - .map(job => job.data.payload) - .sort((a, b) => a.symbol.localeCompare(b.symbol)); - expect(itemJobs).toEqual(items); - expect(await redis.exists(payloadKey)).toBe(0); - } finally { - await Promise.all(managers.map(value => value.shutdown())); - // This unique queue and exact payload key belong only to this test. - try { - await admin.obliterate({ force: true }); - if (payloadKey) { - await redis.del(payloadKey); - } - } finally { - await admin.close(); - redis.disconnect(); - } - } - } -); diff --git a/test/postgres/research-pool.test.ts b/test/postgres/research-pool.test.ts deleted file mode 100644 index f0149d2b..00000000 --- a/test/postgres/research-pool.test.ts +++ /dev/null @@ -1,233 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { readdirSync, readFileSync } from 'node:fs'; -import { afterEach, describe, expect, test } from 'bun:test'; -import type { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research'; -import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository'; -import { BacktestLeaseLostError } from '../../apps/stock/orchestrator/src/backtest/run-repository'; -import { canonicalReproductionHash } from '../../apps/stock/web-api/src/services/reproduction-comparison'; -import { ResearchAgentsService } from '../../apps/stock/web-api/src/services/research-agents.service'; -import { createResearchServices } from '../../apps/stock/web-api/src/services/research-services'; -import { deferred } from '../fixtures/canonical-runner'; -import { logger } from '../fixtures/execution'; -import { nativeReplayFixture } from '../fixtures/native-replay'; -import { admittedTrialIds, researchPoolFixture, untilResearch } from '../fixtures/research-pool'; - -const cleanup: (() => Promise)[] = []; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); -async function fixture(dataset?: ReturnType['dataset']) { - const f = await researchPoolFixture(dataset); - cleanup.push(f.close); - return f; -} -function nativeChildren(): number[] { - const ids = new Set(); - for (const task of readdirSync(`/proc/${process.pid}/task`)) { - try { - for (const value of readFileSync(`/proc/${process.pid}/task/${task}/children`, 'utf8') - .trim() - .split(/\s+/)) { - const pid = Number(value); - if (pid && readFileSync(`/proc/${pid}/cmdline`, 'utf8').includes('/native-worker.js')) { - ids.add(pid); - } - } - } catch { - /* A thread/child can exit between procfs reads. */ - } - } - return [...ids]; -} -const grid4 = { fastPeriod: [1, 2], slowPeriod: [3, 4] }; - -describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL || !process.env.BACKTEST_TEST_REDIS_URL)( - 'bounded durable research pool on real PostgreSQL, Redis and Rust', - () => { - test('parallel_hash_parity: 1/2/4 slots retain candidate order and identical validated economic hashes', async () => { - const f = await fixture(); - let baseline: string[] | undefined; - for (const concurrency of [1, 2, 4] as const) { - const experiment = await f.submit(grid4), - ids = admittedTrialIds(experiment); - const workers = f.createWorkers(concurrency); - await workers.queue.getBullQueue().waitUntilReady(); - await workers.dispatcher.tick(); - const rows = await f.wait(ids); - expect(rows.map(row => row.trial_index)).toEqual([0, 1, 2, 3]); - expect(rows.map(row => row.status)).toEqual(Array(4).fill('completed')); - expect(rows.map(row => row.attempt_number)).toEqual(Array(4).fill(1)); - expect(rows.map(row => row.result_count)).toEqual(Array(4).fill(1)); - const hashes: string[] = []; - for (const id of ids) { - const result = await f.api.getRunResults(id); - if (!result || !('kind' in result) || result.kind !== 'canonical-result/v1') { - throw new Error('Missing canonical result'); - } - hashes.push(canonicalReproductionHash(result)); - // Redelivery cannot claim or write a second outcome. - expect(await workers.runtime.runQueued(id)).toEqual({ runId: id, status: 'completed' }); - } - if (baseline) { - expect(hashes).toEqual(baseline); - } else { - baseline = hashes; - } - await workers.stop(); - } - }, 60000); - test('cancellation_under_load: pending and running cancellations leave unrelated native trials intact', async () => { - const f = await fixture(nativeReplayFixture(1000).dataset); - const experiment = await f.submit(grid4), - ids = admittedTrialIds(experiment); - await f.api.cancelRun(ids[3]!); - const workers = f.createWorkers(2, { heartbeatMs: 20 }); - await workers.dispatcher.tick(); - await untilResearch( - async () => (await f.rows(ids)).filter(row => row.status === 'running').length === 2 - ); - const running = (await f.rows(ids)).find(row => row.status === 'running')!; - await f.api.cancelRun(running.id); - const rows = await f.wait(ids); - expect( - rows - .filter(row => row.status === 'cancelled') - .map(row => row.id) - .sort() - ).toEqual([running.id, ids[3]!].sort()); - expect(rows.filter(row => row.status === 'cancelled').map(row => row.result_count)).toEqual([ - 0, 0, - ]); - expect(rows.filter(row => row.status === 'completed')).toHaveLength(2); - expect(rows.find(row => row.id === ids[3])!.attempt_number).toBe(0); - expect(rows.every(row => row.attempt_number <= 1)).toBe(true); - await workers.stop(); - }, 60000); - test('worker_crash_retry: one real native child exit fails only its trial; explicit same-run retry recovers', async () => { - const f = await fixture(nativeReplayFixture(1000).dataset); - const experiment = await f.submit(), - ids = admittedTrialIds(experiment); - const holdOther = deferred(); - const workers = f.createWorkers(2, { - beforeExecute: async (_request, slot) => { - if (slot === 1) { - await holdOther.promise; - } - }, - }); - const baseline = new Set(nativeChildren()); - await workers.dispatcher.tick(); - let child: number | undefined; - await untilResearch(async () => { - child = nativeChildren().find(pid => !baseline.has(pid)); - return child !== undefined; - }); - process.kill(child!, 'SIGKILL'); - holdOther.resolve(); - const rows = await f.wait(ids); - const failed = rows.find(row => row.status === 'failed')!; - expect(failed).toBeDefined(); - expect(failed.result_count).toBe(0); - expect(rows.filter(row => row.status === 'completed')).toHaveLength(1); - expect(rows.every(row => row.attempt_number === 1)).toBe(true); - const before = await f.sql.query('SELECT request_snapshot FROM runs WHERE id=$1', [ - failed.id, - ]); - const retry = await f.experiments.retryTrial( - experiment.id, - failed.id, - { expectedAttemptNumber: 1, expectedRetryCount: 0 }, - { principal: 'operator', key: randomUUID() } - ); - expect(retry.retry.previousAttemptId).toBe(failed.attempt_id); - await workers.dispatcher.tick(); - const after = await f.wait(ids); - expect(after.every(row => row.status === 'completed' && row.result_count === 1)).toBe(true); - expect(after.find(row => row.id === failed.id)!.attempt_number).toBe(2); - expect(after.find(row => row.id !== failed.id)!.attempt_number).toBe(1); - expect(after.find(row => row.id === failed.id)!.request_snapshot).toEqual( - before.rows[0].request_snapshot - ); - await workers.stop(); - }, 60000); - test('lease_fencing_pool: recovery replaces only an expired owner and rejects all its late writes', async () => { - const f = await fixture(); - const experiment = await f.submit(), - ids = admittedTrialIds(experiment); - const repo = new PostgresBacktestRunRepository(f.postgres); - const original = (await f.rows(ids))[0]!; - const abandoned = await repo.startCanonical(original.request_snapshot); - const otherEntered = deferred(), - otherRelease = deferred(); - const workers = f.createWorkers(2, { - beforeExecute: async request => { - if (request.runId === ids[1]) { - otherEntered.resolve(); - await otherRelease.promise; - } - }, - }); - const unaffected = workers.runtime.runQueued(ids[1]!); - await otherEntered.promise; - const otherAttempt = (await f.rows(ids))[1]!.attempt_id; - await f.sql.query("UPDATE runs SET lease_expires_at=NOW()-INTERVAL '1 second' WHERE id=$1", [ - ids[0], - ]); - await workers.dispatcher.tick(); - await untilResearch(async () => (await f.rows(ids))[0]!.status === 'completed'); - otherRelease.resolve(); - await unaffected; - const rows = await f.rows(ids); - expect(rows[0]!.attempt_number).toBe(2); - expect(rows[1]!.attempt_number).toBe(1); - expect(rows[1]!.attempt_id).toBe(otherAttempt); - const result = (await f.api.getRunResults(ids[0]!)) as CanonicalRunResult; - for (const late of [ - () => repo.completeCanonical(result, abandoned.attemptId), - () => repo.cancel(ids[0]!, abandoned.attemptId), - () => repo.updateProgress(ids[0]!, 1, undefined, abandoned.attemptId), - ]) { - await expect(late()).rejects.toBeInstanceOf(BacktestLeaseLostError); - } - const beforeLateFailure = await f.rows(ids); - await repo.fail(ids[0]!, 'late owner failure', abandoned.attemptId); // Deliberate no-op for abandoned failures. - expect(await f.rows(ids)).toEqual(beforeLateFailure); - expect( - (await f.rows(ids)).every(row => row.status === 'completed' && row.result_count === 1) - ).toBe(true); - await workers.stop(); - }, 60000); - test('four slots cannot bypass agent admission capacity or per-attempt absolute deadlines', async () => { - const f = await fixture(); - const research = createResearchServices({ postgres: f.postgres, logger }).research; - const project = await research.createProject({ title: 'Pool budget gate' }, 'operator'); - const agents = new ResearchAgentsService({ postgres: f.postgres, logger }); - const agent = await agents.create({ - name: 'Pool researcher', - allowedProjectIds: [project.id], - allowedBacktestIds: [f.draft.id], - limits: { - maxActiveTrials: 2, - maxTrialsPerExperiment: 4, - maxBarEvaluationsPerExperiment: 1000, - maxAttemptWallMs: 1, - maxAttempts: 1, - }, - }); - const principal = agent.agent.id; - const experiment = await f.submit({ fastPeriod: [1, 2] }, principal), - ids = admittedTrialIds(experiment); - await expect(f.submit({ fastPeriod: [1] }, principal)).rejects.toThrow(); - const workers = f.createWorkers(4); - await workers.dispatcher.tick(); - const rows = await f.wait(ids); - expect(rows.map(row => row.status)).toEqual(['failed', 'failed']); - expect(rows.map(row => row.result_count)).toEqual([0, 0]); - expect(rows.every(row => row.attempt_number === 1)).toBe(true); - expect(rows.every(row => /deadline|wall time/i.test(row.error))).toBe(true); - await workers.stop(); - }, 60000); - } -); diff --git a/test/postgres/research-retention.test.ts b/test/postgres/research-retention.test.ts deleted file mode 100644 index 6d838358..00000000 --- a/test/postgres/research-retention.test.ts +++ /dev/null @@ -1,488 +0,0 @@ -import { 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 { getLogger, setLoggerConfig } from '@stock-bot/logger'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import { parseBacktestRequest } from '@stock-bot/stock-config/backtest'; -import type { BacktestRunResult, HistoricalDataset } from '@stock-bot/types'; -import { LegacyBacktestRunWriter } from '../../apps/stock/orchestrator/src/backtest/compatibility/LegacyBacktestRunWriter'; -import { loadDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset'; -import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes'; -import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service'; -import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher'; -import { seedHistoricalRun } from '../fixtures/historical-run'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('research-retention-test'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const cleanup: (() => Promise)[] = []; -const sql = (name: string) => - readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8'); -const retention = - sql('17-research-retention.sql') + - '\n' + - sql('18-backtest-strategy-versions.sql') + - '\n' + - sql('19-canonical-research.sql') + - '\n' + - sql('21-run-reproduction.sql') + - sql('22-experiments.sql') + - '\n' + - sql('23-experiment-retries.sql') + - '\n' + - sql('24-chronological-validation.sql') + - '\n' + - sql('25-walk-forward.sql') + - '\n' + - sql('26-cost-sensitivity.sql'); -const request = { - name: 'Retained evidence', - strategy: 'sma-crossover', - symbols: ['FIXTURE.TEST'], - startDate: '2024-01-01T00:00:00.000Z', - endDate: '2024-01-05T00:00:00.000Z', - initialCapital: 1000, - config: { fastPeriod: 1, slowPeriod: 2, commission: 0, slippage: 0 }, -}; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); -async function fixture() { - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Dedicated stock_bot_safety database required'); - } - const schema = 'stock_bot_safety_retention_' + randomUUID().replaceAll('-', ''); - const admin = new Pool({ connectionString: url }); - await admin.query(`CREATE SCHEMA ${schema}`); - const pool = new Pool({ - connectionString: url, - application_name: schema, - options: `-c search_path=${schema} -c statement_timeout=10000`, - }); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - for (const name of [ - '06-create-backtest-tables.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', - ]) { - await pool.query(sql(name)); - } - await pool.query(retention); - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, - logger - ); - Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); - Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); - const api = new BacktestServiceV2({ postgres, logger }, async () => { - throw new Error('No remote execution in retention tests'); - }); - const repository = new LegacyBacktestRunWriter(postgres); - const definition = await api.createBacktest(request, { autoStart: false }); - const snapshot = async (runId: string) => - parseBacktestRequest( - (await pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])).rows[0] - .request_snapshot - ); - const dataset = async (runId: string) => - loadDataset( - { - async getHistoricalBars() { - return [0, 1, 2].map(day => ({ - symbol: 'FIXTURE.TEST', - timestamp: new Date(Date.parse(request.startDate) + day * 86400000), - source: 'eod' as const, - open: 10, - high: 11, - low: 9, - close: 10, - volume: 100, - })); - }, - }, - await snapshot(runId) - ); - const app = new Hono().route('/', createBacktestV2Routes({ postgres, logger })); - return { pool, schema, postgres, api, repository, definition, snapshot, dataset, app }; -} -// These fixed values exercise persistence only; no financial simulation is claimed. -function result(runId: string, backtestId: string, dataset: HistoricalDataset): BacktestRunResult { - return { - runId, - backtestId, - engine: 'native', - status: 'completed', - completedAt: new Date().toISOString(), - config: { - name: request.name, - strategy: request.strategy, - symbols: request.symbols, - startDate: request.startDate, - endDate: request.endDate, - initialCapital: request.initialCapital, - commission: 0, - slippage: 0, - dataFrequency: '1d', - parameters: request.config, - dataset: dataset.manifest, - }, - metrics: { - totalReturn: 0, - sharpeRatio: null, - maxDrawdown: 0, - winRate: 0, - totalTrades: 0, - profitFactor: null, - avgWin: 0, - avgLoss: 0, - }, - equity: [], - ohlcData: {}, - trades: [], - positions: [], - analytics: { exposureTime: null }, - executionTime: 1, - }; -} -async function waitForBlocked(pool: Pool, schema: string) { - for (let attempt = 0; attempt < 100; attempt++) { - const waiting = await pool.query( - "SELECT 1 FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock'", - [schema] - ); - if (waiting.rows.length) { - return; - } - await new Promise(resolve => setTimeout(resolve, 10)); - } - throw new Error('Expected concurrent operation to wait for the parent lock'); -} - -describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => { - test('retained_run_delete_restricted_postgres blocks raw cascades, mutations and truncation while preserving runless legacy deletion', async () => { - const f = await fixture(); - const run = await seedHistoricalRun( - f.pool, - f.api, - { backtestId: f.definition.id }, - { principal: 'operator', key: 'retained' } - ); - const claim = await f.repository.start(await f.snapshot(run.id)); - const frozen = await f.repository.freezeDataset( - run.id, - claim.attemptId, - await f.dataset(run.id) - ); - await f.repository.complete(result(run.id, f.definition.id, frozen), claim.attemptId); - await expect(f.api.deleteBacktest(f.definition.id)).rejects.toMatchObject({ - code: 'retained_runs', - runCount: 1, - }); - for (const statement of [ - 'DELETE FROM backtests', - 'DELETE FROM runs', - 'DELETE FROM backtest_results', - 'DELETE FROM backtest_datasets', - "UPDATE backtest_results SET metrics='{}'", - "UPDATE backtest_datasets SET payload='{}'", - 'TRUNCATE backtests CASCADE', - 'TRUNCATE runs CASCADE', - 'TRUNCATE backtest_results', - 'TRUNCATE backtest_datasets CASCADE', - ]) { - await expect(f.pool.query(statement)).rejects.toThrow(); - } - const empty = await f.api.createBacktest( - { ...request, name: 'Unreferenced legacy definition' }, - { autoStart: false } - ); - await f.api.deleteBacktest(empty.id); - expect(await f.api.getBacktest(empty.id)).toBeNull(); - await f.api.deleteBacktest(empty.id); - expect(await f.api.getRunResults(run.id)).not.toBeNull(); - expect((await f.pool.query('SELECT count(*)::int AS n FROM backtest_dispatch')).rows[0].n).toBe( - 1 - ); - }); - - test('archive_preserves_replay hides discovery only and rejects new admission or edits until restored', async () => { - const f = await fixture(); - const receipt = { principal: 'operator' as const, key: 'archive-retry' }; - const run = await seedHistoricalRun(f.pool, f.api, { backtestId: f.definition.id }, receipt); - const before = await f.snapshot(run.id); - const archived = await f.api.archiveBacktest(f.definition.id, true); - expect(archived?.archivedAt).toBeString(); - expect((await f.api.archiveBacktest(f.definition.id, true))?.archivedAt).toBe( - archived?.archivedAt ?? null - ); - expect(await f.api.listBacktests({ limit: 50, offset: 0 })).toEqual([]); - expect(await f.api.listBacktests({ limit: 50, offset: 0, includeArchived: true })).toHaveLength( - 1 - ); - expect((await f.api.getBacktest(f.definition.id))?.archivedAt).toBe( - archived?.archivedAt ?? null - ); - expect(await f.api.listRuns(f.definition.id)).toHaveLength(1); - expect((await f.api.createRun({ backtestId: f.definition.id }, receipt)).id).toBe(run.id); - expect(await f.snapshot(run.id)).toEqual(before); - await expect( - f.api.createRun({ backtestId: f.definition.id }, { ...receipt, key: 'fresh' }) - ).rejects.toMatchObject({ code: 'backtest_archived' }); - await expect( - f.api.updateBacktest(f.definition.id, { name: 'Cannot edit' }) - ).rejects.toMatchObject({ code: 'backtest_archived' }); - await expect( - f.api.createRun({ backtestId: f.definition.id, speedMultiplier: 5 }, receipt) - ).rejects.toThrow('submission key'); - expect((await f.api.archiveBacktest(f.definition.id, false))?.archivedAt).toBeNull(); - expect((await f.api.updateBacktest(f.definition.id, { name: 'Restored' }))?.name).toBe( - 'Restored' - ); - await expect(f.api.createRun({ backtestId: f.definition.id })).rejects.toThrow( - 'Legacy backtest execution is retired' - ); - expect(await f.api.listRuns(f.definition.id)).toHaveLength(1); - }); - - test('archive and admission use one parent lock, including direct repository inserts', async () => { - const f = await fixture(); - const accepted = await seedHistoricalRun(f.pool, f.api, { backtestId: f.definition.id }); - const blocker = await f.pool.connect(); - await blocker.query('BEGIN'); - await blocker.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [f.definition.id]); - const pending = f.api.createRun({ backtestId: f.definition.id }).then( - () => null, - error => error - ); - await waitForBlocked(f.pool, f.schema); - await blocker.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.definition.id]); - await blocker.query('COMMIT'); - blocker.release(); - expect(await pending).toMatchObject({ code: 'backtest_archived' }); - const direct = { ...(await f.snapshot(accepted.id)), runId: undefined }; - await expect(f.repository.start(direct)).rejects.toThrow('archived'); - await expect( - f.pool.query("INSERT INTO runs(backtest_id,run_number,status) VALUES($1,99,'pending')", [ - f.definition.id, - ]) - ).rejects.toThrow('archived'); - expect(await f.api.listRuns(f.definition.id)).toHaveLength(1); - // Its pre-archive request remains accepted and can claim normally. - expect((await f.repository.start(await f.snapshot(accepted.id))).runId).toBe(accepted.id); - }); - - test('accepted archived work retains binding, lease recovery, controls, progress and terminal result writes', async () => { - const f = await fixture(); - const run = await seedHistoricalRun(f.pool, f.api, { backtestId: f.definition.id }); - await f.api.archiveBacktest(f.definition.id, true); - const claim = await f.repository.start(await f.snapshot(run.id)); - const frozen = await f.repository.freezeDataset( - run.id, - claim.attemptId, - await f.dataset(run.id) - ); - await f.repository.freezeDataset(run.id, claim.attemptId, frozen); - await f.repository.heartbeat(run.id, claim.attemptId); - await f.repository.updateProgress(run.id, 25, request.startDate, claim.attemptId); - await f.repository.updateControl( - run.id, - { status: 'paused', speedMultiplier: 2 }, - claim.attemptId - ); - await f.pool.query("UPDATE runs SET lease_expires_at=NOW()-INTERVAL '1 second' WHERE id=$1", [ - run.id, - ]); - const delivered: unknown[] = []; - const dispatcher = new BacktestDispatcher( - f.postgres, - { - async add(...args) { - delivered.push(args); - return null as never; - }, - }, - logger - ); - await dispatcher.tick(); - expect((await f.api.getRun(run.id))?.status).toBe('pending'); - expect(delivered).toHaveLength(1); - const retry = await f.repository.start(await f.snapshot(run.id)); - expect(retry.attemptId).not.toBe(claim.attemptId); - await expect(f.repository.heartbeat(run.id, claim.attemptId)).rejects.toThrow('lease lost'); - expect(await f.repository.loadDataset(run.id, retry.attemptId)).toEqual(frozen); - await f.api.updateRunProgress(run.id, { progress: 90, attemptId: retry.attemptId }); - await f.repository.complete(result(run.id, f.definition.id, frozen), retry.attemptId); - const saved = await f.api.getRunResults(run.id); - if (!saved || !('config' in saved)) { - throw new Error('Expected preserved historical result'); - } - expect(saved.config.dataset?.hash).toBe(frozen.manifest.hash); - expect((await f.api.getRun(run.id))?.attemptNumber).toBe(2); - expect((await f.api.getRun(run.id))?.status).toBe('completed'); - await f.pool.query(retention); - expect(await f.api.getRunResults(run.id)).toEqual(saved); - await dispatcher.shutdown(); - }); - - test('run identity and frozen inputs reject rewrites while legacy NULL snapshots can be populated once', async () => { - const f = await fixture(); - const run = await seedHistoricalRun( - f.pool, - f.api, - { backtestId: f.definition.id }, - { principal: 'service', key: 'immutable' } - ); - const claim = await f.repository.start(await f.snapshot(run.id)); - await f.repository.freezeDataset(run.id, claim.attemptId, await f.dataset(run.id)); - const other = await f.api.createBacktest(request, { autoStart: false }); - for (const [field, value] of [ - ['id', randomUUID()], - ['backtest_id', other.id], - ['run_number', 99], - ['created_at', '2020-01-01'], - ['request_snapshot', '{}'], - ['request_snapshot', null], - ['submission_key', 'changed'], - ['submission_principal', 'operator'], - ['submission_hash', 'changed'], - ['dataset_hash', null], - ['dataset_hash', 'f'.repeat(64)], - ]) { - await expect( - f.pool.query(`UPDATE runs SET ${field}=$2 WHERE id=$1`, [run.id, value]) - ).rejects.toThrow('immutable'); - } - const legacy = randomUUID(); - await f.pool.query( - "INSERT INTO runs(id,backtest_id,run_number,status) VALUES($1,$2,2,'pending')", - [legacy, f.definition.id] - ); - await f.api.archiveBacktest(f.definition.id, true); - await f.pool.query(sql('10-durable-backtest-dispatch.sql')); - const frozen = await f.snapshot(legacy); - expect(frozen.runId).toBe(legacy); - await f.pool.query(sql('10-durable-backtest-dispatch.sql')); - expect(await f.snapshot(legacy)).toEqual(frozen); - await expect( - f.pool.query("UPDATE runs SET request_snapshot='{}' WHERE id=$1", [legacy]) - ).rejects.toThrow('immutable'); - await f.api.archiveBacktest(f.definition.id, false); - const terminalLegacy = randomUUID(); - await f.pool.query( - "INSERT INTO runs(id,backtest_id,run_number,status) VALUES($1,$2,3,'completed')", - [terminalLegacy, f.definition.id] - ); - await expect( - f.pool.query("UPDATE runs SET request_snapshot='{}' WHERE id=$1", [terminalLegacy]) - ).rejects.toThrow('immutable'); - }); - - test('pending and running cancellation/failure still terminate accepted archived requests', async () => { - const f = await fixture(); - const runs = await Promise.all( - Array.from({ length: 4 }, () => - seedHistoricalRun(f.pool, f.api, { backtestId: f.definition.id }) - ) - ); - await f.api.archiveBacktest(f.definition.id, true); - await f.api.cancelRun(runs[0]!.id); - await f.api.cancelRun(runs[0]!.id); - await f.repository.rejectPending(runs[1]!.id, 'Fixture validation failure'); - const active = await f.repository.start(await f.snapshot(runs[2]!.id)); - await f.api.cancelRun(active.runId); - expect(await f.repository.heartbeat(active.runId, active.attemptId)).toEqual({ - cancelRequested: true, - }); - await f.repository.cancel(active.runId, active.attemptId); - const failed = await f.repository.start(await f.snapshot(runs[3]!.id)); - await f.repository.fail(failed.runId, 'Fixture execution failure', failed.attemptId); - expect((await f.api.listRuns(f.definition.id)).map(run => run.status).sort()).toEqual([ - 'cancelled', - 'cancelled', - 'failed', - 'failed', - ]); - }); - - test('preexisting corrupted datasets remain immutable and fail checksum verification on retrieval', async () => { - const f = await fixture(); - const run = await seedHistoricalRun(f.pool, f.api, { backtestId: f.definition.id }); - const claim = await f.repository.start(await f.snapshot(run.id)); - const dataset = await f.dataset(run.id); - const corrupt = structuredClone(dataset); - corrupt.bars[0]!.volume = 0; - await f.pool.query('INSERT INTO backtest_datasets(hash,payload) VALUES($1,$2)', [ - dataset.manifest.hash, - corrupt, - ]); - await f.pool.query('UPDATE runs SET dataset_hash=$2 WHERE id=$1', [ - run.id, - dataset.manifest.hash, - ]); - await f.pool.query(retention); - await expect(f.repository.loadDataset(run.id, claim.attemptId)).rejects.toThrow('hash/content'); - await expect( - f.pool.query('UPDATE backtest_datasets SET payload=$2 WHERE hash=$1', [ - dataset.manifest.hash, - JSON.stringify(dataset), - ]) - ).rejects.toThrow('cannot be rewritten'); - }); - - test('HTTP archive/list/delete errors are actionable and direct saved resources remain accessible', async () => { - const f = await fixture(); - const run = await seedHistoricalRun(f.pool, f.api, { backtestId: f.definition.id }); - const archived = await f.app.request(`/api/v2/backtests/${f.definition.id}/archive`, { - method: 'POST', - body: JSON.stringify({ archived: true }), - }); - expect(archived.status).toBe(200); - expect((await archived.json()).archivedAt).toBeString(); - expect(await (await f.app.request('/api/v2/backtests')).json()).toEqual([]); - expect( - await (await f.app.request('/api/v2/backtests?includeArchived=true')).json() - ).toHaveLength(1); - expect((await f.app.request(`/api/v2/runs/${run.id}`)).status).toBe(200); - expect((await f.app.request(`/api/v2/backtests/${f.definition.id}`)).status).toBe(200); - const deleted = await f.app.request(`/api/v2/backtests/${f.definition.id}`, { - method: 'DELETE', - }); - expect(deleted.status).toBe(409); - expect(await deleted.json()).toMatchObject({ code: 'retained_runs', runCount: 1 }); - const submit = await f.app.request(`/api/v2/backtests/${f.definition.id}/runs`, { - method: 'POST', - body: '{}', - }); - expect(submit.status).toBe(409); - expect(await submit.json()).toMatchObject({ code: 'backtest_archived' }); - const edit = await f.app.request(`/api/v2/backtests/${f.definition.id}`, { - method: 'PUT', - body: JSON.stringify({ name: 'Changed' }), - }); - expect(edit.status).toBe(409); - expect(await edit.json()).toMatchObject({ code: 'backtest_archived' }); - expect( - ( - await f.app.request(`/api/v2/backtests/${randomUUID()}/archive`, { - method: 'POST', - body: '{"archived":true}', - }) - ).status - ).toBe(404); - expect( - (await f.app.request(`/api/v2/backtests/${randomUUID()}`, { method: 'DELETE' })).status - ).toBe(204); - }); -}); diff --git a/test/postgres/research-runtime-isolation.test.ts b/test/postgres/research-runtime-isolation.test.ts deleted file mode 100644 index 10ac8c0e..00000000 --- a/test/postgres/research-runtime-isolation.test.ts +++ /dev/null @@ -1,146 +0,0 @@ -import { asValue } from 'awilix'; -import { afterEach, describe, expect, spyOn, test } from 'bun:test'; -import { ServiceContainerBuilder } from '@stock-bot/di'; -import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine'; -import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter'; -import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container'; -import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types'; -import { canonicalAdmissionFixture } from '../fixtures/canonical-admission'; -import { logger } from '../fixtures/execution'; -import { paperFixture, paperFrame } from '../fixtures/paper-runtime'; - -const cleanup: (() => Promise)[] = []; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); -async function fixture() { - const paper = await paperFixture(); - cleanup.push(paper.close); - await paper.runtime.connect({ sourceId: 'fixture', connectionId: 'one' }); - await paper.runtime.ingest(paperFrame(1)); - await paper.runtime.activate({ recoverPending: false }); - paper.clock(20); - await paper.runtime.ingest(paperFrame(2)); - const admitted = await canonicalAdmissionFixture(paper.pool, paper.postgres); - const container = await new ServiceContainerBuilder() - .withOptions({ - enableCache: false, - enableQueue: false, - enableMongoDB: false, - enablePostgres: false, - enableQuestDB: false, - enableBrowser: false, - enableProxy: false, - }) - .build(); - const services: OrchestratorServices = { logger, postgres: paper.postgres }; - container.register({ serviceContainer: asValue(services) }); - await registerOrchestratorServices(container); - const runtime = services.custom!, - runner = runtime.BacktestRunner!; - cleanup.push(async () => { - await runner.shutdown(); - await paper.runtime.shutdown(); - await container.dispose(); - }); - return { paper, ...admitted, container, services, runtime, runner }; -} -describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)( - 'canonical research isolation from durable paper custody', - () => { - test('default research composition cannot activate, reset or overlay the existing paper account', async () => { - const f = await fixture(), - before = await f.paper.snapshot(); - for (const key of [ - 'ModeManager', - 'ExecutionService', - 'MarketDataService', - 'StrategyManager', - 'PaperTradingManager', - 'CanonicalPaperRuntime', - ]) { - expect(f.runtime).not.toHaveProperty(key); - } - await expect(registerOrchestratorServices(f.container, { role: 'paper' })).rejects.toThrow( - 'explicit canonicalPaper' - ); - await expect( - registerOrchestratorServices(f.container, { useRustEngine: false }) - ).rejects.toThrow('Legacy financial execution is retired'); - await expect( - registerOrchestratorServices(f.container, { - role: 'paper', - canonicalPaper: f.paper.configuration, - }) - ).rejects.toThrow('fresh runtime composition'); - expect(await f.paper.snapshot()).toEqual(before); - expect((await f.paper.runtime.status()).active).toBe(true); - }); - test('real native success, cancellation and failed durable research leave paper ledger/checkpoint/decisions unchanged', async () => { - const f = await fixture(), - before = await f.paper.snapshot(); - const unchanged = async () => { - expect(await f.paper.snapshot()).toEqual(before); - expect((await f.paper.runtime.status()).active).toBe(true); - }; - const accept = () => f.api.createRun({ backtestId: f.draft.id }); - const completed = await accept(); - expect((await f.runner.runQueued(completed.id)).status).toBe('completed'); - await unchanged(); - const result = await f.api.getRunResults(completed.id); - expect(result).not.toBeNull(); - expect(result).toHaveProperty('kind', 'canonical-result/v1'); - for (let index = 0; index < 2; index++) { - const run = await accept(); - let stopped: Promise | undefined; - const cancelOnProgress = () => { - f.runner.off('progress', cancelOnProgress); - stopped = f.runner.stopBacktest(); - }; - f.runner.on('progress', cancelOnProgress); - const cancelled = await f.runner.runQueued(run.id).catch(error => error); - await stopped; - expect(stopped).toBeDefined(); - expect(cancelled).toBeInstanceOf(BacktestCancelledError); - await unchanged(); - const failed = await accept(); - // The pool deliberately keeps engines private; inject only at the adapter seam. - const failure = spyOn(RustBacktestAdapter.prototype, 'runCanonical').mockImplementationOnce( - async () => { - throw new Error('Injected canonical execution failure'); - } - ); - try { - await expect(f.runner.runQueued(failed.id)).rejects.toThrow( - 'Injected canonical execution failure' - ); - } finally { - failure.mockRestore(); - } - await unchanged(); - } - expect((await f.runner.runQueued((await accept()).id)).status).toBe('completed'); - await unchanged(); - expect( - ( - await f.paper.pool.query( - 'SELECT status,count(*)::int AS count FROM runs GROUP BY status ORDER BY status::text' - ) - ).rows - ).toEqual([ - { status: 'cancelled', count: 2 }, - { status: 'completed', count: 2 }, - { status: 'failed', count: 2 }, - ]); - f.paper.clock(30); - await f.paper.runtime.ingest(paperFrame(3)); - const continued = await f.paper.snapshot(); - expect(continued.owners[0]!.diagnostic.nextDecisionSequence).toBe( - before.owners[0]!.diagnostic.nextDecisionSequence + 1 - ); - expect(continued.account.view.portfolio.positions).toHaveLength(1); - }, 15000); - } -); diff --git a/test/postgres/research-source-evidence.test.ts b/test/postgres/research-source-evidence.test.ts deleted file mode 100644 index 60d04957..00000000 --- a/test/postgres/research-source-evidence.test.ts +++ /dev/null @@ -1,878 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { readFileSync } from 'node:fs'; -import { afterEach, describe, expect, test } from 'bun:test'; -import { Hono } from 'hono'; -import { Pool, type PoolClient } from 'pg'; -import { createHttpSecurity } from '@stock-bot/di'; -import { getLogger, setLoggerConfig } from '@stock-bot/logger'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import type { WalkForwardInput } from '@stock-bot/stock-config/walk-forward'; -import type { ResearchEvidenceReference, ResearchFindingSource } 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 { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes'; -import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service'; -import { experimentHash } from '../../apps/stock/web-api/src/services/experiment-input'; -import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service'; -import { createResearchServices } from '../../apps/stock/web-api/src/services/research-services'; -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 '../fixtures/canonical-research'; -import { walkForwardDataset } from '../fixtures/walk-forward'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('chronological-validation'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const cleanup: (() => Promise)[] = []; -let packages: ReturnType | undefined; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); -async function fixture(poolMax = 1, withSources = true) { - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Disposable safety database required'); - } - const schema = 'stock_bot_safety_validation_' + randomUUID().replaceAll('-', ''); - const admin = new Pool({ connectionString: url }); - await admin.query(`CREATE SCHEMA ${schema}`); - // A single connection detects accidental nested pool reads while the admission lock is held. - const pool = new Pool({ - connectionString: url, - application_name: schema, - max: poolMax, - options: `-c search_path=${schema} -c statement_timeout=10000`, - }); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - for (const name of [ - '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', - '20-research-workspace.sql', - '21-run-reproduction.sql', - '22-experiments.sql', - '23-experiment-retries.sql', - '24-chronological-validation.sql', - '25-walk-forward.sql', - '26-cost-sensitivity.sql', - ...(withSources ? ['27-research-evidence-sources.sql'] : []), - ]) { - await pool.query( - readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') - ); - } - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, - logger - ); - Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); - Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); - const container = { postgres, logger }, - api = new BacktestServiceV2(container), - experiments = new ExperimentsService(container), - catalog = new StrategyCatalogService(container); - const version = await catalog.seedBuiltin( - 'Validation SMA', - (await (packages ??= packageBuiltinStrategies()))[0]!, - 'seed' - ); - const data = walkForwardDataset(), - dataset = data.dataset; - await retainResearchDataset(pool, dataset); - const draft = await api.createBacktest( - { - name: 'Validation template', - strategy: 'catalog', - strategyVersionId: version.id, - strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, - symbols: ['X0.US'], - startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(), - endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(), - initialCapital: 10000, - config: { - datasetHash: dataset.manifest.hash, - dataFrequency: '1m', - canonical: canonicalSettings, - }, - }, - { autoStart: false } - ); - const input: WalkForwardInput = { - backtestId: draft.id, - name: 'Two rolling windows', - grid: { fastPeriod: [1, 2], slowPeriod: [3] }, - windows: data.windows, - }; - const review = async (decision: 'approve' | 'revoke' = 'approve') => { - await catalog.reviewVersion( - version.id, - { decision, reason: 'Disposable validation proof' }, - 'operator' - ); - return (await catalog.getVersionReviews(version.id)).at(-1)!; - }; - const snapshot = async () => { - const tables = ( - await pool.query('SELECT tablename FROM pg_tables WHERE schemaname=$1 ORDER BY tablename', [ - schema, - ]) - ).rows; - const rows: Record = {}; - for (const { tablename } of tables) { - const quoted = '"' + String(tablename).replaceAll('"', '""') + '"'; - rows[String(tablename)] = ( - await pool.query( - `SELECT COALESCE(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text),'[]'::jsonb) AS rows FROM ${quoted} t` - ) - ).rows[0].rows; - } - return rows; - }; - const services = createResearchServices(container); - const validations = services.validations; - const repository = new PostgresBacktestRunRepository(postgres); - const execute = async (id: string) => { - const engine = new RustBacktestAdapter({ - logger, - }); - const runner = new BacktestRunner({ engine, repository, logger }); - try { - await runner.runQueued(id); - } finally { - await runner.shutdown(); - } - }; - return { - cloneTemplate: async (sourceDataset = dataset) => - api.createBacktest( - { - name: 'Other validation template', - strategy: 'catalog', - strategyVersionId: version.id, - strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, - symbols: ['X0.US'], - startDate: new Date(sourceDataset.manifest.bounds.tradeStart).toISOString(), - endDate: new Date(sourceDataset.manifest.bounds.tradeEnd).toISOString(), - initialCapital: 10000, - config: { - datasetHash: sourceDataset.manifest.hash, - dataFrequency: '1m', - canonical: canonicalSettings, - }, - }, - { autoStart: false } - ), - validations, - walks: services.walkForwards, - repository, - execute, - api, - pool, - postgres, - experiments, - catalog, - version, - draft, - dataset, - input, - research: services.research, - container, - schema, - review, - snapshot, - }; -} - -const actor = (key = randomUUID()) => ({ principal: 'operator' as const, key }); -type Fixture = Awaited>; -async function submit(f: Fixture, input = f.input, identity = actor()) { - await f.review(); - const preview = await f.walks.preview(input), - body = { ...input, previewHash: preview.previewHash }; - return { preview, body, identity, walk: await f.walks.submit(body, identity) }; -} -async function finishWindow(f: Fixture, id: string) { - const initial = await f.validations.get(id); - for (const trial of initial.phases[0]!.experiment!.trials) { - await f.execute(trial.runId!); - } - const selected = await f.validations.select(id, { previewHash: initial.previewHash }, actor()); - for (const phase of selected.validation.phases.slice(1)) { - for (const trial of phase.experiment!.trials) { - await f.execute(trial.runId!); - } - } - return f.validations.finalize( - id, - { - previewHash: initial.previewHash, - selectionHash: selected.validation.selection!.selectionHash, - }, - actor() - ); -} - -const reference = ( - runId: string, - metricPath = 'analytics.metrics.totalReturn' -): ResearchEvidenceReference => ({ - runId, - metricsVersion: 'canonical-analytics/v1', - metricPath, -}); -async function save( - f: Fixture, - source: ResearchFindingSource, - evidence: ResearchEvidenceReference[] -) { - const project = await f.research.createProject({ title: 'Evidence workspace' }, 'operator'); - const artifact = await f.research.createArtifact( - project.id, - { - kind: 'finding', - title: 'Selected observations', - body: 'Not a validated claim', - source, - evidence, - }, - 'operator' - ); - return { project, artifact }; -} -async function cost(f: Fixture) { - await f.review(); - const input = { - backtestId: f.draft.id, - name: 'Costs', - scenarios: [ - { feeRate: '0.001', slippageRate: '0.002' }, - { feeRate: '0.003', slippageRate: '0.004' }, - ], - }; - const preview = await f.experiments.previewCosts(input); - const detail = await f.experiments.submitCosts( - { ...input, previewHash: preview.previewHash }, - actor() - ); - return { - detail, - source: { - kind: 'experiment/v1', - experimentId: detail.id, - previewHash: detail.previewHash, - } as const, - }; -} -function rehash>(value: T, field: string): T { - const copy = structuredClone(value), - { _receipt: _private, ...document } = copy; - delete document[field]; - return { ...copy, [field]: experimentHash(document) }; -} -async function mutate(f: Fixture, table: string, id: string, field: string, value: unknown) { - await f.postgres.transaction(async client => { - await client.query(`ALTER TABLE ${table} DISABLE TRIGGER USER`); - await client.query(`UPDATE ${table} SET ${field}=$2 WHERE id=$1`, [id, value]); - await client.query(`ALTER TABLE ${table} ENABLE TRIGGER USER`); - }); -} -async function rawRevision( - f: Fixture, - artifactId: string, - source: unknown, - refs: ResearchEvidenceReference[], - after?: (client: PoolClient, revisionId: string) => Promise -) { - return f.postgres.transaction(async client => { - const revisionId = randomUUID(); - const ordinal = Number( - ( - await client.query( - 'SELECT COALESCE(MAX(ordinal),0)+1 AS n FROM analysis_artifact_revisions WHERE artifact_id=$1', - [artifactId] - ) - ).rows[0].n - ); - await client.query( - "INSERT INTO analysis_artifact_revisions(id,artifact_id,ordinal,title,body,submitted_by,content_origin,source) VALUES($1,$2,$3,'Raw source','Unvalidated','operator','human',$4)", - [revisionId, artifactId, ordinal, source] - ); - for (const [index, ref] of refs.entries()) { - await client.query( - 'INSERT INTO analysis_evidence(revision_id,ordinal,run_id,metrics_version,metric_path) VALUES($1,$2,$3,$4,$5)', - [revisionId, index + 1, ref.runId, ref.metricsVersion, ref.metricPath] - ); - } - if (after) { - await after(client, revisionId); - } - return revisionId; - }); -} -describe.skipIf(!url)('source-linked findings', () => { - test('pool1 cost source saves exact selected facts and nulls; historical read survives cancellation/archive; omitted source persists and explicit null detaches', async () => { - const f = await fixture(), - c = await cost(f); - for (const trial of c.detail.trials.slice(0, 2)) { - await f.execute(trial.runId!); - } - expect((await f.experiments.get(c.detail.id)).standalone).toBe(true); - const evidence = [ - reference(c.detail.trials[0]!.runId!), - reference(c.detail.trials[0]!.runId!, 'analytics.metrics.sharpeRatio'), - reference(c.detail.trials[1]!.runId!), - ]; - const native = await f.api.getRunResults(evidence[0]!.runId); - const { artifact, project } = await save(f, c.source, evidence); - expect(artifact.latestRevision.source).toEqual(c.source); - expect(artifact.latestRevision.validationState).toBe('unvalidated'); - expect(artifact.latestRevision.evidence[0]!.value).toBe( - (native as any).analytics.metrics.totalReturn - ); - expect(artifact.latestRevision.evidence[1]).toMatchObject({ - value: null, - availability: 'unavailable', - }); - await f.experiments.cancel(c.detail.id); - await f.review('revoke'); - await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]); - await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [ - f.version.strategyId, - ]); - const before = await f.snapshot(); - expect(await f.research.getArtifact(artifact.id)).toEqual(artifact); - expect(await f.research.listArtifacts(project.id)).toEqual([artifact]); - expect(await f.research.listArtifactRevisions(artifact.id)).toEqual([artifact.latestRevision]); - expect(await f.snapshot()).toEqual(before); - const revised = await f.research.reviseArtifact( - artifact.id, - { expectedRevision: 1, title: 'New interpretation', body: 'Still unvalidated', evidence }, - 'operator' - ); - expect(revised.latestRevision.source).toEqual(c.source); - const detached = await f.research.reviseArtifact( - artifact.id, - { - expectedRevision: 2, - title: 'Unscoped', - body: 'Deliberately detached', - evidence, - source: null, - }, - 'operator' - ); - expect(detached.latestRevision.source).toBeNull(); - expect((await f.research.listArtifactRevisions(artifact.id)).map(r => r.source)).toEqual([ - c.source, - c.source, - null, - ]); - }, 60000); - test('native sealed chronological and walk-forward sources retain all proof but only published series segment metrics are selectable', async () => { - const f = await fixture(), - start = await submit(f); - for (const window of start.walk.windows) { - await finishWindow(f, window.validationId); - } - const completed = await f.walks.finalize( - start.walk.id, - { previewHash: start.preview.previewHash }, - actor() - ); - const series = completed.walkForward.report!; - const member = completed.walkForward.windows[0]!.validation!.report!; - const source: ResearchFindingSource = { - kind: 'walk-forward-report/v1', - walkForwardId: start.walk.id, - previewHash: series.previewHash, - reportId: series.id, - reportHash: series.reportHash, - }; - const saved = await save( - f, - source, - series.segments.flatMap(s => [reference(s.validation.runId), reference(s.test.runId)]) - ); - expect(saved.artifact.latestRevision.evidence.map(e => e.value)).toEqual( - series.segments.flatMap(s => [s.validation.metrics.totalReturn, s.test.metrics.totalReturn]) - ); - const chrono: ResearchFindingSource = { - kind: 'chronological-report/v1', - validationId: member.validationId, - previewHash: member.previewHash, - reportId: member.id, - reportHash: member.reportHash, - }; - const original = await save(f, chrono, [ - reference(member.training[0]!.runId), - reference(member.test.runId, 'analytics.metrics.sharpeRatio'), - ]); - expect(original.artifact.latestRevision.evidence[1]!.value).toBeNull(); - expect((await f.experiments.get(member.validationId)).standalone).toBe(false); - await expect(save(f, source, [reference(member.training[0]!.runId)])).rejects.toMatchObject({ - status: 422, - }); - await expect( - save( - f, - { - kind: 'experiment/v1', - experimentId: member.validationId, - previewHash: - completed.walkForward.windows[0]!.validation!.phases[0]!.experiment!.previewHash, - }, - [reference(member.training[0]!.runId)] - ) - ).rejects.toMatchObject({ status: 422 }); - await f.walks.cancel(start.walk.id); - await f.review('revoke'); - await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]); - await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [ - f.version.strategyId, - ]); - const before = await f.snapshot(); - expect(await f.research.getArtifact(saved.artifact.id)).toEqual(saved.artifact); - expect(await f.research.getArtifact(original.artifact.id)).toEqual(original.artifact); - expect(await f.snapshot()).toEqual(before); - }, 60000); - - test('wrong input identity, empty notes, foreign or incomplete refs and omitted-source revisions reject atomically', async () => { - const f = await fixture(), - c = await cost(f), - other = await cost(f); - await f.execute(c.detail.trials[0]!.runId!); - await f.execute(other.detail.trials[0]!.runId!); - const ref = reference(c.detail.trials[0]!.runId!), - foreign = reference(other.detail.trials[0]!.runId!); - const { artifact, project } = await save(f, c.source, [ref]); - const before = await f.snapshot(); - for (const input of [ - { source: { ...c.source, previewHash: 'f'.repeat(64) }, evidence: [ref] }, - { source: c.source, evidence: [foreign] }, - { source: c.source, evidence: [reference(c.detail.trials[1]!.runId!)] }, - { source: c.source, evidence: [] }, - { - source: c.source, - evidence: [ - { ...ref, metricsVersion: 'legacy-display/v1', metricPath: 'metrics.totalReturn' }, - ], - }, - ]) { - await expect( - f.research.createArtifact( - project.id, - { kind: 'note', title: 'Rejected source', body: '', ...input }, - 'operator' - ) - ).rejects.toMatchObject({ status: 422 }); - } - await expect( - f.research.reviseArtifact( - artifact.id, - { expectedRevision: 1, title: 'Foreign omitted', body: '', evidence: [foreign] }, - 'operator' - ) - ).rejects.toMatchObject({ status: 422 }); - expect(await f.snapshot()).toEqual(before); - expect((await f.research.getArtifact(artifact.id)).latestRevision.source).toEqual(c.source); - const detached = await f.research.reviseArtifact( - artifact.id, - { - expectedRevision: 1, - title: 'Explicit new scope', - body: '', - source: null, - evidence: [foreign], - }, - 'operator' - ); - expect(detached.latestRevision.source).toBeNull(); - }, 60000); - test('recomputed-hash selection, training, holdout, series and document metadata corruption cannot become cited evidence', async () => { - const f = await fixture(), - start = await submit(f); - for (const window of start.walk.windows) { - await finishWindow(f, window.validationId); - } - const done = await f.walks.finalize( - start.walk.id, - { previewHash: start.preview.previewHash }, - actor() - ); - const first = done.walkForward.windows[0]!.validation!, - report = first.report!; - const root = (await f.pool.query('SELECT * FROM research_experiments WHERE id=$1', [first.id])) - .rows[0]; - const header = ( - await f.pool.query('SELECT * FROM research_walk_forwards WHERE id=$1', [start.walk.id]) - ).rows[0]; - const project = await f.research.createProject({ title: 'Corruption refusals' }, 'operator'); - const ref = reference(report.test.runId); - const originalSource: ResearchFindingSource = { - kind: 'chronological-report/v1', - validationId: first.id, - previewHash: report.previewHash, - reportId: report.id, - reportHash: report.reportHash, - }; - const saved = await f.research.createArtifact( - project.id, - { kind: 'finding', title: 'Original', body: '', source: originalSource, evidence: [ref] }, - 'operator' - ); - for (const change of [ - 'training', - 'winner', - 'holdout', - 'principal', - 'time', - 'limitations', - ] as const) { - let selection = structuredClone(root.validation_selection), - changed = structuredClone(root.validation_report); - if (change === 'training') { - selection.training[0].metrics.totalReturn += 1; - changed.training = structuredClone(selection.training); - } - if (change === 'winner') { - selection.winner = structuredClone( - root.preview.candidates.find( - (candidate: any) => candidate.index !== selection.winner.index - ) - ); - } - if (change === 'holdout') { - changed.test.metrics.totalReturn += 1; - } - if (change === 'principal') { - changed.principal = 'fabricated'; - } - if (change === 'time') { - changed.createdAt = 'not-a-time'; - } - if (change === 'limitations') { - changed.limitations = ['ok', 42]; - } - selection = rehash(selection, 'selectionHash'); - changed.selectionHash = selection.selectionHash; - changed = rehash(changed, 'reportHash'); - await mutate(f, 'research_experiments', first.id, 'validation_selection', selection); - await mutate(f, 'research_experiments', first.id, 'validation_report', changed); - const source = { ...originalSource, reportHash: changed.reportHash }; - await expect( - f.research.createArtifact( - project.id, - { kind: 'finding', title: 'Corrupt', body: '', source, evidence: [ref] }, - 'operator' - ) - ).rejects.toThrow('Retained research source could not be verified'); - await mutate( - f, - 'research_experiments', - first.id, - 'validation_selection', - root.validation_selection - ); - await mutate( - f, - 'research_experiments', - first.id, - 'validation_report', - root.validation_report - ); - } - const originalResult = ( - await f.pool.query('SELECT canonical_result FROM backtest_results WHERE run_id=$1', [ - ref.runId, - ]) - ).rows[0].canonical_result; - for (const field of ['analytics', 'financial']) { - const damaged = structuredClone(originalResult); - if (field === 'analytics') { - damaged.analytics.metrics.totalReturn += 1; - } else { - expect(typeof damaged.financial.view.equity).toBe('string'); - damaged.financial.view.equity = '900.00000000'; - } - expect(damaged).not.toEqual(originalResult); - const write = async (value: unknown) => - f.postgres.transaction(async client => { - await client.query('ALTER TABLE backtest_results DISABLE TRIGGER USER'); - await client.query('UPDATE backtest_results SET canonical_result=$2 WHERE run_id=$1', [ - ref.runId, - value, - ]); - await client.query('ALTER TABLE backtest_results ENABLE TRIGGER USER'); - }); - await write(damaged); - await expect( - f.research.createArtifact( - project.id, - { - kind: 'finding', - title: 'Corrupt canonical result', - body: '', - source: originalSource, - evidence: [ref], - }, - 'operator' - ) - ).rejects.toThrow('Retained research source could not be verified'); - await expect(f.research.getArtifact(saved.id)).rejects.toThrow( - 'Retained finding source evidence could not be resolved' - ); - await write(originalResult); - } - const forged = structuredClone(header.report); - forged.segments[1].test.metrics.totalReturn += 1; - const changed = rehash(forged, 'reportHash'); - await mutate(f, 'research_walk_forwards', header.id, 'report', changed); - await expect( - f.research.createArtifact( - project.id, - { - kind: 'finding', - title: 'Forged series', - body: '', - source: { - kind: 'walk-forward-report/v1', - walkForwardId: header.id, - previewHash: header.preview_hash, - reportId: changed.id, - reportHash: changed.reportHash, - }, - evidence: [ref], - }, - 'operator' - ) - ).rejects.toThrow('Retained research source could not be verified'); - await mutate(f, 'research_walk_forwards', header.id, 'report', header.report); - const broken = structuredClone(root.validation_report); - broken.test.metrics.totalReturn += 1; - await mutate( - f, - 'research_experiments', - first.id, - 'validation_report', - rehash(broken, 'reportHash') - ); - const app = new Hono(); - const token = 'source-evidence-read-fixture-not-a-real-secret-1234'; - createHttpSecurity({ - readToken: token, - adminToken: 'source-evidence-admin-fixture-not-a-real-secret-1234', - serviceToken: 'source-evidence-service-fixture-not-a-real-secret-1234', - environment: 'test', - hostname: '127.0.0.1', - }).mount(app); - app.route('/', createResearchRoutes(f.container)); - const response = await app.request('/api/v2/analysis-artifacts/' + saved.id, { - headers: { Authorization: `Bearer ${token}` }, - }); - expect(response.status).toBe(500); - expect(await response.json()).toEqual({ error: 'Research workspace unavailable' }); - }, 60000); - test('SQL source guards reject malformed/member/empty refs, protect immutable history and recheck evidence after constraints become immediate', async () => { - const f = await fixture(), - c = await cost(f), - other = await cost(f); - await f.execute(c.detail.trials[0]!.runId!); - await f.execute(other.detail.trials[0]!.runId!); - const ref = reference(c.detail.trials[0]!.runId!), - foreign = reference(other.detail.trials[0]!.runId!); - const { artifact } = await save(f, c.source, [ref]); - for (const bad of [ - { ...c.source, extra: true }, - { ...c.source, experimentId: null }, - { ...c.source, previewHash: null }, - { ...c.source, previewHash: 'f'.repeat(64) }, - { ...c.source, kind: 'unknown' }, - 'null', - ]) { - await expect(rawRevision(f, artifact.id, bad, [ref])).rejects.toMatchObject({ - code: '23514', - }); - } - await expect(rawRevision(f, artifact.id, c.source, [])).rejects.toMatchObject({ - code: '23514', - }); - await expect(rawRevision(f, artifact.id, c.source, [foreign])).rejects.toThrow( - 'completed canonical members' - ); - await expect( - rawRevision(f, artifact.id, c.source, [ref], async (client, revisionId) => { - await client.query('SET CONSTRAINTS workspace_source_evidence IMMEDIATE'); - await client.query( - 'INSERT INTO analysis_evidence(revision_id,ordinal,run_id,metrics_version,metric_path) VALUES($1,2,$2,$3,$4)', - [revisionId, foreign.runId, foreign.metricsVersion, foreign.metricPath] - ); - }) - ).rejects.toThrow('completed canonical members'); - const accepted = await rawRevision(f, artifact.id, c.source, [ref]); - for (const statement of [ - 'UPDATE analysis_artifact_revisions SET source=NULL WHERE id=$1', - 'DELETE FROM analysis_artifact_revisions WHERE id=$1', - "INSERT INTO analysis_evidence(revision_id,ordinal,run_id,metrics_version,metric_path) VALUES($1,2,'" + - ref.runId + - "','canonical-analytics/v1','analytics.metrics.maxDrawdown')", - ]) { - await expect(f.pool.query(statement, [accepted])).rejects.toMatchObject({ code: '23514' }); - } - await expect( - f.pool.query('TRUNCATE analysis_artifact_revisions CASCADE') - ).rejects.toMatchObject({ code: '23514' }); - expect((await f.research.listArtifactRevisions(artifact.id)).map(item => item.source)).toEqual([ - c.source, - c.source, - ]); - }, 60000); - test('first migration and reapply preserve existing artifacts, receipts, results and pending run custody', async () => { - const f = await fixture(1, false), - c = await cost(f); - await f.execute(c.detail.trials[0]!.runId!); - const project = randomUUID(), - artifact = randomUUID(), - revision = randomUUID(), - runId = c.detail.trials[0]!.runId!; - await f.postgres.transaction(async client => { - await client.query( - "INSERT INTO research_projects(id,title,owner_principal,updated_by) VALUES($1,'Before27','operator','operator')", - [project] - ); - await client.query( - "INSERT INTO analysis_artifacts(id,project_id,kind,owner_principal,updated_by) VALUES($1,$2,'finding','operator','operator')", - [artifact, project] - ); - await client.query( - "INSERT INTO analysis_artifact_revisions(id,artifact_id,ordinal,title,body,submitted_by,content_origin) VALUES($1,$2,1,'Before27','Immutable','operator','human')", - [revision, artifact] - ); - await client.query( - "INSERT INTO analysis_evidence(revision_id,ordinal,run_id,metrics_version,metric_path) VALUES($1,1,$2,'canonical-analytics/v1','analytics.metrics.totalReturn')", - [revision, runId] - ); - }); - const claimedId = c.detail.trials[1]!.runId!; - const request = ( - await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [claimedId]) - ).rows[0].request_snapshot; - const claim = await f.repository.startCanonical(request); - const custody = ( - await f.pool.query( - 'SELECT attempt_id,attempt_number,lease_expires_at,status FROM runs WHERE id=$1', - [claimedId] - ) - ).rows[0]; - expect(custody.attempt_id).toBe(claim.attemptId); - expect(custody.status).toBe('running'); - expect(custody.lease_expires_at).not.toBeNull(); - const before = await f.snapshot(); - const sql = readFileSync( - new URL('../../database/postgres/init/27-research-evidence-sources.sql', import.meta.url), - 'utf8' - ); - await f.pool.query(sql); - const after = await f.snapshot(); - const revisions = after.analysis_artifact_revisions as Record[]; - expect(revisions.every(item => item.source === null)).toBe(true); - after.analysis_artifact_revisions = revisions.map(({ source: _source, ...row }) => row); - expect(after).toEqual(before); - expect( - ( - await f.pool.query( - 'SELECT attempt_id,attempt_number,lease_expires_at,status FROM runs WHERE id=$1', - [claimedId] - ) - ).rows[0] - ).toEqual(custody); - expect((await f.research.getArtifact(artifact)).latestRevision.source).toBeNull(); - const saved = await save(f, c.source, [reference(runId)]), - retained = await f.snapshot(); - await f.pool.query(sql); - expect(await f.snapshot()).toEqual(retained); - expect(await f.research.getArtifact(saved.artifact.id)).toEqual(saved.artifact); - }, 60000); - test('artifact get/list/history use a coherent readonly snapshot despite a committed source/result change', async () => { - const f = await fixture(4), - c = await cost(f); - await f.execute(c.detail.trials[0]!.runId!); - const { artifact, project } = await save(f, c.source, [reference(c.detail.trials[0]!.runId!)]); - const transaction = f.postgres.transaction.bind(f.postgres); - const original = ( - await f.pool.query('SELECT validation_phase FROM research_experiments WHERE id=$1', [ - c.detail.id, - ]) - ).rows[0]; - for (const read of [ - () => f.research.getArtifact(artifact.id), - () => f.research.listArtifacts(project.id), - () => f.research.listArtifactRevisions(artifact.id), - ]) { - let changed = false; - const trace: string[] = []; - let mode: unknown; - Object.defineProperty(f.postgres, 'transaction', { - configurable: true, - value: (work: (client: PoolClient) => Promise) => - transaction(async client => { - const query = client.query.bind(client), - proxy = Object.create(client) as PoolClient; - Object.defineProperty(proxy, 'query', { - value: async (sql: string, values?: unknown[]) => { - trace.push(sql); - const result = await query(sql, values); - if (sql.startsWith('SET TRANSACTION')) { - mode = ( - await query( - "SELECT current_setting('transaction_isolation') AS isolation,current_setting('transaction_read_only') AS readonly" - ) - ).rows[0]; - } - if (sql.startsWith('SELECT * FROM analysis_artifact_revisions') && !changed) { - changed = true; - await transaction(async other => { - await other.query('ALTER TABLE research_experiments DISABLE TRIGGER USER'); - await other.query( - 'UPDATE research_experiments SET preview_hash=$2 WHERE id=$1', - [c.detail.id, 'f'.repeat(64)] - ); - await other.query('ALTER TABLE research_experiments ENABLE TRIGGER USER'); - }); - } - return result; - }, - }); - return work(proxy); - }), - }); - await read(); - expect(changed).toBe(true); - expect(mode).toEqual({ isolation: 'repeatable read', readonly: 'on' }); - expect(trace[0]).toBe('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY'); - expect(trace.some(sql => /FOR (UPDATE|SHARE)|^(INSERT|UPDATE|DELETE)/i.test(sql))).toBe( - false - ); - Object.defineProperty(f.postgres, 'transaction', { configurable: true, value: transaction }); - await expect(f.research.getArtifact(artifact.id)).rejects.toThrow( - 'Retained finding source evidence could not be resolved' - ); - await mutate(f, 'research_experiments', c.detail.id, 'preview_hash', c.source.previewHash); - } - expect(original.validation_phase).toBeNull(); - }, 60000); -}); diff --git a/test/postgres/research-workspace.test.ts b/test/postgres/research-workspace.test.ts deleted file mode 100644 index e4af65ce..00000000 --- a/test/postgres/research-workspace.test.ts +++ /dev/null @@ -1,741 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { readFileSync } from 'node:fs'; -import { afterEach, describe, expect, test } from 'bun:test'; -import { Pool } from 'pg'; -import { getLogger, setLoggerConfig } from '@stock-bot/logger'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import type { ResearchEvidenceReference } 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 { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service'; -import { createResearchServices } from '../../apps/stock/web-api/src/services/research-services'; -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 '../fixtures/canonical-research'; -import { canonicalSmaFixture } from '../fixtures/canonical-sma'; -import { seedHistoricalRun } from '../fixtures/historical-run'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('research-workspace'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const cleanup: (() => Promise)[] = []; -let packages: ReturnType | undefined; -const sql = (name: string) => - readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8'); -const migration = sql('20-research-workspace.sql'); -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); -async function fixture(applyWorkspace = true, maxConnections = 10) { - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Disposable safety database required'); - } - const schema = 'stock_bot_safety_workspace_' + randomUUID().replaceAll('-', ''); - const admin = new Pool({ connectionString: url }); - await admin.query(`CREATE SCHEMA ${schema}`); - const pool = new Pool({ - connectionString: url, - max: maxConnections, - connectionTimeoutMillis: 2000, - application_name: schema, - options: `-c search_path=${schema} -c statement_timeout=10000`, - }); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - for (const name of [ - '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(sql(name)); - } - if (applyWorkspace) { - await pool.query(migration); - await pool.query(sql('27-research-evidence-sources.sql')); - } - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, - logger - ); - Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); - Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); - const container = { postgres, logger }; - const service = createResearchServices(container).research; - const backtests = new BacktestServiceV2(container); - const catalog = new StrategyCatalogService(container); - const legacy = async (status = 'completed') => { - const definition = await backtests.createBacktest( - { - name: 'Retained legacy fixture', - strategy: 'sma-crossover', - symbols: ['X0.US'], - startDate: '2024-01-01T00:00:00Z', - endDate: '2024-01-04T00:00:00Z', - initialCapital: 10000, - config: { fastPeriod: 2, slowPeriod: 3, commission: 0, slippage: 0 }, - }, - { autoStart: false } - ); - const run = await seedHistoricalRun(pool, backtests, { backtestId: definition.id }); - // Fixed old-display fixtures exercise custody/conversion, not financial simulation. - await pool.query( - `INSERT INTO backtest_results(run_id,metrics,equity_curve,ohlc_data,trades,positions,analytics,execution_time,engine) - VALUES($1,$2,'[]','{}','[]','[]',$3,0,'native')`, - [ - run.id, - { - totalReturn: 12, - sharpeRatio: null, - maxDrawdown: -0.1, - winRate: 50, - totalTrades: 0, - profitFactor: null, - avgWin: 0, - avgLoss: 0, - }, - { exposureTime: 0 }, - ] - ); - await pool.query('UPDATE runs SET status=$2,completed_at=NOW(),progress=100 WHERE id=$1', [ - run.id, - status, - ]); - return { run, definition }; - }; - const canonical = async () => { - const pkg = (await (packages ??= packageBuiltinStrategies()))[0]!; - const version = await catalog.seedBuiltin('Retained SMA', pkg, 'seed'); - await catalog.reviewVersion( - version.id, - { decision: 'approve', reason: 'Reviewed fixture' }, - 'operator' - ); - const { dataset } = canonicalSmaFixture(); - await retainResearchDataset(pool, dataset); - const definition = await backtests.createBacktest( - { - name: 'Canonical cited fixture', - strategy: 'catalog', - strategyVersionId: version.id, - strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, - symbols: ['X0.US'], - startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(), - endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(), - initialCapital: 10000, - config: { - datasetHash: dataset.manifest.hash, - dataFrequency: '1m', - canonical: canonicalSettings, - }, - }, - { autoStart: false } - ); - const run = await backtests.createRun({ backtestId: definition.id }); - const runner = new BacktestRunner({ - engine: new RustBacktestAdapter({ - logger, - }), - repository: new PostgresBacktestRunRepository(postgres), - logger, - }); - try { - await runner.runQueued(run.id); - } finally { - await runner.shutdown(); - } - expect((await backtests.getRun(run.id))?.status).toBe('completed'); - return { run, definition, version, dataset }; - }; - return { pool, schema, postgres, service, backtests, catalog, legacy, canonical }; -} -const hypothesisInput = { - title: 'Trend hypothesis', - proposition: 'A stated claim', - validationCriteria: 'Evaluate held-out data', -}; -const noteInput = { - kind: 'note' as const, - title: 'Observation', - body: 'A narrative, not a measured conclusion', -}; -const reference = ( - runId: string, - metricPath = 'metrics.totalReturn' -): ResearchEvidenceReference => ({ runId, metricsVersion: 'legacy-display/v1', metricPath }); - -describe.skipIf(!url)('research workspace retained narratives and evidence', () => { - test('evidence create and revise use the transaction connection even with a one-connection pool', async () => { - const f = await fixture(true, 1); - const { run } = await f.legacy(); - const p = await f.service.createProject({ title: 'Single connection' }, 'operator'); - const finding = await f.service.createArtifact( - p.id, - { - ...noteInput, - kind: 'finding', - evidence: [reference(run.id)], - }, - 'operator' - ); - const revised = await f.service.reviseArtifact( - finding.id, - { - title: 'Revised', - body: 'Same retained run', - expectedRevision: 1, - evidence: [reference(run.id, 'metrics.winRate')], - }, - 'operator' - ); - expect(revised.latestRevision.evidence[0]?.value).toBe(0.5); - expect(await f.service.listArtifactRevisions(finding.id)).toHaveLength(2); - }); - test('projects and strategy organization are editable and archiveable without altering catalog identity', async () => { - const f = await fixture(); - expect(await f.service.listProjects()).toEqual([]); - const p = await f.service.createProject( - { title: 'Research πŸš€', description: 'Tokyo 東京' }, - 'operator' - ); - expect(p).toMatchObject({ - revision: 1, - ownerPrincipal: 'operator', - updatedBy: 'operator', - archived: false, - }); - const strategy = await f.catalog.createStrategy({ name: 'Candidate' }, 'operator'); - await f.service.linkStrategy(p.id, strategy.id, 'service'); - await f.service.linkStrategy(p.id, strategy.id, 'operator'); - expect(await f.service.listProjectStrategies(p.id)).toEqual([strategy]); - expect( - (await f.pool.query('SELECT added_by FROM research_project_strategies')).rows[0].added_by - ).toBe('service'); - expect(await f.service.getProject(p.id)).toMatchObject({ revision: 2, updatedBy: 'service' }); - await expect( - f.service.updateProject( - p.id, - { expectedRevision: 1, title: 'Before membership change' }, - 'operator' - ) - ).rejects.toThrow('revision changed'); - const edited = await f.service.updateProject( - p.id, - { expectedRevision: 2, title: 'Changed' }, - 'service' - ); - expect(edited).toMatchObject({ - revision: 3, - title: 'Changed', - ownerPrincipal: 'operator', - updatedBy: 'service', - }); - await expect( - f.service.updateProject(p.id, { expectedRevision: 1, title: 'Stale' }, 'operator') - ).rejects.toThrow('revision changed'); - await f.catalog.updateStrategy(strategy.id, { archived: true }, 'operator'); - await expect(f.service.linkStrategy(p.id, strategy.id, 'operator')).rejects.toThrow('archived'); - await f.service.unlinkStrategy(p.id, strategy.id, 'operator'); - const unlinked = await f.service.getProject(p.id); - expect(unlinked).toMatchObject({ revision: 4, updatedBy: 'operator' }); - await f.service.unlinkStrategy(p.id, strategy.id, 'service'); - expect(await f.service.getProject(p.id)).toEqual(unlinked); - await expect( - f.service.updateProject(p.id, { expectedRevision: 3, title: 'Before unlink' }, 'operator') - ).rejects.toThrow('revision changed'); - expect(await f.service.listProjectStrategies(p.id)).toEqual([]); - const archived = await f.service.updateProject( - p.id, - { expectedRevision: 4, archived: true }, - 'operator' - ); - expect(await f.service.listProjects()).toEqual([]); - expect(await f.service.listProjects(true)).toEqual([archived]); - await expect(f.service.createHypothesis(p.id, hypothesisInput, 'operator')).rejects.toThrow( - 'archived' - ); - await expect(f.service.createArtifact(p.id, noteInput, 'operator')).rejects.toThrow('archived'); - await expect( - f.service.updateProject( - p.id, - { expectedRevision: 5, archived: false, title: 'Hidden edit' }, - 'operator' - ) - ).rejects.toThrow('only permit restoration'); - expect( - (await f.service.updateProject(p.id, { expectedRevision: 5, archived: false }, 'operator')) - .archived - ).toBe(false); - expect((await f.catalog.getStrategy(strategy.id)).archived).toBe(true); - }); - - test('hypothesis_vs_evidence and authorship_audit retain every narrative revision without validation promotion', async () => { - const f = await fixture(); - const p = await f.service.createProject({ title: 'Research' }, 'service'); - const h = await f.service.createHypothesis( - p.id, - { ...hypothesisInput, contentOrigin: 'ai' }, - 'service' - ); - expect(h.updatedBy).toBe('service'); - expect(Number.isFinite(Date.parse(h.updatedAt))).toBe(true); - expect(h.latestRevision).toMatchObject({ - submittedBy: 'service', - contentOrigin: 'ai', - validationState: 'unvalidated', - ordinal: 1, - }); - const revised = await f.service.reviseHypothesis( - h.id, - { ...hypothesisInput, proposition: 'Changed claim', expectedRevision: 1 }, - 'operator' - ); - expect(revised.latestRevision).toMatchObject({ - submittedBy: 'operator', - contentOrigin: 'human', - validationState: 'unvalidated', - ordinal: 2, - }); - expect((await f.service.listHypothesisRevisions(h.id))[0]).toEqual(h.latestRevision); - expect(revised.ownerPrincipal).toBe('service'); - expect(revised.updatedBy).toBe('operator'); - await expect( - f.service.createHypothesis(p.id, { ...hypothesisInput, contentOrigin: 'human' }, 'service') - ).rejects.toThrow('Only operator credentials can declare human authorship'); - await expect( - f.service.reviseHypothesis( - h.id, - { ...hypothesisInput, expectedRevision: 2, validationState: 'validated' }, - 'operator' - ) - ).rejects.toThrow(); - const n = await f.service.createArtifact( - p.id, - { ...noteInput, hypothesisRevisionId: h.latestRevision.id }, - 'service' - ); - expect(n.latestRevision).toMatchObject({ - submittedBy: 'service', - contentOrigin: 'unknown', - validationState: 'unvalidated', - evidenceState: 'none', - evidence: [], - }); - expect(n.hypothesisRevisionId).toBe(h.latestRevision.id); - expect((await f.service.archiveHypothesis(h.id, { archived: true }, 'service')).updatedBy).toBe( - 'service' - ); - expect( - (await f.service.archiveHypothesis(h.id, { archived: false }, 'operator')).updatedBy - ).toBe('operator'); - await f.service.archiveHypothesis(h.id, { archived: true }, 'service'); - expect(await f.service.listHypotheses(p.id)).toEqual([]); - expect(await f.service.listHypotheses(p.id, true)).toHaveLength(1); - await expect( - f.service.reviseHypothesis(h.id, { ...hypothesisInput, expectedRevision: 2 }, 'operator') - ).rejects.toThrow('archived'); - const changed = await f.service.reviseArtifact( - n.id, - { title: 'Human note', body: 'Updated narrative', expectedRevision: 1 }, - 'operator' - ); - expect(changed.hypothesisRevisionId).toBe(h.latestRevision.id); - expect(changed.updatedBy).toBe('operator'); - expect(Number.isFinite(Date.parse(changed.updatedAt))).toBe(true); - expect((await f.service.listArtifactRevisions(n.id))[0]).toEqual(n.latestRevision); - expect((await f.service.archiveArtifact(n.id, { archived: true }, 'service')).updatedBy).toBe( - 'service' - ); - expect((await f.service.archiveArtifact(n.id, { archived: false }, 'operator')).updatedBy).toBe( - 'operator' - ); - await f.service.archiveArtifact(n.id, { archived: true }, 'service'); - expect(await f.service.listArtifacts(p.id)).toEqual([]); - expect(await f.service.listArtifacts(p.id, true)).toHaveLength(1); - await expect( - f.service.reviseArtifact(n.id, { title: 'No', body: '', expectedRevision: 2 }, 'operator') - ).rejects.toThrow('archived'); - await f.service.updateProject(p.id, { expectedRevision: 1, archived: true }, 'operator'); - await expect(f.service.archiveArtifact(n.id, { archived: false }, 'operator')).rejects.toThrow( - 'Project is archived' - ); - await expect( - f.service.archiveHypothesis(h.id, { archived: false }, 'operator') - ).rejects.toThrow('Project is archived'); - expect((await f.service.getArtifact(n.id)).latestRevision).toEqual(changed.latestRevision); - }); - - test('cited_metric_matches_run uses retained legacy conversion, preserves zero/null, and never stores measured copies', async () => { - const f = await fixture(); - const { run, definition } = await f.legacy(); - const p = await f.service.createProject({ title: 'Evidence' }, 'operator'); - const finding = await f.service.createArtifact( - p.id, - { - kind: 'finding', - title: 'AI interpretation', - body: 'This assertion is not validated', - contentOrigin: 'ai', - evidence: [ - reference(run.id), - reference(run.id, 'metrics.totalTrades'), - reference(run.id, 'analytics.exposureTime'), - ], - }, - 'service' - ); - const result = await f.backtests.getRunResults(run.id); - if (!result || 'kind' in result) { - throw new Error('Expected legacy fixture'); - } - const revision = finding.latestRevision; - expect(revision.validationState).toBe('unvalidated'); - expect(revision.evidenceState).toBe('referenced'); - expect(revision.evidence.map(e => e.value)).toEqual([result.metrics.totalReturn, 0, null]); - expect(revision.evidence[0]?.value).toBe(0.12); - expect(revision.evidence[0]?.unit).toBe('fraction'); - expect(revision.evidence[1]?.availability).toBe('available'); - expect(revision.evidence[2]?.availability).toBe('unavailable'); - expect(revision.evidence[0]?.limitations.length).toBeGreaterThan(0); - const stored = (await f.pool.query('SELECT * FROM analysis_evidence ORDER BY ordinal')).rows; - expect(stored).toHaveLength(3); - expect(Object.keys(stored[0]).sort()).toEqual([ - 'metric_path', - 'metrics_version', - 'ordinal', - 'revision_id', - 'run_id', - 'strategy_version_id', - ]); - const edited = await f.service.reviseArtifact( - finding.id, - { - title: 'Revised interpretation', - body: 'A different narrative and citation set', - expectedRevision: 1, - evidence: [reference(run.id, 'metrics.winRate')], - }, - 'operator' - ); - expect(edited.latestRevision.evidence[0]?.value).toBe(0.5); - expect((await f.service.listArtifactRevisions(finding.id))[0]).toEqual(revision); - expect( - (await f.pool.query('SELECT * FROM analysis_evidence WHERE revision_id=$1', [revision.id])) - .rowCount - ).toBe(3); - await f.backtests.updateBacktest(definition.id, { name: 'Changed template' }); - await f.backtests.archiveBacktest(definition.id, true); - await f.service.updateProject(p.id, { expectedRevision: 1, archived: true }, 'operator'); - expect((await f.service.getArtifact(finding.id)).latestRevision).toEqual(edited.latestRevision); - expect((await f.pool.query('SELECT * FROM backtest_results')).rowCount).toBe(1); - }); - - test('canonical citations resolve exact native analytics, immutable strategy binding and unavailable round trips', async () => { - const f = await fixture(); - const { run, version } = await f.canonical(); - const p = await f.service.createProject({ title: 'Canonical evidence' }, 'operator'); - const canonicalReference = (metricPath: string): ResearchEvidenceReference => ({ - runId: run.id, - metricsVersion: 'canonical-analytics/v1', - metricPath, - strategyVersionId: version.id, - }); - const finding = await f.service.createArtifact( - p.id, - { - kind: 'finding', - title: 'Measured result', - body: 'A hypothesis remains unvalidated', - evidence: [ - canonicalReference('analytics.metrics.totalReturn'), - canonicalReference('analytics.fillCount'), - canonicalReference('analytics.metrics.roundTripCount'), - ], - }, - 'operator' - ); - const result = await f.backtests.getRunResults(run.id); - if (!result || !('kind' in result)) { - throw new Error('Expected canonical fixture'); - } - expect(finding.latestRevision.evidence.map(e => e.value)).toEqual([ - result.analytics.metrics.totalReturn, - 2, - null, - ]); - expect(finding.latestRevision.evidence[2]?.unavailableReason).toBe('unsupported-round-trips'); - expect(finding.latestRevision.evidence[0]).toMatchObject({ - resultKind: 'canonical', - financialEngine: 'rust', - strategyVersionId: version.id, - datasetHash: result.request.datasetHash, - }); - await expect( - f.service.createArtifact(p.id, { ...noteInput, evidence: [reference(run.id)] }, 'operator') - ).rejects.toThrow(); - await expect( - f.service.createArtifact( - p.id, - { - ...noteInput, - evidence: [ - { ...canonicalReference('analytics.fillCount'), strategyVersionId: randomUUID() }, - ], - }, - 'operator' - ) - ).rejects.toThrow(); - expect((await f.pool.query('SELECT * FROM analysis_artifacts')).rowCount).toBe(1); - }); - - test('evidence failures and cross-project links reject atomically; incomplete runs cannot become evidence', async () => { - const f = await fixture(); - const p = await f.service.createProject({ title: 'One' }, 'operator'); - const other = await f.service.createProject({ title: 'Two' }, 'operator'); - const h = await f.service.createHypothesis(other.id, hypothesisInput, 'operator'); - await expect( - f.service.createArtifact( - p.id, - { ...noteInput, hypothesisRevisionId: h.latestRevision.id }, - 'operator' - ) - ).rejects.toThrow('this project'); - await expect( - f.service.createArtifact(p.id, { ...noteInput, kind: 'finding' }, 'operator') - ).rejects.toThrow('at least one'); - for (const status of ['pending', 'running', 'failed', 'cancelled']) { - const { run } = await f.legacy(status); - await expect( - f.service.createArtifact(p.id, { ...noteInput, evidence: [reference(run.id)] }, 'operator') - ).rejects.toThrow(); - } - const { run, definition } = await f.legacy(); - const missingResult = await seedHistoricalRun(f.pool, f.backtests, { - backtestId: definition.id, - }); - await f.pool.query("UPDATE runs SET status='completed' WHERE id=$1", [missingResult.id]); - for (const bad of [ - reference(randomUUID()), - reference(missingResult.id), - reference(run.id, '__proto__.value'), - { ...reference(run.id), metricsVersion: 'unknown/v1' }, - { ...reference(run.id), strategyVersionId: randomUUID() }, - ]) { - await expect( - f.service.createArtifact(p.id, { ...noteInput, evidence: [bad] }, 'operator') - ).rejects.toThrow(); - } - await expect( - f.service.createArtifact( - p.id, - { ...noteInput, evidence: [reference(run.id), reference(run.id)] }, - 'operator' - ) - ).rejects.toThrow('Duplicate'); - expect((await f.pool.query('SELECT * FROM analysis_artifacts')).rowCount).toBe(0); - expect((await f.pool.query('SELECT * FROM analysis_artifact_revisions')).rowCount).toBe(0); - expect((await f.pool.query('SELECT * FROM analysis_evidence')).rowCount).toBe(0); - }); - - test('evidence_fk_integrity and immutable history guards survive direct SQL and after-commit insertion attempts', async () => { - const f = await fixture(); - const { run } = await f.legacy(); - const p = await f.service.createProject({ title: 'Retained' }, 'operator'); - const h = await f.service.createHypothesis(p.id, hypothesisInput, 'operator'); - const finding = await f.service.createArtifact( - p.id, - { ...noteInput, kind: 'finding', evidence: [reference(run.id)] }, - 'operator' - ); - const rev = finding.latestRevision.id; - for (const query of [ - "UPDATE research_hypothesis_revisions SET proposition='rewritten'", - 'DELETE FROM research_hypothesis_revisions', - "UPDATE analysis_artifact_revisions SET body='rewritten'", - 'DELETE FROM analysis_artifact_revisions', - "UPDATE analysis_evidence SET metric_path='metrics.winRate'", - 'DELETE FROM analysis_evidence', - 'TRUNCATE analysis_evidence', - 'TRUNCATE research_projects CASCADE', - 'DELETE FROM research_projects', - 'DELETE FROM research_hypotheses', - 'DELETE FROM analysis_artifacts', - "UPDATE analysis_artifacts SET kind='note'", - "UPDATE research_hypotheses SET owner_principal='service'", - ]) { - await expect(f.pool.query(query)).rejects.toThrow(); - } - await expect( - f.pool.query( - 'INSERT INTO analysis_evidence(revision_id,ordinal,run_id,metrics_version,metric_path) VALUES($1,2,$2,$3,$4)', - [rev, run.id, 'legacy-display/v1', 'metrics.winRate'] - ) - ).rejects.toThrow('atomically'); - await expect( - f.postgres.transaction(async client => { - const id = randomUUID(); - await client.query( - 'INSERT INTO analysis_artifact_revisions(id,artifact_id,ordinal,title,body,submitted_by,content_origin) VALUES($1,$2,2,$3,$4,$5,$6)', - [id, finding.id, 'Invalid reference', '', 'operator', 'human'] - ); - await client.query( - 'INSERT INTO analysis_evidence(revision_id,ordinal,run_id,metrics_version,metric_path) VALUES($1,1,$2,$3,$4)', - [id, randomUUID(), 'legacy-display/v1', 'metrics.winRate'] - ); - }) - ).rejects.toThrow('completed retained result'); - await expect( - f.pool.query( - 'INSERT INTO analysis_artifact_revisions(id,artifact_id,ordinal,title,body,submitted_by,content_origin) VALUES($1,$2,2,$3,$4,$5,$6)', - [randomUUID(), finding.id, 'Empty finding', '', 'operator', 'human'] - ) - ).rejects.toThrow('requires retained evidence'); - const fk = ( - await f.pool.query( - "SELECT pg_get_constraintdef(oid) AS definition FROM pg_constraint WHERE conrelid='analysis_evidence'::regclass AND contype='f'" - ) - ).rows.map(row => row.definition); - expect( - fk.some(value => value.includes('REFERENCES backtest_results(run_id) ON DELETE RESTRICT')) - ).toBe(true); - expect(await f.service.listHypothesisRevisions(h.id)).toHaveLength(1); - expect(await f.service.listArtifactRevisions(finding.id)).toHaveLength(1); - expect((await f.service.getArtifact(finding.id)).latestRevision).toEqual( - finding.latestRevision - ); - }); - - test('concurrent revisions use optimistic identity and archive waits on the same project lock', async () => { - const f = await fixture(); - const p = await f.service.createProject({ title: 'Concurrency' }, 'operator'); - const h = await f.service.createHypothesis(p.id, hypothesisInput, 'operator'); - const outcomes = await Promise.allSettled( - [1, 2].map(i => - f.service.reviseHypothesis( - h.id, - { ...hypothesisInput, expectedRevision: 1, proposition: `Claim ${i}` }, - 'operator' - ) - ) - ); - expect(outcomes.filter(o => o.status === 'fulfilled')).toHaveLength(1); - expect(outcomes.filter(o => o.status === 'rejected')).toHaveLength(1); - expect(await f.service.listHypothesisRevisions(h.id)).toHaveLength(2); - const n = await f.service.createArtifact(p.id, noteInput, 'operator'); - const edits = await Promise.allSettled( - [1, 2].map(i => - f.service.reviseArtifact( - n.id, - { title: 'Note', body: `Narrative ${i}`, expectedRevision: 1 }, - 'operator' - ) - ) - ); - expect(edits.filter(o => o.status === 'fulfilled')).toHaveLength(1); - expect(edits.filter(o => o.status === 'rejected')).toHaveLength(1); - expect(await f.service.listArtifactRevisions(n.id)).toHaveLength(2); - const held = await f.pool.connect(); - await held.query('BEGIN'); - await held.query('SELECT id FROM research_projects WHERE id=$1 FOR UPDATE', [p.id]); - const archive = f.service.updateProject( - p.id, - { expectedRevision: 1, archived: true }, - 'operator' - ); - const waiters = async (count: number) => { - const deadline = Date.now() + 5000; - while (Date.now() < deadline) { - const q = await f.pool.query( - "SELECT count(*)::int AS count FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock'", - [f.schema] - ); - if (q.rows[0].count >= count) { - return; - } - await Bun.sleep(10); - } - throw new Error('Expected project lock waiter'); - }; - try { - await waiters(1); - const revision = f.service - .reviseArtifact(n.id, { title: 'After archive', body: '', expectedRevision: 2 }, 'operator') - .then( - value => ({ value }), - error => ({ error }) - ); - await waiters(2); - await held.query('COMMIT'); - expect((await archive).archived).toBe(true); - const result = await revision; - expect('error' in result).toBe(true); - if ('error' in result) { - expect(String(result.error)).toContain('Project is archived'); - } - expect(await f.service.listArtifactRevisions(n.id)).toHaveLength(2); - } finally { - await held.query('ROLLBACK'); - held.release(); - } - }); - - test('migration upgrade and reapply preserve existing canonical and legacy runs/results byte-for-byte', async () => { - const f = await fixture(false); - const legacy = await f.legacy(); - const canonical = await f.canonical(); - const snapshot = async () => ({ - runs: (await f.pool.query('SELECT * FROM runs ORDER BY id')).rows, - results: (await f.pool.query('SELECT * FROM backtest_results ORDER BY run_id')).rows, - datasets: (await f.pool.query('SELECT * FROM backtest_datasets ORDER BY hash')).rows, - versions: (await f.pool.query('SELECT * FROM strategy_versions ORDER BY id')).rows, - }); - const before = await snapshot(); - await f.pool.query(migration); - await f.pool.query(migration); - expect(await snapshot()).toEqual(before); - // Current service writes include optional source identity; historical SQL20 assertions above stay scoped. - await f.pool.query(sql('27-research-evidence-sources.sql')); - const p = await f.service.createProject({ title: 'After upgrade' }, 'operator'); - const finding = await f.service.createArtifact( - p.id, - { - ...noteInput, - kind: 'finding', - evidence: [ - reference(legacy.run.id), - { - runId: canonical.run.id, - metricsVersion: 'canonical-analytics/v1', - metricPath: 'analytics.fillCount', - }, - ], - }, - 'operator' - ); - await f.pool.query(migration); - expect(await snapshot()).toEqual(before); - expect( - (await f.service.getArtifact(finding.id)).latestRevision.evidence.map(e => e.resultKind) - ).toEqual(['legacy', 'canonical']); - }); -}); diff --git a/test/postgres/run-reproduction.test.ts b/test/postgres/run-reproduction.test.ts deleted file mode 100644 index f46ab67c..00000000 --- a/test/postgres/run-reproduction.test.ts +++ /dev/null @@ -1,614 +0,0 @@ -import { 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 { getLogger, setLoggerConfig } from '@stock-bot/logger'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import type { - CanonicalRunRequest, - CanonicalRunResult, -} from '@stock-bot/stock-config/canonical-research'; -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 { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes'; -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 '../fixtures/canonical-research'; -import { canonicalSmaFixture } from '../fixtures/canonical-sma'; -import { seedHistoricalRun } from '../fixtures/historical-run'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('run-reproduction'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const cleanup: (() => Promise)[] = []; -let packages: ReturnType | undefined; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); -async function fixture(poolMax = 4, withReproduction = true) { - const dataset = canonicalSmaFixture().dataset; - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Disposable safety database required'); - } - const schema = 'stock_bot_safety_reproduce_' + randomUUID().replaceAll('-', ''); - const admin = new Pool({ connectionString: url }); - await admin.query(`CREATE SCHEMA ${schema}`); - const pool = new Pool({ - connectionString: url, - application_name: schema, - max: poolMax, - options: `-c search_path=${schema} -c statement_timeout=10000`, - }); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - for (const name of [ - '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', - ...(withReproduction - ? [ - '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') - ); - } - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, - logger - ); - Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); - Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); - const container = { postgres, logger }; - const api = new BacktestServiceV2(container); - const catalog = new StrategyCatalogService(container); - const pkg = (await (packages ??= packageBuiltinStrategies()))[0]!; - const version = await catalog.seedBuiltin('Retained SMA', pkg, 'seed'); - await retainResearchDataset(pool, dataset); - const definition = { - name: 'Canonical API', - strategy: 'catalog', - strategyVersionId: version.id, - strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, - symbols: dataset.manifest.executionSeries.map(s => s.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 }); - const approve = async () => { - await catalog.reviewVersion( - version.id, - { decision: 'approve', reason: 'Reviewed retained builtin' }, - 'operator' - ); - return (await catalog.getVersionReviews(version.id)).at(-1)!; - }; - const execute = async (id: string) => { - const engine = new RustBacktestAdapter({ - logger, - }); - const runner = new BacktestRunner({ - engine, - repository: new PostgresBacktestRunRepository(postgres), - logger, - }); - try { - await runner.runQueued(id); - } finally { - await runner.shutdown(); - } - }; - return { - pool, - schema, - api, - catalog, - pkg, - version, - draft, - definition, - dataset, - approve, - execute, - app: new Hono().route('/', createBacktestV2Routes(container)), - }; -} - -const receipt = (key: string = randomUUID()) => ({ principal: 'operator' as const, key }); -async function completed(f: Awaited>) { - await f.approve(); - const run = await f.api.createRun({ backtestId: f.draft.id }); - await f.execute(run.id); - const result = await f.api.getRunResults(run.id); - if (!result || !('kind' in result)) { - throw new Error('Expected real canonical result'); - } - return { run, result }; -} -function copied(request: CanonicalRunRequest, id: string, reviewId = request.strategy.reviewId) { - const snapshot = structuredClone(request); - snapshot.runId = id; - snapshot.policy.matching.risk.ledger.sessionId = id; - snapshot.policy.matching.risk.ledger.accountId = `research:${id}`; - snapshot.strategy.reviewId = reviewId; - return snapshot; -} -async function insertCopy( - f: Awaited>, - sourceId: string, - snapshot: CanonicalRunRequest, - parent = f.draft.id -) { - return f.pool.query( - `INSERT INTO runs - (id,backtest_id,run_number,status,speed_multiplier,request_snapshot,dataset_hash,original_run_id, - submission_principal,submission_key,submission_hash) - SELECT $1,$2,COALESCE(MAX(run_number),0)+1,'pending',NULL,$3,$4,$5,'operator',$6,$7 - FROM runs WHERE backtest_id=$2 RETURNING *`, - [snapshot.runId, parent, snapshot, snapshot.datasetHash, sourceId, randomUUID(), 'a'.repeat(64)] - ); -} - -describe.skipIf(!url)('retained original-run reproduction', () => { - test('reproduce_after_template_provider_change: original executable/input identities and economic_hash_parity survive another selected version', async () => { - const f = await fixture(1); - const { run, result } = await completed(f); - const originalRows = ( - await f.pool.query('SELECT * FROM backtest_results WHERE run_id=$1', [run.id]) - ).rows; - const otherPackage = (await (packages ??= packageBuiltinStrategies()))[1]!; - const otherVersion = await f.catalog.seedBuiltin( - 'Other current template', - otherPackage, - 'other' - ); - await f.api.updateBacktest(f.draft.id, { - name: 'New template name', - strategyVersionId: otherVersion.id, - strategyParameters: { - lookbackPeriod: 2, - trendPeriod: 3, - momentumPeriod: 1, - volatilityPeriod: 2, - entryZScore: 1, - exitZScore: 0.1, - minTrendReturn: -0.5, - minMomentumReturn: -0.5, - maxVolatility: 1, - minNotionalVolume: '0', - regimeFilter: 'none', - }, - initialCapital: 12000, - config: { ...f.definition.config, canonical: { ...canonicalSettings, feeRate: '0.02' } }, - }); - await f.catalog.reviewVersion( - f.version.id, - { decision: 'revoke', reason: 'Require new review' }, - 'operator' - ); - const approval = await f.approve(); - expect(approval.id).not.toBe(result.request.strategy.reviewId); - const preview = await f.api.getReproductionPreview(run.id); - expect(preview.available).toBe(true); - expect(preview.request).toEqual(result.request); - expect(preview.currentReviewId).toBe(approval.id); - expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1); - const key = receipt(); - const reproduced = await f.api.reproduceRun(run.id, key); - expect(reproduced.originalRunId).toBe(run.id); - expect(reproduced.id).not.toBe(run.id); - expect(reproduced.backtestId).toBe(run.backtestId); - expect((await f.api.getReproductionComparison(reproduced.id)).status).toBe('pending'); - const admitted = ( - await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [reproduced.id]) - ).rows[0].request_snapshot; - expect(admitted).toEqual(copied(result.request, reproduced.id, approval.id)); - // Storage is a provider-read failure fixture; both jobs must use the retained bytes. - await f.execute(reproduced.id); - const repeated = (await f.api.getRunResults(reproduced.id)) as CanonicalRunResult; - expect(String(repeated.financial.projection.valuation.equity)).toBe('9969.30000000'); - expect(String(repeated.financial.projection.valuation.fees)).toBe('0.70000000'); - expect(repeated.financial.projection.fills).toEqual(result.financial.projection.fills); - const comparison = await f.api.getReproductionComparison(reproduced.id); - expect(comparison.status).toBe('match'); - expect(comparison.originalHash).toMatch(/^[a-f0-9]{64}$/); - expect(comparison.reproducedHash).toBe(comparison.originalHash); - expect(await f.api.getRunResults(run.id)).toEqual(result); - expect( - (await f.pool.query('SELECT * FROM backtest_results WHERE run_id=$1', [run.id])).rows - ).toEqual(originalRows); - expect((await f.api.getBacktest(f.draft.id))?.strategyVersionId).toBe(otherVersion.id); - expect((await f.api.getReproductionComparison(run.id)).status).toBe('not-reproduction'); - // Accepted receipts survive later eligibility changes; no second dispatch is admitted. - await f.catalog.reviewVersion( - f.version.id, - { decision: 'revoke', reason: 'No new work' }, - 'operator' - ); - await f.catalog.updateStrategy(f.version.strategyId, { archived: true }, 'operator'); - await f.api.archiveBacktest(f.draft.id, true); - expect((await f.api.reproduceRun(run.id, key)).id).toBe(reproduced.id); - expect((await f.api.getReproductionPreview(run.id)).available).toBe(false); - await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow('archived'); - await f.api.archiveBacktest(f.draft.id, false); - await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow('family is archived'); - await f.catalog.updateStrategy(f.version.strategyId, { archived: false }, 'operator'); - await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow( - 'current operator approval' - ); - expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(2); - }); - - test('comparison reports economic differences without tolerances or rewriting the original', async () => { - const f = await fixture(); - const { run, result } = await completed(f); - const copy = await f.api.reproduceRun(run.id, receipt()); - await f.execute(copy.id); - const first = await f.api.getReproductionComparison(copy.id); - expect(first.status).toBe('match'); - const changed = structuredClone(await f.api.getRunResults(copy.id)) as CanonicalRunResult; - changed.financial.view.risk.dailyHalted = !changed.financial.view.risk.dailyHalted; - // Simulate divergent valid financial diagnostics in this disposable result only. - await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER'); - await f.pool.query('UPDATE backtest_results SET canonical_result=$1 WHERE run_id=$2', [ - changed, - copy.id, - ]); - const mismatch = await f.api.getReproductionComparison(copy.id); - expect(mismatch.status).toBe('mismatch'); - expect(mismatch.originalHash).toBe(first.originalHash); - expect(mismatch.reproducedHash).not.toBe(mismatch.originalHash); - expect(await f.api.getRunResults(run.id)).toEqual(result); - }); - - test('concurrent duplicate receipts are one run/outbox and operations or original identities never alias', async () => { - const f = await fixture(); - const { run } = await completed(f); - const key = receipt('simultaneous'); - const copies = await Promise.all( - Array.from({ length: 5 }, () => f.api.reproduceRun(run.id, key)) - ); - expect(new Set(copies.map(copy => copy.id)).size).toBe(1); - expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(2); - expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(2); - await expect(f.api.createRun({ backtestId: f.draft.id }, key)).rejects.toThrow( - 'different run request' - ); - await expect(f.api.reproduceRun(randomUUID(), key)).rejects.toThrow('different run request'); - const ordinaryKey = receipt('ordinary'); - await f.api.createRun({ backtestId: f.draft.id }, ordinaryKey); - await expect(f.api.reproduceRun(run.id, ordinaryKey)).rejects.toThrow('different run request'); - const other = await f.api.createBacktest( - { ...f.definition, name: 'Second template' }, - { autoStart: false } - ); - const second = await f.api.createRun({ backtestId: other.id }); - await f.execute(second.id); - const racingKey = receipt('cross-parent'); - const racers = await Promise.allSettled([ - f.api.reproduceRun(run.id, racingKey), - f.api.reproduceRun(second.id, racingKey), - ]); - expect(racers.filter(value => value.status === 'fulfilled')).toHaveLength(1); - expect(racers.filter(value => value.status === 'rejected')).toHaveLength(1); - expect( - (await f.pool.query('SELECT * FROM runs WHERE submission_key=$1', [racingKey.key])).rowCount - ).toBe(1); - }); - - test('SQL copy guard rejects altered economics, cross-parent sources, missing receipts and rewritten lineage', async () => { - const f = await fixture(); - const { run, result } = await completed(f); - for (const mutation of [ - (value: CanonicalRunRequest) => { - value.name = 'Rewritten'; - }, - (value: CanonicalRunRequest) => { - value.strategy.selection.parameters = { fastPeriod: 6, slowPeriod: 7 }; - }, - (value: CanonicalRunRequest) => { - value.policy.matching.risk.feeRate = - '0.00000000' as typeof value.policy.matching.risk.feeRate; - }, - (value: CanonicalRunRequest) => { - value.strategy.reviewId = randomUUID(); - }, - (value: CanonicalRunRequest) => { - value.build.workerSha256 = 'b'.repeat(64); - }, - (value: CanonicalRunRequest) => { - value.policy.matching.risk.ledger.accountId = 'wrong'; - }, - ]) { - const snapshot = copied(result.request, randomUUID()); - mutation(snapshot); - await expect(insertCopy(f, run.id, snapshot)).rejects.toThrow( - 'preserve the original frozen request' - ); - } - const other = await f.api.createBacktest( - { ...f.definition, name: 'Other parent' }, - { autoStart: false } - ); - await expect( - insertCopy(f, run.id, copied(result.request, randomUUID()), other.id) - ).rejects.toThrow('same backtest'); - const id = randomUUID(); - await expect(insertCopy(f, id, copied(result.request, id))).rejects.toThrow( - 'completed canonical source' - ); - const accepted = await f.api.reproduceRun(run.id, receipt()); - await expect( - f.pool.query('UPDATE runs SET original_run_id=NULL WHERE id=$1', [accepted.id]) - ).rejects.toThrow('immutable'); - await expect( - f.pool.query('UPDATE runs SET original_run_id=$1 WHERE id=$2', [accepted.id, run.id]) - ).rejects.toThrow('immutable'); - await expect( - f.pool.query('UPDATE runs SET request_snapshot=$1 WHERE id=$2', [{}, accepted.id]) - ).rejects.toThrow('immutable'); - const direct = copied(result.request, randomUUID()); - await expect( - f.pool.query( - `INSERT INTO runs(id,backtest_id,run_number,status,request_snapshot,dataset_hash,original_run_id) - VALUES($1,$2,100,'pending',$3,$4,$5)`, - [direct.runId, f.draft.id, direct, direct.datasetHash, run.id] - ) - ).rejects.toThrow('submission receipt'); - // Reapplying migration keeps all source/result/receipt rows and lineage unchanged. - const before = (await f.pool.query('SELECT * FROM runs ORDER BY run_number')).rows; - await f.pool.query( - readFileSync( - new URL('../../database/postgres/init/21-run-reproduction.sql', import.meta.url), - 'utf8' - ) - ); - expect((await f.pool.query('SELECT * FROM runs ORDER BY run_number')).rows).toEqual(before); - expect(await f.api.getRunResults(run.id)).toEqual(result); - await f.api.cancelRun(accepted.id); - expect((await f.api.getReproductionComparison(accepted.id)).status).toBe('unavailable'); - expect((await f.api.getReproductionComparison(accepted.id)).originalHash).toBeNull(); - }); - - test('missing_original_artifact and corrupt retained dataset fail without admission or provider fallback', async () => { - const f = await fixture(); - const { run, result } = await completed(f); - await f.pool.query('ALTER TABLE strategy_versions DISABLE TRIGGER USER'); - const broken = structuredClone(f.pkg); - broken.artifact.content += '\n// damaged retained bytes'; - await f.pool.query('UPDATE strategy_versions SET envelope=$1 WHERE id=$2', [ - broken, - f.version.id, - ]); - const unavailable = await f.api.getReproductionPreview(run.id); - expect(unavailable.available).toBe(false); - expect(unavailable.reason).toContain('hash mismatch'); - await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow('hash mismatch'); - await f.pool.query('UPDATE strategy_versions SET envelope=$1 WHERE id=$2', [ - f.pkg, - f.version.id, - ]); - await f.pool.query('ALTER TABLE strategy_versions ENABLE TRIGGER USER'); - await f.pool.query('ALTER TABLE backtest_datasets DISABLE TRIGGER USER'); - const badDataset = { - ...f.dataset, - bars: f.dataset.bars.map((bar, index) => - index === 0 ? { ...bar, close: bar.close + 1 } : bar - ), - }; - await f.pool.query('UPDATE backtest_datasets SET payload=$1 WHERE hash=$2', [ - badDataset, - f.dataset.manifest.hash, - ]); - expect((await f.api.getReproductionPreview(run.id)).available).toBe(false); - await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow('content validation'); - await f.pool.query('ALTER TABLE backtest_datasets DISABLE TRIGGER ALL'); - await f.pool.query('DELETE FROM backtest_datasets WHERE hash=$1', [f.dataset.manifest.hash]); - expect((await f.api.getReproductionPreview(run.id)).reason).toContain('not found'); - await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow('not found'); - expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1); - expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(1); - expect(await f.api.getRunResults(run.id)).toEqual(result); - }); - - test('unsupported_engine_version is explicit and accepted receipt replay survives later installed-build mismatch', async () => { - const f = await fixture(); - const { run, result } = await completed(f); - const key = receipt(); - const accepted = await f.api.reproduceRun(run.id, key); - const historical = structuredClone(result); - historical.request.build.runtimeVersion = 'historical-unsupported'; - // Simulate an older stored build in this disposable schema; never change installed binaries. - await f.pool.query('ALTER TABLE runs DISABLE TRIGGER USER'); - await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER'); - await f.pool.query('UPDATE runs SET request_snapshot=$1 WHERE id=$2', [ - historical.request, - run.id, - ]); - await f.pool.query('UPDATE backtest_results SET canonical_result=$1 WHERE run_id=$2', [ - historical, - run.id, - ]); - await f.pool.query('ALTER TABLE runs ENABLE TRIGGER USER'); - await f.pool.query('ALTER TABLE backtest_results ENABLE TRIGGER USER'); - const preview = await f.api.getReproductionPreview(run.id); - expect(preview.available).toBe(false); - expect(preview.reason).toContain('not installed'); - expect(preview.request?.build.runtimeVersion).toBe('historical-unsupported'); - await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow('not installed'); - expect((await f.api.reproduceRun(run.id, key)).id).toBe(accepted.id); - expect(await f.api.getRunResults(run.id)).toEqual(historical); - expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(2); - }); - - test('current original-family archive serializes with reproduction admission', async () => { - const f = await fixture(); - const { run } = await completed(f); - const blocker = await f.pool.connect(); - await blocker.query('BEGIN'); - await blocker.query('SELECT id FROM strategies WHERE id=$1 FOR UPDATE', [f.version.strategyId]); - let settled = false; - const pending = f.api.reproduceRun(run.id, receipt()).finally(() => { - settled = true; - }); - const outcome = pending.then( - value => ({ value, error: null }), - error => ({ value: null, error }) - ); - try { - for (let attempt = 0; attempt < 200; attempt++) { - const waiters = await f.pool.query( - `SELECT count(*)::int AS count FROM pg_stat_activity - WHERE application_name=$1 AND wait_event_type='Lock' AND query LIKE '%FOR UPDATE OF s%'`, - [f.schema] - ); - if (waiters.rows[0].count > 0) { - break; - } - if (attempt === 199) { - throw new Error('Reproduction did not wait on original-family lock'); - } - await new Promise(resolve => setTimeout(resolve, 5)); - } - expect(settled).toBe(false); - await blocker.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [ - f.version.strategyId, - ]); - await blocker.query('COMMIT'); - expect((await outcome).error?.message).toContain('family is archived'); - expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1); - } finally { - await blocker.query('ROLLBACK'); - blocker.release(); - } - }); - - test('first SQL21 upgrade preserves existing results, snapshots, receipts and active lease state', async () => { - const f = await fixture(4, false); - const { run, result } = await completed(f); - const key = receipt('pre-upgrade'); - const active = await f.api.createRun({ backtestId: f.draft.id }, key); - await f.pool.query( - `UPDATE runs SET status='running',attempt_number=2,attempt_id=$1, - lease_expires_at=NOW()+INTERVAL '1 hour',progress=25 WHERE id=$2`, - [randomUUID(), active.id] - ); - const before = (await f.pool.query('SELECT * FROM runs ORDER BY run_number')).rows; - const dispatch = (await f.pool.query('SELECT * FROM backtest_dispatch ORDER BY run_id')).rows; - await f.pool.query( - readFileSync( - new URL('../../database/postgres/init/21-run-reproduction.sql', import.meta.url), - 'utf8' - ) - ); - const after = (await f.pool.query('SELECT * FROM runs ORDER BY run_number')).rows; - expect( - after.map(({ original_run_id, ...row }) => { - expect(original_run_id).toBeNull(); - return row; - }) - ).toEqual(before); - expect((await f.pool.query('SELECT * FROM backtest_dispatch ORDER BY run_id')).rows).toEqual( - dispatch - ); - expect((await f.api.createRun({ backtestId: f.draft.id }, key)).id).toBe(active.id); - expect(await f.api.getRunResults(run.id)).toEqual(result); - const copy = await f.api.reproduceRun(run.id, receipt()); - await f.execute(copy.id); - expect((await f.api.getReproductionComparison(copy.id)).status).toBe('match'); - }); - - test('corrupt retained canonical request or result is a sanitized server failure, never a valid preview or input400', async () => { - const f = await fixture(); - const { run, result } = await completed(f); - await f.pool.query('ALTER TABLE runs DISABLE TRIGGER USER'); - // A valid but different SQL snapshot must not be replaced by the embedded request. - await f.pool.query('UPDATE runs SET request_snapshot=$1 WHERE id=$2', [ - { ...result.request, name: 'Different trusted snapshot' }, - run.id, - ]); - await expect(f.api.getRunResults(run.id)).rejects.toThrow('does not match'); - await f.pool.query('UPDATE runs SET request_snapshot=NULL WHERE id=$1', [run.id]); - await expect(f.api.getRunResults(run.id)).rejects.toThrow(); - await f.pool.query('UPDATE runs SET request_snapshot=$1 WHERE id=$2', [ - { ...result.request, policy: {} }, - run.id, - ]); - const response = await f.app.request(`/api/v2/runs/${run.id}/reproduction`); - expect(response.status).toBe(500); - expect(await response.json()).toEqual({ error: 'Could not inspect original run reproduction' }); - await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow(); - await f.pool.query('UPDATE runs SET request_snapshot=$1 WHERE id=$2', [result.request, run.id]); - await f.pool.query('ALTER TABLE runs ENABLE TRIGGER USER'); - await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER'); - const corrupt = structuredClone(result); - corrupt.analytics.metrics.totalReturn = 99; - await f.pool.query('UPDATE backtest_results SET canonical_result=$1 WHERE run_id=$2', [ - corrupt, - run.id, - ]); - expect((await f.app.request(`/api/v2/runs/${run.id}/reproduction`)).status).toBe(500); - await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow('does not match'); - expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1); - expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(1); - }); - - test('incomplete, missing and legacy source inputs are explicit unavailable states', async () => { - const f = await fixture(); - await f.approve(); - const run = await f.api.createRun({ backtestId: f.draft.id }); - expect((await f.api.getReproductionPreview(run.id)).reason).toContain('completed'); - await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow('completed'); - await expect(f.api.getReproductionPreview(randomUUID())).rejects.toThrow('not found'); - await expect(f.api.getReproductionComparison(randomUUID())).rejects.toThrow('not found'); - // Legacy rows remain readable and acquire NULL lineage after additive migration. - const legacy = await f.api.createBacktest( - { - name: 'Legacy', - strategy: 'sma', - symbols: ['X0.US'], - startDate: '2024-01-01', - endDate: '2024-01-02', - initialCapital: 10000, - }, - { autoStart: false } - ); - const legacyRun = await seedHistoricalRun(f.pool, f.api, { backtestId: legacy.id }); - await f.pool.query("UPDATE runs SET status='completed' WHERE id=$1", [legacyRun.id]); - expect((await f.api.getRun(legacyRun.id))?.originalRunId).toBeNull(); - expect((await f.api.getReproductionPreview(legacyRun.id)).reason).toContain( - 'frozen canonical inputs' - ); - expect((await f.api.getReproductionComparison(legacyRun.id)).status).toBe('not-reproduction'); - }); -}); diff --git a/test/postgres/stored-dataset-preparation.test.ts b/test/postgres/stored-dataset-preparation.test.ts deleted file mode 100644 index b79d7408..00000000 --- a/test/postgres/stored-dataset-preparation.test.ts +++ /dev/null @@ -1,336 +0,0 @@ -import { 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 { getLogger, setLoggerConfig } from '@stock-bot/logger'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import type { MongoDBClient } from '@stock-bot/services'; -import type { CanonicalStoredSourcePreparation } from '@stock-bot/stock-config/canonical-research'; -import { - createDatasetV2, - validateDatasetV2, -} from '../../apps/stock/orchestrator/src/data/historical-dataset-v2'; -import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes'; -import { readCanonicalDataset } from '../../apps/stock/web-api/src/services/canonical-research.service'; -import { nativeReplayFixture } from '../fixtures/native-replay'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('stored-source-postgres'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const cleanup: Array<() => Promise> = []; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); -function at(values: readonly T[], index = 0): T { - const value = values[index]; - if (value === undefined) { - throw new Error('Missing fixture item'); - } - return value; -} -function source() { - const { dataset } = nativeReplayFixture(3); - const { calendars, series, executionSeries, bounds, universe, corporateActions } = - dataset.manifest; - const metadata = { - calendars, - series: series.map(value => ({ - ...value, - source: { provider: 'eod', revision: 'operator-declared-v1' }, - availability: 'interval-end-assumption' as const, - })), - executionSeries, - bounds, - universe, - corporateActions, - }; - const rows = dataset.bars.map(bar => ({ - symbol: 'X0', - exchange: 'US', - eodSearchCode: 'X0.US', - timestamp: bar.intervalStart / 1000, - open: bar.open, - high: bar.high, - low: bar.low, - close: bar.close, - volume: bar.volume, - })); - return { metadata, rows }; -} -async function fixture(input = source(), scopedReads = false) { - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Dedicated stock_bot_safety database required'); - } - const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; - const admin = new Pool({ connectionString: url }); - await admin.query(`CREATE SCHEMA ${schema}`); - const pool = new Pool({ - connectionString: url, - max: 4, - application_name: schema, - options: `-c search_path=${schema} -c statement_timeout=10000`, - }); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - for (const name of [ - '06-create-backtest-tables.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', - '20-research-workspace.sql', - '21-run-reproduction.sql', - '22-experiments.sql', - '23-experiment-retries.sql', - '24-chronological-validation.sql', - '25-walk-forward.sql', - '26-cost-sensitivity.sql', - '27-research-evidence-sources.sql', - ]) { - await pool.query( - readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') - ); - } - await pool.query(`INSERT INTO backtests(name,strategy,symbols,start_date,end_date,initial_capital,config) - VALUES('untouched legacy draft','sma-crossover','["A.US"]','2024-03-01','2024-04-01',1000,'{"fastPeriod":2,"slowPeriod":3}')`); - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, - logger - ); - let queryCount = 0; - Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); - Object.defineProperty(postgres, 'query', { - value: async (sql: string, values?: unknown[]) => { - queryCount++; - return pool.query(sql, values); - }, - }); - let reads = 0; - const mongodb = { - async find(_collection: string, filter: { timestamp: { $gte: number; $lt: number } }) { - reads++; - return structuredClone( - scopedReads - ? input.rows.filter( - row => row.timestamp >= filter.timestamp.$gte && row.timestamp < filter.timestamp.$lt - ) - : input.rows - ); - }, - } as unknown as MongoDBClient; - const routes = new Hono().route('/', createDatasetRoutes({ postgres, mongodb, logger })); - const post = (operation: 'stored-source' | 'preview' | 'retain', body: unknown) => - routes.request(`/api/v2/datasets/canonical/${operation}`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(body), - }); - const snapshot = async (includeDatasets = true) => { - const tables = ( - await pool.query<{ tablename: string }>( - 'SELECT tablename FROM pg_tables WHERE schemaname=$1 ORDER BY tablename', - [schema] - ) - ).rows; - const rows: Record = {}; - for (const { tablename } of tables) { - if (includeDatasets || tablename !== 'backtest_datasets') { - rows[tablename] = ( - await pool.query( - `SELECT to_jsonb(t) AS row FROM "${tablename}" t ORDER BY to_jsonb(t)::text` - ) - ).rows; - } - } - return rows; - }; - const defaults = async () => - ( - await pool.query( - `SELECT table_name,column_name,column_default FROM information_schema.columns WHERE table_schema=$1 ORDER BY table_name,column_name`, - [schema] - ) - ).rows; - return { - input, - get reads() { - return reads; - }, - pool, - schema, - post, - routes, - snapshot, - defaults, - get queryCount() { - return queryCount; - }, - }; -} - -describe.skipIf(!url)('stored source materialization and immutable retention on PostgreSQL', () => { - test('declared sessions retain captured rows across an invalid intervening close marker without further source reads', async () => { - const input = source(); - const first = input.metadata.bounds.warmupStart; - const day = 86_400_000; - const close = first + 180_000; - const originals = structuredClone(input.rows); - input.metadata = { - ...input.metadata, - calendars: input.metadata.calendars.map(calendar => ({ - ...calendar, - endDate: '2024-01-03', - sessions: [ - { date: '2024-01-01', open: first, close }, - { date: '2024-01-02', open: first + day, close: close + day }, - ], - })), - bounds: { ...input.metadata.bounds, tradeEnd: close + day }, - corporateActions: input.metadata.corporateActions.map(coverage => ({ - ...coverage, - end: close + day, - })), - }; - input.rows = [ - ...originals, - { ...at(originals), timestamp: close / 1000, volume: -1 }, - ...originals.map(row => ({ ...row, timestamp: row.timestamp + day / 1000 })), - ]; - const f = await fixture(input, true); - const before = await f.snapshot(); - expect((await f.post('stored-source', { metadata: input.metadata })).status).toBe(500); - const response = await f.post('stored-source', { - metadata: input.metadata, - selection: 'declared-sessions', - }); - expect(response.status).toBe(200); - const captured = (await response.json()) as CanonicalStoredSourcePreparation; - expect(captured.selection).toBe('declared-sessions'); - expect(captured.input.bars).toHaveLength(6); - expect(captured.input.bars.map(bar => bar.sourceSequence)).toEqual([0, 1, 2, 3, 4, 5]); - expect(f.reads).toBe(3); - expect(await f.snapshot()).toEqual(before); - const expected = createDatasetV2(captured.input); - const retainBody = { input: captured.input, expectedHash: expected.manifest.hash }; - input.rows.splice(0); - for (let attempt = 0; attempt < 2; attempt++) { - expect((await f.post('retain', retainBody)).status).toBe(200); - } - expect(f.reads).toBe(3); - const rows = (await f.pool.query('SELECT payload FROM backtest_datasets')).rows; - expect(rows).toHaveLength(1); - expect(validateDatasetV2(at(rows).payload)).toEqual(expected); - const { backtest_datasets: _datasets, ...unchangedBefore } = before; - expect(await f.snapshot(false)).toEqual(unchangedBefore); - }); - - test('source read writes nothing; edits after capture cannot change exact retention/retry, and a fresh read has a different identity', async () => { - const f = await fixture(); - const before = await f.snapshot(), - defaults = await f.defaults(); - const initial = await f.post('stored-source', { metadata: f.input.metadata }); - expect(initial.status).toBe(200); - expect(initial.headers.get('Cache-Control')).toBe('no-store'); - const captured = (await initial.json()) as CanonicalStoredSourcePreparation; - expect(f.reads).toBe(1); - expect(f.queryCount).toBe(0); - expect(await f.snapshot()).toEqual(before); - expect(captured.preparation.hash).toBe(createDatasetV2(captured.input).manifest.hash); - at(f.input.rows).close = 10.5; - const newer = await f.post('stored-source', { metadata: f.input.metadata }); - expect(newer.status).toBe(200); - const refreshed = (await newer.json()) as CanonicalStoredSourcePreparation; - expect(f.reads).toBe(2); - expect(refreshed.preparation.hash).not.toBe(captured.preparation.hash); - expect(at(refreshed.input.bars).close).toBe(10.5); - expect(at(captured.input.bars).close).toBe(11); - expect(await f.snapshot()).toEqual(before); - const retainBody = { input: captured.input, expectedHash: captured.preparation.hash }; - for (const response of await Promise.all([ - f.post('retain', retainBody), - f.post('retain', retainBody), - ])) { - expect(response.status).toBe(200); - expect(await response.json()).toEqual({ preparation: captured.preparation }); - } - const rows = (await f.pool.query('SELECT * FROM backtest_datasets')).rows; - expect(rows).toHaveLength(1); - const saved = validateDatasetV2(at(rows).payload); - expect(saved).toEqual(createDatasetV2(captured.input)); - expect(saved.manifest.hash).toBe(captured.preparation.hash); - expect(saved.bars.every(bar => bar.vwap === null && bar.availableAt === bar.intervalEnd)).toBe( - true - ); - expect(f.reads).toBe(2); - const retry = await f.post('retain', retainBody); - expect(retry.status).toBe(200); - expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toEqual(rows); - expect(f.reads).toBe(2); - const lookup = await f.routes.request( - `/api/v2/datasets/canonical/${captured.preparation.hash}` - ); - expect((await lookup.json()).dataset).toMatchObject({ - available: true, - hash: captured.preparation.hash, - manifest: captured.preparation.manifest, - }); - expect(await readCanonicalDataset(f.pool, captured.preparation.hash)).toEqual(saved); - const { backtest_datasets: _datasets, ...untouched } = before; - expect(await f.snapshot(false)).toEqual(untouched); - expect(await f.defaults()).toEqual(defaults); - expect((await f.pool.query('SELECT count(*) AS n FROM runs')).rows).toEqual([{ n: '0' }]); - expect((await f.pool.query('SELECT count(*) AS n FROM backtest_dispatch')).rows).toEqual([ - { n: '0' }, - ]); - }); - - test('stored previews cannot bypass scope/hash validation or overwrite corrupt retained custody', async () => { - const f = await fixture(); - const initial = await f.post('stored-source', { metadata: f.input.metadata }); - const captured = (await initial.json()) as CanonicalStoredSourcePreparation; - const before = await f.snapshot(); - const wrong = { - ...f.input.metadata, - series: f.input.metadata.series.map(value => ({ - ...value, - source: { ...value.source, provider: 'auto' }, - })), - }; - expect((await f.post('stored-source', { metadata: wrong })).status).toBe(400); - expect(f.reads).toBe(1); - expect( - (await f.post('retain', { input: captured.input, expectedHash: '0'.repeat(64) })).status - ).toBe(409); - expect(await f.snapshot()).toEqual(before); - const dataset = createDatasetV2(captured.input); - const corrupt = { - ...dataset, - bars: dataset.bars.map((bar, index) => (index === 0 ? { ...bar, close: 10.5 } : bar)), - }; - expect(corrupt).not.toEqual(dataset); - await f.pool.query('INSERT INTO backtest_datasets(hash,payload) VALUES($1,$2)', [ - dataset.manifest.hash, - corrupt, - ]); - const damaged = await f.snapshot(); - const response = await f.post('retain', { - input: captured.input, - expectedHash: captured.preparation.hash, - }); - expect(response.status).toBe(500); - expect(await response.json()).toEqual({ error: 'Source dataset retention unavailable' }); - expect(await f.snapshot()).toEqual(damaged); - expect(f.reads).toBe(1); - }); -}); diff --git a/test/postgres/strategy-catalog-seed.test.ts b/test/postgres/strategy-catalog-seed.test.ts deleted file mode 100644 index c13229b7..00000000 --- a/test/postgres/strategy-catalog-seed.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { createHash, randomUUID } from 'node:crypto'; -import { readFileSync } from 'node:fs'; -import { expect, test } from 'bun:test'; -import { Pool } from 'pg'; -import { createHttpSecurity } from '@stock-bot/di'; -import { getLogger } from '@stock-bot/logger'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import { createRoutes } from '../../apps/stock/web-api/src/routes/create-routes'; -import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service'; -import { seedBuiltinCatalog } from '../../scripts/seed-builtin-strategies'; - -const url = process.env.PIPELINE_TEST_DATABASE_URL; -test('trusted local seed retains real bundles and exposes only reviewed catalog operations over HTTP', async () => { - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Disposable stock_bot_safety database required'); - } - const schema = `stock_bot_safety_seed_${randomUUID().replaceAll('-', '')}`; - const admin = new Pool({ connectionString: url }); - let pool: Pool | undefined; - try { - await admin.query(`CREATE SCHEMA ${schema}`); - pool = new Pool({ connectionString: url, options: `-c search_path=${schema}` }); - await pool.query( - readFileSync( - new URL('../../database/postgres/init/16-strategy-catalog.sql', import.meta.url), - 'utf8' - ) - ); - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, - getLogger('seed-fixture') - ); - Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); - Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); - const container = { postgres, logger: getLogger('catalog-seed') }; - const service = new StrategyCatalogService(container); - const versions = await seedBuiltinCatalog(service); - expect(versions).toHaveLength(2); - expect( - versions.every(v => v.origin === 'builtin' && v.reviewStatus === 'pending' && !v.runnable) - ).toBe(true); - expect((await seedBuiltinCatalog(service)).map(v => v.id)).toEqual(versions.map(v => v.id)); - expect((await pool.query('SELECT count(*) FROM strategies')).rows[0].count).toBe('2'); - expect((await pool.query('SELECT count(*) FROM strategy_versions')).rows[0].count).toBe('2'); - const security = { - adminToken: 'operator-catalog-fixture-not-real-123456', - serviceToken: 'service-catalog-fixture-not-real-123456', - environment: 'test', - }; - const app = createRoutes(container, createHttpSecurity(security)); - const request = (path: string, body?: unknown, operator = false, key?: string) => - app.request(path, { - method: body === undefined ? 'GET' : 'POST', - headers: { - Authorization: `Bearer ${operator ? security.adminToken : security.serviceToken}`, - 'Content-Type': 'application/json', - ...(key ? { 'Idempotency-Key': key } : {}), - }, - ...(body === undefined ? {} : { body: JSON.stringify(body) }), - }); - const selected = versions.find(v => v.package.program.strategyId === 'sma_crossover')!; - const path = `/api/v2/strategy-versions/${selected.id}`; - const detail = await (await request(path)).json(); - expect(detail.version.package.artifact.content).toBeUndefined(); - expect(detail.version.package.dependencyLock.content).toBeUndefined(); - expect(detail.version.runnable).toBe(false); - const artifact = await (await request(`${path}/artifact`)).json(); - expect(createHash('sha256').update(artifact.package.artifact.content).digest('hex')).toBe( - artifact.package.artifact.sha256 - ); - const invalid = await request(`${path}/validate`, { - parameters: { fastPeriod: 20, slowPeriod: 10 }, - }); - expect(invalid.status).toBe(400); - const valid = await request(`${path}/validate`, { parameters: {} }); - expect(valid.status).toBe(200); - expect((await valid.json()).parameters).toEqual({ fastPeriod: 5, slowPeriod: 15 }); - expect( - (await request(`${path}/reviews`, { decision: 'approve', reason: 'service cannot approve' })) - .status - ).toBe(403); - const approved = await request( - `${path}/reviews`, - { decision: 'approve', reason: 'fixture operator reviewed bundle' }, - true - ); - expect(approved.status).toBe(201); - const reviewed = await approved.json(); - expect(reviewed.version.reviewStatus).toBe('approved'); - expect(reviewed.version.runnable).toBe(false); - // Even exact built-in bytes uploaded through HTTP do not self-register as trusted code. - const upload = await request( - `/api/v2/strategies/${selected.strategyId}/versions`, - { package: artifact.package }, - false, - 'candidate-copy' - ); - expect(upload.status).toBe(201); - const candidate = await upload.json(); - expect(candidate.version.origin).toBe('candidate'); - expect(candidate.version.parentVersionId).toBe(selected.id); - expect(candidate.version.reviewStatus).toBe('pending'); - expect(candidate.version.runnable).toBe(false); - const replay = await request( - `/api/v2/strategies/${selected.strategyId}/versions`, - { package: artifact.package }, - false, - 'candidate-copy' - ); - expect((await replay.json()).version.id).toBe(candidate.version.id); - } finally { - await pool?.end(); - await admin.query(`DROP SCHEMA IF EXISTS ${schema} CASCADE`); - await admin.end(); - } -}, 30000); diff --git a/test/postgres/strategy-catalog.test.ts b/test/postgres/strategy-catalog.test.ts deleted file mode 100644 index 84d4607c..00000000 --- a/test/postgres/strategy-catalog.test.ts +++ /dev/null @@ -1,532 +0,0 @@ -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 { - builtinCatalogDescriptors, - parseStrategyVersionPackage, -} from '@stock-bot/stock-config/strategy'; -import type { StrategyVersionPackage } from '@stock-bot/types'; -import { createStrategyRoutes } from '../../apps/stock/web-api/src/routes/strategies.routes'; -import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('strategy-catalog-test'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const cleanup: (() => Promise)[] = []; -const migration = readFileSync( - new URL('../../database/postgres/init/16-strategy-catalog.sql', import.meta.url), - 'utf8' -); -const tokens = { - operator: 'catalog-admin-fixture-not-a-real-secret-1234', - service: 'catalog-service-fixture-not-a-real-secret-1234', - read: 'catalog-read-fixture-not-a-real-secret-1234', -}; -const hash = (text: string) => createHash('sha256').update(text).digest('hex'); -function candidate( - content = 'throw new Error("ARTIFACT_MUST_NEVER_EXECUTE");' -): StrategyVersionPackage { - const lock = '{"lockfileVersion":1,"workspaces":{}}'; - return { - version: 1, - program: { - strategyId: 'candidate-fixture', - strategyVersion: 'v1', - apiVersion: 'canonical-ts/v1', - checkpointVersion: 'v1', - }, - artifact: { - format: 'esm-bundle/v1', - entryExport: 'createStrategy', - content, - sha256: hash(content), - }, - dependencyLock: { format: 'bun-lock/v1', content: lock, sha256: hash(lock) }, - parameterSchema: { - version: 1, - type: 'object', - additionalProperties: false, - properties: { - lookback: { type: 'integer', minimum: 1, default: 3 }, - mode: { type: 'string', enum: ['long', 'flat'] }, - }, - required: ['mode'], - }, - source: { revision: 'a'.repeat(40), dirty: false }, - build: { tool: 'bun', version: 'fixture', target: 'browser' }, - }; -} -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); -async function fixture() { - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Dedicated stock_bot_safety database required'); - } - const schema = 'stock_bot_safety_catalog_' + randomUUID().replaceAll('-', ''); - const admin = new Pool({ connectionString: url }); - await admin.query(`CREATE SCHEMA ${schema}`); - const pool = new Pool({ - connectionString: url, - application_name: schema, - options: `-c search_path=${schema} -c statement_timeout=10000`, - }); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - await pool.query(migration); - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, - logger - ); - Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); - Object.defineProperty(postgres, 'query', { configurable: true, value: pool.query.bind(pool) }); - const api = new StrategyCatalogService({ postgres, logger }); - const app = new Hono(); - createHttpSecurity({ - adminToken: tokens.operator, - serviceToken: tokens.service, - readToken: tokens.read, - environment: 'test', - }).mount(app); - app.route('/', createStrategyRoutes({ postgres, logger })); - return { - pool, - postgres, - api, - app, - request( - path: string, - role: keyof typeof tokens, - body?: unknown, - key?: string, - method = body === undefined ? 'GET' : 'POST' - ) { - return app.request(`/api/v2/${path}`, { - method, - headers: { - Authorization: `Bearer ${tokens[role]}`, - 'Content-Type': 'application/json', - ...(key ? { 'Idempotency-Key': key } : {}), - }, - ...(body === undefined ? {} : { body: JSON.stringify(body) }), - }); - }, - }; -} - -describe.skipIf(!url)('immutable strategy catalog on real PostgreSQL', () => { - test('valid UTF-8 metadata and artifact content retain exact bytes and hashes', async () => { - const f = await fixture(); - const name = 'Research πŸš€ 東京'; - const s = await f.api.createStrategy({ name }, 'service'); - const pkg = candidate('export const label = "πŸ“ˆ cafΓ©";'); - const v = await f.api.publishVersion(s.id, pkg, null, 'service', 'unicode'); - expect((await f.api.getStrategy(s.id)).name).toBe(name); - expect(await f.api.getVersionArtifact(v.id)).toEqual(pkg); - expect( - (await f.api.reviewVersion(v.id, { decision: 'approve', reason: 'Reviewed πŸ“ˆ' }, 'operator')) - .reviewStatus - ).toBe('approved'); - expect((await f.api.getVersionReviews(v.id))[0]!.reason).toBe('Reviewed πŸ“ˆ'); - }); - test('retains exact artifact bytes without execution, projects lightweight metadata and validates parameters only', async () => { - const f = await fixture(); - const s = await f.api.createStrategy({ name: 'Candidate' }, 'service'); - const pkg = candidate(); - const v = await f.api.publishVersion(s.id, pkg, null, 'service', 'publish-1'); - expect(s).toMatchObject({ ownerPrincipal: 'service', updatedBy: 'service' }); - expect( - await f.api.updateStrategy(s.id, { description: 'Operator note' }, 'operator') - ).toMatchObject({ ownerPrincipal: 'service', updatedBy: 'operator' }); - expect(v).toMatchObject({ - ordinal: 1, - createdBy: 'service', - origin: 'candidate', - reviewStatus: 'pending', - runnable: false, - }); - expect(v.reason).toContain('isolated execution declaration'); - expect(v.package.artifact).not.toHaveProperty('content'); - expect(v.package.dependencyLock).not.toHaveProperty('content'); - expect(await f.api.getVersionArtifact(v.id)).toEqual(pkg); - expect(await f.api.validateVersionParameters(v.id, { mode: 'long' })).toMatchObject({ - parameters: { mode: 'long', lookback: 3 }, - runnable: false, - }); - for (const invalid of [ - {}, - { mode: 'short' }, - { mode: 'long', lookback: 0 }, - { mode: 'long', extra: true }, - { mode: 'long', lookback: 1.5 }, - ]) { - await expect(f.api.validateVersionParameters(v.id, invalid)).rejects.toMatchObject({ - status: 400, - }); - } - const metadataQueries: string[] = []; - const realQuery = f.pool.query.bind(f.pool); - Object.defineProperty(f.postgres, 'query', { - configurable: true, - value: async (text: string, values: unknown[]) => { - metadataQueries.push(text); - const result = await realQuery(text, values); - for (const row of result.rows) { - expect(row).not.toHaveProperty('envelope'); - if (row.package) { - expect(row.package.artifact).not.toHaveProperty('content'); - } - } - return result; - }, - }); - await f.api.listVersions(s.id); - await f.api.getVersion(v.id); - expect( - metadataQueries - .filter(text => text.includes('FROM strategy_versions')) - .every(text => text.includes("#- '{artifact,content}'")) - ).toBe(true); - }); - - test('hash and schema failures are atomic, and missing references do not leave versions', async () => { - const f = await fixture(); - const s = await f.api.createStrategy({ name: 'Invalid submissions' }, 'operator'); - const badHash = candidate(); - badHash.artifact.content += '\nchanged'; - const badLock = candidate(); - badLock.dependencyLock.content += 'changed'; - const badSchema = candidate(); - badSchema.parameterSchema.required.push('missing'); - for (const [index, pkg] of [badHash, badLock, badSchema].entries()) { - await expect( - f.api.publishVersion(s.id, pkg, null, 'operator', `bad-${index}`) - ).rejects.toMatchObject({ status: 400 }); - } - await expect( - f.api.publishVersion(s.id, candidate(), randomUUID(), 'operator', 'missing-parent') - ).rejects.toMatchObject({ status: 404 }); - expect(await f.api.listVersions(s.id)).toHaveLength(0); - }); - - test('receipt replay is key-order independent, survives archive, and rejects changed intent', async () => { - const f = await fixture(); - const s = await f.api.createStrategy({ name: 'Receipts' }, 'operator'); - const pkg = candidate(); - const v = await f.api.publishVersion(s.id, pkg, null, 'operator', 'same'); - const reordered = { - ...pkg, - program: { - checkpointVersion: pkg.program.checkpointVersion, - apiVersion: pkg.program.apiVersion, - strategyVersion: pkg.program.strategyVersion, - strategyId: pkg.program.strategyId, - }, - }; - expect((await f.api.publishVersion(s.id, reordered, null, 'operator', 'same')).id).toBe(v.id); - const next = await f.api.publishVersion(s.id, pkg, null, 'operator', 'intentional-new'); - expect(next).toMatchObject({ ordinal: 2, parentVersionId: v.id }); - const fork = await f.api.publishVersion(s.id, pkg, v.id, 'operator', 'older-parent'); - expect(fork).toMatchObject({ ordinal: 3, parentVersionId: v.id }); - const foreign = await f.api.createStrategy({ name: 'Foreign parent' }, 'operator'); - await expect( - f.api.publishVersion(foreign.id, pkg, v.id, 'operator', 'cross-parent-invalid') - ).rejects.toMatchObject({ status: 400 }); - await f.api.updateStrategy(s.id, { archived: true }, 'operator'); - expect((await f.api.publishVersion(s.id, pkg, null, 'operator', 'same')).id).toBe(v.id); - await expect( - f.api.publishVersion(s.id, candidate('different'), null, 'operator', 'same') - ).rejects.toMatchObject({ status: 409 }); - await expect( - f.api.publishVersion(s.id, pkg, null, 'operator', 'new-after-archive') - ).rejects.toMatchObject({ status: 409 }); - expect(await f.api.listVersions(s.id)).toHaveLength(3); - }); - - test('parallel publication serializes ordinals and global actor receipts across strategies', async () => { - const f = await fixture(); - const s = await f.api.createStrategy({ name: 'Parallel' }, 'operator'); - const pkg = candidate(); - const repeated = await Promise.all( - Array.from({ length: 5 }, () => f.api.publishVersion(s.id, pkg, null, 'operator', 'repeat')) - ); - expect(new Set(repeated.map(v => v.id)).size).toBe(1); - const unique = await Promise.all( - Array.from({ length: 4 }, (_, index) => - f.api.publishVersion(s.id, pkg, null, 'operator', `unique-${index}`) - ) - ); - expect(unique.map(v => v.ordinal).sort()).toEqual([2, 3, 4, 5]); - const other = await f.api.createStrategy({ name: 'Other' }, 'operator'); - const conflict = await Promise.allSettled( - [s, other].map(target => - f.api.publishVersion(target.id, pkg, null, 'operator', 'cross-parent') - ) - ); - expect(conflict.filter(item => item.status === 'fulfilled')).toHaveLength(1); - expect(conflict.find(item => item.status === 'rejected')).toMatchObject({ - reason: { status: 409 }, - }); - // Different credential cohorts have independent receipt namespaces. - expect((await f.api.publishVersion(other.id, pkg, null, 'service', 'repeat')).createdBy).toBe( - 'service' - ); - }); - - test('archive row lock prevents a blocked publication from entering an archived strategy', async () => { - const f = await fixture(); - const s = await f.api.createStrategy({ name: 'Archive race' }, 'operator'); - const blocker = await f.pool.connect(); - await blocker.query('BEGIN'); - await blocker.query('SELECT id FROM strategies WHERE id=$1 FOR UPDATE', [s.id]); - const attempt = f.api.publishVersion(s.id, candidate(), null, 'operator', 'archive-race').then( - () => null, - error => error - ); - await blocker.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [s.id]); - await blocker.query('COMMIT'); - blocker.release(); - expect(await attempt).toMatchObject({ status: 409 }); - expect(await f.api.listVersions(s.id)).toEqual([]); - }); - - test('reviews are explicit human-only append-only evidence, with immutable version and lineage storage', async () => { - const f = await fixture(); - const s = await f.api.createStrategy({ name: 'Audit' }, 'operator'); - const v = await f.api.publishVersion(s.id, candidate(), null, 'operator', 'audit-version'); - await expect( - f.api.reviewVersion(v.id, { decision: 'approve', reason: 'pretend human' }, 'service') - ).rejects.toMatchObject({ status: 403 }); - expect(await f.api.getVersionReviews(v.id)).toHaveLength(0); - expect( - await f.api.reviewVersion( - v.id, - { decision: 'approve', reason: 'Reviewed retained artifact' }, - 'operator' - ) - ).toMatchObject({ reviewStatus: 'approved', runnable: false }); - expect( - await f.api.reviewVersion( - v.id, - { decision: 'revoke', reason: 'Needs further validation' }, - 'operator' - ) - ).toMatchObject({ reviewStatus: 'revoked', runnable: false }); - expect( - (await f.api.getVersionReviews(v.id)).map(event => [ - event.ordinal, - event.decision, - event.actor, - ]) - ).toEqual([ - [1, 'approve', 'operator'], - [2, 'revoke', 'operator'], - ]); - for (const query of [ - 'UPDATE strategy_versions SET ordinal=99', - 'DELETE FROM strategy_versions', - "UPDATE strategy_review_events SET reason='rewrite'", - 'DELETE FROM strategy_review_events', - 'DELETE FROM strategies', - ]) { - await expect(f.pool.query(query)).rejects.toThrow('immutable'); - } - await poolMigrationAgain(f.pool); - expect(await f.api.getVersionReviews(v.id)).toHaveLength(2); - expect(await f.api.getVersionArtifact(v.id)).toEqual(candidate()); - }); - - test('clones retain parent lineage, do not inherit approval, and retry without orphan strategies', async () => { - const f = await fixture(); - const s = await f.api.createStrategy({ name: 'Original' }, 'operator'); - const v = await f.api.publishVersion(s.id, candidate(), null, 'operator', 'source'); - await f.api.reviewVersion(v.id, { decision: 'approve', reason: 'Source reviewed' }, 'operator'); - const clones = await Promise.all( - Array.from({ length: 4 }, () => - f.api.cloneVersion(v.id, { name: 'Copy' }, 'service', 'clone') - ) - ); - expect(new Set(clones.map(item => item.strategy.id)).size).toBe(1); - expect(clones[0]!.version).toMatchObject({ - parentVersionId: v.id, - ordinal: 1, - origin: 'candidate', - reviewStatus: 'pending', - runnable: false, - }); - expect(clones[0]!.strategy.ownerPrincipal).toBe('service'); - expect(await f.api.getVersionReviews(clones[0]!.version.id)).toHaveLength(0); - expect(await f.api.listStrategies()).toHaveLength(2); - await expect( - f.api.cloneVersion(v.id, { name: 'Different copy' }, 'service', 'clone') - ).rejects.toMatchObject({ status: 409 }); - const revision = await f.api.publishVersion( - s.id, - candidate('revision'), - v.id, - 'operator', - 'revision' - ); - expect(revision.parentVersionId).toBe(v.id); - expect(revision.reviewStatus).toBe('pending'); - }); - - test('trusted builtin seeding is idempotent and never grants review or execution', async () => { - const f = await fixture(); - const descriptor = builtinCatalogDescriptors[0]!; - const base = candidate(); - const pkg = parseStrategyVersionPackage({ - ...base, - program: descriptor.program, - parameterSchema: descriptor.parameterSchema, - artifact: { ...base.artifact, entryExport: descriptor.entryExport }, - }); - const seeded = await Promise.all( - Array.from({ length: 3 }, () => f.api.seedBuiltin(descriptor.name, pkg, 'builtin-seed')) - ); - expect(new Set(seeded.map(v => v.id)).size).toBe(1); - expect(seeded[0]).toMatchObject({ - origin: 'builtin', - createdBy: 'operator', - reviewStatus: 'pending', - runnable: false, - }); - expect(seeded[0]!.reason).toContain('approve'); - expect(await f.api.listStrategies()).toHaveLength(1); - await expect(f.api.seedBuiltin('Fake builtin', candidate(), 'fake')).rejects.toMatchObject({ - status: 400, - }); - expect((await f.api.validateVersionParameters(seeded[0]!.id, {})).parameters).toMatchObject({ - fastPeriod: 5, - slowPeriod: 15, - }); - await expect( - f.api.validateVersionParameters(seeded[0]!.id, { fastPeriod: 15, slowPeriod: 5 }) - ).rejects.toMatchObject({ status: 400 }); - const first = seeded[0]!; - await f.api.reviewVersion( - first.id, - { decision: 'approve', reason: 'Reviewed first build' }, - 'operator' - ); - await f.api.updateStrategy( - first.strategyId, - { name: 'Personal SMA', description: 'Retained note' }, - 'service' - ); - const changed = structuredClone(pkg); - changed.source.revision = 'b'.repeat(40); - const updates = await Promise.all( - Array.from({ length: 3 }, () => - f.api.seedBuiltin(descriptor.name, changed, 'builtin-revision') - ) - ); - expect(new Set(updates.map(v => v.id)).size).toBe(1); - expect(updates[0]).toMatchObject({ - strategyId: first.strategyId, - ordinal: 2, - parentVersionId: first.id, - reviewStatus: 'pending', - runnable: false, - }); - expect(await f.api.getStrategy(first.strategyId)).toMatchObject({ - name: 'Personal SMA', - description: 'Retained note', - updatedBy: 'service', - }); - expect(await f.api.listStrategies()).toHaveLength(1); - await f.api.updateStrategy(first.strategyId, { archived: true }, 'operator'); - expect((await f.api.seedBuiltin(descriptor.name, pkg, 'builtin-seed')).id).toBe(first.id); - await expect( - f.api.seedBuiltin(descriptor.name, changed, 'new-after-archive') - ).rejects.toMatchObject({ status: 409 }); - }); - - test('HTTP service candidates cannot impersonate builtin authors or reviewers; readers retain artifact access', async () => { - const f = await fixture(); - const created = await f.request('strategies', 'service', { name: 'HTTP candidate' }); - expect(created.status).toBe(201); - const s = (await created.json()).strategy; - const published = await f.request( - `strategies/${s.id}/versions`, - 'service', - { package: candidate() }, - 'http-publish' - ); - expect(published.status).toBe(201); - const v = (await published.json()).version; - expect(v).toMatchObject({ - origin: 'candidate', - createdBy: 'service', - reviewStatus: 'pending', - runnable: false, - }); - expect( - ( - await f.request( - `strategies/${s.id}/versions`, - 'service', - { package: candidate(), origin: 'builtin' }, - 'forgery' - ) - ).status - ).toBe(400); - expect( - ( - await f.request(`strategy-versions/${v.id}/reviews`, 'service', { - decision: 'approve', - reason: 'forged', - actor: 'operator', - }) - ).status - ).toBe(403); - expect( - ( - await f.request(`strategy-versions/${v.id}/reviews`, 'operator', { - decision: 'approve', - reason: 'checked', - }) - ).status - ).toBe(201); - const detail = await f.request(`strategy-versions/${v.id}`, 'read'); - expect(await detail.json()).toMatchObject({ - version: { reviewStatus: 'approved', runnable: false }, - reviews: [{ ordinal: 1, actor: 'operator' }], - }); - const artifact = await f.request(`strategy-versions/${v.id}/artifact`, 'read'); - expect(await artifact.json()).toEqual({ package: candidate() }); - expect( - ( - await f.request(`strategy-versions/${v.id}/validate`, 'service', { - parameters: { mode: 'flat' }, - }) - ).status - ).toBe(200); - expect( - ( - await f.request(`strategy-versions/${v.id}/validate`, 'service', { - parameters: { mode: 'invalid' }, - }) - ).status - ).toBe(400); - expect( - (await f.request(`strategy-versions/${v.id}/artifact`, 'read')).headers.get('Cache-Control') - ).toBe('no-store'); - expect((await f.request('strategies/seed', 'operator', {})).status).toBe(404); - expect((await f.request(`strategy-versions/${randomUUID()}`, 'read')).status).toBe(404); - }); -}); - -async function poolMigrationAgain(pool: Pool) { - await pool.query(migration); -} diff --git a/test/postgres/walk-forward.test.ts b/test/postgres/walk-forward.test.ts deleted file mode 100644 index 9d66d315..00000000 --- a/test/postgres/walk-forward.test.ts +++ /dev/null @@ -1,766 +0,0 @@ -import { 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 { WalkForwardInput } from '@stock-bot/stock-config/walk-forward'; -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 { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service'; -import { ExperimentError } from '../../apps/stock/web-api/src/services/experiment-input'; -import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service'; -import { createResearchServices } from '../../apps/stock/web-api/src/services/research-services'; -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 '../fixtures/canonical-research'; -import { walkForwardDataset } from '../fixtures/walk-forward'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('chronological-validation'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const cleanup: (() => Promise)[] = []; -let packages: ReturnType | undefined; -const tokens = { - operator: 'chronological-operator-fixture-not-a-real-secret-1234', - service: 'chronological-service-fixture-not-a-real-secret-1234', -}; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); -async function fixture(poolMax = 1, withWalkForward = true) { - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Disposable safety database required'); - } - const schema = 'stock_bot_safety_validation_' + randomUUID().replaceAll('-', ''); - const admin = new Pool({ connectionString: url }); - await admin.query(`CREATE SCHEMA ${schema}`); - // A single connection detects accidental nested pool reads while the admission lock is held. - const pool = new Pool({ - connectionString: url, - application_name: schema, - max: poolMax, - options: `-c search_path=${schema} -c statement_timeout=10000`, - }); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - for (const name of [ - '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', - ...(withWalkForward ? ['25-walk-forward.sql', '26-cost-sensitivity.sql'] : []), - ]) { - await pool.query( - readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') - ); - } - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, - logger - ); - Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); - Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); - const container = { postgres, logger }, - api = new BacktestServiceV2(container), - experiments = new ExperimentsService(container), - catalog = new StrategyCatalogService(container); - const version = await catalog.seedBuiltin( - 'Validation SMA', - (await (packages ??= packageBuiltinStrategies()))[0]!, - 'seed' - ); - const data = walkForwardDataset(), - dataset = data.dataset; - await retainResearchDataset(pool, dataset); - const draft = await api.createBacktest( - { - name: 'Validation template', - strategy: 'catalog', - strategyVersionId: version.id, - strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, - symbols: ['X0.US'], - startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(), - endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(), - initialCapital: 10000, - config: { - datasetHash: dataset.manifest.hash, - dataFrequency: '1m', - canonical: canonicalSettings, - }, - }, - { autoStart: false } - ); - const input: WalkForwardInput = { - backtestId: draft.id, - name: 'Two rolling windows', - grid: { fastPeriod: [1, 2], slowPeriod: [3] }, - windows: data.windows, - }; - const app = new Hono(); - createHttpSecurity({ - adminToken: tokens.operator, - serviceToken: tokens.service, - environment: 'test', - hostname: '127.0.0.1', - }).mount(app); - app.route('/', createExperimentRoutes(container)); - const request = (raw: unknown = input, role: keyof typeof tokens = 'operator') => - app.request('/api/v2/experiments/walk-forward/preview', { - method: 'POST', - headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${tokens[role]}` }, - body: JSON.stringify(raw), - }); - const review = async (decision: 'approve' | 'revoke' = 'approve') => { - await catalog.reviewVersion( - version.id, - { decision, reason: 'Disposable validation proof' }, - 'operator' - ); - return (await catalog.getVersionReviews(version.id)).at(-1)!; - }; - const snapshot = async () => { - const tables = ( - await pool.query('SELECT tablename FROM pg_tables WHERE schemaname=$1 ORDER BY tablename', [ - schema, - ]) - ).rows; - const rows: Record = {}; - for (const { tablename } of tables) { - const quoted = '"' + String(tablename).replaceAll('"', '""') + '"'; - rows[String(tablename)] = ( - await pool.query( - `SELECT COALESCE(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text),'[]'::jsonb) AS rows FROM ${quoted} t` - ) - ).rows[0].rows; - } - return rows; - }; - const services = createResearchServices(container); - const validations = services.validations; - const repository = new PostgresBacktestRunRepository(postgres); - const execute = async (id: string) => { - const engine = new RustBacktestAdapter({ - logger, - }); - const runner = new BacktestRunner({ engine, repository, logger }); - try { - await runner.runQueued(id); - } finally { - await runner.shutdown(); - } - }; - return { - cloneTemplate: async (sourceDataset = dataset) => - api.createBacktest( - { - name: 'Other validation template', - strategy: 'catalog', - strategyVersionId: version.id, - strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, - symbols: ['X0.US'], - startDate: new Date(sourceDataset.manifest.bounds.tradeStart).toISOString(), - endDate: new Date(sourceDataset.manifest.bounds.tradeEnd).toISOString(), - initialCapital: 10000, - config: { - datasetHash: sourceDataset.manifest.hash, - dataFrequency: '1m', - canonical: canonicalSettings, - }, - }, - { autoStart: false } - ), - validations, - walks: services.walkForwards, - repository, - execute, - api, - pool, - postgres, - experiments, - catalog, - version, - draft, - dataset, - input, - request, - review, - snapshot, - }; -} - -const actor = (key = randomUUID()) => ({ principal: 'operator' as const, key }); -type Fixture = Awaited>; -async function submit(f: Fixture, input = f.input, identity = actor()) { - await f.review(); - const preview = await f.walks.preview(input), - body = { ...input, previewHash: preview.previewHash }; - return { preview, body, identity, walk: await f.walks.submit(body, identity) }; -} -async function finishWindow(f: Fixture, id: string) { - const initial = await f.validations.get(id); - for (const trial of initial.phases[0]!.experiment!.trials) { - await f.execute(trial.runId!); - } - const selected = await f.validations.select(id, { previewHash: initial.previewHash }, actor()); - for (const phase of selected.validation.phases.slice(1)) { - for (const trial of phase.experiment!.trials) { - await f.execute(trial.runId!); - } - } - return f.validations.finalize( - id, - { - previewHash: initial.previewHash, - selectionHash: selected.validation.selection!.selectionHash, - }, - actor() - ); -} -describe.skipIf(!url)('bounded walk-forward validation', () => { - test('pool1 native windows admit atomically, retain independent reports and finalize historically', async () => { - const f = await fixture(), - start = await submit(f); - expect(start.walk.windows).toHaveLength(2); - expect(start.walk.trainingRunCount).toBe(4); - expect(start.walk.plannedRunCount).toBe(8); - expect((await f.pool.query('SELECT count(*)::int AS n FROM backtest_dispatch')).rows[0].n).toBe( - 4 - ); - expect(await f.walks.submit(start.body, start.identity)).toEqual(start.walk); - await expect( - f.walks.finalize(start.walk.id, { previewHash: start.preview.previewHash }, actor()) - ).rejects.toThrow(); - for (const member of start.walk.windows) { - await finishWindow(f, member.validationId); - } - expect((await f.walks.get(start.walk.id)).actions.finalize.available).toBe(true); - await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]); - await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [ - f.version.strategyId, - ]); - const identity = actor(), - body = { previewHash: start.preview.previewHash }; - const [final, duplicate] = await Promise.all([ - f.walks.finalize(start.walk.id, body, identity), - f.walks.finalize(start.walk.id, body, identity), - ]); - expect(duplicate.receipt).toEqual(final.receipt); - await expect(f.walks.finalize(randomUUID(), body, identity)).rejects.toThrow('different'); - expect(final.walkForward.report!.segments.map(s => s.index)).toEqual([0, 1]); - expect(final.walkForward.report!.segments.map(s => s.validationId)).toEqual( - start.walk.windows.map(w => w.validationId) - ); - expect(final.walkForward.report!.reset).toBe('initial-capital-empty-positions'); - expect(final.walkForward.reportedWindowCount).toBe(2); - expect((await f.walks.list())[0]!.stage).toBe('reported'); - expect(await f.walks.finalize(start.walk.id, body, identity)).toEqual(final); - expect((await f.walks.get(start.walk.id)).report).toEqual(final.walkForward.report); - await f.walks.cancel(start.walk.id); - expect((await f.walks.finalize(start.walk.id, body, identity)).receipt).toEqual(final.receipt); - expect((await f.walks.submit(start.body, start.identity)).id).toBe(start.walk.id); - }, 60_000); -}); - -async function trainWindow(f: Fixture, id: string) { - const detail = await f.validations.get(id); - for (const trial of detail.phases[0]!.experiment!.trials) { - await f.execute(trial.runId!); - } - return f.validations.select(id, { previewHash: detail.previewHash }, actor()); -} - -describe.skipIf(!url)('walk-forward adversarial boundaries', () => { - test('first and idempotent SQL25 preserve ordinary evidence, receipts, active lease and SQL22–24 bodies', async () => { - const f = await fixture(1, false); - await f.review(); - const input = { backtestId: f.draft.id, name: 'Preserved sweep', grid: { fastPeriod: [1, 2] } }; - const preview = await f.experiments.preview(input), - ordinary = await f.experiments.submit( - { ...input, previewHash: preview.previewHash }, - actor() - ); - await f.execute(ordinary.trials[0]!.runId!); - const pending = ordinary.trials[1]!.runId!, - request = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [pending])) - .rows[0].request_snapshot; - await f.repository.startCanonical(request); - const before = await f.snapshot(), - functions = async () => - ( - await f.pool.query( - 'SELECT proname,pg_get_functiondef(oid) AS definition FROM pg_proc WHERE pronamespace=current_schema()::regnamespace ORDER BY proname' - ) - ).rows; - const priorFunctions = await functions(); - const migration = readFileSync( - new URL('../../database/postgres/init/25-walk-forward.sql', import.meta.url), - 'utf8' - ); - await f.pool.query(migration); - const after = await f.snapshot(); - delete after.research_walk_forwards; - after.research_experiments = (after.research_experiments as Record[]).map( - ({ walk_forward_id: _id, walk_forward_index: _index, ...row }) => row - ); - expect(after).toEqual(before); - expect( - (await functions()).filter(row => priorFunctions.some(p => p.proname === row.proname)) - ).toEqual(priorFunctions); - const upgraded = await f.snapshot(); - await f.pool.query(migration); - expect(await f.snapshot()).toEqual(upgraded); - expect( - (await f.pool.query('SELECT status,attempt_number FROM runs WHERE id=$1', [pending])).rows[0] - ).toMatchObject({ status: 'running', attempt_number: 1 }); - expect((await submit(f)).walk.windows).toHaveLength(2); - }, 60000); - test('failure on second root, retained slice, run, outbox or header rolls back every row and receipt', async () => { - const f = await fixture(); - await f.review(); - const preview = await f.walks.preview(f.input), - body = { ...f.input, previewHash: preview.previewHash }; - const secondHash = preview.windows[1]!.preview.partitions[0].dataset.hash; - for (const [table, condition] of [ - ['research_experiments', 'NEW.walk_forward_index=1'], - ['backtest_datasets', `NEW.hash='${secondHash}'`], - [ - 'runs', - 'EXISTS(SELECT 1 FROM research_experiments e WHERE e.id=NEW.experiment_id AND e.walk_forward_index=1)', - ], - [ - 'backtest_dispatch', - 'EXISTS(SELECT 1 FROM runs r JOIN research_experiments e ON e.id=r.experiment_id WHERE r.id=NEW.run_id AND e.walk_forward_index=1)', - ], - ['research_walk_forwards', 'TRUE'], - ]) { - await f.pool.query( - `CREATE OR REPLACE FUNCTION injected_walk_failure() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF ${condition} THEN RAISE EXCEPTION 'Injected walk failure'; END IF; RETURN NEW; END $$` - ); - await f.pool.query( - `CREATE TRIGGER injected_walk_failure BEFORE INSERT ON ${table} FOR EACH ROW EXECUTE FUNCTION injected_walk_failure()` - ); - const before = await f.snapshot(); - await expect(f.walks.submit(body, actor())).rejects.toThrow('Injected'); - expect(await f.snapshot()).toEqual(before); - await f.pool.query(`DROP TRIGGER injected_walk_failure ON ${table}`); - } - expect((await f.walks.submit(body, actor())).windows).toHaveLength(2); - }, 60000); - test('same and cross-parent submission receipts have one owner and replay before changed eligibility', async () => { - const f = await fixture(5); - await f.review(); - const preview = await f.walks.preview(f.input), - body = { ...f.input, previewHash: preview.previewHash }, - identity = actor(); - const [first, replay] = await Promise.all([ - f.walks.submit(body, identity), - f.walks.submit(body, identity), - ]); - expect(first.id).toBe(replay.id); - const other = await f.cloneTemplate(), - otherInput = { ...f.input, backtestId: other.id }, - otherPreview = await f.walks.preview(otherInput), - otherBody = { ...otherInput, previewHash: otherPreview.previewHash }, - raceActor = actor(); - const race = await Promise.allSettled([ - f.walks.submit(body, raceActor), - f.walks.submit(otherBody, raceActor), - ]); - expect(race.filter(r => r.status === 'fulfilled')).toHaveLength(1); - expect(race.filter(r => r.status === 'rejected')).toHaveLength(1); - expect( - (await f.pool.query('SELECT count(*)::int n FROM research_walk_forwards')).rows[0].n - ).toBe(2); - expect((await f.pool.query('SELECT count(*)::int n FROM runs')).rows[0].n).toBe(8); - await f.review('revoke'); - await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]); - expect((await f.walks.submit(body, identity)).id).toBe(first.id); - await expect(f.walks.submit({ ...body, name: 'Changed' }, identity)).rejects.toThrow( - 'different' - ); - await expect(f.walks.submit(body, actor())).rejects.toThrow(); - }, 60000); - test('SQL rejects mixed membership, changed header/source/order, extra or missing roots and report replacement', async () => { - const f = await fixture(), - start = await submit(f), - header = ( - await f.pool.query('SELECT * FROM research_walk_forwards WHERE id=$1', [start.walk.id]) - ).rows[0]; - const cloneHeader = async (patch: Record = {}) => { - const row = { - ...header, - id: randomUUID(), - member_ids: [randomUUID(), randomUUID()], - submission_key: randomUUID(), - ...patch, - }; - return f.pool.query( - 'INSERT INTO research_walk_forwards SELECT * FROM jsonb_populate_record(NULL::research_walk_forwards,$1)', - [row] - ); - }; - await expect(cloneHeader()).rejects.toThrow('must commit together'); - for (const patch of [ - { member_ids: [header.member_ids[0], header.member_ids[0]] }, - { preview: { ...header.preview, counts: { ...header.preview.counts, totalRuns: 4 } } }, - { - preview: { - ...header.preview, - source: { - ...header.preview.source, - input: { ...header.preview.source.input, name: 'Other source' }, - }, - }, - }, - { preview: { ...header.preview, windows: [...header.preview.windows].reverse() } }, - { preview: { ...header.preview, policy: null } }, - ]) { - await expect(cloneHeader(patch)).rejects.toThrow(); - } - for (const sql of [ - "UPDATE research_walk_forwards SET name='changed' WHERE id=$1", - 'UPDATE research_walk_forwards SET member_ids=ARRAY[]::uuid[] WHERE id=$1', - "UPDATE research_walk_forwards SET report='{}' WHERE id=$1", - 'DELETE FROM research_walk_forwards WHERE id=$1', - ]) { - await expect(f.pool.query(sql, [start.walk.id])).rejects.toThrow(); - } - await expect(f.pool.query('TRUNCATE research_walk_forwards CASCADE')).rejects.toThrow(); - const member = ( - await f.pool.query('SELECT * FROM research_experiments WHERE id=$1', [header.member_ids[0]]) - ).rows[0]; - for (const patch of [ - { walk_forward_index: null }, - { walk_forward_index: 2 }, - { walk_forward_id: null }, - { validation_phase: 'validation' }, - { - validation_manifest: { - ...member.validation_manifest, - input: { ...member.validation_manifest.input, name: 'Other' }, - }, - }, - ]) { - await expect( - f.pool.query( - 'INSERT INTO research_experiments SELECT * FROM jsonb_populate_record(NULL::research_experiments,$1)', - [{ ...member, id: randomUUID(), submission_key: randomUUID(), ...patch }] - ) - ).rejects.toThrow(); - } - await expect( - f.pool.query( - 'UPDATE research_experiments SET walk_forward_id=NULL,walk_forward_index=NULL WHERE id=$1', - [member.id] - ) - ).rejects.toThrow('immutable'); - expect((await f.walks.get(start.walk.id)).windows).toHaveLength(2); - }, 60000); - test('member cancellation stays local; direct series cancellation races select and retry without orphan work', async () => { - const f = await fixture(5), - local = await submit(f); - await f.validations.cancel(local.walk.windows[0]!.validationId); - const localDetail = await f.walks.get(local.walk.id); - expect(localDetail.cancelRequested).toBe(false); - expect(localDetail.windows[0]!.validation!.cancelRequested).toBe(true); - expect(localDetail.windows[1]!.validation!.cancelRequested).toBe(false); - await expect( - f.walks.finalize(local.walk.id, { previewHash: local.preview.previewHash }, actor()) - ).rejects.toThrow(); - const start = await submit(f), - first = start.walk.windows[0]!.validation!, - second = start.walk.windows[1]!.validation!; - for (const trial of first.phases[0]!.experiment!.trials) { - await f.execute(trial.runId!); - } - const failed = second.phases[0]!.experiment!.trials[0]!.runId!; - await f.pool.query( - "UPDATE runs SET status='failed',error='Preclaim failure',completed_at=NOW() WHERE id=$1", - [failed] - ); - const race = await Promise.allSettled([ - f.validations.select(first.id, { previewHash: first.previewHash }, actor()), - f.experiments.retryTrial( - second.id, - failed, - { expectedAttemptNumber: 0, expectedRetryCount: 0 }, - actor() - ), - f.pool.query('UPDATE research_walk_forwards SET cancel_requested=TRUE WHERE id=$1', [ - start.walk.id, - ]), - ]); - expect(race[2]!.status).toBe('fulfilled'); - for (const outcome of race.slice(0, 2)) { - if (outcome.status === 'rejected') { - expect(outcome.reason).toBeInstanceOf(ExperimentError); - expect(outcome.reason.status).toBe(409); - } - } - const detail = await f.walks.get(start.walk.id); - expect(detail.cancelRequested).toBe(true); - expect(detail.windows.every(w => w.validation!.cancelRequested)).toBe(true); - const rows = ( - await f.pool.query( - 'SELECT r.status,r.cancel_requested FROM runs r JOIN research_experiments e ON e.id=r.experiment_id WHERE e.walk_forward_id=$1 OR e.validation_parent_id=ANY($2::uuid[])', - [start.walk.id, start.walk.windows.map(w => w.validationId)] - ) - ).rows; - expect(rows.filter(r => r.status === 'cancelled').every(r => r.cancel_requested)).toBe(true); - expect(rows.filter(r => r.status === 'completed')).toHaveLength(2); - expect(rows.some(r => r.status === 'pending' || r.status === 'running')).toBe(false); - expect((await f.walks.cancel(start.walk.id)).cancelRequested).toBe(true); - await expect( - f.pool.query('UPDATE research_walk_forwards SET cancel_requested=FALSE WHERE id=$1', [ - start.walk.id, - ]) - ).rejects.toThrow('permanent'); - }, 60000); - test('only later test-price changes leave both native training scores and winners unchanged', async () => { - const f = await fixture(), - first = await submit(f), - before = []; - for (const member of first.walk.windows) { - before.push((await trainWindow(f, member.validationId)).validation.selection!); - } - const dataset = walkForwardDataset(900).dataset; - await retainResearchDataset(f.pool, dataset); - const other = await f.cloneTemplate(dataset); - const raw = { ...f.input, backtestId: other.id }, - preview = await f.walks.preview(raw), - second = await f.walks.submit({ ...raw, previewHash: preview.previewHash }, actor()); - for (const [index, member] of second.windows.entries()) { - const selected = (await trainWindow(f, member.validationId)).validation.selection!; - expect(selected.winner).toEqual(before[index]!.winner); - expect(selected.training.map(t => t.metrics)).toEqual( - before[index]!.training.map(t => t.metrics) - ); - expect(preview.windows[index]!.preview.partitions[0].dataset.hash).toBe( - first.preview.windows[index]!.preview.partitions[0].dataset.hash - ); - } - expect(preview.windows[1]!.preview.partitions[2].dataset.hash).not.toBe( - first.preview.windows[1]!.preview.partitions[2].dataset.hash - ); - expect( - ( - await f.pool.query( - "SELECT count(*)::int n FROM runs r JOIN research_experiments e ON e.id=r.experiment_id WHERE e.validation_phase IN ('validation','test') AND r.status<>'pending'" - ) - ).rows[0].n - ).toBe(0); - }, 60000); - test('all members and full retained canonical results are required even after member reports were sealed', async () => { - const f = await fixture(), - start = await submit(f); - for (const member of start.walk.windows) { - await finishWindow(f, member.validationId); - } - const body = { previewHash: start.preview.previewHash }, - last = start.walk.windows[1]!.validationId; - const root = (await f.pool.query('SELECT * FROM research_experiments WHERE id=$1', [last])) - .rows[0]; - await f.pool.query('ALTER TABLE research_experiments DISABLE TRIGGER USER'); - await f.pool.query( - 'UPDATE research_experiments SET walk_forward_id=NULL,walk_forward_index=NULL WHERE id=$1', - [last] - ); - expect((await f.walks.get(start.walk.id)).windows[1]!.status).toBe('missing'); - await expect(f.walks.finalize(start.walk.id, body, actor())).rejects.toThrow('missing'); - await f.pool.query( - 'UPDATE research_experiments SET walk_forward_id=$2,walk_forward_index=$3 WHERE id=$1', - [last, root.walk_forward_id, root.walk_forward_index] - ); - await f.pool.query('ALTER TABLE research_experiments ENABLE TRIGGER USER'); - const runId = root.validation_report.test.runId; - const result = ( - await f.pool.query('SELECT canonical_result FROM backtest_results WHERE run_id=$1', [runId]) - ).rows[0].canonical_result; - await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER'); - for (const [path, value] of [ - ['{analytics,metrics,totalReturn}', '900'], - ['{financial,view,equity}', '"900.00000000"'], - ]) { - await f.pool.query( - 'UPDATE backtest_results SET canonical_result=jsonb_set($2::jsonb,$3::text[],$4::jsonb) WHERE run_id=$1', - [runId, result, path, value] - ); - expect( - ( - await f.pool.query('SELECT canonical_result FROM backtest_results WHERE run_id=$1', [ - runId, - ]) - ).rows[0].canonical_result - ).not.toEqual(result); - await expect(f.walks.finalize(start.walk.id, body, actor())).rejects.toThrow(); - expect( - ( - await f.pool.query('SELECT report FROM research_walk_forwards WHERE id=$1', [ - start.walk.id, - ]) - ).rows[0].report - ).toBeNull(); - } - await f.pool.query('UPDATE backtest_results SET canonical_result=$2 WHERE run_id=$1', [ - runId, - result, - ]); - await f.pool.query('ALTER TABLE backtest_results ENABLE TRIGGER USER'); - const final = await f.walks.finalize(start.walk.id, body, actor()); - expect(final.walkForward.report!.segments).toHaveLength(2); - await expect( - f.pool.query( - "UPDATE research_walk_forwards SET report=jsonb_set(report,'{segments}','[]') WHERE id=$1", - [start.walk.id] - ) - ).rejects.toThrow('immutable'); - }, 60000); -}); - -describe.skipIf(!url)('walk-forward concurrent controls', () => { - test('direct cancellation passes downward while select and retry are demonstrably waiting on parent lock', async () => { - const f = await fixture(6), - start = await submit(f), - first = start.walk.windows[0]!.validation!, - second = start.walk.windows[1]!.validation!; - for (const trial of first.phases[0]!.experiment!.trials) { - await f.execute(trial.runId!); - } - const completed = async () => - ( - await f.pool.query( - 'SELECT to_jsonb(r) AS row FROM runs r WHERE experiment_id=$1 ORDER BY trial_index', - [first.id] - ) - ).rows; - const preserved = await completed(), - failed = second.phases[0]!.experiment!.trials[0]!.runId!; - await f.pool.query( - "UPDATE runs SET status='failed',error='Preclaim',completed_at=NOW() WHERE id=$1", - [failed] - ); - const blocker = await f.pool.connect(); - await blocker.query('BEGIN'); - await blocker.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [f.draft.id]); - const pending = Promise.allSettled([ - f.validations.select(first.id, { previewHash: first.previewHash }, actor()), - f.experiments.retryTrial( - second.id, - failed, - { expectedAttemptNumber: 0, expectedRetryCount: 0 }, - actor() - ), - ]); - try { - let waiting = 0; - for (let attempt = 0; attempt < 100; attempt++) { - waiting = Number( - ( - await f.pool.query( - "SELECT count(*)::int n FROM pg_stat_activity WHERE application_name=current_schema() AND wait_event_type='Lock'" - ) - ).rows[0].n - ); - if (waiting >= 2) { - break; - } - await new Promise(resolve => setTimeout(resolve, 10)); - } - expect(waiting).toBeGreaterThanOrEqual(2); - await f.pool.query('UPDATE research_walk_forwards SET cancel_requested=TRUE WHERE id=$1', [ - start.walk.id, - ]); - await blocker.query('COMMIT'); - } finally { - await blocker.query('ROLLBACK'); - blocker.release(); - } - const outcomes = await pending; - for (const outcome of outcomes) { - expect(outcome.status).toBe('rejected'); - if (outcome.status === 'rejected') { - expect(outcome.reason).toBeInstanceOf(ExperimentError); - expect(outcome.reason.status).toBe(409); - } - } - expect(await completed()).toEqual(preserved); - expect( - ( - await f.pool.query( - "SELECT count(*)::int n FROM runs r JOIN research_experiments e ON e.id=r.experiment_id WHERE e.walk_forward_id=$1 AND r.status IN ('pending','running','paused')", - [start.walk.id] - ) - ).rows[0].n - ).toBe(0); - expect( - ( - await f.pool.query( - 'SELECT count(*)::int n FROM experiment_trial_retries WHERE experiment_id=$1', - [second.id] - ) - ).rows[0].n - ).toBe(0); - }, 60000); - test('same and cross-parent finalization receipts serialize exactly once without sealing the losing series', async () => { - const f = await fixture(5), - first = await submit(f), - other = await f.cloneTemplate(); - const raw = { ...f.input, backtestId: other.id }, - preview = await f.walks.preview(raw), - second = await f.walks.submit({ ...raw, previewHash: preview.previewHash }, actor()); - for (const member of [...first.walk.windows, ...second.windows]) { - await finishWindow(f, member.validationId); - } - const identity = actor(), - race = await Promise.allSettled([ - f.walks.finalize(first.walk.id, { previewHash: first.preview.previewHash }, identity), - f.walks.finalize(second.id, { previewHash: preview.previewHash }, identity), - ]); - expect(race.filter(r => r.status === 'fulfilled')).toHaveLength(1); - expect(race.filter(r => r.status === 'rejected')).toHaveLength(1); - const winnerIndex = race[0]!.status === 'fulfilled' ? 0 : 1, - winner = winnerIndex === 0 ? first.walk : second, - loser = winnerIndex === 0 ? second : first.walk; - const rejected = race[1 - winnerIndex]!; - if (rejected.status === 'rejected') { - expect(rejected.reason).toBeInstanceOf(ExperimentError); - expect(rejected.reason.status).toBe(409); - } - expect((await f.walks.get(loser.id)).report).toBeNull(); - const body = { previewHash: winner.previewHash }, - [one, two] = await Promise.all([ - f.walks.finalize(winner.id, body, identity), - f.walks.finalize(winner.id, body, identity), - ]); - expect(one.receipt).toEqual(two.receipt); - await expect(f.walks.finalize(winner.id, body, actor())).rejects.toMatchObject({ status: 409 }); - const secondIdentity = actor(), - [three, four] = await Promise.all([ - f.walks.finalize(loser.id, { previewHash: loser.previewHash }, secondIdentity), - f.walks.finalize(loser.id, { previewHash: loser.previewHash }, secondIdentity), - ]); - expect(three.receipt).toEqual(four.receipt); - }, 60000); -});