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

@ -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',