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); } );