878 lines
33 KiB
TypeScript
878 lines
33 KiB
TypeScript
import { randomUUID } from 'node:crypto';
|
|
import { readFileSync } from 'node:fs';
|
|
import { afterEach, describe, expect, test } from 'bun:test';
|
|
import { Hono } from 'hono';
|
|
import { Pool, type PoolClient } from 'pg';
|
|
import { createHttpSecurity } from '@stock-bot/di';
|
|
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
|
import { PostgreSQLClient } from '@stock-bot/postgres';
|
|
import type { WalkForwardInput } from '@stock-bot/stock-config/walk-forward';
|
|
import type { ResearchEvidenceReference, ResearchFindingSource } 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 { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes';
|
|
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
|
import { experimentHash } from '../../apps/stock/web-api/src/services/experiment-input';
|
|
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 { walkForwardDataset } from '../fixtures/walk-forward';
|
|
|
|
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
|
const logger = getLogger('chronological-validation');
|
|
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
|
const cleanup: (() => Promise<void>)[] = [];
|
|
let packages: ReturnType<typeof packageBuiltinStrategies> | undefined;
|
|
afterEach(async () => {
|
|
for (const close of cleanup.splice(0).reverse()) {
|
|
await close();
|
|
}
|
|
});
|
|
async function fixture(poolMax = 1, withSources = true) {
|
|
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
|
throw new Error('Disposable safety database required');
|
|
}
|
|
const schema = 'stock_bot_safety_validation_' + randomUUID().replaceAll('-', '');
|
|
const admin = new Pool({ connectionString: url });
|
|
await admin.query(`CREATE SCHEMA ${schema}`);
|
|
// A single connection detects accidental nested pool reads while the admission lock is held.
|
|
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',
|
|
...(withSources ? ['27-research-evidence-sources.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 },
|
|
api = new BacktestServiceV2(container),
|
|
experiments = new ExperimentsService(container),
|
|
catalog = new StrategyCatalogService(container);
|
|
const version = await catalog.seedBuiltin(
|
|
'Validation SMA',
|
|
(await (packages ??= packageBuiltinStrategies()))[0]!,
|
|
'seed'
|
|
);
|
|
const data = walkForwardDataset(),
|
|
dataset = data.dataset;
|
|
await retainResearchDataset(pool, dataset);
|
|
const draft = await api.createBacktest(
|
|
{
|
|
name: 'Validation template',
|
|
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 input: WalkForwardInput = {
|
|
backtestId: draft.id,
|
|
name: 'Two rolling windows',
|
|
grid: { fastPeriod: [1, 2], slowPeriod: [3] },
|
|
windows: data.windows,
|
|
};
|
|
const review = async (decision: 'approve' | 'revoke' = 'approve') => {
|
|
await catalog.reviewVersion(
|
|
version.id,
|
|
{ decision, reason: 'Disposable validation proof' },
|
|
'operator'
|
|
);
|
|
return (await catalog.getVersionReviews(version.id)).at(-1)!;
|
|
};
|
|
const snapshot = async () => {
|
|
const tables = (
|
|
await pool.query('SELECT tablename FROM pg_tables WHERE schemaname=$1 ORDER BY tablename', [
|
|
schema,
|
|
])
|
|
).rows;
|
|
const rows: Record<string, unknown> = {};
|
|
for (const { tablename } of tables) {
|
|
const quoted = '"' + String(tablename).replaceAll('"', '""') + '"';
|
|
rows[String(tablename)] = (
|
|
await pool.query(
|
|
`SELECT COALESCE(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text),'[]'::jsonb) AS rows FROM ${quoted} t`
|
|
)
|
|
).rows[0].rows;
|
|
}
|
|
return rows;
|
|
};
|
|
const services = createResearchServices(container);
|
|
const validations = services.validations;
|
|
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();
|
|
}
|
|
};
|
|
return {
|
|
cloneTemplate: async (sourceDataset = dataset) =>
|
|
api.createBacktest(
|
|
{
|
|
name: 'Other validation template',
|
|
strategy: 'catalog',
|
|
strategyVersionId: version.id,
|
|
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
|
|
symbols: ['X0.US'],
|
|
startDate: new Date(sourceDataset.manifest.bounds.tradeStart).toISOString(),
|
|
endDate: new Date(sourceDataset.manifest.bounds.tradeEnd).toISOString(),
|
|
initialCapital: 10000,
|
|
config: {
|
|
datasetHash: sourceDataset.manifest.hash,
|
|
dataFrequency: '1m',
|
|
canonical: canonicalSettings,
|
|
},
|
|
},
|
|
{ autoStart: false }
|
|
),
|
|
validations,
|
|
walks: services.walkForwards,
|
|
repository,
|
|
execute,
|
|
api,
|
|
pool,
|
|
postgres,
|
|
experiments,
|
|
catalog,
|
|
version,
|
|
draft,
|
|
dataset,
|
|
input,
|
|
research: services.research,
|
|
container,
|
|
schema,
|
|
review,
|
|
snapshot,
|
|
};
|
|
}
|
|
|
|
const actor = (key = randomUUID()) => ({ principal: 'operator' as const, key });
|
|
type Fixture = Awaited<ReturnType<typeof fixture>>;
|
|
async function submit(f: Fixture, input = f.input, identity = actor()) {
|
|
await f.review();
|
|
const preview = await f.walks.preview(input),
|
|
body = { ...input, previewHash: preview.previewHash };
|
|
return { preview, body, identity, walk: await f.walks.submit(body, identity) };
|
|
}
|
|
async function finishWindow(f: Fixture, id: string) {
|
|
const initial = await f.validations.get(id);
|
|
for (const trial of initial.phases[0]!.experiment!.trials) {
|
|
await f.execute(trial.runId!);
|
|
}
|
|
const selected = await f.validations.select(id, { previewHash: initial.previewHash }, actor());
|
|
for (const phase of selected.validation.phases.slice(1)) {
|
|
for (const trial of phase.experiment!.trials) {
|
|
await f.execute(trial.runId!);
|
|
}
|
|
}
|
|
return f.validations.finalize(
|
|
id,
|
|
{
|
|
previewHash: initial.previewHash,
|
|
selectionHash: selected.validation.selection!.selectionHash,
|
|
},
|
|
actor()
|
|
);
|
|
}
|
|
|
|
const reference = (
|
|
runId: string,
|
|
metricPath = 'analytics.metrics.totalReturn'
|
|
): ResearchEvidenceReference => ({
|
|
runId,
|
|
metricsVersion: 'canonical-analytics/v1',
|
|
metricPath,
|
|
});
|
|
async function save(
|
|
f: Fixture,
|
|
source: ResearchFindingSource,
|
|
evidence: ResearchEvidenceReference[]
|
|
) {
|
|
const project = await f.research.createProject({ title: 'Evidence workspace' }, 'operator');
|
|
const artifact = await f.research.createArtifact(
|
|
project.id,
|
|
{
|
|
kind: 'finding',
|
|
title: 'Selected observations',
|
|
body: 'Not a validated claim',
|
|
source,
|
|
evidence,
|
|
},
|
|
'operator'
|
|
);
|
|
return { project, artifact };
|
|
}
|
|
async function cost(f: Fixture) {
|
|
await f.review();
|
|
const input = {
|
|
backtestId: f.draft.id,
|
|
name: 'Costs',
|
|
scenarios: [
|
|
{ feeRate: '0.001', slippageRate: '0.002' },
|
|
{ feeRate: '0.003', slippageRate: '0.004' },
|
|
],
|
|
};
|
|
const preview = await f.experiments.previewCosts(input);
|
|
const detail = await f.experiments.submitCosts(
|
|
{ ...input, previewHash: preview.previewHash },
|
|
actor()
|
|
);
|
|
return {
|
|
detail,
|
|
source: {
|
|
kind: 'experiment/v1',
|
|
experimentId: detail.id,
|
|
previewHash: detail.previewHash,
|
|
} as const,
|
|
};
|
|
}
|
|
function rehash<T extends Record<string, unknown>>(value: T, field: string): T {
|
|
const copy = structuredClone(value),
|
|
{ _receipt: _private, ...document } = copy;
|
|
delete document[field];
|
|
return { ...copy, [field]: experimentHash(document) };
|
|
}
|
|
async function mutate(f: Fixture, table: string, id: string, field: string, value: unknown) {
|
|
await f.postgres.transaction(async client => {
|
|
await client.query(`ALTER TABLE ${table} DISABLE TRIGGER USER`);
|
|
await client.query(`UPDATE ${table} SET ${field}=$2 WHERE id=$1`, [id, value]);
|
|
await client.query(`ALTER TABLE ${table} ENABLE TRIGGER USER`);
|
|
});
|
|
}
|
|
async function rawRevision(
|
|
f: Fixture,
|
|
artifactId: string,
|
|
source: unknown,
|
|
refs: ResearchEvidenceReference[],
|
|
after?: (client: PoolClient, revisionId: string) => Promise<void>
|
|
) {
|
|
return f.postgres.transaction(async client => {
|
|
const revisionId = randomUUID();
|
|
const ordinal = Number(
|
|
(
|
|
await client.query(
|
|
'SELECT COALESCE(MAX(ordinal),0)+1 AS n FROM analysis_artifact_revisions WHERE artifact_id=$1',
|
|
[artifactId]
|
|
)
|
|
).rows[0].n
|
|
);
|
|
await client.query(
|
|
"INSERT INTO analysis_artifact_revisions(id,artifact_id,ordinal,title,body,submitted_by,content_origin,source) VALUES($1,$2,$3,'Raw source','Unvalidated','operator','human',$4)",
|
|
[revisionId, artifactId, ordinal, source]
|
|
);
|
|
for (const [index, ref] of refs.entries()) {
|
|
await client.query(
|
|
'INSERT INTO analysis_evidence(revision_id,ordinal,run_id,metrics_version,metric_path) VALUES($1,$2,$3,$4,$5)',
|
|
[revisionId, index + 1, ref.runId, ref.metricsVersion, ref.metricPath]
|
|
);
|
|
}
|
|
if (after) {
|
|
await after(client, revisionId);
|
|
}
|
|
return revisionId;
|
|
});
|
|
}
|
|
describe.skipIf(!url)('source-linked findings', () => {
|
|
test('pool1 cost source saves exact selected facts and nulls; historical read survives cancellation/archive; omitted source persists and explicit null detaches', async () => {
|
|
const f = await fixture(),
|
|
c = await cost(f);
|
|
for (const trial of c.detail.trials.slice(0, 2)) {
|
|
await f.execute(trial.runId!);
|
|
}
|
|
expect((await f.experiments.get(c.detail.id)).standalone).toBe(true);
|
|
const evidence = [
|
|
reference(c.detail.trials[0]!.runId!),
|
|
reference(c.detail.trials[0]!.runId!, 'analytics.metrics.sharpeRatio'),
|
|
reference(c.detail.trials[1]!.runId!),
|
|
];
|
|
const native = await f.api.getRunResults(evidence[0]!.runId);
|
|
const { artifact, project } = await save(f, c.source, evidence);
|
|
expect(artifact.latestRevision.source).toEqual(c.source);
|
|
expect(artifact.latestRevision.validationState).toBe('unvalidated');
|
|
expect(artifact.latestRevision.evidence[0]!.value).toBe(
|
|
(native as any).analytics.metrics.totalReturn
|
|
);
|
|
expect(artifact.latestRevision.evidence[1]).toMatchObject({
|
|
value: null,
|
|
availability: 'unavailable',
|
|
});
|
|
await f.experiments.cancel(c.detail.id);
|
|
await f.review('revoke');
|
|
await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]);
|
|
await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [
|
|
f.version.strategyId,
|
|
]);
|
|
const before = await f.snapshot();
|
|
expect(await f.research.getArtifact(artifact.id)).toEqual(artifact);
|
|
expect(await f.research.listArtifacts(project.id)).toEqual([artifact]);
|
|
expect(await f.research.listArtifactRevisions(artifact.id)).toEqual([artifact.latestRevision]);
|
|
expect(await f.snapshot()).toEqual(before);
|
|
const revised = await f.research.reviseArtifact(
|
|
artifact.id,
|
|
{ expectedRevision: 1, title: 'New interpretation', body: 'Still unvalidated', evidence },
|
|
'operator'
|
|
);
|
|
expect(revised.latestRevision.source).toEqual(c.source);
|
|
const detached = await f.research.reviseArtifact(
|
|
artifact.id,
|
|
{
|
|
expectedRevision: 2,
|
|
title: 'Unscoped',
|
|
body: 'Deliberately detached',
|
|
evidence,
|
|
source: null,
|
|
},
|
|
'operator'
|
|
);
|
|
expect(detached.latestRevision.source).toBeNull();
|
|
expect((await f.research.listArtifactRevisions(artifact.id)).map(r => r.source)).toEqual([
|
|
c.source,
|
|
c.source,
|
|
null,
|
|
]);
|
|
}, 60000);
|
|
test('native sealed chronological and walk-forward sources retain all proof but only published series segment metrics are selectable', async () => {
|
|
const f = await fixture(),
|
|
start = await submit(f);
|
|
for (const window of start.walk.windows) {
|
|
await finishWindow(f, window.validationId);
|
|
}
|
|
const completed = await f.walks.finalize(
|
|
start.walk.id,
|
|
{ previewHash: start.preview.previewHash },
|
|
actor()
|
|
);
|
|
const series = completed.walkForward.report!;
|
|
const member = completed.walkForward.windows[0]!.validation!.report!;
|
|
const source: ResearchFindingSource = {
|
|
kind: 'walk-forward-report/v1',
|
|
walkForwardId: start.walk.id,
|
|
previewHash: series.previewHash,
|
|
reportId: series.id,
|
|
reportHash: series.reportHash,
|
|
};
|
|
const saved = await save(
|
|
f,
|
|
source,
|
|
series.segments.flatMap(s => [reference(s.validation.runId), reference(s.test.runId)])
|
|
);
|
|
expect(saved.artifact.latestRevision.evidence.map(e => e.value)).toEqual(
|
|
series.segments.flatMap(s => [s.validation.metrics.totalReturn, s.test.metrics.totalReturn])
|
|
);
|
|
const chrono: ResearchFindingSource = {
|
|
kind: 'chronological-report/v1',
|
|
validationId: member.validationId,
|
|
previewHash: member.previewHash,
|
|
reportId: member.id,
|
|
reportHash: member.reportHash,
|
|
};
|
|
const original = await save(f, chrono, [
|
|
reference(member.training[0]!.runId),
|
|
reference(member.test.runId, 'analytics.metrics.sharpeRatio'),
|
|
]);
|
|
expect(original.artifact.latestRevision.evidence[1]!.value).toBeNull();
|
|
expect((await f.experiments.get(member.validationId)).standalone).toBe(false);
|
|
await expect(save(f, source, [reference(member.training[0]!.runId)])).rejects.toMatchObject({
|
|
status: 422,
|
|
});
|
|
await expect(
|
|
save(
|
|
f,
|
|
{
|
|
kind: 'experiment/v1',
|
|
experimentId: member.validationId,
|
|
previewHash:
|
|
completed.walkForward.windows[0]!.validation!.phases[0]!.experiment!.previewHash,
|
|
},
|
|
[reference(member.training[0]!.runId)]
|
|
)
|
|
).rejects.toMatchObject({ status: 422 });
|
|
await f.walks.cancel(start.walk.id);
|
|
await f.review('revoke');
|
|
await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]);
|
|
await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [
|
|
f.version.strategyId,
|
|
]);
|
|
const before = await f.snapshot();
|
|
expect(await f.research.getArtifact(saved.artifact.id)).toEqual(saved.artifact);
|
|
expect(await f.research.getArtifact(original.artifact.id)).toEqual(original.artifact);
|
|
expect(await f.snapshot()).toEqual(before);
|
|
}, 60000);
|
|
|
|
test('wrong input identity, empty notes, foreign or incomplete refs and omitted-source revisions reject atomically', async () => {
|
|
const f = await fixture(),
|
|
c = await cost(f),
|
|
other = await cost(f);
|
|
await f.execute(c.detail.trials[0]!.runId!);
|
|
await f.execute(other.detail.trials[0]!.runId!);
|
|
const ref = reference(c.detail.trials[0]!.runId!),
|
|
foreign = reference(other.detail.trials[0]!.runId!);
|
|
const { artifact, project } = await save(f, c.source, [ref]);
|
|
const before = await f.snapshot();
|
|
for (const input of [
|
|
{ source: { ...c.source, previewHash: 'f'.repeat(64) }, evidence: [ref] },
|
|
{ source: c.source, evidence: [foreign] },
|
|
{ source: c.source, evidence: [reference(c.detail.trials[1]!.runId!)] },
|
|
{ source: c.source, evidence: [] },
|
|
{
|
|
source: c.source,
|
|
evidence: [
|
|
{ ...ref, metricsVersion: 'legacy-display/v1', metricPath: 'metrics.totalReturn' },
|
|
],
|
|
},
|
|
]) {
|
|
await expect(
|
|
f.research.createArtifact(
|
|
project.id,
|
|
{ kind: 'note', title: 'Rejected source', body: '', ...input },
|
|
'operator'
|
|
)
|
|
).rejects.toMatchObject({ status: 422 });
|
|
}
|
|
await expect(
|
|
f.research.reviseArtifact(
|
|
artifact.id,
|
|
{ expectedRevision: 1, title: 'Foreign omitted', body: '', evidence: [foreign] },
|
|
'operator'
|
|
)
|
|
).rejects.toMatchObject({ status: 422 });
|
|
expect(await f.snapshot()).toEqual(before);
|
|
expect((await f.research.getArtifact(artifact.id)).latestRevision.source).toEqual(c.source);
|
|
const detached = await f.research.reviseArtifact(
|
|
artifact.id,
|
|
{
|
|
expectedRevision: 1,
|
|
title: 'Explicit new scope',
|
|
body: '',
|
|
source: null,
|
|
evidence: [foreign],
|
|
},
|
|
'operator'
|
|
);
|
|
expect(detached.latestRevision.source).toBeNull();
|
|
}, 60000);
|
|
test('recomputed-hash selection, training, holdout, series and document metadata corruption cannot become cited evidence', async () => {
|
|
const f = await fixture(),
|
|
start = await submit(f);
|
|
for (const window of start.walk.windows) {
|
|
await finishWindow(f, window.validationId);
|
|
}
|
|
const done = await f.walks.finalize(
|
|
start.walk.id,
|
|
{ previewHash: start.preview.previewHash },
|
|
actor()
|
|
);
|
|
const first = done.walkForward.windows[0]!.validation!,
|
|
report = first.report!;
|
|
const root = (await f.pool.query('SELECT * FROM research_experiments WHERE id=$1', [first.id]))
|
|
.rows[0];
|
|
const header = (
|
|
await f.pool.query('SELECT * FROM research_walk_forwards WHERE id=$1', [start.walk.id])
|
|
).rows[0];
|
|
const project = await f.research.createProject({ title: 'Corruption refusals' }, 'operator');
|
|
const ref = reference(report.test.runId);
|
|
const originalSource: ResearchFindingSource = {
|
|
kind: 'chronological-report/v1',
|
|
validationId: first.id,
|
|
previewHash: report.previewHash,
|
|
reportId: report.id,
|
|
reportHash: report.reportHash,
|
|
};
|
|
const saved = await f.research.createArtifact(
|
|
project.id,
|
|
{ kind: 'finding', title: 'Original', body: '', source: originalSource, evidence: [ref] },
|
|
'operator'
|
|
);
|
|
for (const change of [
|
|
'training',
|
|
'winner',
|
|
'holdout',
|
|
'principal',
|
|
'time',
|
|
'limitations',
|
|
] as const) {
|
|
let selection = structuredClone(root.validation_selection),
|
|
changed = structuredClone(root.validation_report);
|
|
if (change === 'training') {
|
|
selection.training[0].metrics.totalReturn += 1;
|
|
changed.training = structuredClone(selection.training);
|
|
}
|
|
if (change === 'winner') {
|
|
selection.winner = structuredClone(
|
|
root.preview.candidates.find(
|
|
(candidate: any) => candidate.index !== selection.winner.index
|
|
)
|
|
);
|
|
}
|
|
if (change === 'holdout') {
|
|
changed.test.metrics.totalReturn += 1;
|
|
}
|
|
if (change === 'principal') {
|
|
changed.principal = 'fabricated';
|
|
}
|
|
if (change === 'time') {
|
|
changed.createdAt = 'not-a-time';
|
|
}
|
|
if (change === 'limitations') {
|
|
changed.limitations = ['ok', 42];
|
|
}
|
|
selection = rehash(selection, 'selectionHash');
|
|
changed.selectionHash = selection.selectionHash;
|
|
changed = rehash(changed, 'reportHash');
|
|
await mutate(f, 'research_experiments', first.id, 'validation_selection', selection);
|
|
await mutate(f, 'research_experiments', first.id, 'validation_report', changed);
|
|
const source = { ...originalSource, reportHash: changed.reportHash };
|
|
await expect(
|
|
f.research.createArtifact(
|
|
project.id,
|
|
{ kind: 'finding', title: 'Corrupt', body: '', source, evidence: [ref] },
|
|
'operator'
|
|
)
|
|
).rejects.toThrow('Retained research source could not be verified');
|
|
await mutate(
|
|
f,
|
|
'research_experiments',
|
|
first.id,
|
|
'validation_selection',
|
|
root.validation_selection
|
|
);
|
|
await mutate(
|
|
f,
|
|
'research_experiments',
|
|
first.id,
|
|
'validation_report',
|
|
root.validation_report
|
|
);
|
|
}
|
|
const originalResult = (
|
|
await f.pool.query('SELECT canonical_result FROM backtest_results WHERE run_id=$1', [
|
|
ref.runId,
|
|
])
|
|
).rows[0].canonical_result;
|
|
for (const field of ['analytics', 'financial']) {
|
|
const damaged = structuredClone(originalResult);
|
|
if (field === 'analytics') {
|
|
damaged.analytics.metrics.totalReturn += 1;
|
|
} else {
|
|
expect(typeof damaged.financial.view.equity).toBe('string');
|
|
damaged.financial.view.equity = '900.00000000';
|
|
}
|
|
expect(damaged).not.toEqual(originalResult);
|
|
const write = async (value: unknown) =>
|
|
f.postgres.transaction(async client => {
|
|
await client.query('ALTER TABLE backtest_results DISABLE TRIGGER USER');
|
|
await client.query('UPDATE backtest_results SET canonical_result=$2 WHERE run_id=$1', [
|
|
ref.runId,
|
|
value,
|
|
]);
|
|
await client.query('ALTER TABLE backtest_results ENABLE TRIGGER USER');
|
|
});
|
|
await write(damaged);
|
|
await expect(
|
|
f.research.createArtifact(
|
|
project.id,
|
|
{
|
|
kind: 'finding',
|
|
title: 'Corrupt canonical result',
|
|
body: '',
|
|
source: originalSource,
|
|
evidence: [ref],
|
|
},
|
|
'operator'
|
|
)
|
|
).rejects.toThrow('Retained research source could not be verified');
|
|
await expect(f.research.getArtifact(saved.id)).rejects.toThrow(
|
|
'Retained finding source evidence could not be resolved'
|
|
);
|
|
await write(originalResult);
|
|
}
|
|
const forged = structuredClone(header.report);
|
|
forged.segments[1].test.metrics.totalReturn += 1;
|
|
const changed = rehash(forged, 'reportHash');
|
|
await mutate(f, 'research_walk_forwards', header.id, 'report', changed);
|
|
await expect(
|
|
f.research.createArtifact(
|
|
project.id,
|
|
{
|
|
kind: 'finding',
|
|
title: 'Forged series',
|
|
body: '',
|
|
source: {
|
|
kind: 'walk-forward-report/v1',
|
|
walkForwardId: header.id,
|
|
previewHash: header.preview_hash,
|
|
reportId: changed.id,
|
|
reportHash: changed.reportHash,
|
|
},
|
|
evidence: [ref],
|
|
},
|
|
'operator'
|
|
)
|
|
).rejects.toThrow('Retained research source could not be verified');
|
|
await mutate(f, 'research_walk_forwards', header.id, 'report', header.report);
|
|
const broken = structuredClone(root.validation_report);
|
|
broken.test.metrics.totalReturn += 1;
|
|
await mutate(
|
|
f,
|
|
'research_experiments',
|
|
first.id,
|
|
'validation_report',
|
|
rehash(broken, 'reportHash')
|
|
);
|
|
const app = new Hono();
|
|
const token = 'source-evidence-read-fixture-not-a-real-secret-1234';
|
|
createHttpSecurity({
|
|
readToken: token,
|
|
adminToken: 'source-evidence-admin-fixture-not-a-real-secret-1234',
|
|
serviceToken: 'source-evidence-service-fixture-not-a-real-secret-1234',
|
|
environment: 'test',
|
|
hostname: '127.0.0.1',
|
|
}).mount(app);
|
|
app.route('/', createResearchRoutes(f.container));
|
|
const response = await app.request('/api/v2/analysis-artifacts/' + saved.id, {
|
|
headers: { Authorization: `Bearer ${token}` },
|
|
});
|
|
expect(response.status).toBe(500);
|
|
expect(await response.json()).toEqual({ error: 'Research workspace unavailable' });
|
|
}, 60000);
|
|
test('SQL source guards reject malformed/member/empty refs, protect immutable history and recheck evidence after constraints become immediate', async () => {
|
|
const f = await fixture(),
|
|
c = await cost(f),
|
|
other = await cost(f);
|
|
await f.execute(c.detail.trials[0]!.runId!);
|
|
await f.execute(other.detail.trials[0]!.runId!);
|
|
const ref = reference(c.detail.trials[0]!.runId!),
|
|
foreign = reference(other.detail.trials[0]!.runId!);
|
|
const { artifact } = await save(f, c.source, [ref]);
|
|
for (const bad of [
|
|
{ ...c.source, extra: true },
|
|
{ ...c.source, experimentId: null },
|
|
{ ...c.source, previewHash: null },
|
|
{ ...c.source, previewHash: 'f'.repeat(64) },
|
|
{ ...c.source, kind: 'unknown' },
|
|
'null',
|
|
]) {
|
|
await expect(rawRevision(f, artifact.id, bad, [ref])).rejects.toMatchObject({
|
|
code: '23514',
|
|
});
|
|
}
|
|
await expect(rawRevision(f, artifact.id, c.source, [])).rejects.toMatchObject({
|
|
code: '23514',
|
|
});
|
|
await expect(rawRevision(f, artifact.id, c.source, [foreign])).rejects.toThrow(
|
|
'completed canonical members'
|
|
);
|
|
await expect(
|
|
rawRevision(f, artifact.id, c.source, [ref], async (client, revisionId) => {
|
|
await client.query('SET CONSTRAINTS workspace_source_evidence IMMEDIATE');
|
|
await client.query(
|
|
'INSERT INTO analysis_evidence(revision_id,ordinal,run_id,metrics_version,metric_path) VALUES($1,2,$2,$3,$4)',
|
|
[revisionId, foreign.runId, foreign.metricsVersion, foreign.metricPath]
|
|
);
|
|
})
|
|
).rejects.toThrow('completed canonical members');
|
|
const accepted = await rawRevision(f, artifact.id, c.source, [ref]);
|
|
for (const statement of [
|
|
'UPDATE analysis_artifact_revisions SET source=NULL WHERE id=$1',
|
|
'DELETE FROM analysis_artifact_revisions WHERE id=$1',
|
|
"INSERT INTO analysis_evidence(revision_id,ordinal,run_id,metrics_version,metric_path) VALUES($1,2,'" +
|
|
ref.runId +
|
|
"','canonical-analytics/v1','analytics.metrics.maxDrawdown')",
|
|
]) {
|
|
await expect(f.pool.query(statement, [accepted])).rejects.toMatchObject({ code: '23514' });
|
|
}
|
|
await expect(
|
|
f.pool.query('TRUNCATE analysis_artifact_revisions CASCADE')
|
|
).rejects.toMatchObject({ code: '23514' });
|
|
expect((await f.research.listArtifactRevisions(artifact.id)).map(item => item.source)).toEqual([
|
|
c.source,
|
|
c.source,
|
|
]);
|
|
}, 60000);
|
|
test('first migration and reapply preserve existing artifacts, receipts, results and pending run custody', async () => {
|
|
const f = await fixture(1, false),
|
|
c = await cost(f);
|
|
await f.execute(c.detail.trials[0]!.runId!);
|
|
const project = randomUUID(),
|
|
artifact = randomUUID(),
|
|
revision = randomUUID(),
|
|
runId = c.detail.trials[0]!.runId!;
|
|
await f.postgres.transaction(async client => {
|
|
await client.query(
|
|
"INSERT INTO research_projects(id,title,owner_principal,updated_by) VALUES($1,'Before27','operator','operator')",
|
|
[project]
|
|
);
|
|
await client.query(
|
|
"INSERT INTO analysis_artifacts(id,project_id,kind,owner_principal,updated_by) VALUES($1,$2,'finding','operator','operator')",
|
|
[artifact, project]
|
|
);
|
|
await client.query(
|
|
"INSERT INTO analysis_artifact_revisions(id,artifact_id,ordinal,title,body,submitted_by,content_origin) VALUES($1,$2,1,'Before27','Immutable','operator','human')",
|
|
[revision, artifact]
|
|
);
|
|
await client.query(
|
|
"INSERT INTO analysis_evidence(revision_id,ordinal,run_id,metrics_version,metric_path) VALUES($1,1,$2,'canonical-analytics/v1','analytics.metrics.totalReturn')",
|
|
[revision, runId]
|
|
);
|
|
});
|
|
const claimedId = c.detail.trials[1]!.runId!;
|
|
const request = (
|
|
await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [claimedId])
|
|
).rows[0].request_snapshot;
|
|
const claim = await f.repository.startCanonical(request);
|
|
const custody = (
|
|
await f.pool.query(
|
|
'SELECT attempt_id,attempt_number,lease_expires_at,status FROM runs WHERE id=$1',
|
|
[claimedId]
|
|
)
|
|
).rows[0];
|
|
expect(custody.attempt_id).toBe(claim.attemptId);
|
|
expect(custody.status).toBe('running');
|
|
expect(custody.lease_expires_at).not.toBeNull();
|
|
const before = await f.snapshot();
|
|
const sql = readFileSync(
|
|
new URL('../../database/postgres/init/27-research-evidence-sources.sql', import.meta.url),
|
|
'utf8'
|
|
);
|
|
await f.pool.query(sql);
|
|
const after = await f.snapshot();
|
|
const revisions = after.analysis_artifact_revisions as Record<string, unknown>[];
|
|
expect(revisions.every(item => item.source === null)).toBe(true);
|
|
after.analysis_artifact_revisions = revisions.map(({ source: _source, ...row }) => row);
|
|
expect(after).toEqual(before);
|
|
expect(
|
|
(
|
|
await f.pool.query(
|
|
'SELECT attempt_id,attempt_number,lease_expires_at,status FROM runs WHERE id=$1',
|
|
[claimedId]
|
|
)
|
|
).rows[0]
|
|
).toEqual(custody);
|
|
expect((await f.research.getArtifact(artifact)).latestRevision.source).toBeNull();
|
|
const saved = await save(f, c.source, [reference(runId)]),
|
|
retained = await f.snapshot();
|
|
await f.pool.query(sql);
|
|
expect(await f.snapshot()).toEqual(retained);
|
|
expect(await f.research.getArtifact(saved.artifact.id)).toEqual(saved.artifact);
|
|
}, 60000);
|
|
test('artifact get/list/history use a coherent readonly snapshot despite a committed source/result change', async () => {
|
|
const f = await fixture(4),
|
|
c = await cost(f);
|
|
await f.execute(c.detail.trials[0]!.runId!);
|
|
const { artifact, project } = await save(f, c.source, [reference(c.detail.trials[0]!.runId!)]);
|
|
const transaction = f.postgres.transaction.bind(f.postgres);
|
|
const original = (
|
|
await f.pool.query('SELECT validation_phase FROM research_experiments WHERE id=$1', [
|
|
c.detail.id,
|
|
])
|
|
).rows[0];
|
|
for (const read of [
|
|
() => f.research.getArtifact(artifact.id),
|
|
() => f.research.listArtifacts(project.id),
|
|
() => f.research.listArtifactRevisions(artifact.id),
|
|
]) {
|
|
let changed = false;
|
|
const trace: string[] = [];
|
|
let mode: unknown;
|
|
Object.defineProperty(f.postgres, 'transaction', {
|
|
configurable: true,
|
|
value: (work: (client: PoolClient) => Promise<unknown>) =>
|
|
transaction(async client => {
|
|
const query = client.query.bind(client),
|
|
proxy = Object.create(client) as PoolClient;
|
|
Object.defineProperty(proxy, 'query', {
|
|
value: async (sql: string, values?: unknown[]) => {
|
|
trace.push(sql);
|
|
const result = await query(sql, values);
|
|
if (sql.startsWith('SET TRANSACTION')) {
|
|
mode = (
|
|
await query(
|
|
"SELECT current_setting('transaction_isolation') AS isolation,current_setting('transaction_read_only') AS readonly"
|
|
)
|
|
).rows[0];
|
|
}
|
|
if (sql.startsWith('SELECT * FROM analysis_artifact_revisions') && !changed) {
|
|
changed = true;
|
|
await transaction(async other => {
|
|
await other.query('ALTER TABLE research_experiments DISABLE TRIGGER USER');
|
|
await other.query(
|
|
'UPDATE research_experiments SET preview_hash=$2 WHERE id=$1',
|
|
[c.detail.id, 'f'.repeat(64)]
|
|
);
|
|
await other.query('ALTER TABLE research_experiments ENABLE TRIGGER USER');
|
|
});
|
|
}
|
|
return result;
|
|
},
|
|
});
|
|
return work(proxy);
|
|
}),
|
|
});
|
|
await read();
|
|
expect(changed).toBe(true);
|
|
expect(mode).toEqual({ isolation: 'repeatable read', readonly: 'on' });
|
|
expect(trace[0]).toBe('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
|
expect(trace.some(sql => /FOR (UPDATE|SHARE)|^(INSERT|UPDATE|DELETE)/i.test(sql))).toBe(
|
|
false
|
|
);
|
|
Object.defineProperty(f.postgres, 'transaction', { configurable: true, value: transaction });
|
|
await expect(f.research.getArtifact(artifact.id)).rejects.toThrow(
|
|
'Retained finding source evidence could not be resolved'
|
|
);
|
|
await mutate(f, 'research_experiments', c.detail.id, 'preview_hash', c.source.previewHash);
|
|
}
|
|
expect(original.validation_phase).toBeNull();
|
|
}, 60000);
|
|
});
|