feat(research): retain exact experiment and report citations in findings

This commit is contained in:
Boki 2026-10-24 14:42:14 -04:00
parent 46a4f13acd
commit 06039d17ba
36 changed files with 4170 additions and 253 deletions

View file

@ -298,6 +298,7 @@ export async function fixture(browser: Browser, native = false) {
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
'27-research-evidence-sources.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')

View file

@ -28,6 +28,7 @@ import type {
WalkForwardDetail,
WalkForwardPreview,
} from '@stock-bot/stock-config/walk-forward';
import type { ResearchArtifact, ResearchFindingSource } from '@stock-bot/types';
import { retainResearchDataset } from '../../scripts/import-research-dataset';
import { canonicalSettings } from '../fixtures/canonical-research';
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
@ -55,6 +56,101 @@ afterAll(async () => {
});
const fixture = (native = false) => createFixture(browser, native);
/** Uses real retained native measurements, then reopens the exact source from immutable history. */
async function saveSourceFindingInBrowser(
f: Awaited<ReturnType<typeof fixture>>,
source: ResearchFindingSource,
choices: { runId: string; metricPath: string }[],
title: string
) {
const sourceUrl = f.page.url();
await f.page.getByRole('heading', { name: 'Regime evidence unavailable', exact: true }).waitFor();
const counts = async () =>
(
await f.pool.query(`SELECT
(SELECT count(*)::int FROM runs) AS runs,
(SELECT count(*)::int FROM backtest_dispatch) AS dispatch`)
).rows[0];
const before = await counts();
const { project } = await f.request('/api/v2/research-projects', 'POST', {
title: `${title} project`,
});
await f.page.getByRole('button', { name: 'Save research finding', exact: true }).click();
const dialog = f.page.getByRole('dialog', { name: 'Save finding', exact: true });
await dialog.getByLabel('Finding project', { exact: true }).selectOption(project.id);
await dialog.getByLabel('Finding title', { exact: true }).fill(title);
await dialog
.getByLabel('Finding body', { exact: true })
.fill(
'Selected retained measurements support further investigation; this narrative is not validated alpha.'
);
expect(await dialog.getByRole('button', { name: 'Save finding', exact: true }).isDisabled()).toBe(
true
);
for (const choice of choices) {
await dialog
.locator(`input[data-run-id="${choice.runId}"][data-metric-path="${choice.metricPath}"]`)
.check();
}
const creating = f.page.waitForResponse(
response =>
response.request().method() === 'POST' &&
response.url().endsWith(`/research-projects/${project.id}/analysis-artifacts`)
);
await dialog.getByRole('button', { name: 'Save finding', exact: true }).click();
const response = await creating;
expect(response.status()).toBe(201);
expect(response.request().postDataJSON().source).toEqual(source);
const { artifact } = (await response.json()) as { artifact: ResearchArtifact };
expect(artifact.latestRevision.source).toEqual(source);
expect(artifact.latestRevision.validationState).toBe('unvalidated');
expect(artifact.latestRevision.evidence).toHaveLength(choices.length);
for (const choice of choices) {
const item = artifact.latestRevision.evidence.find(
evidence => evidence.runId === choice.runId && evidence.metricPath === choice.metricPath
)!;
const result = (await f.request(`/api/v2/runs/${choice.runId}/results`)) as CanonicalRunResult;
const key = choice.metricPath.slice(
'analytics.metrics.'.length
) as keyof typeof result.analytics.metrics;
expect(item.value).toBe(result.analytics.metrics[key]);
expect(item.unavailableReason).toBe(
item.value === null ? (result.analytics.unavailable[key] ?? 'not-reported') : null
);
expect(item.financialEngine).toBe('rust');
expect(item.datasetHash).toBe(result.request.datasetHash);
}
await dialog.getByRole('link', { name: 'Open saved finding', exact: true }).click();
const findingUrl = `${f.origin}/research/${project.id}?artifact=${artifact.id}`;
await f.page.waitForURL(findingUrl);
const sourceLink = f.page.getByRole('link', { name: 'Open cited source', exact: true });
await sourceLink.waitFor();
expect(await sourceLink.getAttribute('href')).toBe(new URL(sourceUrl).pathname);
await f.page.getByRole('button', { name: 'Edit latest revision', exact: true }).click();
await f.page.getByLabel('Revision title', { exact: true }).fill(`${title} revised`);
const revising = f.page.waitForResponse(
reply =>
reply.request().method() === 'POST' &&
reply.url().endsWith(`/analysis-artifacts/${artifact.id}/revisions`)
);
await f.page.getByRole('button', { name: 'Save new revision', exact: true }).click();
const revised = await revising;
expect(revised.status()).toBe(201);
expect(revised.request().postDataJSON().source).toEqual(source);
const updated = (await revised.json()) as { artifact: ResearchArtifact };
expect(updated.artifact.latestRevision.ordinal).toBe(2);
expect(updated.artifact.latestRevision.source).toEqual(source);
expect(updated.artifact.latestRevision.evidence).toEqual(artifact.latestRevision.evidence);
await f.page.getByRole('button', { name: 'View revision 1', exact: true }).click();
await visible(f.page, 'Immutable history: this revision is read-only.');
await f.page.reload();
await visible(f.page, 'Immutable history: this revision is read-only.');
await sourceLink.click();
await f.page.waitForURL(sourceUrl);
await f.page.getByRole('button', { name: 'Save research finding', exact: true }).waitFor();
expect(await counts()).toEqual(before);
}
test('saved_experiment_comparison_preserves_cost_reference_native_summaries_and_archived_history_browser', async () => {
const f = await fixture(true);
f.page.on('dialog', dialog => void dialog.accept());
@ -377,6 +473,19 @@ test('cost_sensitivity_freezes_policy_runs_native_scenarios_and_reopens_existing
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(3);
await f.page.reload();
await visible(f.page, /completed: 3/);
await saveSourceFindingInBrowser(
f,
{
kind: 'experiment/v1',
experimentId: experiment.id,
previewHash: preview.previewHash,
},
[
{ runId: experiment.trials[0]!.runId!, metricPath: 'analytics.metrics.totalReturn' },
{ runId: experiment.trials[2]!.runId!, metricPath: 'analytics.metrics.sharpeRatio' },
],
'Retained cost comparison finding'
);
await f.page.getByRole('link', { name: 'All experiments', exact: true }).click();
await f.page.getByRole('link', { name: 'Fixed fee and slippage study', exact: true }).click();
await visible(f.page, /completed: 3/);
@ -602,6 +711,45 @@ test('walk_forward_freezes_all_windows_runs_native_members_and_reopens_reset_rep
await visible(f.page, 'Saved walk-forward validations');
await f.page.locator(`a[href="/experiments/walk-forward/${initial.id}"]`).click();
await visible(f.page, 'Execution complete · walk-forward report saved');
await saveSourceFindingInBrowser(
f,
{
kind: 'walk-forward-report/v1',
walkForwardId: initial.id,
previewHash: report.previewHash,
reportId: report.id,
reportHash: report.reportHash,
},
[
{
runId: report.segments[0]!.validation.runId,
metricPath: 'analytics.metrics.totalReturn',
},
{ runId: report.segments[1]!.test.runId, metricPath: 'analytics.metrics.maxDrawdown' },
{ runId: report.segments[1]!.test.runId, metricPath: 'analytics.metrics.sharpeRatio' },
],
'Retained walk-forward finding'
);
await f.page.getByRole('link', { name: 'Open window 1 validation', exact: true }).click();
const child = childReports[0]!;
await visible(f.page, 'Execution complete · report saved');
await saveSourceFindingInBrowser(
f,
{
kind: 'chronological-report/v1',
validationId: child.validationId,
previewHash: child.previewHash,
reportId: child.id,
reportHash: child.reportHash,
},
[
{ runId: child.training[0]!.runId, metricPath: 'analytics.metrics.totalReturn' },
{ runId: child.test.runId, metricPath: 'analytics.metrics.sharpeRatio' },
],
'Retained chronological finding'
);
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(8);
expect((await f.pool.query('SELECT * FROM analysis_artifacts')).rowCount).toBe(2);
expect(f.historicalDataReads).toEqual([]);
expect(f.unexpectedNetwork).toEqual([]);
} finally {

View file

@ -17,12 +17,17 @@ function fixture(
security: 'enabled' | 'disabled' | 'absent' = 'enabled',
query: Query = async () => {
throw new Error('Rejected request reached storage');
}
},
allowReadTransaction = false
) {
const transactionQuery = mock(query);
const database = {
query: mock(query),
transaction: mock(async () => {
throw new Error('Rejected request reached transaction');
transaction: mock(async (callback: (client: { query: Query }) => Promise<unknown>) => {
if (!allowReadTransaction) {
throw new Error('Rejected request reached transaction');
}
return callback({ query: transactionQuery });
}),
};
const logger = { error: mock((_message: string, _details?: unknown) => {}) };
@ -44,6 +49,7 @@ function fixture(
app.post('/api/v2/unrelated', c => c.json({ ok: true }));
return {
database,
transactionQuery,
logger,
app,
request(
@ -349,79 +355,94 @@ describe('research HTTP credential and transport boundary', () => {
const runId = randomUUID();
const backtestId = randomUUID();
const stamp = new Date('2026-01-01');
const f = fixture('enabled', async sql => {
if (sql.includes('FROM analysis_artifacts WHERE')) {
return {
rows: [
{
id: artifactId,
project_id: projectId,
hypothesis_revision_id: null,
kind: 'finding',
owner_principal: 'operator',
updated_by: 'operator',
archived_at: null,
created_at: stamp,
updated_at: stamp,
},
],
};
}
if (sql.includes('FROM analysis_artifact_revisions WHERE')) {
return {
rows: [
{
id: revisionId,
artifact_id: artifactId,
ordinal: 1,
title: 'Retained finding',
body: 'Narrative is not a metric',
submitted_by: 'operator',
content_origin: 'human',
created_at: stamp,
},
],
};
}
if (sql.includes('FROM analysis_evidence WHERE')) {
return {
rows: [
{
revision_id: revisionId,
ordinal: 1,
run_id: runId,
metrics_version: 'canonical-analytics/v1',
metric_path: 'analytics.metrics.totalReturn',
strategy_version_id: null,
},
],
};
}
if (sql.includes('FROM runs WHERE')) {
return { rows: [{ id: runId, backtest_id: backtestId, status: 'completed' }] };
}
if (sql.includes('FROM backtest_results br')) {
// The reference is valid. This damage is in retained server evidence,
// and must not be classified as a malformed client request.
return {
rows: [
{
run_id: runId,
backtest_id: backtestId,
run_status: 'completed',
canonical_result: { kind: 'canonical-result/v1' },
request_snapshot: { kind: 'canonical-research/v1', 'private-retained-marker': true },
},
],
};
}
throw new Error(`Unexpected evidence query: ${sql}`);
});
const f = fixture(
'enabled',
async sql => {
if (sql === 'SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY') {
return { rows: [] };
}
if (sql.includes('FROM analysis_artifacts WHERE')) {
return {
rows: [
{
id: artifactId,
project_id: projectId,
hypothesis_revision_id: null,
kind: 'finding',
owner_principal: 'operator',
updated_by: 'operator',
archived_at: null,
created_at: stamp,
updated_at: stamp,
},
],
};
}
if (sql.includes('FROM analysis_artifact_revisions WHERE')) {
return {
rows: [
{
id: revisionId,
artifact_id: artifactId,
ordinal: 1,
title: 'Retained finding',
body: 'Narrative is not a metric',
submitted_by: 'operator',
content_origin: 'human',
created_at: stamp,
},
],
};
}
if (sql.includes('FROM analysis_evidence WHERE')) {
return {
rows: [
{
revision_id: revisionId,
ordinal: 1,
run_id: runId,
metrics_version: 'canonical-analytics/v1',
metric_path: 'analytics.metrics.totalReturn',
strategy_version_id: null,
},
],
};
}
if (sql.includes('FROM runs WHERE')) {
return { rows: [{ id: runId, backtest_id: backtestId, status: 'completed' }] };
}
if (sql.includes('FROM backtest_results br')) {
// The reference is valid. This damage is in retained server evidence,
// and must not be classified as a malformed client request.
return {
rows: [
{
run_id: runId,
backtest_id: backtestId,
run_status: 'completed',
canonical_result: { kind: 'canonical-result/v1' },
request_snapshot: {
kind: 'canonical-research/v1',
'private-retained-marker': true,
},
},
],
};
}
throw new Error(`Unexpected evidence query: ${sql}`);
},
true
);
const response = await f.request(`analysis-artifacts/${artifactId}`, undefined, 'read');
expect(response.status).toBe(500);
expect(await response.json()).toEqual({ error: 'Research workspace unavailable' });
expect(response.headers.get('Cache-Control')).toBe('no-store');
expect(f.database.query.mock.calls).toHaveLength(5);
expect(f.database.query.mock.calls).toHaveLength(0);
expect(f.database.transaction.mock.calls).toHaveLength(1);
expect(f.transactionQuery.mock.calls).toHaveLength(6);
expect(f.transactionQuery.mock.calls[0]?.[0]).toBe(
'SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY'
);
expect(f.logger.error.mock.calls).toHaveLength(1);
const diagnostic = f.logger.error.mock.calls[0]?.[1] as { error?: unknown } | undefined;
expect(diagnostic?.error).toBeInstanceOf(Error);

View file

@ -0,0 +1,149 @@
import { randomUUID } from 'node:crypto';
import { describe, expect, mock, test } from 'bun:test';
import { Hono } from 'hono';
import { createHttpSecurity } from '@stock-bot/di';
import type { IServiceContainer } from '@stock-bot/services';
import { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes';
const tokens = {
operator: 'research-admin-fixture-not-a-real-secret-1234',
service: 'research-service-fixture-not-a-real-secret-1234',
read: 'research-read-fixture-not-a-real-secret-1234',
};
type Query = (sql: string, values?: unknown[]) => Promise<{ rows: Record<string, unknown>[] }>;
function fixture(
security: 'enabled' | 'disabled' | 'absent' = 'enabled',
query: Query = async () => {
throw new Error('Rejected request reached storage');
}
) {
const database = {
query: mock(query),
transaction: mock(async <T>(work: (client: { query: Query }) => Promise<T>) => work({ query })),
};
const logger = { error: mock((_message: string, _details?: unknown) => {}) };
const app = new Hono();
if (security !== 'absent') {
createHttpSecurity({
adminToken: tokens.operator,
serviceToken: tokens.service,
readToken: tokens.read,
environment: 'test',
hostname: '127.0.0.1',
disabled: security === 'disabled',
}).mount(app);
}
app.route(
'/',
createResearchRoutes({ postgres: database, logger } as unknown as IServiceContainer)
);
app.post('/api/v2/unrelated', c => c.json({ ok: true }));
return {
database,
logger,
app,
request(
path: string,
body?: unknown,
role?: keyof typeof tokens,
method = body === undefined ? 'GET' : 'POST',
extra: Record<string, string> = {}
) {
return app.request(`/api/v2/${path}`, {
method,
headers: {
...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}),
'Content-Type': 'application/json',
...extra,
},
...(body === undefined ? {} : { body: JSON.stringify(body) }),
});
},
};
}
const projectId = randomUUID(),
runId = randomUUID();
const source = { kind: 'experiment/v1', experimentId: randomUUID(), previewHash: 'a'.repeat(64) };
const body = {
kind: 'finding',
title: 'Evidence',
body: 'Claim',
source,
evidence: [
{
runId,
metricsVersion: 'canonical-analytics/v1',
metricPath: 'analytics.metrics.totalReturn',
},
],
};
describe('source findings HTTP boundary', () => {
test('malformed source metadata rejects before storage and write credentials remain mandatory', async () => {
for (const change of [
{ ...source, extra: true },
{ ...source, previewHash: null },
{ ...source, experimentId: 'bad' },
{ ...source, kind: 'chronological-report/v1' },
]) {
const f = fixture();
expect(
(
await f.request(
`research-projects/${projectId}/analysis-artifacts`,
{ ...body, source: change },
'operator'
)
).status
).toBe(400);
expect(f.database.transaction.mock.calls).toHaveLength(0);
}
const f = fixture();
expect(
(await f.request(`research-projects/${projectId}/analysis-artifacts`, body)).status
).toBe(401);
expect(
(await f.request(`research-projects/${projectId}/analysis-artifacts`, body, 'read')).status
).toBe(403);
expect(f.database.transaction.mock.calls).toHaveLength(0);
});
test('missing source is422 without exposing storage details; unexpected errors remain sanitized500', async () => {
for (const broken of [false, true]) {
const f = fixture('enabled', async sql => {
if (sql.includes('FROM research_projects')) {
return { rows: [{ id: projectId, archived_at: null }] };
}
if (sql.startsWith('INSERT INTO analysis_artifacts(')) {
return { rows: [{ id: randomUUID() }] };
}
if (broken) {
throw new Error('private database details');
}
return { rows: [] };
});
const response = await f.request(
`research-projects/${projectId}/analysis-artifacts`,
body,
'operator'
);
expect(response.status).toBe(broken ? 500 : 422);
expect(response.headers.get('Cache-Control')).toBe('no-store');
if (broken) {
expect(await response.json()).toEqual({ error: 'Research workspace unavailable' });
}
}
});
test('artifact reads select repeatable read-only mode before storage and do not require mutation credentials', async () => {
const calls: string[] = [];
const f = fixture('enabled', async sql => {
calls.push(sql);
return { rows: [] };
});
const response = await f.request(`analysis-artifacts/${randomUUID()}`, undefined, 'read');
expect(response.status).toBe(404);
expect(calls[0]).toBe('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
expect(calls.every(sql => !sql.includes('FOR UPDATE') && !sql.includes('FOR SHARE'))).toBe(
true
);
});
});

View file

@ -0,0 +1,104 @@
import { describe, expect, mock, test } from 'bun:test';
import {
createResearchArtifactSchema,
parseResearchInput,
researchFindingSourceSchema,
reviseResearchArtifactSchema,
} from '@stock-bot/stock-config/research';
import type { BacktestResultQuery } from '../../apps/stock/web-api/src/services/backtest-v2.service';
import { verifyResearchSource } from '../../apps/stock/web-api/src/services/research-source-evidence';
const id = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
const source = { kind: 'experiment/v1' as const, experimentId: id, previewHash: 'a'.repeat(64) };
const canonical = {
runId: id,
metricsVersion: 'canonical-analytics/v1' as const,
metricPath: 'analytics.metrics.totalReturn',
};
describe('finding source contract', () => {
test('strict source identities normalize UUIDs and reject client measurements, mixed kinds and missing hashes', () => {
expect(
researchFindingSourceSchema.parse({ ...source, experimentId: id.toUpperCase() })
).toEqual(source);
for (const raw of [
{ ...source, previewHash: 'A'.repeat(64) },
{ ...source, previewHash: null },
{ ...source, experimentId: null },
{ ...source, totalReturn: 0 },
{ ...source, reportId: id },
{ ...source, kind: 'unknown' },
{
kind: 'chronological-report/v1',
validationId: id,
previewHash: source.previewHash,
reportId: id,
},
{
kind: 'walk-forward-report/v1',
walkForwardId: id,
previewHash: source.previewHash,
reportId: id,
reportHash: 'bad',
},
]) {
expect(researchFindingSourceSchema.safeParse(raw).success).toBe(false);
}
for (const kind of ['chronological-report/v1', 'walk-forward-report/v1'] as const) {
const owner =
kind === 'chronological-report/v1'
? { validationId: id.toUpperCase() }
: { walkForwardId: id.toUpperCase() };
const parsed = researchFindingSourceSchema.parse({
kind,
...owner,
previewHash: source.previewHash,
reportId: id.toUpperCase(),
reportHash: 'b'.repeat(64),
});
expect('reportId' in parsed && parsed.reportId).toBe(id);
}
});
test('old create and revise requests preserve the distinction between omitted and explicitly detached sources', () => {
const body = { title: 'Observation', body: 'Unvalidated narrative', evidence: [canonical] };
expect(
parseResearchInput(createResearchArtifactSchema, { ...body, kind: 'finding' }).source
).toBeUndefined();
expect(
parseResearchInput(reviseResearchArtifactSchema, { ...body, expectedRevision: 1 }).source
).toBeUndefined();
expect(
parseResearchInput(reviseResearchArtifactSchema, {
...body,
expectedRevision: 1,
source: null,
}).source
).toBeNull();
expect(
parseResearchInput(createResearchArtifactSchema, { ...body, kind: 'note', source }).source
).toEqual(source);
});
test('source cannot substitute for canonical metric evidence; unavailable source fails before any result reader', async () => {
const query = mock(async () => ({ rows: [] })),
read = mock(async () => null);
const database = { query } as unknown as BacktestResultQuery;
for (const evidence of [
[],
[
{
runId: id,
metricsVersion: 'legacy-display/v1' as const,
metricPath: 'metrics.totalReturn',
},
],
]) {
await expect(verifyResearchSource(source, evidence, database, read)).rejects.toMatchObject({
status: 422,
});
}
expect(query.mock.calls).toHaveLength(0);
await expect(verifyResearchSource(source, [canonical], database, read)).rejects.toMatchObject({
status: 422,
});
expect(read.mock.calls).toHaveLength(0);
});
});

File diff suppressed because it is too large Load diff

View file

@ -466,6 +466,8 @@ describe.skipIf(!url)('durable validation adversarial boundaries', () => {
{ ...ordinaryInput, previewHash: preview.previewHash },
actor()
);
// Missing historical role metadata must remain readable without admitting a source citation.
expect(ordinary.standalone).toBe(false);
await f.execute(ordinary.trials[0]!.runId!);
const pending = ordinary.trials[1]!.runId!,
request = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [pending]))
@ -508,6 +510,7 @@ describe.skipIf(!url)('durable validation adversarial boundaries', () => {
await f.pool.query(migration);
expect(await f.snapshot()).toEqual(first);
expect((await f.experiments.list())[0]!.id).toBe(ordinary.id);
expect((await f.experiments.get(ordinary.id)).standalone).toBe(true);
// Current chronological admission can link roots to a walk-forward series.
await f.pool.query(
readFileSync(

View file

@ -29,6 +29,7 @@ const migrations = [
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
'27-research-evidence-sources.sql',
];
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {

View file

@ -0,0 +1,884 @@
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 { ChronologicalValidationService } from '../../apps/stock/web-api/src/services/chronological-validation.service';
import { experimentHash } from '../../apps/stock/web-api/src/services/experiment-input';
import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.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 { 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 validations = new ChronologicalValidationService(container);
const repository = new PostgresBacktestRunRepository(postgres);
const execute = async (id: string) => {
const engine = new RustBacktestAdapter({
logger,
storage: {
async getHistoricalBars() {
throw new Error('No provider reads allowed');
},
},
});
const runner = new BacktestRunner({ engine, engineName: 'native', 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: new WalkForwardService(container),
repository,
execute,
api,
pool,
postgres,
experiments,
catalog,
version,
draft,
dataset,
input,
research: new ResearchService(container),
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);
});

View file

@ -71,6 +71,7 @@ async function fixture(applyWorkspace = true, maxConnections = 10) {
}
if (applyWorkspace) {
await pool.query(migration);
await pool.query(sql('27-research-evidence-sources.sql'));
}
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
@ -715,6 +716,8 @@ describe.skipIf(!url)('research workspace retained narratives and evidence', ()
await f.pool.query(migration);
await f.pool.query(migration);
expect(await snapshot()).toEqual(before);
// Current service writes include optional source identity; historical SQL20 assertions above stay scoped.
await f.pool.query(sql('27-research-evidence-sources.sql'));
const p = await f.service.createProject({ title: 'After upgrade' }, 'operator');
const finding = await f.service.createArtifact(
p.id,