stock-bot/test/postgres/research-workspace.test.ts

738 lines
29 KiB
TypeScript

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 { ResearchService } from '../../apps/stock/web-api/src/services/research.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('research-workspace');
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const cleanup: (() => Promise<void>)[] = [];
let packages: ReturnType<typeof packageBuiltinStrategies> | 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',
]) {
await pool.query(sql(name));
}
if (applyWorkspace) {
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', { value: pool.query.bind(pool) });
const container = { postgres, logger };
const service = new ResearchService(container);
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 backtests.createRun({ 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,
storage: {
async getHistoricalBars() {
throw new Error('No provider fallback');
},
},
}),
engineName: 'native',
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('cannot declare human');
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 f.backtests.createRun({ 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);
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']);
});
});