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 { ChronologicalValidationService } from '../../apps/stock/web-api/src/services/chronological-validation.service'; 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 { WalkForwardService } from '../../apps/stock/web-api/src/services/walk-forward.service'; 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)).available).toBeTrue(); 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 walks = new WalkForwardService(f.container), validations = new ChronologicalValidationService(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); });