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 { 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 { createResearchAgentRoutes } from '../../apps/stock/web-api/src/routes/research-agents.routes'; import { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes'; import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service'; import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher'; 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 { ResearchService } from '../../apps/stock/web-api/src/services/research.service'; import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service'; import { WalkForwardService } from '../../apps/stock/web-api/src/services/walk-forward.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 { walkForwardDataset } from '../fixtures/walk-forward'; 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, withAgents = true, 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_agents_' + 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', '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', ...(withAgents ? ['28-research-agents.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, storage: { async getHistoricalBars() { throw new Error('Canonical execution must never load provider data'); }, }, }); const runner = new BacktestRunner({ engine, engineName: 'native', repository: new PostgresBacktestRunRepository(postgres), logger, }); try { await runner.runQueued(id); } finally { await runner.shutdown(); } }; return { pool, postgres, container, agents: new ResearchAgentsService(container), research: new ResearchService(container), schema, api, experiments, repository, catalog, pkg, version, draft, definition, dataset, approve, execute, app: new Hono().route('/', createExperimentRoutes(container)), }; } const limits = { maxActiveTrials: 2, maxTrialsPerExperiment: 10, maxBarEvaluationsPerExperiment: 10000, maxAttemptWallMs: 60000, maxAttempts: 2, }; function required(value: T | null | undefined): T { if (value === null || value === undefined) { throw new Error('Required fixture value is missing'); } return value; } type Fixture = Awaited>; const receipt = (principal: string = 'operator', key = randomUUID()) => ({ principal, key }); async function provision(f: Fixture, overrides: Partial = {}) { await f.approve(); const project = await f.research.createProject({ title: 'Agent research' }, 'operator'); const created = await f.agents.create({ name: 'Bounded researcher', allowedProjectIds: [project.id], allowedBacktestIds: [f.draft.id], limits: { ...limits, ...overrides }, }); return { ...created, project }; } async function preparation( f: Fixture, name = 'Agent search', backtestId = f.draft.id, grid = { fastPeriod: [1, 2] } ) { const input = { backtestId, name, grid }; const preview = await f.experiments.preview(input); return { ...input, previewHash: preview.previewHash }; } async function requestFor(f: Fixture, id: string): Promise { return (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [id])).rows[0] .request_snapshot; } async function totals(f: Fixture) { return ( await f.pool.query( 'SELECT (SELECT count(*)::int FROM runs) runs,(SELECT count(*)::int FROM research_experiments) experiments,(SELECT count(*)::int FROM backtest_dispatch) dispatch' ) ).rows[0]; } function http(f: Fixture) { const app = new Hono(); const security = createHttpSecurity({ adminToken: 'operator-test-secret-12345678901234567890', serviceToken: 'service-test-secret-123456789012345678901', environment: 'test', resolveResearchCredential: request => f.agents.authenticate(request), }); security.mount(app); app.route('/', createResearchAgentRoutes(f.container, security.researchEnabled)); app.route('/', createExperimentRoutes(f.container)); app.route('/', createResearchRoutes(f.container)); return (path: string, token: string, body?: unknown, key?: string) => app.request(path, { method: body === undefined ? 'GET' : 'POST', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', ...(key ? { 'Idempotency-Key': key } : {}), }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), }); } describe.skipIf(!url)('authoritative research principals and budgets', () => { test('operator provisioning stores only a hash; real mounted authentication, AI authorship and scoped writes', async () => { const f = await fixture(1), p = await provision(f); const request = http(f); expect(p.token.startsWith('sb-research.')).toBe(true); const stored = (await f.pool.query('SELECT * FROM research_agents WHERE id=$1', [p.agent.id])) .rows[0]; expect(JSON.stringify(stored)).not.toContain(p.token); expect(stored.token_hash).toHaveLength(64); const info = await request('/api/v2/research-agent/budget', p.token); expect(info.status).toBe(200); expect((await info.json()).activeTrials).toBe(0); const submitted = await request( `/api/v2/research-projects/${p.project.id}/hypotheses`, p.token, { title: 'AI hypothesis', proposition: 'Test a bounded signal' } ); expect(submitted.status).toBe(201); const hypothesis = await submitted.json(); expect(JSON.stringify(hypothesis)).toContain(p.agent.id); expect(JSON.stringify(hypothesis)).toContain('"contentOrigin":"ai"'); for (const contentOrigin of ['human', 'unknown']) { const bad = await request(`/api/v2/research-projects/${p.project.id}/hypotheses`, p.token, { title: 'False provenance', proposition: 'not human', contentOrigin, }); expect(bad.status).toBe(403); } const denied = await request('/api/v2/research-projects', p.token, { title: 'unauthorized' }); expect(denied.status).toBe(403); const foreign = await f.research.createProject({ title: 'Other project' }, 'operator'); expect( ( await request(`/api/v2/research-projects/${foreign.id}/hypotheses`, p.token, { title: 'Wrong', proposition: 'Wrong project', }) ).status ).toBe(403); expect((await request('/api/v2/research-agents', p.token)).status).toBe(403); expect( ( await f.pool.query('SELECT count(*)::int n FROM research_agent_audit WHERE agent_id=$1', [ p.agent.id, ]) ).rows[0].n ).toBeGreaterThan(2); const clone = await f.catalog.cloneVersion( f.version.id, { name: 'Agent candidate' }, p.agent.id as `agent:${string}`, randomUUID() ); expect(String(clone.strategy.ownerPrincipal)).toBe(p.agent.id); expect(clone.version.origin).toBe('candidate'); const candidate = await f.api.createBacktest( { ...f.definition, strategyVersionId: clone.version.id, name: 'Candidate cannot execute' }, { autoStart: false } ); await expect( f.agents.update(p.agent.id, { expectedRevision: 1, allowedBacktestIds: [candidate.id] }) ).rejects.toThrow('approved canonical templates'); expect((await totals(f)).runs).toBe(0); await f.agents.update(p.agent.id, { expectedRevision: 1, enabled: false }); expect((await request('/api/v2/research-agent/budget', p.token)).status).toBe(401); expect((await f.agents.budget(p.agent.id, true)).agent.enabled).toBe(false); }); test('same receipt is exact after quota changes; capacity and grant errors are typed and atomic', async () => { const f = await fixture(1), p = await provision(f); const submission = await preparation(f), key = randomUUID(); const run = await f.experiments.submit(submission, receipt(p.agent.id, key)); expect(run.trials).toHaveLength(2); expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(2); const policies = ( await f.pool.query( 'SELECT request_snapshot,research_limits,research_agent_id FROM runs ORDER BY run_number' ) ).rows; for (const row of policies) { expect(row.research_agent_id).toBe(p.agent.id); expect(row.research_limits).toEqual(limits); expect( await f.pool .query('SELECT research_grant_policy($1::jsonb) AS p', [row.request_snapshot]) .then(r => r.rows[0].p) ).toEqual(researchGrantPolicy(row.request_snapshot)); } await f.agents.update(p.agent.id, { expectedRevision: 1, limits: { ...limits, maxActiveTrials: 1 }, allowedBacktestIds: [], }); expect((await f.experiments.submit(submission, receipt(p.agent.id, key))).id).toBe(run.id); const before = await totals(f); const denied = await http(f)('/api/v2/experiments', p.token, submission, randomUUID()); expect(denied.status).toBe(403); expect(await totals(f)).toEqual(before); await f.agents.update(p.agent.id, { expectedRevision: 2, allowedBacktestIds: [f.draft.id] }); expect((await http(f)('/api/v2/experiments', p.token, submission, randomUUID())).status).toBe( 429 ); expect(await totals(f)).toEqual(before); await f.agents.update(p.agent.id, { expectedRevision: 3, enabled: false }); expect((await http(f)('/api/v2/experiments', p.token, submission, key)).status).toBe(401); await expect(f.experiments.submit(submission, receipt(p.agent.id, key))).rejects.toThrow( 'disabled' ); }); test('concurrent different-parent grids cannot oversubscribe; failure releases durable capacity and ownership is immutable', async () => { const f = await fixture(), p = await provision(f); const other = await f.api.createBacktest( { ...f.definition, name: 'Second template' }, { autoStart: false } ); await f.agents.update(p.agent.id, { expectedRevision: 1, allowedBacktestIds: [f.draft.id, other.id], }); const [a, b] = await Promise.all([preparation(f), preparation(f, 'Other', other.id)]); const race = await Promise.allSettled([ f.experiments.submit(a, receipt(p.agent.id)), f.experiments.submit(b, receipt(p.agent.id)), ]); expect(race.filter(r => r.status === 'fulfilled')).toHaveLength(1); expect(race.filter(r => r.status === 'rejected')).toHaveLength(1); const failed = race.find(r => r.status === 'rejected'); if (failed?.status !== 'rejected') { throw new Error('Missing failure'); } expect(failed.reason.message).toContain('research_budget:'); expect(await totals(f)).toEqual({ runs: 2, experiments: 1, dispatch: 2 }); const winner = race.find(r => r.status === 'fulfilled'); if (winner?.status !== 'fulfilled') { throw new Error('Missing winner'); } const first = winner.value.trials[0]!; const claim = await f.repository.startCanonical(await requestFor(f, required(first.runId))); expect(claim.executionDeadlineAt).toBeGreaterThan(Date.now()); await expect( f.pool.query('UPDATE runs SET research_agent_id=NULL WHERE id=$1', [required(first.runId)]) ).rejects.toThrow('immutable'); await expect( f.pool.query( "UPDATE runs SET research_limits=jsonb_set(research_limits,'{maxAttempts}','3') WHERE id=$1", [required(first.runId)] ) ).rejects.toThrow('immutable'); await expect( f.pool.query('UPDATE runs SET attempt_number=0 WHERE id=$1', [required(first.runId)]) ).rejects.toThrow('cannot be reset'); await f.repository.fail(required(first.runId), 'controlled failure', claim.attemptId); expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(1); const single = await preparation(f, 'Replacement', f.draft.id, { fastPeriod: [1] }); await f.experiments.submit(single, receipt(p.agent.id)); expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(2); await f.experiments.cancel(winner.value.id); expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(1); }); test('deadline and attempts survive lease renewal/recovery and revocation; no expired completion', async () => { const f = await fixture(), p = await provision(f, { maxAttemptWallMs: 100, maxAttempts: 1 }); const run = await f.experiments.submit( await preparation(f, 'Deadline', f.draft.id, { fastPeriod: [1] }), receipt(p.agent.id) ); const id = required(run.trials[0]!.runId); await expect( f.pool.query("UPDATE runs SET status='running' WHERE id=$1", [id]) ).rejects.toThrow('complete bounded claim'); const claim = await f.repository.startCanonical(await requestFor(f, id)); const frozen = (await f.pool.query('SELECT research_deadline_at FROM runs WHERE id=$1', [id])) .rows[0].research_deadline_at; await f.pool.query( "UPDATE runs SET lease_expires_at=clock_timestamp()+interval '1 hour' WHERE id=$1", [id] ); await expect( f.pool.query( "UPDATE runs SET research_deadline_at=clock_timestamp()+interval '1 hour' WHERE id=$1", [id] ) ).rejects.toThrow('server-owned'); await f.agents.update(p.agent.id, { expectedRevision: 1, enabled: false }); await f.pool.query('SELECT pg_sleep(0.12)'); await expect( f.pool.query("UPDATE runs SET status='completed',completed_at=NOW() WHERE id=$1", [id]) ).rejects.toThrow('wall time'); const dispatcher = new BacktestDispatcher( f.postgres, { add: async () => ({}) as never }, logger ); await dispatcher.tick(); await dispatcher.shutdown(); const saved = (await f.pool.query('SELECT * FROM runs WHERE id=$1', [id])).rows[0]; expect(saved.status).toBe('failed'); expect(saved.error).toContain('wall time'); expect(saved.research_deadline_at).toEqual(frozen); expect(saved.attempt_number).toBe(1); expect((await f.agents.budget(p.agent.id, true)).activeTrials).toBe(0); await f.agents.update(p.agent.id, { expectedRevision: 2, enabled: true }); await expect( f.experiments.retryTrial( run.id, id, { expectedAttemptNumber: 1, expectedRetryCount: 0 }, receipt(p.agent.id) ) ).rejects.toThrow('attempt budget exhausted'); expect( (await f.pool.query('SELECT count(*)::int n FROM experiment_trial_retries')).rows[0].n ).toBe(0); expect(claim.executionDeadlineAt).toBeDefined(); }); test('ordinary native accounting is unchanged; first migration and reapply preserve saved economic evidence and leases', async () => { const f = await fixture(4, false); await f.approve(); const input = await preparation(f); const before = await f.experiments.submit(input, receipt()); await f.execute(required(before.trials[0]!.runId)); const pending = required(before.trials[1]!.runId); const claim = await f.repository.startCanonical(await requestFor(f, pending)); const snapshot = async () => ({ runs: ( await f.pool.query( "SELECT to_jsonb(r)-ARRAY['research_agent_id','research_limits','research_deadline_at'] AS r FROM runs r ORDER BY id" ) ).rows, results: (await f.pool.query('SELECT * FROM backtest_results ORDER BY run_id')).rows, experiments: (await f.pool.query('SELECT * FROM research_experiments ORDER BY id')).rows, dispatch: (await f.pool.query('SELECT * FROM backtest_dispatch ORDER BY run_id')).rows, }); const original = await snapshot(); const sql = readFileSync( new URL('../../database/postgres/init/28-research-agents.sql', import.meta.url), 'utf8' ); await f.pool.query(sql); expect(await snapshot()).toEqual(original); await f.pool.query(sql); expect(await snapshot()).toEqual(original); expect( (await f.pool.query('SELECT attempt_id FROM runs WHERE id=$1', [pending])).rows[0].attempt_id ).toBe(claim.attemptId); const p = await provision(f); const agentRun = await f.experiments.submit( await preparation(f, 'Native agent', f.draft.id, { fastPeriod: [1] }), receipt(p.agent.id) ); await f.execute(required(agentRun.trials[0]!.runId)); const result = await f.api.getRunResults(required(agentRun.trials[0]!.runId)); expect(result && 'kind' in result ? result.kind : null).toBe('canonical-result/v1'); expect(result?.status).toBe('completed'); expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(0); const audit = (await f.pool.query('SELECT * FROM research_agent_audit ORDER BY id')).rows; await f.pool.query(sql); expect((await f.pool.query('SELECT * FROM research_agent_audit ORDER BY id')).rows).toEqual( audit ); await expect(f.pool.query('DELETE FROM research_agent_audit')).rejects.toThrow( 'cannot be rewritten' ); }); test('manual retry reacquires capacity once and lifetime attempts remain bounded across recovery', async () => { const f = await fixture(), p = await provision(f, { maxActiveTrials: 1, maxAttempts: 2 }); const submitted = await f.experiments.submit( await preparation(f, 'Retry', f.draft.id, { fastPeriod: [1] }), receipt(p.agent.id) ); const id = required(submitted.trials[0]!.runId), request = await requestFor(f, id), first = await f.repository.startCanonical(request); await f.pool.query( "UPDATE runs SET lease_expires_at=clock_timestamp()-interval '1 second' WHERE id=$1", [id] ); const dispatcher = new BacktestDispatcher( f.postgres, { add: async () => ({}) as never }, logger ); await dispatcher.tick(); expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(1); const second = await f.repository.startCanonical(request); expect(second.executionDeadlineAt).toBeGreaterThanOrEqual(first.executionDeadlineAt!); await f.repository.fail(id, 'Second attempt failed', second.attemptId); const before = await totals(f); await expect( f.experiments.retryTrial( submitted.id, id, { expectedAttemptNumber: 2, expectedRetryCount: 0 }, receipt(p.agent.id) ) ).rejects.toThrow('attempt budget exhausted'); expect(await totals(f)).toEqual(before); expect( (await f.pool.query('SELECT count(*)::int n FROM experiment_trial_retries')).rows[0].n ).toBe(0); const next = await f.experiments.submit( await preparation(f, 'Manual', f.draft.id, { fastPeriod: [1] }), receipt(p.agent.id) ); const nextId = required(next.trials[0]!.runId); const claim = await f.repository.startCanonical(await requestFor(f, nextId)); await f.repository.fail(nextId, 'Retryable failure', claim.attemptId); const key = randomUUID(), intent = { expectedAttemptNumber: 1, expectedRetryCount: 0 }; await f.agents.update(p.agent.id, { expectedRevision: 1, allowedBacktestIds: [] }); await expect( f.experiments.retryTrial(next.id, nextId, intent, receipt(p.agent.id, key)) ).rejects.toThrow('Operator approval'); await f.agents.update(p.agent.id, { expectedRevision: 2, allowedBacktestIds: [f.draft.id] }); const retry = await f.experiments.retryTrial(next.id, nextId, intent, receipt(p.agent.id, key)); expect(String(retry.retry.principal)).toBe(p.agent.id); expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(1); await f.agents.update(p.agent.id, { expectedRevision: 3, allowedBacktestIds: [] }); expect( (await f.experiments.retryTrial(next.id, nextId, intent, receipt(p.agent.id, key))).retry.id ).toBe(retry.retry.id); await f.agents.update(p.agent.id, { expectedRevision: 4, enabled: false }); const resumed = await f.repository.startCanonical(await requestFor(f, nextId)); expect(resumed.executionDeadlineAt).toBeDefined(); await f.repository.fail( nextId, 'Accepted bounded work still runs after token revocation', resumed.attemptId ); await dispatcher.shutdown(); }); test('cost scenarios and chronological/walk-forward phases retain exact baseline grants and bounded planned work', async () => { const data = walkForwardDataset(), f = await fixture(4, true, data.dataset), p = await provision(f, { maxActiveTrials: 4 }); const costs = { backtestId: f.draft.id, name: 'Fees', scenarios: [{ feeRate: '0.002', slippageRate: '0.001' }], }; const preview = await f.experiments.previewCosts(costs); const cost = await f.experiments.submitCosts( { ...costs, previewHash: preview.previewHash }, receipt(p.agent.id) ); expect(cost.trials).toHaveLength(2); await f.experiments.cancel(cost.id); const validation = new ChronologicalValidationService(f.container), walk = new WalkForwardService(f.container); const input = { backtestId: f.draft.id, name: 'Validation', grid: { fastPeriod: [1, 2] }, recipe: data.windows[0]!, }; const prepared = await f.experiments.previewValidation(input); const train = await validation.submit( { ...input, previewHash: prepared.previewHash }, receipt(p.agent.id) ); await expect( validation.select(train.id, { previewHash: prepared.previewHash }, receipt()) ).rejects.toThrow('owning research principal'); for (const trial of train.phases[0].experiment!.trials) { await f.execute(required(trial.runId)); } await f.agents.update(p.agent.id, { expectedRevision: 1, limits: { ...limits, maxActiveTrials: 1 }, }); const selectKey = randomUUID(); await expect( validation.select( train.id, { previewHash: prepared.previewHash }, receipt(p.agent.id, selectKey) ) ).rejects.toThrow('research_budget:'); expect( ( await f.pool.query('SELECT validation_selection FROM research_experiments WHERE id=$1', [ train.id, ]) ).rows[0].validation_selection ).toBeNull(); expect( ( await f.pool.query( 'SELECT count(*)::int n FROM research_experiments WHERE validation_parent_id=$1', [train.id] ) ).rows[0].n ).toBe(0); await f.agents.update(p.agent.id, { expectedRevision: 2, limits: { ...limits, maxActiveTrials: 4 }, }); const selected = await validation.select( train.id, { previewHash: prepared.previewHash }, receipt(p.agent.id, selectKey) ); expect(String(selected.receipt.principal)).toBe(p.agent.id); for (const phase of selected.validation.phases.slice(1)) { for (const trial of required(phase.experiment).trials) { await f.execute(required(trial.runId)); } } const finalizeInput = { previewHash: prepared.previewHash, selectionHash: required(selected.validation.selection).selectionHash, }, finalKey = randomUUID(); const sealed = await validation.finalize( train.id, finalizeInput, receipt(p.agent.id, finalKey) ); expect(String(required(sealed.validation.report).principal)).toBe(p.agent.id); expect( (await validation.finalize(train.id, finalizeInput, receipt(p.agent.id, finalKey))).receipt ).toEqual(sealed.receipt); const walkInput = { backtestId: f.draft.id, name: 'Rolling', grid: { fastPeriod: [1, 2] }, windows: data.windows, }; const walkPreview = await walk.preview(walkInput); await f.agents.update(p.agent.id, { expectedRevision: 3, limits: { ...limits, maxActiveTrials: 4, maxTrialsPerExperiment: 7 }, }); const before = await totals(f); await expect( walk.submit({ ...walkInput, previewHash: walkPreview.previewHash }, receipt(p.agent.id)) ).rejects.toThrow('trial or observation budget'); expect(await totals(f)).toEqual(before); await f.agents.update(p.agent.id, { expectedRevision: 4, limits: { ...limits, maxActiveTrials: 4 }, }); const series = await walk.submit( { ...walkInput, previewHash: walkPreview.previewHash }, receipt(p.agent.id) ); expect(series.windows).toHaveLength(2); expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(4); for (const window of series.windows) { const member = required(window.validation); for (const trial of required(member.phases[0].experiment).trials) { await f.execute(required(trial.runId)); } const selection = await validation.select( member.id, { previewHash: member.previewHash }, receipt(p.agent.id) ); for (const phase of selection.validation.phases.slice(1)) { for (const trial of required(phase.experiment).trials) { await f.execute(required(trial.runId)); } } await validation.finalize( member.id, { previewHash: member.previewHash, selectionHash: required(selection.validation.selection).selectionHash, }, receipt(p.agent.id) ); } const reportKey = randomUUID(), reportInput = { previewHash: walkPreview.previewHash }; const report = await walk.finalize(series.id, reportInput, receipt(p.agent.id, reportKey)); expect(String(required(report.walkForward.report).principal)).toBe(p.agent.id); expect( (await walk.finalize(series.id, reportInput, receipt(p.agent.id, reportKey))).receipt ).toEqual(report.receipt); expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(0); }, 30000); test('deadline is rechecked at result transaction commit after a valid native result and timely completed transition', async () => { const f = await fixture(), p = await provision(f, { maxAttemptWallMs: 1000 }); const run = await f.experiments.submit( await preparation(f, 'Delayed commit', f.draft.id, { fastPeriod: [1] }), receipt(p.agent.id) ); const id = required(run.trials[0]!.runId), request = await requestFor(f, id); const engine = new RustBacktestAdapter({ logger, storage: { getHistoricalBars: async () => { throw new Error('Provider forbidden'); }, }, }); let economic: Pick; try { economic = await engine.runCanonical(request, async () => f.dataset); } finally { await engine.shutdown(); } const claim = await f.repository.startCanonical(request); const result = { kind: 'canonical-result/v1', status: 'completed', runId: id, backtestId: request.backtestId, request, financialEngine: 'rust', strategyExecution: 'typescript-retained-builtin/v1', completedAt: new Date().toISOString(), executionTime: 1, ...economic, }; const client = await f.pool.connect(); try { await client.query('BEGIN'); await client.query( "UPDATE runs SET status='completed',progress=100,completed_at=NOW() WHERE id=$1 AND attempt_id=$2", [id, claim.attemptId] ); await client.query( "INSERT INTO backtest_results(run_id,completed_at,execution_time,canonical_result,metrics,equity_curve,ohlc_data,trades,positions,analytics) VALUES($1,NOW(),1,$2::jsonb,'null','null','null','null','null','null')", [id, result] ); await client.query('SELECT pg_sleep(1.1)'); await expect(client.query('COMMIT')).rejects.toThrow( 'wall time exceeded before result commit' ); } finally { await client.query('ROLLBACK'); client.release(); } expect((await f.pool.query('SELECT status FROM runs WHERE id=$1', [id])).rows[0].status).toBe( 'running' ); expect( (await f.pool.query('SELECT count(*)::int n FROM backtest_results WHERE run_id=$1', [id])) .rows[0].n ).toBe(0); await f.repository.fail(id, 'Budget expired while saving', claim.attemptId); expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(0); }); test('foreign/disabled agent phase and retry receipts fail through service and direct SQL before any mutation', async () => { const data = walkForwardDataset(), f = await fixture(4, true, data.dataset), a = await provision(f), b = await provision(f); const ordinary = await f.experiments.submit( await preparation(f, 'Owned', f.draft.id, { fastPeriod: [1] }), receipt(a.agent.id) ); const runId = required(ordinary.trials[0]!.runId), claim = await f.repository.startCanonical(await requestFor(f, runId)); await f.repository.fail(runId, 'controlled failure', claim.attemptId); await expect( f.experiments.retryTrial( ordinary.id, runId, { expectedAttemptNumber: 1, expectedRetryCount: 0 }, receipt(b.agent.id) ) ).rejects.toThrow(/owning.*principal/); await expect( 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,experiment_id,id,trial_key,1,attempt_number,attempt_id,error,progress,current_simulation_date,started_at,completed_at,paused_at,updated_at,$3,(SELECT id FROM strategy_review_events ORDER BY created_at DESC LIMIT 1),$4,$5 FROM runs WHERE id=$2`, [randomUUID(), runId, b.agent.id, randomUUID(), 'a'.repeat(64)] ) ).rejects.toThrow(/owning.*principal/); const validation = new ChronologicalValidationService(f.container), input = { backtestId: f.draft.id, name: 'Owned phases', grid: { fastPeriod: [1] }, recipe: data.windows[0]!, }; const preview = await f.experiments.previewValidation(input), train = await validation.submit( { ...input, previewHash: preview.previewHash }, receipt(a.agent.id) ); await expect( validation.select(train.id, { previewHash: preview.previewHash }, receipt(b.agent.id)) ).rejects.toThrow(/owning.*principal/); for (const principal of [b.agent.id, a.agent.id]) { if (principal === a.agent.id) { await f.agents.update(principal, { expectedRevision: 1, enabled: false }); } for (const column of ['validation_selection', 'validation_report']) { await expect( f.pool.query(`UPDATE research_experiments SET ${column}=$2::jsonb WHERE id=$1`, [ train.id, { principal }, ]) ).rejects.toThrow(/owning.*principal/); } } expect( (await f.pool.query('SELECT count(*)::int n FROM experiment_trial_retries')).rows[0].n ).toBe(0); expect( ( await f.pool.query( 'SELECT validation_selection,validation_report FROM research_experiments WHERE id=$1', [train.id] ) ).rows[0] ).toEqual({ validation_selection: null, validation_report: null }); }); test('operator retry reserves owning agent before parent so policy edits cannot deadlock admissions', async () => { const f = await fixture(), p = await provision(f), run = await f.experiments.submit( await preparation(f, 'Lock order', f.draft.id, { fastPeriod: [1] }), receipt(p.agent.id) ); const id = required(run.trials[0]!.runId), claim = await f.repository.startCanonical(await requestFor(f, id)); await f.repository.fail(id, 'controlled', claim.attemptId); const blocker = await f.pool.connect(); await blocker.query('BEGIN'); await blocker.query('SELECT id FROM research_agents WHERE id=$1 FOR UPDATE', [p.agent.id]); const retry = f.experiments.retryTrial( run.id, id, { expectedAttemptNumber: 1, expectedRetryCount: 0 }, receipt() ); try { let waiting = false; for (let i = 0; i < 100; i++) { const rows = ( await f.pool.query( "SELECT 1 FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock' AND query LIKE 'SELECT id,enabled FROM research_agents%'", [f.schema] ) ).rows; if (rows.length) { waiting = true; break; } await blocker.query('SELECT pg_sleep(0.01)'); } expect(waiting).toBe(true); await blocker.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE NOWAIT', [f.draft.id]); await blocker.query('COMMIT'); } finally { await blocker.query('ROLLBACK'); blocker.release(); } expect((await retry).retry.principal).toBe('operator'); expect((await f.agents.budget(p.agent.id)).activeTrials).toBe(1); }); test('multi-template policy locks all parents before shared strategy families', async () => { const f = await fixture(), p = await provision(f), other = await f.api.createBacktest( { ...f.definition, name: 'Shared family' }, { autoStart: false } ); const ids = [f.draft.id, other.id].sort(), blocker = await f.pool.connect(); await blocker.query('BEGIN'); await blocker.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [ids[1]]); const update = f.agents.update(p.agent.id, { expectedRevision: 1, allowedBacktestIds: ids }); try { let waiting = false; for (let i = 0; i < 100; i++) { const rows = ( await f.pool.query( "SELECT 1 FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock' AND query LIKE 'SELECT * FROM backtests WHERE id=ANY%'", [f.schema] ) ).rows; if (rows.length) { waiting = true; break; } await blocker.query('SELECT pg_sleep(0.01)'); } expect(waiting).toBe(true); await blocker.query('SELECT id FROM strategies WHERE id=$1 FOR UPDATE NOWAIT', [ f.version.strategyId, ]); await blocker.query('COMMIT'); } finally { await blocker.query('ROLLBACK'); blocker.release(); } expect((await update).grants).toHaveLength(2); }); test('observation budgets and changed financial policy reject without partial admission', async () => { const f = await fixture(), p = await provision(f, { maxBarEvaluationsPerExperiment: 1 }); const input = await preparation(f), before = await totals(f); await expect(f.experiments.submit(input, receipt(p.agent.id))).rejects.toThrow( 'trial or observation budget' ); expect(await totals(f)).toEqual(before); await f.agents.update(p.agent.id, { expectedRevision: 1, limits }); await f.pool.query('UPDATE backtests SET initial_capital=20000 WHERE id=$1', [f.draft.id]); const changed = await preparation(f); expect(changed.previewHash).not.toBe(input.previewHash); await expect(f.experiments.submit(changed, receipt(p.agent.id))).rejects.toThrow( 'Operator approval' ); expect(await totals(f)).toEqual(before); await f.agents.update(p.agent.id, { expectedRevision: 2, allowedBacktestIds: [f.draft.id] }); expect((await f.experiments.submit(changed, receipt(p.agent.id))).trials).toHaveLength(2); }); });