fix(research): verify single-run finding acknowledgements (RP24)

This commit is contained in:
Boki 2026-10-27 22:14:27 -04:00
parent 2da899daf2
commit f80ae2f3f3
4 changed files with 233 additions and 27 deletions

View file

@ -5,6 +5,7 @@ import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import type {
ResearchArtifact,
ResearchContentOrigin,
ResearchEvidenceReference,
ResearchHypothesis,
ResearchProject,
} from '@stock-bot/types';
@ -24,6 +25,15 @@ import {
} from './findingSources';
import { ResearchEvidenceList, researchMetricLabel } from './ResearchEvidence';
function referenceIdentities(references: ResearchEvidenceReference[]) {
return references.map(({ runId, metricsVersion, metricPath, strategyVersionId }) => ({
runId,
metricsVersion,
metricPath,
strategyVersionId: strategyVersionId ?? null,
}));
}
/** Preserve the original single-run API and initial total-return selection. */
export function SaveFindingDialog({
result,
@ -252,19 +262,11 @@ function FindingDraft({
artifact.projectId !== projectId ||
artifact.hypothesisRevisionId !== input.hypothesisRevisionId ||
artifact.kind !== 'finding' ||
(source.context !== null &&
(canonicalStrategyJson(artifact.latestRevision.source ?? null) !==
canonicalStrategyJson(source.context) ||
canonicalStrategyJson(
artifact.latestRevision.evidence.map(
({ runId, metricsVersion, metricPath, strategyVersionId }) => ({
runId,
metricsVersion,
metricPath,
strategyVersionId,
})
)
) !== canonicalStrategyJson(input.evidence)))
canonicalStrategyJson(artifact.latestRevision.source ?? null) !==
canonicalStrategyJson(source.context) ||
!Array.isArray(artifact.latestRevision.evidence) ||
canonicalStrategyJson(referenceIdentities(artifact.latestRevision.evidence)) !==
canonicalStrategyJson(referenceIdentities(input.evidence ?? []))
) {
throw new ResearchApiError('The saved finding response could not be verified.', null);
}

View file

@ -285,6 +285,7 @@ export async function fixture(browser: Browser, native = false) {
'30-paper-deployments.sql',
'31-research-agent-project-links.sql',
'32-candidate-parameter-defaults.sql',
'33-candidate-decimal-normalization.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')

View file

@ -2136,6 +2136,102 @@ test('canonical_native_smoke', async () => {
}
});
test('single_run_finding_acknowledgement_blocks_duplicates_and_reopens_committed_evidence_browser', async () => {
const f = await fixture(true);
try {
await f.login();
const { id } = await createCanonicalInBrowser(f, 'Finding acknowledgement oracle', true);
const runId = f.page.url().split('/').at(-1)!;
f.dispatcher.start();
await visible(f.page, 'Canonical research result');
const native = (await f.request(`/api/v2/runs/${runId}/results`)) as CanonicalRunResult;
const { project } = await f.request('/api/v2/research-projects', 'POST', {
title: 'Finding acknowledgement recovery',
});
const counts = async () =>
(
await f.pool.query(`SELECT
(SELECT count(*)::int FROM runs) AS runs,
(SELECT count(*)::int FROM backtest_dispatch) AS dispatch,
(SELECT count(*)::int FROM analysis_artifacts) AS artifacts`)
).rows[0];
expect(await counts()).toEqual({ runs: 1, dispatch: 1, artifacts: 0 });
await f.page.getByRole('button', { name: 'Save 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('Keep exact native evidence');
await dialog
.getByLabel('Finding body', { exact: true })
.fill('Retain this draft on uncertainty.');
const endpoint = `**/api/v2/research-projects/${project.id}/analysis-artifacts`;
let posts = 0;
let committed: ResearchArtifact | undefined;
await f.page.route(endpoint, async route => {
posts++;
// The real write commits. Only its browser acknowledgement loses the evidence.
const response = await route.fetch();
expect(response.status()).toBe(201);
const payload = (await response.json()) as { artifact: ResearchArtifact };
committed = structuredClone(payload.artifact);
payload.artifact.latestRevision.evidence = [];
await route.fulfill({ response, json: payload });
});
await dialog.getByRole('button', { name: 'Save finding', exact: true }).click();
await visible(f.page, 'The saved finding response could not be verified.');
await visible(f.page, /Check saved records before creating another/);
expect(await dialog.getByLabel('Finding title', { exact: true }).inputValue()).toBe(
'Keep exact native evidence'
);
expect(await dialog.getByLabel('Finding body', { exact: true }).inputValue()).toBe(
'Retain this draft on uncertainty.'
);
expect(await dialog.getByLabel('Finding title', { exact: true }).isDisabled()).toBe(true);
expect(
await dialog.getByRole('button', { name: 'Save finding', exact: true }).isDisabled()
).toBe(true);
expect(
await dialog.getByRole('link', { name: 'Open saved finding', exact: true }).count()
).toBe(0);
expect(posts).toBe(1);
expect(await counts()).toEqual({ runs: 1, dispatch: 1, artifacts: 1 });
if (!committed) {
throw new Error('Expected the original committed finding');
}
expect(committed.latestRevision.evidence).toHaveLength(1);
expect(committed.latestRevision.evidence[0]).toMatchObject({
runId,
strategyVersionId: native.request.strategy.versionId,
metricPath: 'analytics.metrics.totalReturn',
value: native.analytics.metrics.totalReturn,
});
await f.page.unroute(endpoint);
f.page.on('dialog', event => void event.accept());
await f.page.goto(`${f.origin}/research/${project.id}?artifact=${committed.id}`);
await visible(f.page, 'Keep exact native evidence');
const measurements = f.page.getByRole('region', {
name: 'Referenced measurements',
exact: true,
});
await measurements.waitFor();
expect(await measurements.textContent()).toContain(
`Raw value: ${native.analytics.metrics.totalReturn}`
);
expect(
await measurements
.getByRole('link', { name: 'Open cited run', exact: true })
.getAttribute('href')
).toBe(`/backtests/${id}/run/${runId}`);
await f.page.reload();
await measurements.waitFor();
expect(await counts()).toEqual({ runs: 1, dispatch: 1, artifacts: 1 });
expect(await f.request(`/api/v2/runs/${runId}/results`)).toEqual(native);
expect(posts).toBe(1);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});
test('browser_legacy_frozen_history_reopens_without_reactivating_retired_execution', async () => {
const f = await fixture();
try {

View file

@ -9,6 +9,7 @@ import type {
import type {
BacktestRunResult,
ResearchArtifact,
ResearchEvidenceReference,
ResearchHypothesis,
ResearchProject,
} from '@stock-bot/types';
@ -161,6 +162,24 @@ const artifact = (hypothesisRevisionId: string | null = null): ResearchArtifact
createdAt: '2026-10-23',
},
});
function acceptedFinding(hypothesisRevisionId: string | null = null): ResearchArtifact {
const saved = artifact(hypothesisRevisionId);
const input = post().body as { evidence: ResearchEvidenceReference[] };
saved.latestRevision.source = null;
saved.latestRevision.evidence = input.evidence.map(reference => ({
...reference,
backtestId: 'definition',
value: reference.metricPath.endsWith('sharpeRatio') ? null : 0.23,
unit: 'fraction',
availability: reference.metricPath.endsWith('sharpeRatio') ? 'unavailable' : 'available',
unavailableReason: reference.metricPath.endsWith('sharpeRatio') ? 'insufficient-data' : null,
resultKind: reference.metricsVersion === 'canonical-analytics/v1' ? 'canonical' : 'legacy',
financialEngine: reference.metricsVersion === 'canonical-analytics/v1' ? 'rust' : 'typescript',
datasetHash: 'a'.repeat(64),
limitations: [],
}));
return saved;
}
function legacy(runId = 'run'): BacktestRunResult {
return {
runId,
@ -385,29 +404,117 @@ describe('saved-result finding', () => {
},
],
});
await flush(() => reply(post(), { artifact: artifact('h1-revision') }, 201));
await flush(() => reply(post(), { artifact: acceptedFinding('h1-revision') }, 201));
expect(host.querySelector('a')?.getAttribute('href')).toBe(
'/research/p1?artifact=saved-finding'
);
expect(host.textContent).toContain('narrative remains unvalidated');
expect(closed).toBe(0);
});
test('legacy citations retain qualification and do not infer a strategy version', async () => {
await mountDialog(legacy());
test.each([
'empty',
'missing',
'extra',
'foreign-run',
'foreign-version',
'missing-version',
'foreign-metric',
'legacy-metric',
'foreign-source',
] as const)('%s evidence acknowledgement freezes the single-run finding draft', async failure => {
await mountDialog();
await draft();
await preflight();
expect(host.textContent).toContain('Legacy · Unverified economics');
expect(post().body).toEqual({
kind: 'finding',
title: 'Exact finding',
body: 'Keep this narrative',
contentOrigin: 'human',
hypothesisRevisionId: null,
evidence: [
{ runId: 'run', metricsVersion: 'legacy-display/v1', metricPath: 'metrics.totalReturn' },
],
});
const saved = acceptedFinding();
const reference = saved.latestRevision.evidence[0]!;
switch (failure) {
case 'empty':
saved.latestRevision.evidence = [];
break;
case 'missing':
delete (saved.latestRevision as Partial<ResearchArtifact['latestRevision']>).evidence;
break;
case 'extra':
saved.latestRevision.evidence.push({ ...reference, metricPath: 'analytics.fillCount' });
break;
case 'foreign-run':
reference.runId = 'another-run';
break;
case 'foreign-version':
reference.strategyVersionId = 'another-version';
break;
case 'missing-version':
reference.strategyVersionId = null;
break;
case 'foreign-metric':
reference.metricPath = 'analytics.metrics.maxDrawdown';
break;
case 'legacy-metric':
reference.metricsVersion = 'legacy-display/v1';
reference.metricPath = 'metrics.totalReturn';
break;
case 'foreign-source':
saved.latestRevision.source = {
kind: 'experiment/v1',
experimentId: '22222222-2222-4222-8222-222222222222',
previewHash: 'a'.repeat(64),
};
break;
}
await flush(() => reply(post(), { artifact: saved }, 201));
expect(host.textContent).toContain('saved finding response could not be verified');
expect(host.textContent).toContain('Check saved records before creating another');
expect(host.textContent).not.toContain('Finding saved.');
expect(host.textContent).not.toContain('Open saved finding');
expect(field('Finding title').value).toBe('Exact finding');
expect(field('Finding body').value).toBe('Keep this narrative');
expect(field('Finding title').disabled).toBe(true);
expect(button('Save finding').disabled).toBe(true);
await flush(() => button('Save finding').click());
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
});
test.each(['omitted', 'null'] as const)(
'matching canonical evidence accepts %s aggregate source',
async source => {
await mountDialog();
await draft();
await preflight();
const saved = acceptedFinding();
if (source === 'omitted') {
delete saved.latestRevision.source;
}
await flush(() => reply(post(), { artifact: saved }, 201));
expect(host.textContent).toContain('Finding saved.');
expect(host.querySelector('a')?.getAttribute('href')).toContain('artifact=saved-finding');
}
);
test.each(['omitted', 'null'] as const)(
'legacy citations accept %s version without inferring one',
async version => {
await mountDialog(legacy());
await draft();
await preflight();
expect(host.textContent).toContain('Legacy · Unverified economics');
expect(post().body).toEqual({
kind: 'finding',
title: 'Exact finding',
body: 'Keep this narrative',
contentOrigin: 'human',
hypothesisRevisionId: null,
evidence: [
{ runId: 'run', metricsVersion: 'legacy-display/v1', metricPath: 'metrics.totalReturn' },
],
});
const saved = acceptedFinding();
if (version === 'null') {
saved.latestRevision.evidence[0]!.strategyVersionId = null;
}
await flush(() => reply(post(), { artifact: saved }, 201));
expect(host.textContent).toContain('Finding saved.');
expect(host.textContent).toContain('Legacy · Unverified economics');
expect(host.querySelector('a[href*="/strategies/versions/"]')).toBeNull();
}
);
test('late project and hypothesis responses cannot overwrite the current destination', async () => {
await mountDialog();
await flush(() => edit('Finding project', 'p1'));