fix(research): accept eligible isolated candidate reproduction previews (RP13)

This commit is contained in:
Boki 2026-10-27 14:57:09 -04:00
parent 8807d9e504
commit 773314d29e
6 changed files with 251 additions and 6 deletions

View file

@ -256,7 +256,8 @@ export interface CanonicalReproductionPreview {
available: boolean;
reason: string | null;
request: CanonicalRunRequest | null;
/** Current approval required for a fresh admission; historical approval stays in request. */
/** Current eligible review receipt; built-ins require approval, isolated candidates may have none.
* Unavailable previews may leave this unresolved. The original receipt stays in request. */
currentReviewId: string | null;
}
export interface CanonicalReproductionComparison {

View file

@ -259,7 +259,7 @@ function Reproduction({ run, archived }: Props) {
<p>
This submits a new run using the original dataset, strategy version, parameters, seed
and policies. Current template settings are not used. The same installed engine build
and current strategy approval are required.
and current execution eligibility are required.
</p>
{loading && <p role="status">Loading original inputs...</p>}
{previewError && <p role="alert">{previewError}</p>}
@ -298,8 +298,20 @@ function Reproduction({ run, archived }: Props) {
{preview.request.policy.matching.risk.ledger.baseCurrency}
</p>
<p className="text-xs break-all">
Original review: {preview.request.strategy.reviewId} · Current approval:{' '}
{preview.currentReviewId ?? 'Unavailable'}
Original review: {preview.request.strategy.reviewId ?? 'None recorded'} ·{' '}
{preview.request.strategy.origin === 'candidate'
? 'Current review'
: 'Current approval'}
:{' '}
{preview.currentReviewId ??
(preview.request.strategy.origin === 'candidate' && preview.available
? 'None recorded'
: 'Unavailable')}
</p>
<p className="text-xs">
{preview.request.strategy.origin === 'candidate'
? 'Isolated candidates do not require approval for research reproduction. The retained sandbox must be available, and explicit revocation blocks new reproduction.'
: 'Built-in strategies require current operator approval for reproduction.'}
</p>
<details>
<summary className="cursor-pointer">

View file

@ -441,7 +441,8 @@ export const backtestApiV2 = {
const request = body.request === null ? null : canonicalRunRequestSchema.parse(body.request);
if (
(request && (request.runId !== id || request.backtestId !== body.backtestId)) ||
(body.available && (!request || !body.currentReviewId))
(body.available &&
(!request || (request.strategy.origin === 'builtin' && !body.currentReviewId)))
) {
throw new Error('The original-run preview does not match its retained source');
}

View file

@ -3747,6 +3747,86 @@ test('isolated_candidate_publication_research_validation_and_reviewed_paper_hist
await f.page.reload();
await visible(f.page, result.request.datasetHash);
// Reproduction of an isolated candidate does not require inventing a human review.
const candidateReviewCount = async () =>
(
await f.pool.query(
'SELECT count(*)::int AS count FROM strategy_review_events WHERE version_id=$1',
[version.id]
)
).rows[0].count;
expect(await candidateReviewCount()).toBe(0);
const previewingReproduction = f.page.waitForResponse(response =>
response.url().endsWith(`/runs/${runId}/reproduction`)
);
await f.page.getByRole('button', { name: 'Reproduce original', exact: true }).click();
const reproductionPreview = await previewingReproduction;
expect(reproductionPreview.status()).toBe(200);
expect(await reproductionPreview.json()).toMatchObject({
originalRunId: runId,
available: true,
currentReviewId: null,
request: { strategy: { origin: 'candidate', reviewId: null } },
});
const reproductionDialog = f.page.getByRole('dialog', {
name: 'Reproduce original',
exact: true,
});
const originalInputs = reproductionDialog.getByRole('region', {
name: 'Original retained inputs',
exact: true,
});
await originalInputs.waitFor({ state: 'visible' });
expect(await originalInputs.textContent()).toContain(result.request.datasetHash);
expect(await originalInputs.textContent()).toContain(version.id);
const reproducing = f.page.waitForResponse(
response =>
response.request().method() === 'POST' &&
response.url().endsWith(`/runs/${runId}/reproduce`)
);
await reproductionDialog
.getByRole('button', { name: 'Confirm reproduction', exact: true })
.click();
const reproducedResponse = await reproducing;
expect(reproducedResponse.status()).toBe(202);
expect(reproducedResponse.request().postDataJSON()).toEqual({});
const receipt = reproducedResponse.request().headers()['idempotency-key']!;
expect(receipt).toBeTruthy();
const reproducedRun = await reproducedResponse.json();
expect(reproducedRun.originalRunId).toBe(runId);
expect(reproducedRun.id).not.toBe(runId);
await f.page.waitForURL(`${f.origin}/backtests/${draft.id}/run/${reproducedRun.id}`);
const duplicate = await f.request(
`/api/v2/runs/${runId}/reproduce`,
'POST',
{},
{
'Idempotency-Key': receipt,
}
);
expect(duplicate.id).toBe(reproducedRun.id);
await visible(f.page, 'Economic results match the original.');
const reproducedResult = (await f.request(
`/api/v2/runs/${reproducedRun.id}/results`
)) as CanonicalRunResult;
expect(reproducedResult.strategyExecution).toBe('typescript-isolated-candidate/v1');
expect(reproducedResult.request.strategy).toEqual(result.request.strategy);
expect(reproducedResult.request.build).toEqual(result.request.build);
expect(reproducedResult.request.datasetHash).toBe(result.request.datasetHash);
expect(reproducedResult.financial.projection.valuation).toEqual(
result.financial.projection.valuation
);
expect(reproducedResult.analytics).toEqual(result.analytics);
expect(await f.request(`/api/v2/runs/${runId}/results`)).toEqual(result);
expect(await candidateReviewCount()).toBe(0);
expect(
(await f.pool.query('SELECT id FROM runs WHERE original_run_id=$1', [runId])).rowCount
).toBe(1);
await f.page.reload();
await visible(f.page, 'Economic results match the original.');
await f.page.getByRole('link', { name: 'Open original run', exact: true }).click();
await f.page.waitForURL(`${f.origin}/backtests/${draft.id}/run/${runId}`);
// Real immutable validation and cost evidence prepare the human promotion screen.
const candidate = { versionId: version.id, parameters: { fastPeriod: 2, slowPeriod: 3 } };
const validationInput = {

View file

@ -2,6 +2,7 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } fr
import { GlobalWindow } from 'happy-dom';
import { act, createElement, type ReactElement } from 'react';
import type { Root } from 'react-dom/client';
import { candidateSandboxLimits } from '@stock-bot/stock-config/candidate-execution';
import {
canonicalRunRequestSchema,
type CanonicalReproductionComparison,
@ -169,6 +170,43 @@ function preview(
...extra,
};
}
function candidatePreview(
originalReviewId: string | null = null,
currentReviewId: string | null = null
): CanonicalReproductionPreview {
const value = preview();
const original = value.request!.strategy;
value.request = canonicalRunRequestSchema.parse({
...value.request,
strategy: {
...original,
origin: 'candidate',
reviewId: originalReviewId,
baselineVersionId: '88888888-8888-4888-8888-888888888888',
package: {
...original.package,
execution: { kind: 'isolated-candidate/v1', warmupBars: 0 },
},
execution: {
kind: 'typescript-isolated-candidate/v1',
imageId: `sha256:${'a'.repeat(64)}`,
profile: {
version: 1,
policy: 'linux-docker-guardian/v1',
protocol: 'candidate-controller/v1',
platform: 'linux',
arch: 'x64',
hostSha256: 'b'.repeat(64),
guardianSha256: 'c'.repeat(64),
bunSha256: 'd'.repeat(64),
limits: candidateSandboxLimits,
},
},
},
});
value.currentReviewId = currentReviewId;
return value;
}
const comparison = (
status: CanonicalReproductionComparison['status'] = 'match'
): CanonicalReproductionComparison => ({
@ -256,6 +294,115 @@ afterAll(async () => {
});
describe('original-run reproduction UI', () => {
test.each(['unreviewed', 'reviewed', 'reviewed since original'] as const)(
'%s isolated candidate uses retained inputs and accurately labels review receipts',
async state => {
const originalReview = state === 'reviewed' ? '66666666-6666-4666-8666-666666666666' : null;
const currentReview = state === 'unreviewed' ? null : '77777777-7777-4777-8777-777777777777';
const value = candidatePreview(originalReview, currentReview);
await open();
await flush(() => reply(request(`/api/v2/runs/${sourceId}/reproduction`), value));
expect(button('Confirm reproduction').disabled).toBe(false);
expect(host.textContent).toContain('Frozen original inputs');
expect(host.textContent).toContain(value.request!.datasetHash);
expect(host.textContent).toContain(
`Original review: ${originalReview ?? 'None recorded'} · Current review: ${currentReview ?? 'None recorded'}`
);
expect(host.textContent).toContain('Isolated candidates do not require approval');
expect(host.textContent).not.toContain('Current approval:');
expect(requests.every(item => item.method === 'GET')).toBe(true);
await flush(() => button('Confirm reproduction').click());
expect(post().body).toEqual({});
expect(post().headers.get('Idempotency-Key')).toMatch(/^[a-f0-9-]{36}$/);
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
await flush(() => reply(post(), run(otherId, { originalRunId: sourceId }), 202));
expect(location).toBe(`/backtests/${backtestId}/run/${otherId}`);
}
);
test('an available built-in preview still requires current operator approval', async () => {
await open();
await flush(() =>
reply(
request(`/api/v2/runs/${sourceId}/reproduction`),
preview(sourceId, { currentReviewId: null })
)
);
expect(button('Confirm reproduction').disabled).toBe(true);
expect(host.textContent).toContain('does not match its retained source');
expect(requests.every(item => item.method === 'GET')).toBe(true);
});
test.each([
'The original candidate version is explicitly revoked',
'The retained isolated candidate runtime is not installed',
])('unavailable candidate stays blocked: %s', async reason => {
await open();
await flush(() =>
reply(request(`/api/v2/runs/${sourceId}/reproduction`), {
...candidatePreview(),
available: false,
reason,
})
);
expect(button('Confirm reproduction').disabled).toBe(true);
expect(host.textContent).toContain(reason);
expect(host.textContent).toContain(
'Original review: None recorded · Current review: Unavailable'
);
expect(requests.every(item => item.method === 'GET')).toBe(true);
});
test.each(['runtime', 'missing-runtime', 'run', 'parent'] as const)(
'candidate %s mismatch cannot authorize a fresh reproduction',
async field => {
const value = candidatePreview();
const retained = value.request!;
if (retained.strategy.origin !== 'candidate') {
throw new Error('Expected candidate fixture');
}
if (field === 'runtime') {
retained.strategy.execution.imageId = 'unversioned-image';
} else if (field === 'missing-runtime') {
Reflect.deleteProperty(retained.strategy, 'execution');
} else if (field === 'run') {
retained.runId = otherId;
} else {
retained.backtestId = otherId;
}
await open();
await flush(() => reply(request(`/api/v2/runs/${sourceId}/reproduction`), value));
expect(button('Confirm reproduction').disabled).toBe(true);
expect(host.querySelector('[role="alert"]')).not.toBeNull();
expect(requests.every(item => item.method === 'GET')).toBe(true);
}
);
test('candidate ambiguous submission retries the original source/key after eligibility changes', async () => {
await open();
await flush(() => reply(request(`/api/v2/runs/${sourceId}/reproduction`), candidatePreview()));
await flush(() => button('Confirm reproduction').click());
const first = post();
const key = first.headers.get('Idempotency-Key');
await flush(() => {
first.settled = true;
first.reject(new Error('Lost response'));
});
await flush(() => button('Refresh original inputs').click());
await flush(() =>
reply(request(`/api/v2/runs/${sourceId}/reproduction`), {
...candidatePreview(),
available: false,
reason: 'The original candidate version is explicitly revoked',
})
);
expect(button('Retry reproduction').disabled).toBe(false);
await flush(() => button('Retry reproduction').click());
expect(post().headers.get('Idempotency-Key')).toBe(key);
expect(post().body).toEqual({});
expect(requests.filter(item => item.method === 'POST')).toHaveLength(2);
expect(
requests.filter(item => item.method === 'POST').every(item => item.path === first.path)
).toBe(true);
await flush(() => reply(post(), run(otherId, { originalRunId: sourceId }), 202));
expect(location).toBe(`/backtests/${backtestId}/run/${otherId}`);
});
test('preview is read-only, renders exact retained inputs, and double-click admission sends only source/key', async () => {
const value = await ready();
expect(host.textContent).toContain('Frozen original inputs');

View file

@ -324,7 +324,11 @@ suite('isolated candidate durable research', () => {
expect((await f.experiments.retryTrial(experiment.id, runId, retryBody, actor)).retry.id).toBe(
retry.retry.id
);
expect((await f.api.getReproductionPreview(runId)).available).toBeTrue();
expect(await f.api.getReproductionPreview(runId)).toMatchObject({
available: true,
currentReviewId: null,
request: { strategy: { origin: 'candidate', reviewId: null } },
});
const reproduced = await f.api.reproduceRun(runId, {
principal: 'operator',
key: 'reproduction',