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 '../../apps/stock/orchestrator/src/paper/paper-deployment-custody'; import { readPaperHostIdentity } from '../../apps/stock/orchestrator/src/paper/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); });