feat(research): add durable walk-forward validation workflows

This commit is contained in:
Boki 2026-10-24 12:34:39 -04:00
parent abd1c5b83d
commit 3ed7b98f7c
45 changed files with 5188 additions and 199 deletions

View file

@ -66,6 +66,7 @@ async function fixture(options: { corruptDataset?: boolean; buildMismatch?: bool
'22-experiments.sql',
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')

View file

@ -65,6 +65,7 @@ async function fixture(dataset = canonicalSmaFixture().dataset) {
'22-experiments.sql',
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')

View file

@ -104,6 +104,7 @@ async function fixture() {
'22-experiments.sql',
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
]) {
await pool.query(sql(name));
}

View file

@ -79,7 +79,7 @@ async function fixture(poolMax = 1, withValidation = true) {
'21-run-reproduction.sql',
'22-experiments.sql',
'23-experiment-retries.sql',
...(withValidation ? ['24-chronological-validation.sql'] : []),
...(withValidation ? ['24-chronological-validation.sql', '25-walk-forward.sql'] : []),
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
@ -506,6 +506,13 @@ 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);
// Current chronological admission can link roots to a walk-forward series.
await f.pool.query(
readFileSync(
new URL('../../database/postgres/init/25-walk-forward.sql', import.meta.url),
'utf8'
)
);
const current = await submit(f);
expect(current.validation.stage).toBe('training');
expect(

View file

@ -69,6 +69,7 @@ async function fixture() {
'22-experiments.sql',
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')

View file

@ -77,6 +77,7 @@ async function fixture() {
'22-experiments.sql',
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')

View file

@ -88,6 +88,7 @@ async function fixture() {
'22-experiments.sql',
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')

View file

@ -69,7 +69,9 @@ async function fixture(poolMax = 4, withRetries = true) {
'19-canonical-research.sql',
'21-run-reproduction.sql',
'22-experiments.sql',
...(withRetries ? ['23-experiment-retries.sql', '24-chronological-validation.sql'] : []),
...(withRetries
? ['23-experiment-retries.sql', '24-chronological-validation.sql', '25-walk-forward.sql']
: []),
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')

View file

@ -65,7 +65,12 @@ async function fixture(poolMax = 4, withExperiments = true) {
'19-canonical-research.sql',
'21-run-reproduction.sql',
...(withExperiments
? ['22-experiments.sql', '23-experiment-retries.sql', '24-chronological-validation.sql']
? [
'22-experiments.sql',
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
]
: []),
]) {
await pool.query(

View file

@ -27,6 +27,7 @@ const migrations = [
'22-experiments.sql',
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
];
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {

View file

@ -31,7 +31,9 @@ const retention =
'\n' +
sql('23-experiment-retries.sql') +
'\n' +
sql('24-chronological-validation.sql');
sql('24-chronological-validation.sql') +
'\n' +
sql('25-walk-forward.sql');
const request = {
name: 'Retained evidence',
strategy: 'sma-crossover',

View file

@ -73,6 +73,7 @@ async function fixture() {
'22-experiments.sql',
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')

View file

@ -64,6 +64,7 @@ async function fixture(applyWorkspace = true, maxConnections = 10) {
'22-experiments.sql',
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
]) {
await pool.query(sql(name));
}

View file

@ -67,6 +67,7 @@ async function fixture(poolMax = 4, withReproduction = true) {
'22-experiments.sql',
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
]
: []),
]) {

View file

@ -0,0 +1,771 @@
import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { afterEach, describe, expect, test } from 'bun:test';
import { Hono } from 'hono';
import { Pool } 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 { 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 { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.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 { ExperimentError } from '../../apps/stock/web-api/src/services/experiment-input';
import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.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;
const tokens = {
operator: 'chronological-operator-fixture-not-a-real-secret-1234',
service: 'chronological-service-fixture-not-a-real-secret-1234',
};
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
async function fixture(poolMax = 1, withWalkForward = 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',
'21-run-reproduction.sql',
'22-experiments.sql',
'23-experiment-retries.sql',
'24-chronological-validation.sql',
...(withWalkForward ? ['25-walk-forward.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 app = new Hono();
createHttpSecurity({
adminToken: tokens.operator,
serviceToken: tokens.service,
environment: 'test',
hostname: '127.0.0.1',
}).mount(app);
app.route('/', createExperimentRoutes(container));
const request = (raw: unknown = input, role: keyof typeof tokens = 'operator') =>
app.request('/api/v2/experiments/walk-forward/preview', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${tokens[role]}` },
body: JSON.stringify(raw),
});
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,
request,
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()
);
}
describe.skipIf(!url)('bounded walk-forward validation', () => {
test('pool1 native windows admit atomically, retain independent reports and finalize historically', async () => {
const f = await fixture(),
start = await submit(f);
expect(start.walk.windows).toHaveLength(2);
expect(start.walk.trainingRunCount).toBe(4);
expect(start.walk.plannedRunCount).toBe(8);
expect((await f.pool.query('SELECT count(*)::int AS n FROM backtest_dispatch')).rows[0].n).toBe(
4
);
expect(await f.walks.submit(start.body, start.identity)).toEqual(start.walk);
await expect(
f.walks.finalize(start.walk.id, { previewHash: start.preview.previewHash }, actor())
).rejects.toThrow();
for (const member of start.walk.windows) {
await finishWindow(f, member.validationId);
}
expect((await f.walks.get(start.walk.id)).actions.finalize.available).toBe(true);
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 identity = actor(),
body = { previewHash: start.preview.previewHash };
const [final, duplicate] = await Promise.all([
f.walks.finalize(start.walk.id, body, identity),
f.walks.finalize(start.walk.id, body, identity),
]);
expect(duplicate.receipt).toEqual(final.receipt);
await expect(f.walks.finalize(randomUUID(), body, identity)).rejects.toThrow('different');
expect(final.walkForward.report!.segments.map(s => s.index)).toEqual([0, 1]);
expect(final.walkForward.report!.segments.map(s => s.validationId)).toEqual(
start.walk.windows.map(w => w.validationId)
);
expect(final.walkForward.report!.reset).toBe('initial-capital-empty-positions');
expect(final.walkForward.reportedWindowCount).toBe(2);
expect((await f.walks.list())[0]!.stage).toBe('reported');
expect(await f.walks.finalize(start.walk.id, body, identity)).toEqual(final);
expect((await f.walks.get(start.walk.id)).report).toEqual(final.walkForward.report);
await f.walks.cancel(start.walk.id);
expect((await f.walks.finalize(start.walk.id, body, identity)).receipt).toEqual(final.receipt);
expect((await f.walks.submit(start.body, start.identity)).id).toBe(start.walk.id);
}, 60_000);
});
async function trainWindow(f: Fixture, id: string) {
const detail = await f.validations.get(id);
for (const trial of detail.phases[0]!.experiment!.trials) {
await f.execute(trial.runId!);
}
return f.validations.select(id, { previewHash: detail.previewHash }, actor());
}
describe.skipIf(!url)('walk-forward adversarial boundaries', () => {
test('first and idempotent SQL25 preserve ordinary evidence, receipts, active lease and SQL22–24 bodies', async () => {
const f = await fixture(1, false);
await f.review();
const input = { backtestId: f.draft.id, name: 'Preserved sweep', grid: { fastPeriod: [1, 2] } };
const preview = await f.experiments.preview(input),
ordinary = await f.experiments.submit(
{ ...input, previewHash: preview.previewHash },
actor()
);
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]))
.rows[0].request_snapshot;
await f.repository.startCanonical(request);
const before = await f.snapshot(),
functions = async () =>
(
await f.pool.query(
'SELECT proname,pg_get_functiondef(oid) AS definition FROM pg_proc WHERE pronamespace=current_schema()::regnamespace ORDER BY proname'
)
).rows;
const priorFunctions = await functions();
const migration = readFileSync(
new URL('../../database/postgres/init/25-walk-forward.sql', import.meta.url),
'utf8'
);
await f.pool.query(migration);
const after = await f.snapshot();
delete after.research_walk_forwards;
after.research_experiments = (after.research_experiments as Record<string, unknown>[]).map(
({ walk_forward_id: _id, walk_forward_index: _index, ...row }) => row
);
expect(after).toEqual(before);
expect(
(await functions()).filter(row => priorFunctions.some(p => p.proname === row.proname))
).toEqual(priorFunctions);
const upgraded = await f.snapshot();
await f.pool.query(migration);
expect(await f.snapshot()).toEqual(upgraded);
expect(
(await f.pool.query('SELECT status,attempt_number FROM runs WHERE id=$1', [pending])).rows[0]
).toMatchObject({ status: 'running', attempt_number: 1 });
expect((await submit(f)).walk.windows).toHaveLength(2);
}, 60000);
test('failure on second root, retained slice, run, outbox or header rolls back every row and receipt', async () => {
const f = await fixture();
await f.review();
const preview = await f.walks.preview(f.input),
body = { ...f.input, previewHash: preview.previewHash };
const secondHash = preview.windows[1]!.preview.partitions[0].dataset.hash;
for (const [table, condition] of [
['research_experiments', 'NEW.walk_forward_index=1'],
['backtest_datasets', `NEW.hash='${secondHash}'`],
[
'runs',
'EXISTS(SELECT 1 FROM research_experiments e WHERE e.id=NEW.experiment_id AND e.walk_forward_index=1)',
],
[
'backtest_dispatch',
'EXISTS(SELECT 1 FROM runs r JOIN research_experiments e ON e.id=r.experiment_id WHERE r.id=NEW.run_id AND e.walk_forward_index=1)',
],
['research_walk_forwards', 'TRUE'],
]) {
await f.pool.query(
`CREATE OR REPLACE FUNCTION injected_walk_failure() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF ${condition} THEN RAISE EXCEPTION 'Injected walk failure'; END IF; RETURN NEW; END $$`
);
await f.pool.query(
`CREATE TRIGGER injected_walk_failure BEFORE INSERT ON ${table} FOR EACH ROW EXECUTE FUNCTION injected_walk_failure()`
);
const before = await f.snapshot();
await expect(f.walks.submit(body, actor())).rejects.toThrow('Injected');
expect(await f.snapshot()).toEqual(before);
await f.pool.query(`DROP TRIGGER injected_walk_failure ON ${table}`);
}
expect((await f.walks.submit(body, actor())).windows).toHaveLength(2);
}, 60000);
test('same and cross-parent submission receipts have one owner and replay before changed eligibility', async () => {
const f = await fixture(5);
await f.review();
const preview = await f.walks.preview(f.input),
body = { ...f.input, previewHash: preview.previewHash },
identity = actor();
const [first, replay] = await Promise.all([
f.walks.submit(body, identity),
f.walks.submit(body, identity),
]);
expect(first.id).toBe(replay.id);
const other = await f.cloneTemplate(),
otherInput = { ...f.input, backtestId: other.id },
otherPreview = await f.walks.preview(otherInput),
otherBody = { ...otherInput, previewHash: otherPreview.previewHash },
raceActor = actor();
const race = await Promise.allSettled([
f.walks.submit(body, raceActor),
f.walks.submit(otherBody, raceActor),
]);
expect(race.filter(r => r.status === 'fulfilled')).toHaveLength(1);
expect(race.filter(r => r.status === 'rejected')).toHaveLength(1);
expect(
(await f.pool.query('SELECT count(*)::int n FROM research_walk_forwards')).rows[0].n
).toBe(2);
expect((await f.pool.query('SELECT count(*)::int n FROM runs')).rows[0].n).toBe(8);
await f.review('revoke');
await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]);
expect((await f.walks.submit(body, identity)).id).toBe(first.id);
await expect(f.walks.submit({ ...body, name: 'Changed' }, identity)).rejects.toThrow(
'different'
);
await expect(f.walks.submit(body, actor())).rejects.toThrow();
}, 60000);
test('SQL rejects mixed membership, changed header/source/order, extra or missing roots and report replacement', async () => {
const f = await fixture(),
start = await submit(f),
header = (
await f.pool.query('SELECT * FROM research_walk_forwards WHERE id=$1', [start.walk.id])
).rows[0];
const cloneHeader = async (patch: Record<string, unknown> = {}) => {
const row = {
...header,
id: randomUUID(),
member_ids: [randomUUID(), randomUUID()],
submission_key: randomUUID(),
...patch,
};
return f.pool.query(
'INSERT INTO research_walk_forwards SELECT * FROM jsonb_populate_record(NULL::research_walk_forwards,$1)',
[row]
);
};
await expect(cloneHeader()).rejects.toThrow('must commit together');
for (const patch of [
{ member_ids: [header.member_ids[0], header.member_ids[0]] },
{ preview: { ...header.preview, counts: { ...header.preview.counts, totalRuns: 4 } } },
{
preview: {
...header.preview,
source: {
...header.preview.source,
input: { ...header.preview.source.input, name: 'Other source' },
},
},
},
{ preview: { ...header.preview, windows: [...header.preview.windows].reverse() } },
{ preview: { ...header.preview, policy: null } },
]) {
await expect(cloneHeader(patch)).rejects.toThrow();
}
for (const sql of [
"UPDATE research_walk_forwards SET name='changed' WHERE id=$1",
'UPDATE research_walk_forwards SET member_ids=ARRAY[]::uuid[] WHERE id=$1',
"UPDATE research_walk_forwards SET report='{}' WHERE id=$1",
'DELETE FROM research_walk_forwards WHERE id=$1',
]) {
await expect(f.pool.query(sql, [start.walk.id])).rejects.toThrow();
}
await expect(f.pool.query('TRUNCATE research_walk_forwards CASCADE')).rejects.toThrow();
const member = (
await f.pool.query('SELECT * FROM research_experiments WHERE id=$1', [header.member_ids[0]])
).rows[0];
for (const patch of [
{ walk_forward_index: null },
{ walk_forward_index: 2 },
{ walk_forward_id: null },
{ validation_phase: 'validation' },
{
validation_manifest: {
...member.validation_manifest,
input: { ...member.validation_manifest.input, name: 'Other' },
},
},
]) {
await expect(
f.pool.query(
'INSERT INTO research_experiments SELECT * FROM jsonb_populate_record(NULL::research_experiments,$1)',
[{ ...member, id: randomUUID(), submission_key: randomUUID(), ...patch }]
)
).rejects.toThrow();
}
await expect(
f.pool.query(
'UPDATE research_experiments SET walk_forward_id=NULL,walk_forward_index=NULL WHERE id=$1',
[member.id]
)
).rejects.toThrow('immutable');
expect((await f.walks.get(start.walk.id)).windows).toHaveLength(2);
}, 60000);
test('member cancellation stays local; direct series cancellation races select and retry without orphan work', async () => {
const f = await fixture(5),
local = await submit(f);
await f.validations.cancel(local.walk.windows[0]!.validationId);
const localDetail = await f.walks.get(local.walk.id);
expect(localDetail.cancelRequested).toBe(false);
expect(localDetail.windows[0]!.validation!.cancelRequested).toBe(true);
expect(localDetail.windows[1]!.validation!.cancelRequested).toBe(false);
await expect(
f.walks.finalize(local.walk.id, { previewHash: local.preview.previewHash }, actor())
).rejects.toThrow();
const start = await submit(f),
first = start.walk.windows[0]!.validation!,
second = start.walk.windows[1]!.validation!;
for (const trial of first.phases[0]!.experiment!.trials) {
await f.execute(trial.runId!);
}
const failed = second.phases[0]!.experiment!.trials[0]!.runId!;
await f.pool.query(
"UPDATE runs SET status='failed',error='Preclaim failure',completed_at=NOW() WHERE id=$1",
[failed]
);
const race = await Promise.allSettled([
f.validations.select(first.id, { previewHash: first.previewHash }, actor()),
f.experiments.retryTrial(
second.id,
failed,
{ expectedAttemptNumber: 0, expectedRetryCount: 0 },
actor()
),
f.pool.query('UPDATE research_walk_forwards SET cancel_requested=TRUE WHERE id=$1', [
start.walk.id,
]),
]);
expect(race[2]!.status).toBe('fulfilled');
for (const outcome of race.slice(0, 2)) {
if (outcome.status === 'rejected') {
expect(outcome.reason).toBeInstanceOf(ExperimentError);
expect(outcome.reason.status).toBe(409);
}
}
const detail = await f.walks.get(start.walk.id);
expect(detail.cancelRequested).toBe(true);
expect(detail.windows.every(w => w.validation!.cancelRequested)).toBe(true);
const rows = (
await f.pool.query(
'SELECT r.status,r.cancel_requested FROM runs r JOIN research_experiments e ON e.id=r.experiment_id WHERE e.walk_forward_id=$1 OR e.validation_parent_id=ANY($2::uuid[])',
[start.walk.id, start.walk.windows.map(w => w.validationId)]
)
).rows;
expect(rows.filter(r => r.status === 'cancelled').every(r => r.cancel_requested)).toBe(true);
expect(rows.filter(r => r.status === 'completed')).toHaveLength(2);
expect(rows.some(r => r.status === 'pending' || r.status === 'running')).toBe(false);
expect((await f.walks.cancel(start.walk.id)).cancelRequested).toBe(true);
await expect(
f.pool.query('UPDATE research_walk_forwards SET cancel_requested=FALSE WHERE id=$1', [
start.walk.id,
])
).rejects.toThrow('permanent');
}, 60000);
test('only later test-price changes leave both native training scores and winners unchanged', async () => {
const f = await fixture(),
first = await submit(f),
before = [];
for (const member of first.walk.windows) {
before.push((await trainWindow(f, member.validationId)).validation.selection!);
}
const dataset = walkForwardDataset(900).dataset;
await retainResearchDataset(f.pool, dataset);
const other = await f.cloneTemplate(dataset);
const raw = { ...f.input, backtestId: other.id },
preview = await f.walks.preview(raw),
second = await f.walks.submit({ ...raw, previewHash: preview.previewHash }, actor());
for (const [index, member] of second.windows.entries()) {
const selected = (await trainWindow(f, member.validationId)).validation.selection!;
expect(selected.winner).toEqual(before[index]!.winner);
expect(selected.training.map(t => t.metrics)).toEqual(
before[index]!.training.map(t => t.metrics)
);
expect(preview.windows[index]!.preview.partitions[0].dataset.hash).toBe(
first.preview.windows[index]!.preview.partitions[0].dataset.hash
);
}
expect(preview.windows[1]!.preview.partitions[2].dataset.hash).not.toBe(
first.preview.windows[1]!.preview.partitions[2].dataset.hash
);
expect(
(
await f.pool.query(
"SELECT count(*)::int n FROM runs r JOIN research_experiments e ON e.id=r.experiment_id WHERE e.validation_phase IN ('validation','test') AND r.status<>'pending'"
)
).rows[0].n
).toBe(0);
}, 60000);
test('all members and full retained canonical results are required even after member reports were sealed', async () => {
const f = await fixture(),
start = await submit(f);
for (const member of start.walk.windows) {
await finishWindow(f, member.validationId);
}
const body = { previewHash: start.preview.previewHash },
last = start.walk.windows[1]!.validationId;
const root = (await f.pool.query('SELECT * FROM research_experiments WHERE id=$1', [last]))
.rows[0];
await f.pool.query('ALTER TABLE research_experiments DISABLE TRIGGER USER');
await f.pool.query(
'UPDATE research_experiments SET walk_forward_id=NULL,walk_forward_index=NULL WHERE id=$1',
[last]
);
expect((await f.walks.get(start.walk.id)).windows[1]!.status).toBe('missing');
await expect(f.walks.finalize(start.walk.id, body, actor())).rejects.toThrow('missing');
await f.pool.query(
'UPDATE research_experiments SET walk_forward_id=$2,walk_forward_index=$3 WHERE id=$1',
[last, root.walk_forward_id, root.walk_forward_index]
);
await f.pool.query('ALTER TABLE research_experiments ENABLE TRIGGER USER');
const runId = root.validation_report.test.runId;
const result = (
await f.pool.query('SELECT canonical_result FROM backtest_results WHERE run_id=$1', [runId])
).rows[0].canonical_result;
await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER');
for (const [path, value] of [
['{analytics,metrics,totalReturn}', '900'],
['{financial,view,equity}', '"900.00000000"'],
]) {
await f.pool.query(
'UPDATE backtest_results SET canonical_result=jsonb_set($2::jsonb,$3::text[],$4::jsonb) WHERE run_id=$1',
[runId, result, path, value]
);
expect(
(
await f.pool.query('SELECT canonical_result FROM backtest_results WHERE run_id=$1', [
runId,
])
).rows[0].canonical_result
).not.toEqual(result);
await expect(f.walks.finalize(start.walk.id, body, actor())).rejects.toThrow();
expect(
(
await f.pool.query('SELECT report FROM research_walk_forwards WHERE id=$1', [
start.walk.id,
])
).rows[0].report
).toBeNull();
}
await f.pool.query('UPDATE backtest_results SET canonical_result=$2 WHERE run_id=$1', [
runId,
result,
]);
await f.pool.query('ALTER TABLE backtest_results ENABLE TRIGGER USER');
const final = await f.walks.finalize(start.walk.id, body, actor());
expect(final.walkForward.report!.segments).toHaveLength(2);
await expect(
f.pool.query(
"UPDATE research_walk_forwards SET report=jsonb_set(report,'{segments}','[]') WHERE id=$1",
[start.walk.id]
)
).rejects.toThrow('immutable');
}, 60000);
});
describe.skipIf(!url)('walk-forward concurrent controls', () => {
test('direct cancellation passes downward while select and retry are demonstrably waiting on parent lock', async () => {
const f = await fixture(6),
start = await submit(f),
first = start.walk.windows[0]!.validation!,
second = start.walk.windows[1]!.validation!;
for (const trial of first.phases[0]!.experiment!.trials) {
await f.execute(trial.runId!);
}
const completed = async () =>
(
await f.pool.query(
'SELECT to_jsonb(r) AS row FROM runs r WHERE experiment_id=$1 ORDER BY trial_index',
[first.id]
)
).rows;
const preserved = await completed(),
failed = second.phases[0]!.experiment!.trials[0]!.runId!;
await f.pool.query(
"UPDATE runs SET status='failed',error='Preclaim',completed_at=NOW() WHERE id=$1",
[failed]
);
const blocker = await f.pool.connect();
await blocker.query('BEGIN');
await blocker.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [f.draft.id]);
const pending = Promise.allSettled([
f.validations.select(first.id, { previewHash: first.previewHash }, actor()),
f.experiments.retryTrial(
second.id,
failed,
{ expectedAttemptNumber: 0, expectedRetryCount: 0 },
actor()
),
]);
try {
let waiting = 0;
for (let attempt = 0; attempt < 100; attempt++) {
waiting = Number(
(
await f.pool.query(
"SELECT count(*)::int n FROM pg_stat_activity WHERE application_name=current_schema() AND wait_event_type='Lock'"
)
).rows[0].n
);
if (waiting >= 2) {
break;
}
await new Promise(resolve => setTimeout(resolve, 10));
}
expect(waiting).toBeGreaterThanOrEqual(2);
await f.pool.query('UPDATE research_walk_forwards SET cancel_requested=TRUE WHERE id=$1', [
start.walk.id,
]);
await blocker.query('COMMIT');
} finally {
await blocker.query('ROLLBACK');
blocker.release();
}
const outcomes = await pending;
for (const outcome of outcomes) {
expect(outcome.status).toBe('rejected');
if (outcome.status === 'rejected') {
expect(outcome.reason).toBeInstanceOf(ExperimentError);
expect(outcome.reason.status).toBe(409);
}
}
expect(await completed()).toEqual(preserved);
expect(
(
await f.pool.query(
"SELECT count(*)::int n FROM runs r JOIN research_experiments e ON e.id=r.experiment_id WHERE e.walk_forward_id=$1 AND r.status IN ('pending','running','paused')",
[start.walk.id]
)
).rows[0].n
).toBe(0);
expect(
(
await f.pool.query(
'SELECT count(*)::int n FROM experiment_trial_retries WHERE experiment_id=$1',
[second.id]
)
).rows[0].n
).toBe(0);
}, 60000);
test('same and cross-parent finalization receipts serialize exactly once without sealing the losing series', async () => {
const f = await fixture(5),
first = await submit(f),
other = await f.cloneTemplate();
const raw = { ...f.input, backtestId: other.id },
preview = await f.walks.preview(raw),
second = await f.walks.submit({ ...raw, previewHash: preview.previewHash }, actor());
for (const member of [...first.walk.windows, ...second.windows]) {
await finishWindow(f, member.validationId);
}
const identity = actor(),
race = await Promise.allSettled([
f.walks.finalize(first.walk.id, { previewHash: first.preview.previewHash }, identity),
f.walks.finalize(second.id, { previewHash: preview.previewHash }, identity),
]);
expect(race.filter(r => r.status === 'fulfilled')).toHaveLength(1);
expect(race.filter(r => r.status === 'rejected')).toHaveLength(1);
const winnerIndex = race[0]!.status === 'fulfilled' ? 0 : 1,
winner = winnerIndex === 0 ? first.walk : second,
loser = winnerIndex === 0 ? second : first.walk;
const rejected = race[1 - winnerIndex]!;
if (rejected.status === 'rejected') {
expect(rejected.reason).toBeInstanceOf(ExperimentError);
expect(rejected.reason.status).toBe(409);
}
expect((await f.walks.get(loser.id)).report).toBeNull();
const body = { previewHash: winner.previewHash },
[one, two] = await Promise.all([
f.walks.finalize(winner.id, body, identity),
f.walks.finalize(winner.id, body, identity),
]);
expect(one.receipt).toEqual(two.receipt);
await expect(f.walks.finalize(winner.id, body, actor())).rejects.toMatchObject({ status: 409 });
const secondIdentity = actor(),
[three, four] = await Promise.all([
f.walks.finalize(loser.id, { previewHash: loser.previewHash }, secondIdentity),
f.walks.finalize(loser.id, { previewHash: loser.previewHash }, secondIdentity),
]);
expect(three.receipt).toEqual(four.receipt);
}, 60000);
});