feat(research): archive backtests and protect retained evidence

This commit is contained in:
Boki 2026-10-23 20:18:58 -04:00
parent 4a2e5ad362
commit 8cca0ee588
25 changed files with 1550 additions and 79 deletions

View file

@ -50,6 +50,7 @@ function deferred<T>() {
}
type Request = ReturnType<typeof deferred<Response>> & {
path: string;
query: string;
method: string;
signal?: AbortSignal | null;
settled: boolean;
@ -127,6 +128,7 @@ const definition = {
config: {},
createdAt: '2024-01-01',
updatedAt: '2024-01-01',
archivedAt: null,
};
class TestSocket {
@ -285,6 +287,7 @@ beforeEach(() => {
const pending: Request = {
...deferred<Response>(),
path: new URL(String(input)).pathname,
query: new URL(String(input)).search,
method: init?.method ?? 'GET',
signal: init?.signal,
body: typeof init?.body === 'string' ? init.body : undefined,
@ -939,3 +942,223 @@ describe('explicit save and repeat-safe run submission', () => {
});
}
});
describe('template archive and restore', () => {
const archived = { ...definition, archivedAt: '2024-03-01T00:00:00.000Z' };
function button(label: string) {
const found = [...host.querySelectorAll('button')].find(
item => item.textContent?.trim() === label || item.getAttribute('aria-label') === label
);
if (!found) {
throw new Error(`Missing button ${label}`);
}
return found;
}
test('confirmation archives only the template while active cancellation, history and restore remain available', async () => {
await mountPage('running');
await flush(() => click('Archive backtest'));
expect(host.querySelector('[role="dialog"]')?.getAttribute('aria-label')).toBe(
'Archive backtest'
);
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
await flush(() => {
click('Confirm archive');
click('Confirm archive');
});
const archive = request('/api/v2/backtests/definition/archive', 'POST');
expect(JSON.parse(archive.body!)).toEqual({ archived: true });
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
expect(button('Confirm archive').disabled).toBe(true);
expect(host.textContent).not.toContain('This backtest is archived.');
await flush(() => reply(archive, archived));
expect(host.querySelector('[role="dialog"]')).toBeNull();
expect(host.textContent).toContain('This backtest is archived.');
expect(button('Run current settings').disabled).toBe(true);
expect(button('Cancel run').disabled).toBe(false);
expect(pageLocation).toBe('/backtests/definition/run/A');
expect(polls()).toBe(1);
await flush(() => click('Settings'));
expect(button('Save').disabled).toBe(true);
expect((host.querySelector('input[name="name"]') as HTMLInputElement).disabled).toBe(true);
await flush(() => click('Runs'));
expect(button('New Run').disabled).toBe(true);
await flush(() => click('Restore backtest'));
expect(host.querySelector('[role="dialog"]')?.getAttribute('aria-label')).toBe(
'Restore backtest'
);
await flush(() => click('Confirm restore'));
const restore = request('/api/v2/backtests/definition/archive', 'POST');
expect(JSON.parse(restore.body!)).toEqual({ archived: false });
await flush(() => reply(restore, definition));
expect(button('New Run').disabled).toBe(false);
expect(button('Run current settings').disabled).toBe(false);
expect(host.textContent).not.toContain('This backtest is archived.');
expect(pageLocation).toBe('/backtests/definition/run/A');
});
test('archive cancellation writes nothing; failed archive stays open with actionable error and retries', async () => {
await mountPage('running');
await flush(() => click('Archive backtest'));
await flush(() => click('Cancel'));
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
await flush(() => click('Archive backtest'));
await flush(() => click('Confirm archive'));
await flush(() =>
reply(
request('/api/v2/backtests/definition/archive', 'POST'),
{ error: 'Archive storage is unavailable' },
503
)
);
expect(host.querySelector('[role="dialog"]')).not.toBeNull();
expect(host.textContent).toContain('Archive storage is unavailable');
expect(host.textContent).not.toContain('This backtest is archived.');
expect(button('Confirm archive').disabled).toBe(false);
await flush(() => click('Confirm archive'));
await flush(() => reply(request('/api/v2/backtests/definition/archive', 'POST'), archived));
expect(host.textContent).toContain('This backtest is archived.');
});
test('archival preserves a lost submission response key/body and completed evidence; only restore permits new intent', async () => {
await mount();
await loadDefinition();
await flush(() => {
void latest.createRun(2);
});
const first = request('/api/v2/backtests/definition/runs', 'POST');
await flush(() => fail(first));
await selectRunning('A', 'completed');
await flush(() => reply(request('/api/v2/runs/A/results'), results('A')));
const savedResults = latest.runResults;
await flush(() => {
void latest.setBacktestArchived('definition', true);
});
await flush(() => reply(request('/api/v2/backtests/definition/archive', 'POST'), archived));
expect(latest.backtest?.archivedAt).toBe(archived.archivedAt);
expect(latest.runResults).toBe(savedResults);
expect(latest.currentRun?.id).toBe('A');
expect(latest.runs.map(run => run.id)).toEqual(['A']);
expect(latest.hasPendingSubmission).toBe(true);
await flush(() => {
void latest.createRun(9);
});
const retry = request('/api/v2/backtests/definition/runs', 'POST');
expect(retry.body).toBe(first.body);
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
await flush(() => reply(retry, run('A', 'completed'), 202));
expect(latest.hasPendingSubmission).toBe(false);
const count = requests.length;
await flush(() => {
void latest.createRun(9);
});
expect(requests).toHaveLength(count);
expect(latest.submissionError).toContain('Restore this archived backtest');
await expect(latest.updateBacktest('definition', { name: 'Disallowed edit' })).rejects.toThrow(
'Restore'
);
expect(requests).toHaveLength(count);
await flush(() => {
void latest.setBacktestArchived('definition', false);
});
await flush(() => reply(request('/api/v2/backtests/definition/archive', 'POST'), definition));
await flush(() => {
void latest.createRun(9);
});
const fresh = request('/api/v2/backtests/definition/runs', 'POST');
expect(fresh.headers.get('Idempotency-Key')).not.toBe(first.headers.get('Idempotency-Key'));
expect(JSON.parse(fresh.body!)).toEqual({ speedMultiplier: 9 });
await flush(() => reply(fresh, run('B', 'pending'), 202));
expect(latest.runResults).toBe(savedResults);
});
test('archived page still exposes recovery of the frozen submission key', async () => {
await mountPage('running');
await flush(() => click('Run current settings'));
const first = request('/api/v2/backtests/definition/runs', 'POST');
await flush(() => fail(first));
await flush(() => click('Archive backtest'));
await flush(() => click('Confirm archive'));
await flush(() => reply(request('/api/v2/backtests/definition/archive', 'POST'), archived));
expect(button('Retry submission').disabled).toBe(false);
await flush(() => click('Retry submission'));
const retry = request('/api/v2/backtests/definition/runs', 'POST');
expect(retry.body).toBe(first.body);
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
await flush(() => reply(retry, run('A', 'running'), 202));
expect(button('Run current settings').disabled).toBe(true);
});
test('late archive completion cannot overwrite a different template after navigation', async () => {
await mount();
await loadDefinition();
await flush(() => {
void latest.setBacktestArchived('definition', true);
});
const previous = request('/api/v2/backtests/definition/archive', 'POST');
await loadDefinition('other');
await flush(() => reply(previous, archived));
expect(latest.backtest?.id).toBe('other');
expect(latest.backtest?.archivedAt).toBeNull();
expect(latest.isLoading).toBe(false);
});
test('retained-delete conflict surfaces archive guidance without clearing selected evidence', async () => {
await mount();
await loadDefinition();
await selectRunning('A', 'completed');
await flush(() => reply(request('/api/v2/runs/A/results'), results('A')));
let failure: string | undefined;
await flush(() => {
void latest.deleteBacktest('definition').catch(error => {
failure = error.message;
});
});
await flush(() =>
reply(
request('/api/v2/backtests/definition', 'DELETE'),
{
error: 'This backtest retains 1 run. Archive it to preserve its research history.',
code: 'retained_runs',
runCount: 1,
},
409
)
);
expect(failure).toContain('Archive it');
expect(latest.error).toBe(failure);
expect(latest.backtest?.id).toBe('definition');
expect(latest.currentRun?.id).toBe('A');
expect(latest.runResults?.runId).toBe('A');
});
for (const lateFailure of [false, true]) {
test(`archive list filter ignores stale ${lateFailure ? 'failure' : 'success'} and keeps truthful loading/empty states`, async () => {
await mount(createElement(router.MemoryRouter, null, createElement(BacktestListPageV2)));
const original = request('/api/v2/backtests');
expect(original.query).not.toContain('includeArchived');
expect(host.textContent).toContain('Loading backtests...');
await flush(() => (host.querySelector('input[type="checkbox"]') as HTMLInputElement).click());
const current = requests.find(
item => item.path === '/api/v2/backtests' && item !== original && !item.settled
)!;
expect(current.query).toContain('includeArchived=true');
expect(original.signal?.aborted).toBe(true);
await flush(() => (lateFailure ? fail(original) : reply(original, [definition])));
expect(host.textContent).toContain('Loading backtests...');
expect(host.textContent).not.toContain('Network unavailable');
await flush(() => reply(current, []));
expect(host.textContent).toContain('No backtests yet.');
expect(host.textContent).not.toContain('Loading backtests...');
await flush(() => (host.querySelector('input[type="checkbox"]') as HTMLInputElement).click());
const failed = request('/api/v2/backtests');
expect(failed.query).not.toContain('includeArchived');
await flush(() => reply(failed, { error: 'Retained history storage is unavailable' }, 503));
expect(host.textContent).toContain('Retained history storage is unavailable');
await flush(() => click('Retry backtests'));
await flush(() => reply(request('/api/v2/backtests'), []));
expect(host.textContent).toContain('No active backtests.');
expect(host.textContent).not.toContain('Retained history storage is unavailable');
});
}
});

View file

@ -75,7 +75,7 @@ async function fixture(
});
db.public
.none(`CREATE TYPE run_status AS ENUM ('pending','running','completed','failed','cancelled','paused');
CREATE TABLE backtests (id uuid PRIMARY KEY, name text, strategy text, symbols jsonb,
CREATE TABLE backtests (id uuid PRIMARY KEY, name text, strategy text, symbols jsonb, archived_at timestamptz,
start_date timestamptz, end_date timestamptz, initial_capital numeric, config jsonb,
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW());
CREATE TABLE runs (id uuid PRIMARY KEY, backtest_id uuid REFERENCES backtests(id), run_number integer,

View file

@ -0,0 +1,97 @@
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 { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
const tokens = {
operator: 'retention-operator-fixture-not-secret-123456',
service: 'retention-service-fixture-not-secret-123456',
read: 'retention-reader-fixture-not-secret-123456',
};
function fixture(secured = false) {
const database = {
query: mock(async (_query: string, _values?: unknown[]) => ({ rows: [] })),
transaction: mock(async () => {
throw new Error('Invalid archive request reached storage');
}),
};
const app = new Hono();
if (secured) {
createHttpSecurity({
adminToken: tokens.operator,
serviceToken: tokens.service,
readToken: tokens.read,
environment: 'test',
}).mount(app);
}
app.route(
'/',
createBacktestV2Routes({
postgres: database,
logger: { info() {}, error() {} },
} as unknown as IServiceContainer)
);
return { app, database };
}
describe('research retention route validation', () => {
test('archive requires exactly a boolean and rejects malformed JSON before a transaction', async () => {
const f = fixture();
for (const body of [
{},
null,
[],
{ archived: 'true' },
{ archived: 1 },
{ archived: true, purge: true },
{ archived: false, runId: randomUUID() },
]) {
expect(
(
await f.app.request(`/api/v2/backtests/${randomUUID()}/archive`, {
method: 'POST',
body: JSON.stringify(body),
})
).status
).toBe(400);
}
expect(
(
await f.app.request(`/api/v2/backtests/${randomUUID()}/archive`, {
method: 'POST',
body: '{',
})
).status
).toBe(400);
expect(f.database.transaction.mock.calls).toHaveLength(0);
});
test('includeArchived accepts only literal query booleans and defaults to active templates', async () => {
const f = fixture();
for (const value of ['1', 'yes', 'TRUE', '']) {
expect((await f.app.request(`/api/v2/backtests?includeArchived=${value}`)).status).toBe(400);
}
expect(f.database.query.mock.calls).toHaveLength(0);
for (const query of ['', '?includeArchived=false', '?includeArchived=true']) {
expect((await f.app.request(`/api/v2/backtests${query}`)).status).toBe(200);
}
expect(f.database.query.mock.calls.map(call => call[1])).toEqual([
[50, 0, false],
[50, 0, false],
[50, 0, true],
]);
});
test('the existing security boundary prevents anonymous and read-only archive mutations', async () => {
const f = fixture(true);
for (const token of [undefined, tokens.read]) {
const response = await f.app.request(`/api/v2/backtests/${randomUUID()}/archive`, {
method: 'POST',
headers: token ? { Authorization: `Bearer ${token}` } : {},
body: '{"archived":true}',
});
expect(response.status).toBe(token ? 403 : 401);
}
expect(f.database.transaction.mock.calls).toHaveLength(0);
});
});