feat(research): isolate candidates and add reviewed paper promotion
This commit is contained in:
parent
26b97265c6
commit
25b5cbf481
128 changed files with 13038 additions and 1388 deletions
|
|
@ -263,8 +263,11 @@ export async function fixture(browser: Browser, native = false) {
|
|||
for (const name of [
|
||||
'09-backtest-run-contract.sql',
|
||||
'10-durable-backtest-dispatch.sql',
|
||||
'11-simulation-execution-ledger.sql',
|
||||
'12-historical-datasets.sql',
|
||||
'13-strategy-recovery.sql',
|
||||
'14-backtest-submission.sql',
|
||||
'15-canonical-paper-intents.sql',
|
||||
'16-strategy-catalog.sql',
|
||||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
|
|
@ -278,6 +281,9 @@ export async function fixture(browser: Browser, native = false) {
|
|||
'26-cost-sensitivity.sql',
|
||||
'27-research-evidence-sources.sql',
|
||||
'28-research-agents.sql',
|
||||
'29-isolated-candidates.sql',
|
||||
'30-paper-deployments.sql',
|
||||
'31-research-agent-project-links.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
@ -410,7 +416,7 @@ export async function fixture(browser: Browser, native = false) {
|
|||
origins: [],
|
||||
resolveResearchCredential: request => researchAgents.authenticate(request),
|
||||
});
|
||||
const routes = createRoutes(container, security);
|
||||
const routes = createRoutes(container, security, {});
|
||||
const wsRoute = createWebSocketRoute(container, security);
|
||||
const sockets = new Set<ServerWebSocket<RunSocketData>>();
|
||||
const unexpectedNetwork: string[] = [];
|
||||
|
|
@ -446,6 +452,7 @@ export async function fixture(browser: Browser, native = false) {
|
|||
!pathname.startsWith('/api/v2/research-agents') &&
|
||||
!pathname.startsWith('/api/v2/research-agent/') &&
|
||||
!pathname.startsWith('/api/v2/experiments') &&
|
||||
!pathname.startsWith('/api/v2/paper-deployments') &&
|
||||
!pathname.startsWith('/api/v2/hypotheses/') &&
|
||||
!pathname.startsWith('/api/v2/analysis-artifacts/') &&
|
||||
pathname !== '/api/auth/session') ||
|
||||
|
|
@ -507,6 +514,7 @@ export async function fixture(browser: Browser, native = false) {
|
|||
}
|
||||
});
|
||||
const origin = `http://127.0.0.1:${server.port}`;
|
||||
security.allowedOrigins.push(origin);
|
||||
const context = await browser.newContext({ viewport: { width: 1440, height: 1080 } });
|
||||
cleanup.push(() => context.close());
|
||||
await context.route('**/*', route => {
|
||||
|
|
|
|||
|
|
@ -3010,3 +3010,262 @@ test('research_project_to_finding_browser_with_canonical_strategy_setup_run_and_
|
|||
await f.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('isolated_candidate_publication_research_validation_and_reviewed_paper_history_browser', async () => {
|
||||
const f = await fixture(true);
|
||||
try {
|
||||
const data = chronologicalDataset();
|
||||
await retainResearchDataset(f.pool, data.dataset);
|
||||
const builtin = (await f.seedCatalog()).find(
|
||||
item => item.package.program.strategyId === 'sma_crossover'
|
||||
)!;
|
||||
await f.request(`/api/v2/strategy-versions/${builtin.id}/reviews`, 'POST', {
|
||||
decision: 'approve',
|
||||
reason: 'Disposable template baseline',
|
||||
});
|
||||
const retained = (await f.request(`/api/v2/strategy-versions/${builtin.id}/artifact`)).package;
|
||||
const pkg = { ...retained, execution: { kind: 'isolated-candidate/v1', warmupBars: 3 } };
|
||||
const family = (
|
||||
await f.request('/api/v2/strategies', 'POST', {
|
||||
name: 'Browser isolated candidate',
|
||||
description: 'Retained controlled parity program',
|
||||
})
|
||||
).strategy;
|
||||
await f.login();
|
||||
await f.page.goto(`${f.origin}/strategies/${family.id}`);
|
||||
await f.page.getByLabel('Candidate package (JSON)').setInputFiles({
|
||||
name: 'candidate.json',
|
||||
mimeType: 'application/json',
|
||||
buffer: Buffer.from(JSON.stringify(pkg)),
|
||||
});
|
||||
await visible(f.page, pkg.artifact.sha256);
|
||||
const published = f.page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'POST' &&
|
||||
response.url().endsWith(`/strategies/${family.id}/versions`)
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Publish immutable candidate', exact: true }).click();
|
||||
const publication = await published;
|
||||
expect(publication.status()).toBe(201);
|
||||
const version = (await publication.json()).version;
|
||||
expect(version.origin).toBe('candidate');
|
||||
await f.page.waitForURL(url => url.pathname.endsWith(`/versions/${version.id}`));
|
||||
expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(0);
|
||||
const draft = await f.request('/api/v2/backtests', 'POST', {
|
||||
name: 'Browser candidate template',
|
||||
autoStart: false,
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: builtin.id,
|
||||
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
symbols: ['X0.US'],
|
||||
startDate: new Date(data.dataset.manifest.bounds.tradeStart).toISOString(),
|
||||
endDate: new Date(data.dataset.manifest.bounds.tradeEnd).toISOString(),
|
||||
initialCapital: 10000,
|
||||
config: {
|
||||
datasetHash: data.dataset.manifest.hash,
|
||||
dataFrequency: '1m',
|
||||
canonical: canonicalSettings,
|
||||
},
|
||||
});
|
||||
await f.page.goto(`${f.origin}/experiments?backtestId=${draft.id}`);
|
||||
await f.page.getByLabel('Experiment name', { exact: true }).fill('Isolated browser experiment');
|
||||
await f.page.getByLabel('Use an isolated candidate version', { exact: true }).check();
|
||||
const section = f.page.getByRole('region', {
|
||||
name: 'Candidate experiment strategy',
|
||||
exact: true,
|
||||
});
|
||||
await section.getByLabel('Strategy family', { exact: true }).selectOption(family.id);
|
||||
await section
|
||||
.getByLabel('Immutable strategy version', { exact: true })
|
||||
.selectOption(version.id);
|
||||
await section.getByLabel('fastPeriod', { exact: true }).fill('2');
|
||||
await section.getByLabel('slowPeriod', { exact: true }).fill('3');
|
||||
await section.getByRole('button', { name: 'Validate parameters', exact: true }).click();
|
||||
await visible(f.page, /Parameters validated/);
|
||||
await f.page.getByRole('button', { name: 'Preview experiment', exact: true }).click();
|
||||
await visible(f.page, /Isolated TypeScript candidate/);
|
||||
const submitted = f.page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'POST' && response.url().endsWith('/api/v2/experiments')
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Confirm experiment', exact: true }).click();
|
||||
const experiment = (await (await submitted).json()).experiment as ExperimentDetail;
|
||||
expect(experiment.preview.input.candidate).toEqual({
|
||||
versionId: version.id,
|
||||
parameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
});
|
||||
expect(experiment.preview.request.strategy.reviewId).toBeNull();
|
||||
await f.dispatcher.start();
|
||||
const completeExperiment = async (id: string) => {
|
||||
await until(
|
||||
async () =>
|
||||
(await f.request(`/api/v2/experiments/${id}`)).experiment.trials.every(
|
||||
(trial: { status: string }) =>
|
||||
['completed', 'failed', 'cancelled', 'missing'].includes(trial.status)
|
||||
),
|
||||
'candidate trials finish',
|
||||
45000
|
||||
);
|
||||
const result = (await f.request(`/api/v2/experiments/${id}`)).experiment;
|
||||
expect(result.trials.every((trial: { status: string }) => trial.status === 'completed')).toBe(
|
||||
true
|
||||
);
|
||||
return result;
|
||||
};
|
||||
const completed = await completeExperiment(experiment.id);
|
||||
const runId = completed.trials[0].runId;
|
||||
const result = (await f.request(`/api/v2/runs/${runId}/results`)) as CanonicalRunResult;
|
||||
expect(result.strategyExecution).toBe('typescript-isolated-candidate/v1');
|
||||
expect(result.request.strategy.origin).toBe('candidate');
|
||||
await f.page.goto(`${f.origin}/backtests/${draft.id}/run/${runId}`);
|
||||
await visible(f.page, /isolated TypeScript candidate/);
|
||||
await f.page.reload();
|
||||
await visible(f.page, result.request.datasetHash);
|
||||
|
||||
// Real immutable validation and cost evidence prepare the human promotion screen.
|
||||
const candidate = { versionId: version.id, parameters: { fastPeriod: 2, slowPeriod: 3 } };
|
||||
const validationInput = {
|
||||
backtestId: draft.id,
|
||||
name: 'Browser candidate holdouts',
|
||||
grid: {},
|
||||
recipe: data.recipe,
|
||||
candidate,
|
||||
};
|
||||
const previewResponse = await f.request(
|
||||
'/api/v2/experiments/validation/preview',
|
||||
'POST',
|
||||
validationInput
|
||||
);
|
||||
const preview = previewResponse.preview as ChronologicalValidationPreview;
|
||||
const validation = (
|
||||
await f.request(
|
||||
'/api/v2/experiments/validation',
|
||||
'POST',
|
||||
{ ...validationInput, previewHash: preview.previewHash },
|
||||
{ 'Idempotency-Key': randomUUID() }
|
||||
)
|
||||
).validation as ChronologicalValidationDetail;
|
||||
expect(preview.policy.model).toBe('unverified-candidate');
|
||||
await completeExperiment(validation.phases[0]!.experimentId!);
|
||||
const selected = (await f.request(
|
||||
`/api/v2/experiments/validation/${validation.id}/select`,
|
||||
'POST',
|
||||
{ previewHash: preview.previewHash },
|
||||
{ 'Idempotency-Key': randomUUID() }
|
||||
)) as ChronologicalValidationActionResult;
|
||||
for (const phase of selected.validation.phases.slice(1)) {
|
||||
await completeExperiment(phase.experimentId!);
|
||||
}
|
||||
const finished = (await f.request(
|
||||
`/api/v2/experiments/validation/${validation.id}/finalize`,
|
||||
'POST',
|
||||
{
|
||||
previewHash: preview.previewHash,
|
||||
selectionHash: selected.validation.selection!.selectionHash,
|
||||
},
|
||||
{ 'Idempotency-Key': randomUUID() }
|
||||
)) as ChronologicalValidationActionResult;
|
||||
expect(finished.validation.report).not.toBeNull();
|
||||
const costInput = {
|
||||
backtestId: draft.id,
|
||||
name: 'Browser candidate costs',
|
||||
scenarios: [{ feeRate: '0.02', slippageRate: '0.01' }],
|
||||
candidate,
|
||||
};
|
||||
const costPreview = (
|
||||
await f.request('/api/v2/experiments/cost-sensitivity/preview', 'POST', costInput)
|
||||
).preview as CostSensitivityPreview;
|
||||
const cost = (
|
||||
await f.request(
|
||||
'/api/v2/experiments/cost-sensitivity',
|
||||
'POST',
|
||||
{ ...costInput, previewHash: costPreview.previewHash },
|
||||
{ 'Idempotency-Key': randomUUID() }
|
||||
)
|
||||
).experiment as CostSensitivityDetail;
|
||||
await completeExperiment(cost.id);
|
||||
await f.request(`/api/v2/strategy-versions/${version.id}/reviews`, 'POST', {
|
||||
decision: 'approve',
|
||||
reason: 'Human reviewed controlled candidate bytes and actual held-out/cost evidence',
|
||||
});
|
||||
await f.page.goto(`${f.origin}/paper`);
|
||||
await visible(f.page, /No paper deployments/);
|
||||
await f.page.getByLabel('Deployment name', { exact: true }).fill('Reviewed browser candidate');
|
||||
await f.page.getByLabel('Report owner ID', { exact: true }).fill(validation.id);
|
||||
await f.page.getByLabel('Cost experiment ID', { exact: true }).fill(cost.id);
|
||||
await f.page.getByRole('button', { name: 'Load evidence', exact: true }).click();
|
||||
await f.page
|
||||
.getByLabel('Paper cost scenario', { exact: true })
|
||||
.selectOption(cost.trials[1]!.runId!);
|
||||
const start = Date.parse('2030-01-01T14:30:00Z');
|
||||
await f.page.getByLabel('Paper transport', { exact: true }).fill(
|
||||
JSON.stringify({
|
||||
accountId: `paper:${randomUUID()}`,
|
||||
sessionId: `paper:${randomUUID()}`,
|
||||
quoteSeriesId: 'X0.US:quote',
|
||||
riskSession: {
|
||||
calendarId: 'paper-risk',
|
||||
calendarRevision: 'v1',
|
||||
sessionId: 'paper-day',
|
||||
startsAt: start,
|
||||
},
|
||||
policy: {
|
||||
version: 1,
|
||||
sourceId: 'disposable-browser-feed',
|
||||
priceBasis: 'raw',
|
||||
maxFeedAgeMs: 300000,
|
||||
observations: [
|
||||
{
|
||||
instrumentId: 'X0.US',
|
||||
seriesId: 'X0.US:1m',
|
||||
intervalMs: 60000,
|
||||
staleAfterMs: 300000,
|
||||
},
|
||||
],
|
||||
cadence: [{ ownerId: `strategy:${version.id}`, seriesIds: ['X0.US:1m'] }],
|
||||
calendars: [
|
||||
{
|
||||
instrumentId: 'X0.US',
|
||||
calendarId: 'explicit-venue',
|
||||
revision: 'v1',
|
||||
sessions: [{ sessionId: 'paper-day', opensAt: start, closesAt: start + 3600000 }],
|
||||
},
|
||||
],
|
||||
riskBoundaries: [],
|
||||
},
|
||||
})
|
||||
);
|
||||
await f.page
|
||||
.getByLabel('Review rationale', { exact: true })
|
||||
.fill(
|
||||
'Controlled fixture evidence and code reviewed; no profitability claim or real activation.'
|
||||
);
|
||||
await f.page.getByLabel('Authorize trusted paper code', { exact: true }).check();
|
||||
await f.page.getByRole('button', { name: 'Preview promotion', exact: true }).click();
|
||||
await visible(f.page, 'Exact promotion preview');
|
||||
const promotionResponse = f.page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'POST' &&
|
||||
response.url().endsWith('/api/v2/paper-deployments')
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Create halted deployment', exact: true }).click();
|
||||
const promoted = await promotionResponse;
|
||||
expect(promoted.status()).toBe(201);
|
||||
const deployment = await promoted.json();
|
||||
await f.page.waitForURL(url => url.pathname.endsWith(`/paper/${deployment.id}`));
|
||||
await visible(f.page, 'Reviewed browser candidate');
|
||||
await visible(f.page, /Paper orchestrator origin is not configured/);
|
||||
expect(
|
||||
(await f.pool.query('SELECT count(*)::int AS count FROM simulation_accounts')).rows[0].count
|
||||
).toBe(0);
|
||||
await f.page.reload();
|
||||
await visible(f.page, 'Reviewed browser candidate');
|
||||
expect(
|
||||
(await f.request(`/api/v2/paper-deployments/${deployment.id}`)).preview.strategy.versionId
|
||||
).toBe(version.id);
|
||||
expect(f.unexpectedNetwork).toEqual([]);
|
||||
expect(f.historicalDataReads).toEqual([]);
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
}, 180000);
|
||||
|
|
|
|||
200
test/integration/candidate-contract.test.ts
Normal file
200
test/integration/candidate-contract.test.ts
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { PassThrough } from 'node:stream';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
candidateExecutionSchema,
|
||||
candidateSandboxLimits,
|
||||
} from '../../apps/stock/config/src/contracts/candidate-execution';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
canonicalStrategyExecution,
|
||||
} from '../../apps/stock/config/src/contracts/canonical-research';
|
||||
import {
|
||||
chronologicalPolicyForOrigin,
|
||||
chronologicalValidationPolicy,
|
||||
} from '../../apps/stock/config/src/contracts/chronological-validation';
|
||||
import { experimentInputSchema } from '../../apps/stock/config/src/contracts/experiments';
|
||||
import {
|
||||
readCandidateFrames,
|
||||
writeCandidateFrame,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/candidate-protocol';
|
||||
import { researchGrantPolicy } from '../../apps/stock/web-api/src/services/research-agent-budget';
|
||||
import { canonicalRunnerFixture } from '../fixtures/canonical-runner';
|
||||
|
||||
export const fakeCandidateExecution = () =>
|
||||
candidateExecutionSchema.parse({
|
||||
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,
|
||||
},
|
||||
});
|
||||
function candidateFixture() {
|
||||
const { request } = canonicalRunnerFixture();
|
||||
const candidateId = randomUUID(),
|
||||
ownerId = `strategy:${candidateId}`;
|
||||
const policy = structuredClone(request.policy);
|
||||
policy.matching.risk.ledger.ownerIds = [ownerId];
|
||||
policy.matching.owners = [{ ownerId, mode: 'Target' }];
|
||||
policy.cadence = [{ owner_id: ownerId, series_ids: [request.strategy.selection.seriesId] }];
|
||||
const candidate = {
|
||||
...request,
|
||||
policy,
|
||||
strategy: {
|
||||
...request.strategy,
|
||||
origin: 'candidate',
|
||||
versionId: candidateId,
|
||||
baselineVersionId: request.strategy.versionId,
|
||||
reviewId: null,
|
||||
execution: fakeCandidateExecution(),
|
||||
package: {
|
||||
...request.strategy.package,
|
||||
execution: { kind: 'isolated-candidate/v1', warmupBars: 0 },
|
||||
},
|
||||
selection: { ...request.strategy.selection, ownerId },
|
||||
},
|
||||
};
|
||||
return { builtin: request, candidate: canonicalRunRequestSchema.parse(candidate) };
|
||||
}
|
||||
describe('isolated candidate contracts', () => {
|
||||
test('builtin snapshots and grant projection retain exact existing bytes', () => {
|
||||
const { builtin } = candidateFixture();
|
||||
expect(JSON.stringify(canonicalRunRequestSchema.parse(builtin))).toBe(JSON.stringify(builtin));
|
||||
expect(canonicalStrategyExecution(builtin)).toBe('typescript-retained-builtin/v1');
|
||||
expect(builtin.strategy).not.toHaveProperty('execution');
|
||||
expect(builtin.strategy).not.toHaveProperty('baselineVersionId');
|
||||
const policy = researchGrantPolicy(builtin);
|
||||
expect(policy.versionId).toBe(builtin.strategy.versionId);
|
||||
expect(policy.policy.matching.owners).toEqual(builtin.policy.matching.owners);
|
||||
});
|
||||
test('candidate alone accepts no review, generic identity and fixed declared warmup', () => {
|
||||
const { builtin, candidate } = candidateFixture();
|
||||
expect(candidate.strategy.reviewId).toBeNull();
|
||||
expect(canonicalStrategyExecution(candidate)).toBe('typescript-isolated-candidate/v1');
|
||||
expect(
|
||||
canonicalRunRequestSchema.safeParse({
|
||||
...builtin,
|
||||
strategy: { ...builtin.strategy, reviewId: null },
|
||||
}).success
|
||||
).toBeFalse();
|
||||
for (const field of ['execution', 'baselineVersionId']) {
|
||||
const malformed = {
|
||||
...candidate,
|
||||
strategy: Object.fromEntries(
|
||||
Object.entries(candidate.strategy).filter(([name]) => name !== field)
|
||||
),
|
||||
};
|
||||
expect(canonicalRunRequestSchema.safeParse(malformed).success).toBeFalse();
|
||||
}
|
||||
expect(
|
||||
canonicalRunRequestSchema.safeParse({
|
||||
...builtin,
|
||||
strategy: { ...builtin.strategy, execution: fakeCandidateExecution() },
|
||||
}).success
|
||||
).toBeFalse();
|
||||
});
|
||||
test('candidate maps only its derived identities back to the frozen baseline grant', () => {
|
||||
const { builtin, candidate } = candidateFixture();
|
||||
expect(researchGrantPolicy(candidate)).toEqual(researchGrantPolicy(builtin));
|
||||
const changed = structuredClone(candidate);
|
||||
changed.policy.matching.risk.maxGrossExposure =
|
||||
'1.00000000' as typeof changed.policy.matching.risk.maxGrossExposure;
|
||||
expect(researchGrantPolicy(changed)).not.toEqual(researchGrantPolicy(builtin));
|
||||
if (changed.strategy.origin !== 'candidate') {
|
||||
throw new Error('fixture origin');
|
||||
}
|
||||
changed.strategy.baselineVersionId = randomUUID();
|
||||
expect(researchGrantPolicy(changed).versionId).not.toBe(researchGrantPolicy(builtin).versionId);
|
||||
});
|
||||
test('profile cannot raise limits, choose trusted execution, add host flags or choose an unsupported platform', () => {
|
||||
const execution = fakeCandidateExecution();
|
||||
for (const changed of [
|
||||
{ ...execution, kind: 'typescript-retained-builtin/v1' },
|
||||
{ ...execution, flags: ['--privileged'] },
|
||||
{ ...execution, profile: { ...execution.profile, arch: 'arm64' } },
|
||||
{
|
||||
...execution,
|
||||
profile: {
|
||||
...execution.profile,
|
||||
limits: { ...execution.profile.limits, memoryBytes: 1073741824 },
|
||||
},
|
||||
},
|
||||
]) {
|
||||
expect(candidateExecutionSchema.safeParse(changed).success).toBeFalse();
|
||||
}
|
||||
});
|
||||
test('candidate input is explicit and strategy policy never claims inferred determinism', () => {
|
||||
const input = {
|
||||
backtestId: randomUUID(),
|
||||
name: 'Candidate',
|
||||
grid: {},
|
||||
candidate: { versionId: randomUUID(), parameters: {} },
|
||||
};
|
||||
expect(experimentInputSchema.parse(input)).toEqual(input);
|
||||
expect(
|
||||
experimentInputSchema.safeParse({ ...input, candidate: { ...input.candidate, feeRate: '0' } })
|
||||
.success
|
||||
).toBeFalse();
|
||||
expect(chronologicalPolicyForOrigin('builtin')).toBe(chronologicalValidationPolicy);
|
||||
expect(chronologicalPolicyForOrigin('candidate')).toEqual({
|
||||
...chronologicalValidationPolicy,
|
||||
model: 'unverified-candidate',
|
||||
});
|
||||
});
|
||||
test('framing preserves exact JSON across chunks and rejects truncation/oversize before parsing', async () => {
|
||||
const encoded = new PassThrough();
|
||||
const output: unknown[] = [];
|
||||
const read = (async () => {
|
||||
for await (const frame of readCandidateFrames(encoded)) {
|
||||
output.push(frame);
|
||||
}
|
||||
})();
|
||||
await writeCandidateFrame(encoded, { version: 1, string: 'Unicode α', sequence: 1 });
|
||||
encoded.end();
|
||||
await read;
|
||||
expect(output).toEqual([{ version: 1, string: 'Unicode α', sequence: 1 }]);
|
||||
for (const length of [0, candidateSandboxLimits.frameBytes + 1]) {
|
||||
const input = new PassThrough(),
|
||||
bytes = Buffer.alloc(4);
|
||||
bytes.writeUInt32BE(length);
|
||||
input.end(bytes);
|
||||
await expect(readCandidateFrames(input).next()).rejects.toThrow('Invalid or oversized');
|
||||
}
|
||||
const input = new PassThrough();
|
||||
input.end(Buffer.from([0, 0, 0, 5, 123]));
|
||||
await expect(readCandidateFrames(input).next()).rejects.toThrow('Truncated');
|
||||
});
|
||||
test('split UTF-8 frames are decoded only when complete; malformed UTF-8 and flooding are rejected', async () => {
|
||||
const content = Buffer.from(JSON.stringify({ value: 'αβ😀' }));
|
||||
const header = Buffer.alloc(4);
|
||||
header.writeUInt32BE(content.length);
|
||||
const input = new PassThrough();
|
||||
const collected = (async () => {
|
||||
const out: unknown[] = [];
|
||||
for await (const value of readCandidateFrames(input)) {
|
||||
out.push(value);
|
||||
}
|
||||
return out;
|
||||
})();
|
||||
for (const byte of Buffer.concat([header, content])) {
|
||||
input.write(Buffer.from([byte]));
|
||||
await Promise.resolve();
|
||||
}
|
||||
input.end();
|
||||
expect(await collected).toEqual([{ value: 'αβ😀' }]);
|
||||
const invalid = new PassThrough();
|
||||
invalid.end(Buffer.from([0, 0, 0, 1, 255]));
|
||||
await expect(readCandidateFrames(invalid).next()).rejects.toThrow();
|
||||
const flood = new PassThrough();
|
||||
flood.end(Buffer.alloc(candidateSandboxLimits.frameBytes + 5));
|
||||
await expect(readCandidateFrames(flood).next()).rejects.toThrow('buffer exceeds');
|
||||
});
|
||||
});
|
||||
296
test/integration/candidate-publication-ui.test.tsx
Normal file
296
test/integration/candidate-publication-ui.test.tsx
Normal file
|
|
@ -0,0 +1,296 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from 'bun:test';
|
||||
import { GlobalWindow } from 'happy-dom';
|
||||
import { act, createElement } from 'react';
|
||||
import type { Root } from 'react-dom/client';
|
||||
import type { StrategyVersionPackage } from '@stock-bot/types';
|
||||
import { tableFixture } from '../../scripts/benchmark-experiment-tables';
|
||||
|
||||
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
||||
const keys = ['window', 'document', 'IS_REACT_ACT_ENVIRONMENT'] as const;
|
||||
const originals = keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)] as const);
|
||||
const familyId = '11111111-1111-4111-8111-111111111111';
|
||||
const versionId = '22222222-2222-4222-8222-222222222222';
|
||||
let createRoot: typeof import('react-dom/client').createRoot;
|
||||
let Publication: typeof import('../../apps/stock/web-app/src/features/strategies/components/CandidatePublication').CandidatePublication;
|
||||
let readPackage: typeof import('../../apps/stock/web-app/src/features/strategies/services/candidatePublication').readCandidatePackage;
|
||||
let publish: typeof import('../../apps/stock/web-app/src/features/strategies/services/candidatePublication').publishCandidate;
|
||||
let root: Root | undefined;
|
||||
let host: HTMLDivElement;
|
||||
const saved: unknown[] = [];
|
||||
const dirty: boolean[] = [];
|
||||
type Pending = {
|
||||
url: string;
|
||||
body: { package: StrategyVersionPackage; parentVersionId: string | null };
|
||||
key: string;
|
||||
resolve: (response: Response) => void;
|
||||
reject: (error: Error) => void;
|
||||
settled: boolean;
|
||||
};
|
||||
const calls: Pending[] = [];
|
||||
function pkg(label = 'first'): StrategyVersionPackage {
|
||||
const value = structuredClone(tableFixture(1).preview.request.strategy.package);
|
||||
value.execution = { kind: 'isolated-candidate/v1', warmupBars: 0 };
|
||||
value.artifact.content = `globalThis.__candidatePublicationExecuted = '${label}';`;
|
||||
value.artifact.sha256 = createHash('sha256').update(value.artifact.content).digest('hex');
|
||||
value.dependencyLock.sha256 = createHash('sha256')
|
||||
.update(value.dependencyLock.content)
|
||||
.digest('hex');
|
||||
return value;
|
||||
}
|
||||
async function flush(action = () => {}) {
|
||||
await act(async () => {
|
||||
action();
|
||||
await Promise.resolve();
|
||||
});
|
||||
}
|
||||
function button(text: string) {
|
||||
return [...host.querySelectorAll('button')].find(item => item.textContent?.trim() === text)!;
|
||||
}
|
||||
const fileField = () => host.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
async function choose(value: { name: string; text: () => Promise<string> }) {
|
||||
await flush(() => {
|
||||
Object.defineProperty(fileField(), 'files', { configurable: true, value: [value] });
|
||||
fileField().dispatchEvent(new browser.Event('change', { bubbles: true }) as unknown as Event);
|
||||
});
|
||||
}
|
||||
async function upload(value = pkg()) {
|
||||
await choose({ name: 'candidate.json', text: async () => JSON.stringify(value) });
|
||||
}
|
||||
function reply(request: Pending, body: unknown, status: number) {
|
||||
request.settled = true;
|
||||
request.resolve(Response.json(body, { status }));
|
||||
}
|
||||
function receipt(request: Pending) {
|
||||
return {
|
||||
version: {
|
||||
id: versionId,
|
||||
strategyId: familyId,
|
||||
ordinal: 1,
|
||||
origin: 'candidate',
|
||||
parentVersionId: request.body.parentVersionId,
|
||||
package: request.body.package,
|
||||
},
|
||||
};
|
||||
}
|
||||
async function mount(parentVersionId: string | null = null) {
|
||||
root = createRoot(host);
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
createElement(Publication, {
|
||||
strategyId: familyId,
|
||||
parentVersionId,
|
||||
disabled: false,
|
||||
onDirtyChange: value => dirty.push(value),
|
||||
onPublished: value => saved.push(value),
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
beforeAll(async () => {
|
||||
for (const [key, value] of Object.entries({
|
||||
window: browser,
|
||||
document: browser.document,
|
||||
IS_REACT_ACT_ENVIRONMENT: true,
|
||||
})) {
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
}
|
||||
({ createRoot } = await import('react-dom/client'));
|
||||
({ CandidatePublication: Publication } = await import(
|
||||
'../../apps/stock/web-app/src/features/strategies/components/CandidatePublication'
|
||||
));
|
||||
({ readCandidatePackage: readPackage, publishCandidate: publish } = await import(
|
||||
'../../apps/stock/web-app/src/features/strategies/services/candidatePublication'
|
||||
));
|
||||
});
|
||||
beforeEach(() => {
|
||||
calls.length = 0;
|
||||
saved.length = 0;
|
||||
dirty.length = 0;
|
||||
host = browser.document.createElement('div') as unknown as HTMLDivElement;
|
||||
browser.document.body.append(host as never);
|
||||
browser.fetch = ((url: unknown, init?: RequestInit) =>
|
||||
new Promise<Response>((resolve, reject) => {
|
||||
calls.push({
|
||||
url: String(url),
|
||||
body: JSON.parse(String(init?.body)),
|
||||
key: new Headers(init?.headers).get('Idempotency-Key')!,
|
||||
resolve,
|
||||
reject,
|
||||
settled: false,
|
||||
});
|
||||
})) as unknown as typeof browser.fetch;
|
||||
});
|
||||
afterEach(async () => {
|
||||
await flush(() => root?.unmount());
|
||||
root = undefined;
|
||||
host.remove();
|
||||
});
|
||||
afterAll(() => {
|
||||
for (const [key, descriptor] of originals) {
|
||||
if (descriptor) {
|
||||
Object.defineProperty(globalThis, key, descriptor);
|
||||
} else {
|
||||
Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
}
|
||||
browser.happyDOM.abort();
|
||||
});
|
||||
|
||||
test('package upload verifies retained hashes and declaration without executing generated source', async () => {
|
||||
await mount();
|
||||
expect(button('Publish immutable candidate').disabled).toBe(true);
|
||||
const value = pkg();
|
||||
await upload(value);
|
||||
expect(host.textContent).toContain(value.artifact.sha256);
|
||||
expect(host.textContent).toContain('Author-declared warmup bars');
|
||||
expect((globalThis as Record<string, unknown>).__candidatePublicationExecuted).toBeUndefined();
|
||||
expect(calls).toHaveLength(0);
|
||||
await flush(() => button('Publish immutable candidate').click());
|
||||
expect(calls[0]!.body).toEqual({ package: value, parentVersionId: null });
|
||||
expect(calls[0]!.key).not.toBe('');
|
||||
await flush(() => reply(calls[0]!, receipt(calls[0]!), 201));
|
||||
expect(saved).toEqual([{ id: versionId, strategyId: familyId, ordinal: 1 }]);
|
||||
expect(dirty.at(-1)).toBe(false);
|
||||
expect(button('Publish immutable candidate').disabled).toBe(true);
|
||||
});
|
||||
|
||||
test('invalid bytes, absent execution declaration and stale file reads never become a publication', async () => {
|
||||
const invalid = pkg();
|
||||
invalid.artifact.sha256 = 'f'.repeat(64);
|
||||
await expect(readPackage(JSON.stringify(invalid))).rejects.toThrow('hash does not match');
|
||||
const legacy = pkg();
|
||||
delete legacy.execution;
|
||||
await expect(readPackage(JSON.stringify(legacy))).rejects.toThrow('must declare');
|
||||
await mount();
|
||||
await upload(invalid);
|
||||
expect(host.querySelector('[role="alert"]')).not.toBeNull();
|
||||
expect(button('Publish immutable candidate').disabled).toBe(true);
|
||||
let release!: (text: string) => void;
|
||||
await choose({
|
||||
name: 'old.json',
|
||||
text: () =>
|
||||
new Promise(resolve => {
|
||||
release = resolve;
|
||||
}),
|
||||
});
|
||||
const current = pkg('current');
|
||||
await upload(current);
|
||||
await flush(() => release(JSON.stringify(pkg('old'))));
|
||||
expect(host.textContent).toContain(current.artifact.sha256);
|
||||
expect(host.textContent).not.toContain(pkg('old').artifact.sha256);
|
||||
await flush(() => button('Clear package').click());
|
||||
expect(button('Publish immutable candidate').disabled).toBe(true);
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('lost publication freezes package, lineage and key; repeated clicks recover one receipt', async () => {
|
||||
const parent = '33333333-3333-4333-8333-333333333333';
|
||||
await mount(parent);
|
||||
await upload();
|
||||
await flush(() => {
|
||||
button('Publish immutable candidate').click();
|
||||
button('Publish immutable candidate').click();
|
||||
});
|
||||
expect(calls).toHaveLength(1);
|
||||
await flush(() => {
|
||||
calls[0]!.settled = true;
|
||||
calls[0]!.reject(new Error('Connection lost'));
|
||||
});
|
||||
expect(fileField().disabled).toBe(true);
|
||||
expect(button('Clear package').disabled).toBe(true);
|
||||
await upload(pkg('changed'));
|
||||
await flush(() => button('Retry same publication').click());
|
||||
expect(calls).toHaveLength(2);
|
||||
expect(calls[1]!.body).toEqual(calls[0]!.body);
|
||||
expect(calls[1]!.key).toBe(calls[0]!.key);
|
||||
expect(calls[1]!.body.parentVersionId).toBe(parent);
|
||||
await flush(() => reply(calls[1]!, receipt(calls[1]!), 201));
|
||||
expect(saved).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('definitive rejection permits correction; wrong success receipt remains uncertain', async () => {
|
||||
await mount();
|
||||
await upload();
|
||||
await flush(() => button('Publish immutable candidate').click());
|
||||
await flush(() => reply(calls[0]!, { error: 'Archived family' }, 409));
|
||||
expect(fileField().disabled).toBe(false);
|
||||
expect(host.textContent).toContain('Archived family');
|
||||
await flush(() => button('Publish immutable candidate').click());
|
||||
expect(calls[1]!.key).not.toBe(calls[0]!.key);
|
||||
const wrong = receipt(calls[1]!);
|
||||
wrong.version.strategyId = versionId;
|
||||
await flush(() => reply(calls[1]!, wrong, 201));
|
||||
expect(fileField().disabled).toBe(true);
|
||||
expect(button('Retry same publication')).not.toBeUndefined();
|
||||
expect(saved).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('unmounted publication cannot navigate or replace a new family', async () => {
|
||||
await mount();
|
||||
await upload();
|
||||
await flush(() => button('Publish immutable candidate').click());
|
||||
await flush(() => root!.unmount());
|
||||
root = undefined;
|
||||
await flush(() => reply(calls[0]!, receipt(calls[0]!), 201));
|
||||
expect(saved).toHaveLength(0);
|
||||
expect(host.textContent).toBe('');
|
||||
});
|
||||
|
||||
test('same-event Publish then Clear preserves the only recoverable package and receipt', async () => {
|
||||
await mount();
|
||||
const value = pkg();
|
||||
await upload(value);
|
||||
await flush(() => {
|
||||
button('Publish immutable candidate').click();
|
||||
button('Clear package').click();
|
||||
});
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(host.textContent).toContain(value.artifact.sha256);
|
||||
await flush(() => calls[0]!.reject(new Error('Lost accepted response')));
|
||||
expect(button('Retry same publication').disabled).toBe(false);
|
||||
await flush(() => button('Retry same publication').click());
|
||||
expect(calls[1]!.key).toBe(calls[0]!.key);
|
||||
expect(calls[1]!.body).toEqual(calls[0]!.body);
|
||||
await flush(() => reply(calls[1]!, receipt(calls[1]!), 201));
|
||||
expect(saved).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('later archive or eligibility loss blocks new publication but preserves an accepted receipt retry', async () => {
|
||||
await mount();
|
||||
await upload();
|
||||
await flush(() => button('Publish immutable candidate').click());
|
||||
await flush(() => calls[0]!.reject(new Error('Lost accepted response')));
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
createElement(Publication, {
|
||||
strategyId: familyId,
|
||||
parentVersionId: null,
|
||||
disabled: true,
|
||||
onDirtyChange: value => dirty.push(value),
|
||||
onPublished: value => saved.push(value),
|
||||
})
|
||||
)
|
||||
);
|
||||
expect(fileField().disabled).toBe(true);
|
||||
expect(button('Retry same publication').disabled).toBe(false);
|
||||
await flush(() => button('Retry same publication').click());
|
||||
expect(calls[1]!.body).toEqual(calls[0]!.body);
|
||||
expect(calls[1]!.key).toBe(calls[0]!.key);
|
||||
await flush(() => reply(calls[1]!, receipt(calls[1]!), 201));
|
||||
expect(saved).toHaveLength(1);
|
||||
expect(button('Publish immutable candidate').disabled).toBe(true);
|
||||
});
|
||||
|
||||
test('uppercase family and parent identities normalize before sending and checking publication', async () => {
|
||||
const family = 'abcdefab-abcd-4bcd-8bcd-abcdefabcdef';
|
||||
const parent = 'fabcdefa-abcd-4bcd-8bcd-abcdefabcdef';
|
||||
const published = publish(family.toUpperCase(), pkg(), parent.toUpperCase(), 'case-normalized');
|
||||
const call = calls[0]!;
|
||||
expect(call.url).toContain(`/strategies/${family}/versions`);
|
||||
expect(call.body.parentVersionId).toBe(parent);
|
||||
const body = receipt(call);
|
||||
body.version.strategyId = family;
|
||||
reply(call, body, 201);
|
||||
expect((await published).strategyId).toBe(family);
|
||||
});
|
||||
63
test/integration/candidate-response-contract.test.ts
Normal file
63
test/integration/candidate-response-contract.test.ts
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { candidateSandboxLimits } from '@stock-bot/stock-config/candidate-execution';
|
||||
import { validateStrategyParameters } from '@stock-bot/stock-config/strategy';
|
||||
import { parseExperimentPreview } from '../../apps/stock/config/src/contracts/research-responses/experiment';
|
||||
import { tableFixture } from '../../scripts/benchmark-experiment-tables';
|
||||
|
||||
function candidatePreview() {
|
||||
const value = structuredClone(tableFixture(1).preview);
|
||||
const strategy = value.request.strategy;
|
||||
value.input.candidate = {
|
||||
versionId: strategy.versionId,
|
||||
parameters: { ...strategy.selection.parameters },
|
||||
};
|
||||
value.request.strategy = {
|
||||
...strategy,
|
||||
origin: 'candidate',
|
||||
reviewId: null,
|
||||
baselineVersionId: strategy.versionId,
|
||||
package: { ...strategy.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,
|
||||
},
|
||||
},
|
||||
};
|
||||
return value;
|
||||
}
|
||||
test('candidate preview binds normalized base parameters independently of valid package/version identity', () => {
|
||||
const value = candidatePreview();
|
||||
expect(parseExperimentPreview(value).input.candidate).toEqual(value.input.candidate!);
|
||||
const changed = structuredClone(value);
|
||||
changed.input.candidate!.parameters.fastPeriod = 1;
|
||||
expect(() => parseExperimentPreview(changed)).toThrow('could not be verified');
|
||||
const changedRequest = structuredClone(value);
|
||||
if (changedRequest.request.strategy.origin !== 'candidate') {
|
||||
throw new Error('Expected candidate fixture');
|
||||
}
|
||||
changedRequest.request.strategy.selection.parameters.fastPeriod = 1;
|
||||
expect(() => parseExperimentPreview(changedRequest)).toThrow('could not be verified');
|
||||
});
|
||||
test('candidate parameter defaults are accepted when they exactly match the retained base selection', () => {
|
||||
const value = candidatePreview();
|
||||
value.input.candidate!.parameters = {};
|
||||
value.request.strategy.selection.parameters = validateStrategyParameters(
|
||||
value.request.strategy.package,
|
||||
{}
|
||||
);
|
||||
expect(parseExperimentPreview(value).request.strategy.selection.parameters).toEqual(
|
||||
value.request.strategy.selection.parameters
|
||||
);
|
||||
value.input.candidate!.parameters.fastPeriod = 1;
|
||||
expect(() => parseExperimentPreview(value)).toThrow('could not be verified');
|
||||
});
|
||||
497
test/integration/candidate-sandbox.test.ts
Normal file
497
test/integration/candidate-sandbox.test.ts
Normal file
|
|
@ -0,0 +1,497 @@
|
|||
import { execFile, fork, type ChildProcessWithoutNullStreams } from 'node:child_process';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { readlinkSync } from 'node:fs';
|
||||
import { access, mkdtemp, rename, rm, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { promisify } from 'node:util';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { canonicalRunRequestSchema } from '../../apps/stock/config/src/contracts/canonical-research';
|
||||
import {
|
||||
candidateDescriptorPath,
|
||||
IsolatedCandidateController,
|
||||
readCandidateExecution,
|
||||
removeCandidateContainer,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/candidate-sandbox';
|
||||
import {
|
||||
canonicalWorkerUrl,
|
||||
readCanonicalBuildIdentity,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/canonical-build';
|
||||
import {
|
||||
NativeReplaySession,
|
||||
prepareReplayLoad,
|
||||
runReplaySessionAsync,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import { packageCandidateStrategy } from '../../scripts/package-candidate-strategy';
|
||||
import { canonicalRunnerFixture } from '../fixtures/canonical-runner';
|
||||
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
||||
|
||||
const suite = process.env.CANDIDATE_SANDBOX_TESTS === '1' ? describe : describe.skip;
|
||||
const hash = (s: string) => createHash('sha256').update(s).digest('hex');
|
||||
const runFile = promisify(execFile);
|
||||
const hostPidNamespace = readlinkSync('/proc/self/ns/pid');
|
||||
const program = (
|
||||
decision = "return {nextState:c.state,intent:{mode:'target',targets:[]}}",
|
||||
prefix = ''
|
||||
) =>
|
||||
`${prefix}\nexport function createStrategy(s) { return {ownerId:s.ownerId,strategyId:s.strategyId,strategyVersion:s.strategyVersion,seed:s.seed,mode:'target',initialState:null,decide(c){${decision}}}; }`;
|
||||
async function fixture(content: string) {
|
||||
const f = canonicalRunnerFixture();
|
||||
const pkg = {
|
||||
...f.request.strategy.package,
|
||||
execution: { kind: 'isolated-candidate/v1', warmupBars: 0 },
|
||||
program: {
|
||||
strategyId: 'isolated-probe',
|
||||
strategyVersion: 'v1',
|
||||
apiVersion: 'canonical-ts/v1',
|
||||
checkpointVersion: '1',
|
||||
},
|
||||
parameterSchema: {
|
||||
version: 1,
|
||||
type: 'object',
|
||||
properties: {},
|
||||
required: [],
|
||||
additionalProperties: false,
|
||||
},
|
||||
artifact: {
|
||||
format: 'esm-bundle/v1',
|
||||
entryExport: 'createStrategy',
|
||||
content,
|
||||
sha256: hash(content),
|
||||
},
|
||||
dependencyLock: { format: 'bun-lock/v1', content: '{}', sha256: hash('{}') },
|
||||
};
|
||||
const request = canonicalRunRequestSchema.parse({
|
||||
...f.request,
|
||||
strategy: {
|
||||
...f.request.strategy,
|
||||
origin: 'candidate',
|
||||
baselineVersionId: f.request.strategy.versionId,
|
||||
reviewId: null,
|
||||
execution: await readCandidateExecution(),
|
||||
package: pkg,
|
||||
selection: {
|
||||
...f.request.strategy.selection,
|
||||
strategyId: 'isolated-probe',
|
||||
strategyVersion: 'v1',
|
||||
parameters: {},
|
||||
},
|
||||
},
|
||||
});
|
||||
return { ...f, request, name: `stock-bot-candidate-${randomUUID()}` };
|
||||
}
|
||||
async function absent(name: string) {
|
||||
expect(
|
||||
(
|
||||
await runFile('/usr/bin/docker', [
|
||||
'--host',
|
||||
'unix:///var/run/docker.sock',
|
||||
'ps',
|
||||
'-a',
|
||||
'-q',
|
||||
'--filter',
|
||||
`name=^/${name}$`,
|
||||
])
|
||||
).stdout.trim()
|
||||
).toBe('');
|
||||
}
|
||||
suite('actual OS-isolated candidate runtime', () => {
|
||||
test('host environment/files/network/process spawning denied; ordinary prefix-only computation completes under native finance', async () => {
|
||||
const f = await fixture(
|
||||
program(
|
||||
"if(c.observations.some(o=>o.available_at>c.now))throw Error('future observation'); if('dataset' in c || 'history' in c)throw Error('unexpected dataset'); return {nextState:null,intent:{mode:'target',targets:[]}}",
|
||||
`
|
||||
if(Object.keys(process.env).length!==0)throw Error('inherited environment');
|
||||
if(process.getuid()!==65534)throw Error('privileged child');
|
||||
const fs=await import('node:fs');
|
||||
try{fs.readFileSync('/home/boki/repos/stock-bot/.env');throw Error('host file visible')}catch(e){if(e.code!=='ENOENT')throw e}
|
||||
try{fs.writeFileSync('/app/forbidden','x');throw Error('root writable')}catch(e){if(!['EROFS','EACCES'].includes(e.code))throw e}
|
||||
const cp=await import('node:child_process');
|
||||
const spawned=cp.spawnSync('/usr/bin/bun',['--version']); if(!spawned.error)throw Error('process spawn allowed');
|
||||
try{await fetch('http://127.0.0.1:5432');throw Error('network allowed')}catch(e){if(e.message==='network allowed')throw e}
|
||||
if(fs.readlinkSync('/proc/self/ns/pid')===${JSON.stringify(hostPidNamespace)})throw Error('host PID namespace');
|
||||
const ffi=await import('bun:ffi'); const libc=ffi.dlopen('/lib/x86_64-linux-gnu/libc.so.6',{unshare:{args:['i32'],returns:'i32'}}); if(libc.symbols.unshare(0x10000000)!==-1)throw Error('namespace creation allowed');libc.close();
|
||||
try{fs.writeFileSync('/tmp/overflow',Buffer.alloc(20*1024*1024));throw Error('tmp quota absent')}catch(e){if(e.code!=='ENOSPC')throw e}
|
||||
const status=fs.readFileSync('/proc/self/status','utf8'); if(!/NoNewPrivs:\\s+1/.test(status)||!/Seccomp:\\s+2/.test(status))throw Error('seccomp missing');
|
||||
`
|
||||
)
|
||||
);
|
||||
const c = await IsolatedCandidateController.start(f.request, f.name);
|
||||
try {
|
||||
const result = await runReplaySessionAsync(
|
||||
new NativeReplaySession(prepareReplayLoad(f.dataset, f.request.policy)),
|
||||
c,
|
||||
{ resultFormat: 'report' }
|
||||
);
|
||||
await c.finish();
|
||||
if (!('format' in result.result) || result.result.format !== 'report') {
|
||||
throw new Error('Expected native report');
|
||||
}
|
||||
expect(result.result.projection.fills).toEqual([]);
|
||||
expect(String(result.result.view.equity)).toBe('10000.00000000');
|
||||
} finally {
|
||||
await c.dispose();
|
||||
}
|
||||
await absent(f.name);
|
||||
}, 30000);
|
||||
test('native financial risk rejects malicious huge targets without treating ownerBudget as an allocation constraint', async () => {
|
||||
const f = await fixture(
|
||||
program(
|
||||
"return {nextState:null,intent:{mode:'target',targets:[{instrumentId:'X0.US',quantity:'999999999'}]}}"
|
||||
)
|
||||
);
|
||||
const c = await IsolatedCandidateController.start(f.request, f.name);
|
||||
try {
|
||||
const admissions: unknown[] = [];
|
||||
const result = await runReplaySessionAsync(
|
||||
new NativeReplaySession(prepareReplayLoad(f.dataset, f.request.policy)),
|
||||
{
|
||||
stage: c.stage.bind(c),
|
||||
async committed(outcome) {
|
||||
admissions.push(outcome);
|
||||
await c.committed(outcome);
|
||||
},
|
||||
},
|
||||
{ resultFormat: 'report' }
|
||||
);
|
||||
await c.finish();
|
||||
if (!('format' in result.result) || result.result.format !== 'report') {
|
||||
throw new Error('Expected native report');
|
||||
}
|
||||
expect(result.result.projection.fills).toEqual([]);
|
||||
expect(String(result.result.view.equity)).toBe('10000.00000000');
|
||||
expect(JSON.stringify(admissions)).toContain('OrderSize');
|
||||
} finally {
|
||||
await c.dispose();
|
||||
}
|
||||
await absent(f.name);
|
||||
}, 30000);
|
||||
test('infinite callback deadline fails and disposal confirms no surviving container', async () => {
|
||||
const f = await fixture(program('for(;;){}'));
|
||||
const c = await IsolatedCandidateController.start(f.request, f.name, Date.now() + 2500);
|
||||
const start = performance.now();
|
||||
try {
|
||||
await expect(
|
||||
runReplaySessionAsync(
|
||||
new NativeReplaySession(prepareReplayLoad(f.dataset, f.request.policy)),
|
||||
c
|
||||
)
|
||||
).rejects.toThrow();
|
||||
} finally {
|
||||
await c.dispose();
|
||||
}
|
||||
expect(performance.now() - start).toBeLessThan(8000);
|
||||
await absent(f.name);
|
||||
}, 15000);
|
||||
test('process exit between ready and first callback rejects promptly instead of waiting for the wall budget', async () => {
|
||||
const f = await fixture(program(undefined, 'setTimeout(()=>process.exit(0),50);'));
|
||||
const c = await IsolatedCandidateController.start(f.request, f.name);
|
||||
await Bun.sleep(150);
|
||||
const start = performance.now();
|
||||
try {
|
||||
await expect(
|
||||
runReplaySessionAsync(
|
||||
new NativeReplaySession(prepareReplayLoad(f.dataset, f.request.policy)),
|
||||
c
|
||||
)
|
||||
).rejects.toThrow(/closed|exited/);
|
||||
} finally {
|
||||
await c.dispose();
|
||||
}
|
||||
expect(performance.now() - start).toBeLessThan(3000);
|
||||
await absent(f.name);
|
||||
}, 15000);
|
||||
test('unsolicited stdout frames, oversized frames and stderr flood cannot create a valid financial result', async () => {
|
||||
for (const attack of [
|
||||
"const b=Buffer.from(JSON.stringify({version:1,type:'ready',sequence:999}));const h=Buffer.alloc(4);h.writeUInt32BE(b.length);process.stdout.write(Buffer.concat([h,b]));",
|
||||
'process.stdout.write(Buffer.from([255,255,255,255]));',
|
||||
"process.stderr.write('x'.repeat(200000));throw Error('bounded diagnostic');",
|
||||
]) {
|
||||
const f = await fixture(program(undefined, attack));
|
||||
await expect(IsolatedCandidateController.start(f.request, f.name)).rejects.toThrow();
|
||||
await absent(f.name);
|
||||
}
|
||||
}, 30000);
|
||||
test('isolated TS packaging transforms types without evaluating top-level code and refuses dependency edges', async () => {
|
||||
const f = await fixture(program());
|
||||
const metadata = {
|
||||
program: f.request.strategy.package.program,
|
||||
parameterSchema: f.request.strategy.package.parameterSchema,
|
||||
execution: f.request.strategy.package.execution,
|
||||
source: f.request.strategy.package.source,
|
||||
entryExport: 'createStrategy',
|
||||
};
|
||||
const pkg = await packageCandidateStrategy(
|
||||
metadata,
|
||||
`const typed: number = 1; ${program()}\nfor(;;){}`
|
||||
);
|
||||
expect(pkg.artifact.content).not.toContain(': number');
|
||||
expect(pkg.artifact.sha256).toBe(hash(pkg.artifact.content));
|
||||
expect(pkg.build.version).toBe(Bun.version);
|
||||
for (const source of [
|
||||
"import x from 'node:fs'; export {x};",
|
||||
"const x = import('node:fs');",
|
||||
'const x:number = ;',
|
||||
]) {
|
||||
await expect(packageCandidateStrategy(metadata, source)).rejects.toThrow();
|
||||
}
|
||||
}, 30000);
|
||||
test('Docker client SIGKILL and stdin EOF independently trigger guardian cleanup during infinite callback', async () => {
|
||||
for (const disconnect of ['kill', 'stdin'] as const) {
|
||||
const f = await fixture(program('for(;;){}'));
|
||||
const c = await IsolatedCandidateController.start(f.request, f.name);
|
||||
const pending = runReplaySessionAsync(
|
||||
new NativeReplaySession(prepareReplayLoad(f.dataset, f.request.policy)),
|
||||
c
|
||||
);
|
||||
void pending.catch(() => undefined);
|
||||
await Bun.sleep(100);
|
||||
const child = Reflect.get(c, 'child') as ChildProcessWithoutNullStreams;
|
||||
const started = performance.now();
|
||||
if (disconnect === 'kill') {
|
||||
child.kill('SIGKILL');
|
||||
} else {
|
||||
child.stdin.destroy();
|
||||
}
|
||||
await expect(pending).rejects.toThrow();
|
||||
// Verify the independent guardian has removed the namespace BEFORE explicit cleanup.
|
||||
for (let i = 0; i < 80; i++) {
|
||||
const present = (
|
||||
await runFile('/usr/bin/docker', ['ps', '-a', '-q', '--filter', `name=^/${f.name}$`])
|
||||
).stdout.trim();
|
||||
if (!present) {
|
||||
break;
|
||||
}
|
||||
await Bun.sleep(25);
|
||||
}
|
||||
await absent(f.name);
|
||||
expect(performance.now() - started).toBeLessThan(5000);
|
||||
await c.dispose();
|
||||
}
|
||||
}, 20000);
|
||||
test('memory allocation failure cannot produce a successful result or leave the container running', async () => {
|
||||
const f = await fixture(
|
||||
program('const blocks=[];for(;;)blocks.push(new Uint8Array(16*1024*1024).fill(1));')
|
||||
);
|
||||
const c = await IsolatedCandidateController.start(f.request, f.name, Date.now() + 10000);
|
||||
try {
|
||||
await expect(
|
||||
runReplaySessionAsync(
|
||||
new NativeReplaySession(prepareReplayLoad(f.dataset, f.request.policy)),
|
||||
c
|
||||
)
|
||||
).rejects.toThrow();
|
||||
} finally {
|
||||
await c.dispose();
|
||||
}
|
||||
await absent(f.name);
|
||||
}, 20000);
|
||||
test('forged owner/decision identity on raw stdout is rejected before native admission', async () => {
|
||||
const attack = `const d={version:1,sessionId:c.portfolio.portfolio.sessionId,barrierId:c.barrier.barrier_id,revision:c.barrier.revision,decision:{ownerId:'forged',decisionId:JSON.stringify(['strategy','forged',c.strategyId,c.strategyVersion,0]),sequence:0},intent:{mode:'target',targets:[]}};const b=Buffer.from(JSON.stringify({version:1,type:'decisions',sequence:1,decisions:[d]}));const h=Buffer.alloc(4);h.writeUInt32BE(b.length);process.stdout.write(Buffer.concat([h,b]));for(;;){}`;
|
||||
const f = await fixture(program(attack));
|
||||
const c = await IsolatedCandidateController.start(f.request, f.name);
|
||||
try {
|
||||
await expect(
|
||||
runReplaySessionAsync(
|
||||
new NativeReplaySession(prepareReplayLoad(f.dataset, f.request.policy)),
|
||||
c
|
||||
)
|
||||
).rejects.toThrow('forged decision');
|
||||
} finally {
|
||||
await c.dispose();
|
||||
}
|
||||
await absent(f.name);
|
||||
}, 15000);
|
||||
test('changing a future suffix cannot alter the earlier published prefix or candidate decisions', async () => {
|
||||
const content = program(
|
||||
"const last=c.observations.at(-1);return {nextState:null,intent:{mode:'target',targets:last?[{instrumentId:'X0.US',quantity:Number(last.close)>2?'1':'0'}]:[]}}"
|
||||
);
|
||||
const first = await fixture(content);
|
||||
const changed = canonicalSmaFixture([first.request.strategy.selection.ownerId], {
|
||||
closes: [3, 2, 1, 4, 5, 90, 100],
|
||||
}).dataset;
|
||||
const cutoff = changed.bars[5]!.availableAt;
|
||||
const prefixes: unknown[][] = [];
|
||||
for (const dataset of [first.dataset, changed]) {
|
||||
const request = canonicalRunRequestSchema.parse({
|
||||
...first.request,
|
||||
datasetHash: dataset.manifest.hash,
|
||||
});
|
||||
const name = `stock-bot-candidate-${randomUUID()}`,
|
||||
c = await IsolatedCandidateController.start(request, name),
|
||||
seen: unknown[] = [];
|
||||
try {
|
||||
await runReplaySessionAsync(
|
||||
new NativeReplaySession(prepareReplayLoad(dataset, request.policy)),
|
||||
{
|
||||
async stage(context, observations) {
|
||||
const decisions = await c.stage(context, observations);
|
||||
if (context.barrier.at < cutoff) {
|
||||
seen.push({
|
||||
at: context.barrier.at,
|
||||
observations,
|
||||
intents: decisions.map(d => d.intent),
|
||||
});
|
||||
}
|
||||
return decisions;
|
||||
},
|
||||
committed: c.committed.bind(c),
|
||||
}
|
||||
);
|
||||
await c.finish();
|
||||
} finally {
|
||||
await c.dispose();
|
||||
}
|
||||
prefixes.push(seen);
|
||||
await absent(name);
|
||||
}
|
||||
const [original, changedPrefix] = prefixes;
|
||||
if (!original || !changedPrefix) {
|
||||
throw new Error('Missing prefix comparisons');
|
||||
}
|
||||
expect(original.length).toBeGreaterThan(1);
|
||||
expect(changedPrefix).toEqual(original);
|
||||
}, 20000);
|
||||
|
||||
test('killing the actual native worker or its parent leaves no isolated candidate descendant', async () => {
|
||||
for (const target of ['worker', 'parent'] as const) {
|
||||
const f = await fixture(program('for(;;){}'));
|
||||
f.request.build = await readCanonicalBuildIdentity();
|
||||
const input = {
|
||||
type: 'runRetainedStrategy',
|
||||
request: f.request,
|
||||
dataset: f.dataset,
|
||||
candidateContainerName: f.name,
|
||||
executionDeadlineAt: Date.now() + 30000,
|
||||
};
|
||||
const directory = await mkdtemp(join(tmpdir(), 'stock-bot-candidate-parent-'));
|
||||
const parentPath = join(directory, 'parent.mjs');
|
||||
// The candidate artifact remains inert JSON in this trusted supervisor fixture.
|
||||
await writeFile(
|
||||
parentPath,
|
||||
`import {fork} from 'node:child_process';const child=fork(${JSON.stringify(fileURLToPath(canonicalWorkerUrl))},[],{execPath:process.execPath,execArgv:[],serialization:'json',stdio:['ignore','ignore','pipe','ipc']});child.stderr?.resume();child.send(${JSON.stringify(input)});`
|
||||
);
|
||||
const child = fork(target === 'worker' ? fileURLToPath(canonicalWorkerUrl) : parentPath, [], {
|
||||
execPath: process.execPath,
|
||||
execArgv: [],
|
||||
serialization: 'json',
|
||||
stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
|
||||
});
|
||||
child.stderr?.resume();
|
||||
const closed = new Promise<void>(resolve => child.once('close', () => resolve()));
|
||||
if (target === 'worker') {
|
||||
child.send(input);
|
||||
}
|
||||
try {
|
||||
let running = false;
|
||||
for (let i = 0; i < 100; i++) {
|
||||
if (
|
||||
(
|
||||
await runFile('/usr/bin/docker', ['ps', '-q', '--filter', `name=^/${f.name}$`])
|
||||
).stdout.trim()
|
||||
) {
|
||||
running = true;
|
||||
break;
|
||||
}
|
||||
await Bun.sleep(25);
|
||||
}
|
||||
expect(running).toBeTrue();
|
||||
const started = performance.now();
|
||||
child.kill('SIGKILL');
|
||||
await closed;
|
||||
for (let i = 0; i < 100; i++) {
|
||||
if (
|
||||
!(
|
||||
await runFile('/usr/bin/docker', ['ps', '-a', '-q', '--filter', `name=^/${f.name}$`])
|
||||
).stdout.trim()
|
||||
) {
|
||||
break;
|
||||
}
|
||||
await Bun.sleep(25);
|
||||
}
|
||||
await absent(f.name);
|
||||
expect(performance.now() - started).toBeLessThan(6000);
|
||||
} finally {
|
||||
child.kill('SIGKILL');
|
||||
await closed;
|
||||
await removeCandidateContainer(f.name);
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
}, 20000);
|
||||
|
||||
test('cleanup still closes the client and removes private configuration when explicit removal fails', async () => {
|
||||
const f = await fixture(program());
|
||||
const c = await IsolatedCandidateController.start(f.request, f.name);
|
||||
const directory = Reflect.get(c, 'dockerConfig') as string;
|
||||
const child = Reflect.get(c, 'child') as ChildProcessWithoutNullStreams;
|
||||
// Fault injection at the exact-name validation seam; never disables the daemon or another container.
|
||||
Reflect.set(c, 'name', 'invalid-owned-container-name');
|
||||
await expect(c.dispose()).rejects.toThrow('Candidate cleanup failed');
|
||||
expect(child.exitCode !== null || child.signalCode !== null).toBeTrue();
|
||||
await expect(access(directory)).rejects.toThrow();
|
||||
for (let i = 0; i < 80; i++) {
|
||||
if (
|
||||
!(
|
||||
await runFile('/usr/bin/docker', ['ps', '-a', '-q', '--filter', `name=^/${f.name}$`])
|
||||
).stdout.trim()
|
||||
) {
|
||||
break;
|
||||
}
|
||||
await Bun.sleep(25);
|
||||
}
|
||||
await absent(f.name);
|
||||
}, 15000);
|
||||
test('missing installed descriptor and altered retained runtime fail closed before candidate launch', async () => {
|
||||
const f = await fixture(program());
|
||||
const altered = structuredClone(f.request);
|
||||
if (altered.strategy.origin !== 'candidate') {
|
||||
throw Error('candidate fixture');
|
||||
}
|
||||
altered.strategy.execution.imageId = `sha256:${'0'.repeat(64)}`;
|
||||
await expect(IsolatedCandidateController.start(altered, f.name)).rejects.toThrow(
|
||||
'not installed'
|
||||
);
|
||||
await absent(f.name);
|
||||
const hidden = candidateDescriptorPath + '.missing-test-' + randomUUID();
|
||||
await rename(candidateDescriptorPath, hidden);
|
||||
try {
|
||||
await expect(IsolatedCandidateController.start(f.request, f.name)).rejects.toThrow(
|
||||
'unavailable'
|
||||
);
|
||||
} finally {
|
||||
await rename(hidden, candidateDescriptorPath);
|
||||
}
|
||||
await absent(f.name);
|
||||
if (f.request.strategy.origin !== 'candidate') {
|
||||
throw new Error('Expected candidate fixture');
|
||||
}
|
||||
expect(await readCandidateExecution()).toEqual(f.request.strategy.execution);
|
||||
}, 15000);
|
||||
test('closing stdout while continuing an infinite callback fails promptly before the wall deadline', async () => {
|
||||
const f = await fixture(
|
||||
program(
|
||||
"const pipe=fs.readlinkSync('/proc/self/fd/1');for(const name of fs.readdirSync('/proc/self/fd')){try{if(fs.readlinkSync('/proc/self/fd/'+name)===pipe){libc.symbols.close(Number(name));}}catch{}}const remaining=fs.readdirSync('/proc/self/fd').filter(name=>{try{return fs.readlinkSync('/proc/self/fd/'+name)===pipe}catch{return false}});if(remaining.length)throw Error('stdout still open');process.stderr.write('candidate-test:stdout-eof-confirmed');for(;;){}",
|
||||
"const fs=await import('node:fs');const ffi=await import('bun:ffi');const libc=ffi.dlopen('/lib/x86_64-linux-gnu/libc.so.6',{close:{args:['i32'],returns:'i32'}});"
|
||||
)
|
||||
);
|
||||
const c = await IsolatedCandidateController.start(f.request, f.name, Date.now() + 5000);
|
||||
const started = performance.now();
|
||||
try {
|
||||
await expect(
|
||||
runReplaySessionAsync(
|
||||
new NativeReplaySession(prepareReplayLoad(f.dataset, f.request.policy)),
|
||||
c
|
||||
)
|
||||
).rejects.toThrow();
|
||||
} finally {
|
||||
await c.dispose();
|
||||
}
|
||||
expect((Reflect.get(c, 'stderr') as Buffer).toString()).toContain(
|
||||
'candidate-test:stdout-eof-confirmed'
|
||||
);
|
||||
expect(performance.now() - started).toBeLessThan(3000);
|
||||
await absent(f.name);
|
||||
}, 10000);
|
||||
});
|
||||
|
|
@ -296,6 +296,22 @@ async function ready(value = preview()) {
|
|||
await flush(() => reply(request('/api/v2/experiments/preview', 'POST'), { preview: value }));
|
||||
return value;
|
||||
}
|
||||
|
||||
test('same-event candidate toggle then Preview never captures the old builtin strategy', async () => {
|
||||
await list();
|
||||
await flush(() => change('Experiment name', 'Candidate draft'));
|
||||
const checkbox = [...host.querySelectorAll('input[type="checkbox"]')].find(input =>
|
||||
input.closest('label')?.textContent?.includes('Use an isolated candidate version')
|
||||
) as HTMLInputElement;
|
||||
expect(checkbox).toBeDefined();
|
||||
await flush(() => {
|
||||
checkbox.click();
|
||||
button('Preview experiment').click();
|
||||
});
|
||||
expect(requests.filter(item => item.path === '/api/v2/experiments/preview')).toHaveLength(0);
|
||||
expect(button('Preview experiment').disabled).toBe(true);
|
||||
expect(host.textContent).toContain('Select an immutable candidate');
|
||||
});
|
||||
async function showDetail(value?: ExperimentDetail) {
|
||||
const routes = createElement(
|
||||
router.Routes,
|
||||
|
|
|
|||
|
|
@ -1,9 +1,12 @@
|
|||
import { asFunction, createContainer as createDiContainer } from 'awilix';
|
||||
import { asFunction, asValue, createContainer as createDiContainer } from 'awilix';
|
||||
import { expect, test } from 'bun:test';
|
||||
import type { ServiceCradle } from '@stock-bot/di';
|
||||
import { ServiceContainerBuilder, type ServiceCradle } from '@stock-bot/di';
|
||||
import type { StockAppConfig } from '@stock-bot/stock-config';
|
||||
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
|
||||
import type { PaperConfigurationInput } from '../../apps/stock/orchestrator/src/contracts/paper-runtime';
|
||||
import { createContainer } from '../../apps/stock/orchestrator/src/simple-container';
|
||||
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
|
||||
import { logger } from '../fixtures/execution';
|
||||
import { paperFeedConfiguration } from '../fixtures/paper-feed';
|
||||
|
||||
test('canonical paper rejects invalid role/configuration before resolving services', async () => {
|
||||
|
|
@ -44,3 +47,83 @@ test('live defaults, research canonical configuration and missing custody fail b
|
|||
createContainer(config({ defaultMode: 'paper', canonicalPaper: paperFeedConfiguration() }))
|
||||
).rejects.toThrow('requires durable PostgreSQL');
|
||||
});
|
||||
|
||||
test('reviewed deployment host is explicit, exclusive, durable and never enabled for research', async () => {
|
||||
const container = createDiContainer<ServiceCradle>();
|
||||
let resolved = 0;
|
||||
container.register({
|
||||
serviceContainer: asFunction(() => {
|
||||
resolved++;
|
||||
throw new Error('Unexpected service resolution');
|
||||
}),
|
||||
});
|
||||
await expect(
|
||||
registerOrchestratorServices(container, {
|
||||
role: 'research-only',
|
||||
paperDeploymentHost: { enabled: true },
|
||||
})
|
||||
).rejects.toThrow('requires a paper composition');
|
||||
await expect(
|
||||
registerOrchestratorServices(container, {
|
||||
role: 'paper',
|
||||
canonicalPaper: paperFeedConfiguration(),
|
||||
paperDeploymentHost: { enabled: true },
|
||||
})
|
||||
).rejects.toThrow('never two account owners');
|
||||
await expect(
|
||||
registerOrchestratorServices(container, {
|
||||
role: 'paper',
|
||||
paperDeploymentHost: { enabled: true, deploymentId: 'not-a-uuid' },
|
||||
})
|
||||
).rejects.toThrow();
|
||||
await expect(
|
||||
registerOrchestratorServices(container, {
|
||||
role: 'paper',
|
||||
canonicalPaper: { ...paperFeedConfiguration(), version: 2 } as PaperConfigurationInput,
|
||||
})
|
||||
).rejects.toThrow('reviewed deployment host');
|
||||
expect(resolved).toBe(0);
|
||||
const config = {
|
||||
services: { orchestrator: { defaultMode: 'paper', paperDeploymentHost: { enabled: true } } },
|
||||
} as StockAppConfig;
|
||||
await expect(createContainer(config)).rejects.toThrow('requires durable PostgreSQL');
|
||||
});
|
||||
|
||||
test('explicit deployment host initializes unbound without account reads, writes or activation', async () => {
|
||||
const container = await new ServiceContainerBuilder()
|
||||
.withOptions({
|
||||
enableCache: false,
|
||||
enableQueue: false,
|
||||
enableMongoDB: false,
|
||||
enablePostgres: false,
|
||||
enableQuestDB: false,
|
||||
enableBrowser: false,
|
||||
enableProxy: false,
|
||||
})
|
||||
.build();
|
||||
let transactions = 0;
|
||||
const services: OrchestratorServices = {
|
||||
logger,
|
||||
postgres: {
|
||||
transaction() {
|
||||
transactions++;
|
||||
throw new Error('Unbound host must not access account state');
|
||||
},
|
||||
} as unknown as NonNullable<OrchestratorServices['postgres']>,
|
||||
};
|
||||
container.register({ serviceContainer: asValue(services) });
|
||||
try {
|
||||
await registerOrchestratorServices(container, {
|
||||
role: 'paper',
|
||||
paperDeploymentHost: { enabled: true },
|
||||
});
|
||||
expect(services.custom?.PaperDeploymentHost).toBeDefined();
|
||||
expect(services.custom?.CanonicalPaperRuntime).toBeUndefined();
|
||||
expect(() => services.custom!.PaperDeploymentHost!.runtime()).toThrow('not bound');
|
||||
expect(transactions).toBe(0);
|
||||
} finally {
|
||||
await services.custom?.PaperDeploymentHost?.shutdown();
|
||||
await services.custom?.BacktestRunner?.shutdown();
|
||||
await container.dispose();
|
||||
}
|
||||
});
|
||||
|
|
|
|||
226
test/integration/paper-deployments-api.test.ts
Normal file
226
test/integration/paper-deployments-api.test.ts
Normal file
|
|
@ -0,0 +1,226 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { createHttpSecurity } from '@stock-bot/di';
|
||||
import { createPaperRoutes } from '../../apps/stock/orchestrator/src/api/rest/paper';
|
||||
import { createPaperDeploymentHostRoutes } from '../../apps/stock/orchestrator/src/api/rest/paper-deployments';
|
||||
import {
|
||||
PaperDeploymentHost,
|
||||
unboundPaperReadiness,
|
||||
} from '../../apps/stock/orchestrator/src/paper/PaperDeploymentHost';
|
||||
import {
|
||||
createPaperDeploymentRoutes,
|
||||
forwardPaperCommand,
|
||||
} from '../../apps/stock/web-api/src/routes/paper-deployments.routes';
|
||||
import type { PaperDeploymentsService } from '../../apps/stock/web-api/src/services/paper-deployments.service';
|
||||
import { logger } from '../fixtures/execution';
|
||||
|
||||
const id = 'abcdefab-1234-4234-8234-123456789abc',
|
||||
admin = 'paper-admin-fixture-only-01234567890123456789',
|
||||
serviceToken = 'paper-service-fixture-only-01234567890123456789',
|
||||
origin = 'http://localhost:5173';
|
||||
const status = { deploymentId: id, boundDeploymentId: null, readiness: unboundPaperReadiness() };
|
||||
const security = (disabled = false) =>
|
||||
createHttpSecurity({
|
||||
adminToken: admin,
|
||||
serviceToken,
|
||||
environment: 'test',
|
||||
hostname: '127.0.0.1',
|
||||
origins: [origin],
|
||||
browserSessions: true,
|
||||
disabled,
|
||||
});
|
||||
const json = (token = admin, extra: Record<string, string> = {}) => ({
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', ...extra },
|
||||
body: '{}',
|
||||
});
|
||||
function fixture(disabled = false) {
|
||||
const events: string[] = [],
|
||||
host = {
|
||||
async bind(value: string) {
|
||||
events.push('bind:' + value);
|
||||
return status;
|
||||
},
|
||||
async activate(value: string) {
|
||||
events.push('activate:' + value);
|
||||
return status;
|
||||
},
|
||||
async halt(value: string) {
|
||||
events.push('halt:' + value);
|
||||
return status;
|
||||
},
|
||||
async status() {
|
||||
return status;
|
||||
},
|
||||
} as unknown as PaperDeploymentHost;
|
||||
const orchestrator = new Hono();
|
||||
security(disabled).mount(orchestrator);
|
||||
orchestrator.route('/api/paper/deployments', createPaperDeploymentHostRoutes(host, [origin]));
|
||||
orchestrator.route(
|
||||
'/api/paper',
|
||||
createPaperRoutes({ logger, custom: {} }, { origins: [origin] })
|
||||
);
|
||||
const api = new Hono();
|
||||
security(disabled).mount(api);
|
||||
const custody = {
|
||||
async authorizeCommand(value: string) {
|
||||
events.push('authorize:' + value);
|
||||
},
|
||||
async get() {
|
||||
return {};
|
||||
},
|
||||
async list() {
|
||||
return [];
|
||||
},
|
||||
} as unknown as PaperDeploymentsService;
|
||||
let forwarded: Request | undefined;
|
||||
let forwardedInit: RequestInit | undefined;
|
||||
const transport = async (url: string | URL | Request, init?: RequestInit) => {
|
||||
forwardedInit = init;
|
||||
forwarded = new Request(url, init);
|
||||
return orchestrator.fetch(forwarded);
|
||||
};
|
||||
api.route(
|
||||
'/',
|
||||
createPaperDeploymentRoutes(
|
||||
{ logger },
|
||||
{
|
||||
service: custody,
|
||||
origin: 'http://paper.internal',
|
||||
origins: [origin],
|
||||
request: transport as typeof fetch,
|
||||
}
|
||||
)
|
||||
);
|
||||
return {
|
||||
api,
|
||||
orchestrator,
|
||||
events,
|
||||
forwarded: () => forwarded,
|
||||
forwardedInit: () => forwardedInit,
|
||||
};
|
||||
}
|
||||
test('original human bearer is verified by both endpoints, normalizes IDs, and never substitutes service credentials', async () => {
|
||||
const f = fixture(),
|
||||
response = await f.api.request(`/api/v2/paper-deployments/${id.toUpperCase()}/bind`, json());
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get('cache-control')).toBe('no-store');
|
||||
expect(await response.json()).toEqual(status);
|
||||
expect(f.events).toEqual(['authorize:' + id, 'bind:' + id]);
|
||||
expect(f.forwarded()?.headers.get('authorization')).toBe('Bearer ' + admin);
|
||||
expect(f.forwardedInit()?.redirect).toBe('error');
|
||||
for (const token of [serviceToken, 'sb-research.' + id + '.untrusted']) {
|
||||
expect((await f.api.request(`/api/v2/paper-deployments/${id}/bind`, json(token))).status).toBe(
|
||||
403
|
||||
);
|
||||
expect(
|
||||
(await f.orchestrator.request(`/api/paper/deployments/${id}/bind`, json(token))).status
|
||||
).toBe(403);
|
||||
}
|
||||
expect(f.events).toHaveLength(2);
|
||||
});
|
||||
test('signed browser session keeps original Origin and is independently verified upstream', async () => {
|
||||
const f = fixture(),
|
||||
login = await f.api.request('/api/auth/session', {
|
||||
method: 'POST',
|
||||
headers: { Origin: origin, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token: admin }),
|
||||
});
|
||||
expect(login.status).toBe(200);
|
||||
const cookie = login.headers.get('set-cookie')?.split(';')[0];
|
||||
expect(cookie).toBeDefined();
|
||||
const response = await f.api.request(`/api/v2/paper-deployments/${id}/activate`, {
|
||||
method: 'POST',
|
||||
headers: { Cookie: cookie!, Origin: origin, 'Content-Type': 'application/json' },
|
||||
body: '{}',
|
||||
});
|
||||
expect(response.status).toBe(200);
|
||||
expect(f.forwarded()?.headers.get('cookie')).toBe(cookie!);
|
||||
expect(f.forwarded()?.headers.get('origin')).toBe(origin);
|
||||
expect(f.forwarded()?.headers.has('authorization')).toBe(false);
|
||||
for (const app of [f.api, f.orchestrator]) {
|
||||
const prefix = app === f.api ? '/api/v2/paper-deployments' : '/api/paper/deployments';
|
||||
expect(
|
||||
(
|
||||
await app.request(
|
||||
`${prefix}/${id}/bind`,
|
||||
json(admin, { Origin: 'https://untrusted.invalid' })
|
||||
)
|
||||
).status
|
||||
).toBe(403);
|
||||
}
|
||||
expect(f.events).toHaveLength(2);
|
||||
});
|
||||
test('auth-disabled development bypass cannot promote or activate through either endpoint or old direct activation', async () => {
|
||||
const f = fixture(true);
|
||||
expect((await f.api.request(`/api/v2/paper-deployments/${id}/bind`, json())).status).toBe(403);
|
||||
expect(
|
||||
(await f.orchestrator.request(`/api/paper/deployments/${id}/activate`, json())).status
|
||||
).toBe(403);
|
||||
expect((await f.orchestrator.request('/api/paper/activate', json())).status).toBe(403);
|
||||
expect(f.events).toEqual([]);
|
||||
});
|
||||
test('unconfigured fixed origin and mismatched upstream identity fail honestly without arbitrary routing', async () => {
|
||||
const request = new Request('http://web/api', { headers: { Authorization: 'Bearer ' + admin } });
|
||||
await expect(forwardPaperCommand(request, id, 'bind', {}, {})).rejects.toThrow('not configured');
|
||||
for (const origin of [
|
||||
'file:///tmp/private',
|
||||
'http://user:pass@paper',
|
||||
'http://paper/other',
|
||||
'http://paper?token=x',
|
||||
]) {
|
||||
await expect(forwardPaperCommand(request, id, 'bind', {}, { origin })).rejects.toThrow(
|
||||
'fixed HTTP origin'
|
||||
);
|
||||
}
|
||||
await expect(
|
||||
forwardPaperCommand(
|
||||
request,
|
||||
id,
|
||||
'bind',
|
||||
{},
|
||||
{
|
||||
origin: 'http://paper',
|
||||
request: async () =>
|
||||
Response.json({ ...status, deploymentId: '11111111-1111-4111-8111-111111111111' }),
|
||||
}
|
||||
)
|
||||
).rejects.toThrow('another deployment');
|
||||
});
|
||||
test('missing upstream origin policy rejects browser command even with valid operator token', async () => {
|
||||
const app = new Hono();
|
||||
security().mount(app);
|
||||
app.route('/api/paper/deployments', createPaperDeploymentHostRoutes(undefined, []));
|
||||
const response = await app.request(
|
||||
`/api/paper/deployments/${id}/bind`,
|
||||
json(admin, { Origin: origin })
|
||||
);
|
||||
expect(response.status).toBe(403);
|
||||
expect(await response.json()).toEqual({
|
||||
error: 'Paper commands require an explicitly configured trusted Origin',
|
||||
});
|
||||
});
|
||||
|
||||
test('unbound legacy readiness remains truthful and never creates an account or imports a program', async () => {
|
||||
let calls = 0;
|
||||
const unexpected = async () => {
|
||||
calls++;
|
||||
throw new Error('No persistence on unbound readiness');
|
||||
};
|
||||
const host = new PaperDeploymentHost({
|
||||
database: { transaction: unexpected },
|
||||
repository: { initialize: unexpected, transact: unexpected },
|
||||
});
|
||||
const app = new Hono();
|
||||
security().mount(app);
|
||||
app.route(
|
||||
'/api/paper',
|
||||
createPaperRoutes({ logger, custom: {} }, { deploymentHost: host, origins: [origin] })
|
||||
);
|
||||
const response = await app.request('/api/paper/readiness', {
|
||||
headers: { Authorization: `Bearer ${admin}` },
|
||||
});
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toEqual(unboundPaperReadiness());
|
||||
expect(calls).toBe(0);
|
||||
});
|
||||
448
test/integration/paper-deployments-ui.test.tsx
Normal file
448
test/integration/paper-deployments-ui.test.tsx
Normal file
|
|
@ -0,0 +1,448 @@
|
|||
import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from 'bun:test';
|
||||
import { GlobalWindow } from 'happy-dom';
|
||||
import { act, createElement } from 'react';
|
||||
import type { Root } from 'react-dom/client';
|
||||
import {
|
||||
paperPromotionPreviewSchema,
|
||||
type PaperDeployment,
|
||||
type PaperPromotionInput,
|
||||
} from '@stock-bot/stock-config/paper-deployments';
|
||||
import { paperConfig } from '../fixtures/paper-runtime';
|
||||
|
||||
const browser = new GlobalWindow({ url: 'http://localhost:5173' }),
|
||||
names = ['window', 'document', 'IS_REACT_ACT_ENVIRONMENT'] as const,
|
||||
old = names.map(name => [name, Object.getOwnPropertyDescriptor(globalThis, name)] as const);
|
||||
let createRoot: typeof import('react-dom/client').createRoot,
|
||||
router: typeof import('react-router-dom'),
|
||||
Page: typeof import('../../apps/stock/web-app/src/features/paper/PaperDeploymentsPage').PaperDeploymentsPage,
|
||||
Detail: typeof import('../../apps/stock/web-app/src/features/paper/PaperDeploymentPage').PaperDeploymentPage,
|
||||
api: typeof import('../../apps/stock/web-app/src/features/paper/paperApi').paperApi,
|
||||
ApiError: typeof import('../../apps/stock/web-app/src/features/paper/paperApi').PaperApiError,
|
||||
validationApi: typeof import('../../apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi').chronologicalValidationDurableApi,
|
||||
experimentApi: typeof import('../../apps/stock/web-app/src/features/experiments/services/experimentApi').experimentApi;
|
||||
let root: Root | undefined, host: HTMLDivElement;
|
||||
const restore: Array<() => void> = [];
|
||||
const id = '11111111-1111-4111-8111-111111111111',
|
||||
testId = '22222222-2222-4222-8222-222222222222',
|
||||
costId = '33333333-3333-4333-8333-333333333333',
|
||||
hash = 'a'.repeat(64);
|
||||
const configuration = paperConfig();
|
||||
const transport = {
|
||||
accountId: 'new-paper',
|
||||
sessionId: 'new-session',
|
||||
quoteSeriesId: 'X:quote',
|
||||
riskSession: configuration.matching.risk.ledger.riskSession,
|
||||
policy: configuration.policy,
|
||||
};
|
||||
function preview(input: PaperPromotionInput) {
|
||||
return paperPromotionPreviewSchema.parse({
|
||||
version: 'paper-promotion-preview/v1',
|
||||
previewHash: hash,
|
||||
input,
|
||||
strategy: {
|
||||
familyId: id,
|
||||
versionId: id,
|
||||
reviewId: id,
|
||||
origin: 'candidate',
|
||||
artifactSha256: hash,
|
||||
dependencyLockSha256: hash,
|
||||
},
|
||||
configuration: { ...configuration, version: 2 },
|
||||
host: {
|
||||
version: 'paper-host/v1',
|
||||
hostSha256: hash,
|
||||
engineWrapperSha256: hash,
|
||||
engineBinarySha256: hash,
|
||||
dependencyLockSha256: hash,
|
||||
runtime: 'bun',
|
||||
runtimeVersion: 'test',
|
||||
platform: 'linux',
|
||||
arch: 'x64',
|
||||
},
|
||||
evidence: {
|
||||
test: {
|
||||
runId: testId,
|
||||
datasetHash: hash,
|
||||
economicHash: hash,
|
||||
resultHash: hash,
|
||||
metrics: { totalReturn: null },
|
||||
fillCount: 0,
|
||||
limitations: [],
|
||||
},
|
||||
costs: [
|
||||
{
|
||||
runId: costId,
|
||||
datasetHash: hash,
|
||||
economicHash: hash,
|
||||
resultHash: hash,
|
||||
metrics: { totalReturn: 0 },
|
||||
fillCount: 0,
|
||||
limitations: [],
|
||||
},
|
||||
{
|
||||
runId: id,
|
||||
datasetHash: hash,
|
||||
economicHash: hash,
|
||||
resultHash: hash,
|
||||
metrics: { totalReturn: -0.1 },
|
||||
fillCount: 1,
|
||||
limitations: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
limitations: ['Trusted code requires human review.'],
|
||||
});
|
||||
}
|
||||
function patch<T extends object, K extends keyof T>(object: T, key: K, value: T[K]) {
|
||||
const previous = object[key];
|
||||
object[key] = value;
|
||||
restore.push(() => {
|
||||
object[key] = previous;
|
||||
});
|
||||
}
|
||||
async function flush(fn: () => void = () => {}) {
|
||||
await act(async () => {
|
||||
fn();
|
||||
await Promise.resolve();
|
||||
});
|
||||
}
|
||||
function button(text: string) {
|
||||
const value = [...host.querySelectorAll('button')].find(e => e.textContent?.trim() === text);
|
||||
if (!value) {
|
||||
throw new Error('Missing button ' + text);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function fieldEvent(label: string, value: string) {
|
||||
const element = host.querySelector(`[aria-label="${label}"]`)!;
|
||||
const prototype =
|
||||
element.tagName === 'TEXTAREA'
|
||||
? browser.HTMLTextAreaElement.prototype
|
||||
: browser.HTMLInputElement.prototype;
|
||||
Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(element, value);
|
||||
element.dispatchEvent(new browser.Event('input', { bubbles: true }) as unknown as Event);
|
||||
}
|
||||
async function fill(label: string, value: string) {
|
||||
await flush(() => fieldEvent(label, value));
|
||||
}
|
||||
function LocationProbe() {
|
||||
return createElement('output', { 'aria-label': 'Route' }, router.useLocation().pathname);
|
||||
}
|
||||
async function mount() {
|
||||
root = createRoot(host);
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
createElement(
|
||||
router.MemoryRouter,
|
||||
{ initialEntries: ['/paper'] },
|
||||
createElement(Page),
|
||||
createElement(LocationProbe)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
beforeAll(async () => {
|
||||
Object.defineProperty(globalThis, 'window', { value: browser, configurable: true });
|
||||
Object.defineProperty(globalThis, 'document', { value: browser.document, configurable: true });
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||
value: true,
|
||||
configurable: true,
|
||||
});
|
||||
createRoot = (await import('react-dom/client')).createRoot;
|
||||
router = await import('react-router-dom');
|
||||
({ PaperDeploymentsPage: Page } = await import(
|
||||
'../../apps/stock/web-app/src/features/paper/PaperDeploymentsPage'
|
||||
));
|
||||
({ PaperDeploymentPage: Detail } = await import(
|
||||
'../../apps/stock/web-app/src/features/paper/PaperDeploymentPage'
|
||||
));
|
||||
({ paperApi: api, PaperApiError: ApiError } = await import(
|
||||
'../../apps/stock/web-app/src/features/paper/paperApi'
|
||||
));
|
||||
validationApi = (
|
||||
await import(
|
||||
'../../apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi'
|
||||
)
|
||||
).chronologicalValidationDurableApi;
|
||||
experimentApi = (
|
||||
await import('../../apps/stock/web-app/src/features/experiments/services/experimentApi')
|
||||
).experimentApi;
|
||||
});
|
||||
beforeEach(() => {
|
||||
host = browser.document.createElement('div') as unknown as HTMLDivElement;
|
||||
browser.document.body.appendChild(host as never);
|
||||
patch(api, 'list', async () => ({ deployments: [] }));
|
||||
});
|
||||
afterEach(async () => {
|
||||
await flush(() => root?.unmount());
|
||||
root = undefined;
|
||||
host.remove();
|
||||
for (const reset of restore.splice(0).reverse()) {
|
||||
reset();
|
||||
}
|
||||
});
|
||||
afterAll(() => {
|
||||
for (const [name, value] of old) {
|
||||
if (value) {
|
||||
Object.defineProperty(globalThis, name, value);
|
||||
} else {
|
||||
delete (globalThis as Record<string, unknown>)[name];
|
||||
}
|
||||
}
|
||||
browser.happyDOM.cancelAsync();
|
||||
});
|
||||
async function review() {
|
||||
patch(
|
||||
validationApi,
|
||||
'get',
|
||||
async () =>
|
||||
({
|
||||
id,
|
||||
report: { id, reportHash: hash, previewHash: hash, test: { runId: testId } },
|
||||
}) as never
|
||||
);
|
||||
patch(
|
||||
experimentApi,
|
||||
'get',
|
||||
async () =>
|
||||
({
|
||||
id: costId,
|
||||
previewHash: hash,
|
||||
preview: {
|
||||
version: 'cost-sensitivity-preview/v1',
|
||||
candidates: [{ costs: { feeRate: '0', slippageRate: '0' } }],
|
||||
},
|
||||
trials: [{ runId: costId, status: 'completed' }],
|
||||
}) as never
|
||||
);
|
||||
patch(api, 'preview', async input => preview(input));
|
||||
await fill('Deployment name', 'Reviewed candidate');
|
||||
await fill('Report owner ID', id);
|
||||
await fill('Cost experiment ID', costId);
|
||||
await flush(() => button('Load evidence').click());
|
||||
await fill('Paper transport', JSON.stringify(transport));
|
||||
await fill('Review rationale', 'I reviewed exact evidence and strategy');
|
||||
await flush(() =>
|
||||
(host.querySelector('[aria-label="Authorize trusted paper code"]') as HTMLInputElement).click()
|
||||
);
|
||||
await flush(() => button('Preview promotion').click());
|
||||
}
|
||||
test('empty/loading/error states and explicit human review precede promotion; cost data never implies approval', async () => {
|
||||
await mount();
|
||||
expect(host.textContent).toContain('No paper deployments yet');
|
||||
expect(host.textContent).toContain('Live trading is unavailable');
|
||||
await flush(() => button('Preview promotion').click());
|
||||
expect(host.textContent).toContain('Load sealed test');
|
||||
await review();
|
||||
expect(host.textContent).toContain('candidate');
|
||||
expect(host.textContent).toContain('Test return: Unavailable');
|
||||
expect(host.textContent).toContain('Trusted code requires human review.');
|
||||
expect(button('Create halted deployment').disabled).toBe(false);
|
||||
await fill('Review rationale', 'Changed review');
|
||||
expect(host.textContent).not.toContain('Exact promotion preview');
|
||||
});
|
||||
test('uncertain create freezes the exact preview and retries the same idempotency key', async () => {
|
||||
const requests: Array<{ input: PaperPromotionInput; previewHash: string; key: string }> = [];
|
||||
patch(api, 'create', async (input, previewHash, key) => {
|
||||
requests.push({ input, previewHash, key });
|
||||
throw new ApiError('Response lost', null);
|
||||
});
|
||||
await mount();
|
||||
await review();
|
||||
await flush(() => button('Create halted deployment').click());
|
||||
expect(host.textContent).toContain('draft is frozen');
|
||||
expect((host.querySelector('fieldset') as HTMLFieldSetElement).disabled).toBe(true);
|
||||
await flush(() => button('Retry same promotion receipt').click());
|
||||
expect(requests).toHaveLength(2);
|
||||
expect(requests[1]!).toEqual(requests[0]!);
|
||||
});
|
||||
test('same-event withdrawal of trusted-code authorization cannot preview or submit the previous consent', async () => {
|
||||
await mount();
|
||||
await review();
|
||||
const previews: PaperPromotionInput[] = [],
|
||||
creates: PaperPromotionInput[] = [];
|
||||
patch(api, 'preview', async input => {
|
||||
previews.push(input);
|
||||
return preview(input);
|
||||
});
|
||||
patch(api, 'create', async input => {
|
||||
creates.push(input);
|
||||
throw new ApiError('Unexpected create', 422);
|
||||
});
|
||||
const oldCreate = button('Create halted deployment');
|
||||
await flush(() => {
|
||||
(host.querySelector('[aria-label="Authorize trusted paper code"]') as HTMLInputElement).click();
|
||||
button('Preview promotion').click();
|
||||
oldCreate.click();
|
||||
});
|
||||
expect(previews).toHaveLength(0);
|
||||
expect(creates).toHaveLength(0);
|
||||
expect(host.textContent).not.toContain('Exact promotion preview');
|
||||
expect(
|
||||
(host.querySelector('[aria-label="Authorize trusted paper code"]') as HTMLInputElement).checked
|
||||
).toBe(false);
|
||||
await flush(() =>
|
||||
(host.querySelector('[aria-label="Authorize trusted paper code"]') as HTMLInputElement).click()
|
||||
);
|
||||
await fill('Deployment name', 'Current draft');
|
||||
await flush(() => button('Preview promotion').click());
|
||||
expect(previews).toHaveLength(1);
|
||||
expect(previews[0]?.name).toBe('Current draft');
|
||||
});
|
||||
test('same-event edits cannot discard an inflight receipt or mutate an uncertain promotion draft', async () => {
|
||||
const requests: Array<{ input: PaperPromotionInput; previewHash: string; key: string }> = [];
|
||||
let rejectCreate: (cause: Error) => void = () => {
|
||||
throw new Error('Create not started');
|
||||
};
|
||||
const pendingCreate = new Promise<PaperDeployment>((_resolve, reject) => {
|
||||
rejectCreate = reject;
|
||||
});
|
||||
patch(api, 'create', async (input, previewHash, key) => {
|
||||
requests.push({ input, previewHash, key });
|
||||
if (requests.length === 1) {
|
||||
return pendingCreate;
|
||||
}
|
||||
throw new ApiError('Response still uncertain', null);
|
||||
});
|
||||
await mount();
|
||||
await review();
|
||||
await flush(() => {
|
||||
button('Create halted deployment').click();
|
||||
fieldEvent('Deployment name', 'Must not replace the submitted name');
|
||||
});
|
||||
expect(requests).toHaveLength(1);
|
||||
expect((host.querySelector('[aria-label="Deployment name"]') as HTMLInputElement).value).toBe(
|
||||
'Reviewed candidate'
|
||||
);
|
||||
await flush(() => rejectCreate(new ApiError('Response lost', null)));
|
||||
expect(host.textContent).toContain('draft is frozen');
|
||||
await flush(() => {
|
||||
fieldEvent('Review rationale', 'Must not replace the frozen rationale');
|
||||
button('Retry same promotion receipt').click();
|
||||
});
|
||||
expect(requests).toHaveLength(2);
|
||||
expect(requests.slice(1)).toEqual(requests.slice(0, 1));
|
||||
expect(requests[1]?.input.name).toBe('Reviewed candidate');
|
||||
expect(requests[1]?.input.reason).toBe('I reviewed exact evidence and strategy');
|
||||
});
|
||||
test('owned links confirm discarding pending or uncertain receipts and refusal preserves the exact retry', async () => {
|
||||
patch(api, 'list', async () => ({ deployments: [savedDeployment()] }));
|
||||
const requests: Array<{ input: PaperPromotionInput; previewHash: string; key: string }> = [];
|
||||
let rejectCreate: (cause: Error) => void = () => {
|
||||
throw new Error('Create not started');
|
||||
};
|
||||
const pendingCreate = new Promise<PaperDeployment>((_resolve, reject) => {
|
||||
rejectCreate = reject;
|
||||
});
|
||||
patch(api, 'create', async (input, previewHash, key) => {
|
||||
requests.push({ input, previewHash, key });
|
||||
if (requests.length === 1) {
|
||||
return pendingCreate;
|
||||
}
|
||||
throw new ApiError('Response lost', null);
|
||||
});
|
||||
let confirmations = 0;
|
||||
patch(browser as unknown as Window, 'confirm', () => {
|
||||
confirmations++;
|
||||
return false;
|
||||
});
|
||||
await mount();
|
||||
await review();
|
||||
const link = (href: string) => {
|
||||
const element = host.querySelector(`a[href="${href}"]`) as HTMLAnchorElement | null;
|
||||
if (!element) {
|
||||
throw new Error('Missing link');
|
||||
}
|
||||
return element;
|
||||
};
|
||||
await flush(() => {
|
||||
button('Create halted deployment').click();
|
||||
link('/experiments').click();
|
||||
});
|
||||
expect(confirmations).toBe(1);
|
||||
expect(host.querySelector('[aria-label="Route"]')?.textContent).toBe('/paper');
|
||||
await flush(() => rejectCreate(new ApiError('Response lost', null)));
|
||||
await flush(() => link(`/paper/${id}`).click());
|
||||
expect(confirmations).toBe(2);
|
||||
expect(host.querySelector('[aria-label="Route"]')?.textContent).toBe('/paper');
|
||||
await flush(() => {
|
||||
link('/experiments').dispatchEvent(
|
||||
new browser.MouseEvent('click', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
ctrlKey: true,
|
||||
}) as unknown as MouseEvent
|
||||
);
|
||||
link(`/paper/${id}`).dispatchEvent(
|
||||
new browser.MouseEvent('click', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
button: 1,
|
||||
}) as unknown as MouseEvent
|
||||
);
|
||||
});
|
||||
expect(confirmations).toBe(2);
|
||||
expect(host.querySelector('[aria-label="Route"]')?.textContent).toBe('/paper');
|
||||
await flush(() => button('Retry same promotion receipt').click());
|
||||
expect(requests).toHaveLength(2);
|
||||
expect(requests.slice(1)).toEqual(requests.slice(0, 1));
|
||||
});
|
||||
function savedDeployment(): PaperDeployment {
|
||||
const input: PaperPromotionInput = {
|
||||
name: 'History',
|
||||
outOfSample: {
|
||||
kind: 'chronological-report/v1',
|
||||
validationId: id,
|
||||
reportId: id,
|
||||
reportHash: hash,
|
||||
previewHash: hash,
|
||||
},
|
||||
testRunId: testId,
|
||||
costExperimentId: costId,
|
||||
costPreviewHash: hash,
|
||||
costRunId: costId,
|
||||
transport,
|
||||
reason: 'Reviewed',
|
||||
acknowledgeTrustedCode: true,
|
||||
};
|
||||
return {
|
||||
id,
|
||||
version: 'paper-deployment/v1',
|
||||
principal: 'operator',
|
||||
createdAt: '2026-10-24T12:00:00.000Z',
|
||||
promotionHash: hash,
|
||||
preview: preview(input),
|
||||
};
|
||||
}
|
||||
test('historical deployment remains visible when host is unavailable; activation stays disabled and halt can still be requested', async () => {
|
||||
const deployment = savedDeployment();
|
||||
patch(api, 'get', async () => deployment);
|
||||
patch(api, 'status', async () => {
|
||||
throw new ApiError('Host disabled', 503);
|
||||
});
|
||||
root = createRoot(host);
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
createElement(
|
||||
router.MemoryRouter,
|
||||
{ initialEntries: [`/paper/${id}`] },
|
||||
createElement(
|
||||
router.Routes,
|
||||
{},
|
||||
createElement(router.Route, {
|
||||
path: '/paper/:deploymentId',
|
||||
element: createElement(Detail),
|
||||
})
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
await flush();
|
||||
expect(host.textContent).toContain('Host disabled');
|
||||
expect(host.textContent).toContain('History');
|
||||
expect(host.textContent).toContain('Activation is unavailable');
|
||||
expect([...host.querySelectorAll('button')].some(b => b.textContent === 'Activate paper')).toBe(
|
||||
false
|
||||
);
|
||||
expect(button('Halt paper').disabled).toBe(false);
|
||||
});
|
||||
66
test/integration/paper-native-identity.test.ts
Normal file
66
test/integration/paper-native-identity.test.ts
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { copyFile, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { expect, test } from 'bun:test';
|
||||
import { loadedNativeIdentity } from '@stock-bot/engine';
|
||||
import { readPaperHostIdentity } from '../../apps/stock/orchestrator/src/paper/paper-host-identity';
|
||||
|
||||
test('paper identity names the actual bundle and loaded immutable native bytes, not the research worker', async () => {
|
||||
const identity = await readPaperHostIdentity();
|
||||
expect(identity.version).toBe('paper-host/v1');
|
||||
expect(Object.isFrozen(loadedNativeIdentity)).toBe(true);
|
||||
expect(loadedNativeIdentity.engineWrapperSha256).toBe(identity.engineWrapperSha256);
|
||||
expect(loadedNativeIdentity.engineBinarySha256).toBe(identity.engineBinarySha256);
|
||||
const hash = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex');
|
||||
expect(identity.hostSha256).toBe(
|
||||
hash(
|
||||
await readFile(new URL('../../apps/stock/orchestrator/dist/paper-host.js', import.meta.url))
|
||||
)
|
||||
);
|
||||
expect(identity.hostSha256).not.toBe(
|
||||
hash(
|
||||
await readFile(
|
||||
new URL('../../apps/stock/orchestrator/dist/native-worker.js', import.meta.url)
|
||||
)
|
||||
)
|
||||
);
|
||||
});
|
||||
test('cached loaded identity remains the original bytes after a temporary wrapper file changes; artifacts require restart', async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), 'stock-bot-native-identity-'));
|
||||
try {
|
||||
await mkdir(join(directory, 'dist'));
|
||||
await copyFile(
|
||||
new URL('../../apps/stock/engine/index.mjs', import.meta.url),
|
||||
join(directory, 'index.mjs')
|
||||
);
|
||||
await copyFile(
|
||||
new URL('../../apps/stock/engine/dist/engine.node', import.meta.url),
|
||||
join(directory, 'dist/engine.node')
|
||||
);
|
||||
await writeFile(
|
||||
join(directory, 'check.mjs'),
|
||||
`import { readFileSync, appendFileSync } from 'node:fs';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { loadedNativeIdentity as before } from './index.mjs';
|
||||
const path = new URL('./index.mjs', import.meta.url);
|
||||
appendFileSync(path, '\\n// temporary post-load change\\n');
|
||||
const { loadedNativeIdentity: after } = await import('./index.mjs');
|
||||
const current = createHash('sha256').update(readFileSync(path)).digest('hex');
|
||||
console.log(JSON.stringify({same:before===after,frozen:Object.isFrozen(after),loaded:after.engineWrapperSha256,current}));`
|
||||
);
|
||||
const child = Bun.spawn([process.execPath, join(directory, 'check.mjs')], {
|
||||
stdout: 'pipe',
|
||||
stderr: 'pipe',
|
||||
});
|
||||
const output = await new Response(child.stdout).text(),
|
||||
error = await new Response(child.stderr).text();
|
||||
expect(await child.exited, error).toBe(0);
|
||||
const value = JSON.parse(output);
|
||||
expect(value.same).toBe(true);
|
||||
expect(value.frozen).toBe(true);
|
||||
expect(value.loaded).not.toBe(value.current);
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
|
@ -343,3 +343,32 @@ test('per-agent budget request order fences older success and failure responses'
|
|||
expect(host.textContent).toContain('Active trials: 1; available slots: 0');
|
||||
expect(host.textContent).not.toContain('Obsolete unavailable response');
|
||||
});
|
||||
|
||||
test('owned candidate permission is explicit per template and visible on saved grants', async () => {
|
||||
await mount();
|
||||
await draft();
|
||||
await fill('Allow own candidates on backtest IDs', backtestId);
|
||||
await flush(() => button('Create credential').click());
|
||||
const request = pending('', 'POST');
|
||||
expect(request.body).toMatchObject({ allowOwnCandidateBacktestIds: [backtestId] });
|
||||
await flush(() =>
|
||||
reply(
|
||||
request,
|
||||
{
|
||||
agent: record({
|
||||
grants: [{ backtestId, policyHash: 'a'.repeat(64), allowOwnCandidates: true }],
|
||||
}),
|
||||
token: 'fixture-only-token',
|
||||
},
|
||||
201
|
||||
)
|
||||
);
|
||||
expect(host.textContent).toContain('Owned isolated candidates allowed');
|
||||
expect(
|
||||
(
|
||||
host.querySelector(
|
||||
'[aria-label="Allow own candidates on backtest IDs"]'
|
||||
) as HTMLTextAreaElement
|
||||
).value
|
||||
).toBe('');
|
||||
});
|
||||
|
|
|
|||
460
test/postgres/ai-research-workflow.test.ts
Normal file
460
test/postgres/ai-research-workflow.test.ts
Normal file
|
|
@ -0,0 +1,460 @@
|
|||
/** Real authenticated APIs + disposable PostgreSQL + isolated candidate/Rust execution. No finance mocks. */
|
||||
import { createHash, 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 { StrategyVersionPackage } from '@stock-bot/types';
|
||||
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 { createResearchAgentRoutes } from '../../apps/stock/web-api/src/routes/research-agents.routes';
|
||||
import { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes';
|
||||
import { createStrategyRoutes } from '../../apps/stock/web-api/src/routes/strategies.routes';
|
||||
import { ResearchAgentsService } from '../../apps/stock/web-api/src/services/research-agents.service';
|
||||
import { ResearchService } from '../../apps/stock/web-api/src/services/research.service';
|
||||
import {
|
||||
runResearchCycle,
|
||||
type ResearchCycleEvent,
|
||||
type ResearchCyclePlan,
|
||||
} from '../../scripts/examples/research-cycle';
|
||||
import { retainResearchDataset } from '../../scripts/import-research-dataset';
|
||||
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
|
||||
import { ResearchClient } from '../../scripts/research-client';
|
||||
import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';
|
||||
import { canonicalRegimeSelection } from '../fixtures/canonical-regime-research';
|
||||
import { walkForwardDataset } from '../fixtures/walk-forward';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('ai-research-workflow');
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const cleanups: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanups.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
let packages: ReturnType<typeof packageBuiltinStrategies> | undefined;
|
||||
async function fixture() {
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Disposable safety database required');
|
||||
}
|
||||
const schema = `stock_bot_safety_ai_cycle_${randomUUID().replaceAll('-', '')}`;
|
||||
const admin = new Pool({ connectionString: url });
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
const pool = new Pool({
|
||||
connectionString: url,
|
||||
max: 4,
|
||||
options: `-c search_path=${schema} -c statement_timeout=10000`,
|
||||
});
|
||||
cleanups.push(async () => {
|
||||
await pool.end();
|
||||
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
||||
await admin.end();
|
||||
});
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
const base = await canonicalAdmissionFixture(pool, postgres);
|
||||
for (const name of [
|
||||
'20-research-workspace.sql',
|
||||
'27-research-evidence-sources.sql',
|
||||
'28-research-agents.sql',
|
||||
'29-isolated-candidates.sql',
|
||||
'31-research-agent-project-links.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
);
|
||||
}
|
||||
const dataset = walkForwardDataset();
|
||||
await retainResearchDataset(pool, dataset.dataset);
|
||||
const draft = await base.api.createBacktest(
|
||||
{
|
||||
...base.definition,
|
||||
name: 'AI workflow granted source',
|
||||
startDate: new Date(dataset.dataset.manifest.bounds.tradeStart).toISOString(),
|
||||
endDate: new Date(dataset.dataset.manifest.bounds.tradeEnd).toISOString(),
|
||||
config: { ...base.definition.config, datasetHash: dataset.dataset.manifest.hash },
|
||||
},
|
||||
{ autoStart: false }
|
||||
);
|
||||
const container = { postgres, logger };
|
||||
const agents = new ResearchAgentsService(container),
|
||||
research = new ResearchService(container);
|
||||
const project = await research.createProject({ title: 'AI research acceptance' }, 'operator');
|
||||
const provisioned = await agents.create({
|
||||
name: 'Workflow researcher',
|
||||
allowedProjectIds: [project.id],
|
||||
allowedBacktestIds: [draft.id],
|
||||
allowOwnCandidateBacktestIds: [draft.id],
|
||||
limits: {
|
||||
maxActiveTrials: 4,
|
||||
maxTrialsPerExperiment: 4,
|
||||
maxBarEvaluationsPerExperiment: 10000,
|
||||
maxAttemptWallMs: 60000,
|
||||
maxAttempts: 1,
|
||||
},
|
||||
});
|
||||
const app = new Hono();
|
||||
const security = createHttpSecurity({
|
||||
adminToken: 'operator-test-secret-12345678901234567890',
|
||||
serviceToken: 'service-test-secret-123456789012345678901',
|
||||
environment: 'test',
|
||||
resolveResearchCredential: request => agents.authenticate(request),
|
||||
});
|
||||
security.mount(app);
|
||||
app.route('/', createResearchAgentRoutes(container, security.researchEnabled));
|
||||
app.route('/', createStrategyRoutes(container));
|
||||
app.route('/', createResearchRoutes(container));
|
||||
app.route('/', createExperimentRoutes(container));
|
||||
const engine = new RustBacktestAdapter({
|
||||
logger,
|
||||
storage: {
|
||||
async getHistoricalBars() {
|
||||
throw new Error('Research must use the frozen dataset');
|
||||
},
|
||||
},
|
||||
});
|
||||
const runner = new BacktestRunner({
|
||||
engine,
|
||||
engineName: 'native',
|
||||
repository: new PostgresBacktestRunRepository(postgres),
|
||||
logger,
|
||||
});
|
||||
const executionErrors: unknown[] = [];
|
||||
let pending = Promise.resolve();
|
||||
// A small test worker drives the existing durable runner. It changes no engine/fill behavior.
|
||||
const drain = () => {
|
||||
pending = pending.then(async () => {
|
||||
for (const row of (
|
||||
await pool.query<{ id: string }>(
|
||||
"SELECT id FROM runs WHERE status='pending' ORDER BY created_at,id"
|
||||
)
|
||||
).rows) {
|
||||
try {
|
||||
await runner.runQueued(row.id);
|
||||
} catch (error) {
|
||||
executionErrors.push(error);
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
cleanups.push(async () => {
|
||||
await pending;
|
||||
await runner.shutdown();
|
||||
await engine.shutdown();
|
||||
});
|
||||
const requests: {
|
||||
path: string;
|
||||
method: string;
|
||||
key: string | null;
|
||||
body: unknown;
|
||||
status: number;
|
||||
}[] = [];
|
||||
const transport: typeof fetch = (async (input: string | URL | Request, init?: RequestInit) => {
|
||||
const request = new Request(input, init);
|
||||
const body: unknown = request.body === null ? undefined : await request.clone().json();
|
||||
const response = await app.fetch(request);
|
||||
requests.push({
|
||||
path: new URL(request.url).pathname,
|
||||
method: request.method,
|
||||
key: request.headers.get('Idempotency-Key'),
|
||||
body,
|
||||
status: response.status,
|
||||
});
|
||||
if (response.status === 202) {
|
||||
drain();
|
||||
}
|
||||
return response;
|
||||
}) as typeof fetch;
|
||||
const client = new ResearchClient({
|
||||
origin: 'http://127.0.0.1:2003',
|
||||
token: provisioned.token,
|
||||
fetch: transport,
|
||||
});
|
||||
const prepared = await (packages ??= packageBuiltinStrategies());
|
||||
function candidate(index: number): StrategyVersionPackage {
|
||||
const pkg = prepared[index];
|
||||
if (!pkg) {
|
||||
throw new Error('Missing prepared fixture');
|
||||
}
|
||||
return { ...structuredClone(pkg), execution: { kind: 'isolated-candidate/v1', warmupBars: 3 } };
|
||||
}
|
||||
function suggestions(): ResearchCyclePlan {
|
||||
const trend = candidate(0),
|
||||
regime = candidate(1),
|
||||
failure = candidate(0);
|
||||
failure.artifact.content += '\nthrow new Error("Deliberate research candidate failure");\n';
|
||||
failure.artifact.sha256 = createHash('sha256').update(failure.artifact.content).digest('hex');
|
||||
const common = {
|
||||
recipe: dataset.windows[0]!,
|
||||
costScenarios: [{ feeRate: '0.02', slippageRate: '0.01' }],
|
||||
};
|
||||
// Deterministic fake-model suggestions; bundles are inert input until the real isolated worker.
|
||||
return {
|
||||
cycleId: 'acceptance-cycle',
|
||||
projectId: project.id,
|
||||
backtestId: draft.id,
|
||||
maxTotalTrials: 16,
|
||||
hypothesis: {
|
||||
title: 'Trend and regime-aware mean reversion',
|
||||
proposition:
|
||||
'These independent candidates may respond differently to the same market observations',
|
||||
validationCriteria:
|
||||
'Train-only selection, held-out diagnostics, fixed cost scenarios; no fitted-model or profitable-strategy claim',
|
||||
},
|
||||
candidates: [
|
||||
{
|
||||
...common,
|
||||
key: 'trend',
|
||||
name: 'Trend candidate',
|
||||
rationale: 'Short/long trend signals',
|
||||
package: trend,
|
||||
parameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
grid: { fastPeriod: [1, 2] },
|
||||
},
|
||||
{
|
||||
...common,
|
||||
key: 'regime',
|
||||
name: 'Regime candidate',
|
||||
rationale: 'Mean reversion with momentum, trend, volume and volatility gates',
|
||||
package: regime,
|
||||
parameters: canonicalRegimeSelection().parameters,
|
||||
grid: {},
|
||||
},
|
||||
{
|
||||
...common,
|
||||
key: 'broken',
|
||||
name: 'Broken candidate',
|
||||
rationale: 'Failure is evidence of implementation failure, not a zero return',
|
||||
package: failure,
|
||||
parameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
grid: {},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
return {
|
||||
...base,
|
||||
pool,
|
||||
agents,
|
||||
research,
|
||||
project,
|
||||
provisioned,
|
||||
app,
|
||||
client,
|
||||
requests,
|
||||
suggestions,
|
||||
executionErrors,
|
||||
transport,
|
||||
drain,
|
||||
};
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('AI research workflow through authenticated APIs and Rust', () => {
|
||||
test('two generated candidates, train-only selection, costs, exact saved evidence and a retained failure', async () => {
|
||||
const f = await fixture();
|
||||
const events: ResearchCycleEvent[] = [];
|
||||
const result = await runResearchCycle(f.client, f.suggestions(), {
|
||||
onEvent: async event => {
|
||||
events.push(structuredClone(event));
|
||||
},
|
||||
poll: { timeoutMs: 60000, intervalMs: 20 },
|
||||
});
|
||||
expect(result.totalPlannedTrials).toBe(16);
|
||||
expect(result.outcomes).toHaveLength(3);
|
||||
expect(result.hypothesis.latestRevision.contentOrigin).toBe('ai');
|
||||
expect(result.hypothesis.latestRevision.validationState).toBe('unvalidated');
|
||||
expect(result.regimeAttribution).toContain('unavailable');
|
||||
for (const outcome of result.outcomes.slice(0, 2)) {
|
||||
expect(outcome.stoppedReason).toBeNull();
|
||||
expect(
|
||||
outcome.screening?.trials.every(trial => trial.status === 'completed' && trial.comparable)
|
||||
).toBeTrue();
|
||||
const report = outcome.validation?.report,
|
||||
selection = outcome.validation?.selection;
|
||||
if (!report || !selection || !outcome.costs) {
|
||||
throw new Error('Missing sealed native evidence');
|
||||
}
|
||||
expect(outcome.validation?.preview.policy.model).toBe('unverified-candidate');
|
||||
expect(selection.training.every(run => run.phase === 'train')).toBeTrue();
|
||||
expect(report.test.phase).toBe('test');
|
||||
expect(outcome.costs.trials).toHaveLength(2);
|
||||
for (const trial of outcome.costs.trials) {
|
||||
expect(trial.status).toBe('completed');
|
||||
expect(trial.comparable).toBeTrue();
|
||||
expect(trial.parameters).toEqual(selection.winner.parameters);
|
||||
}
|
||||
const finding = outcome.findings[0]!;
|
||||
expect(finding.latestRevision.source).toEqual({
|
||||
kind: 'chronological-report/v1',
|
||||
validationId: outcome.validation!.id,
|
||||
previewHash: outcome.validation!.previewHash,
|
||||
reportId: report.id,
|
||||
reportHash: report.reportHash,
|
||||
});
|
||||
expect(finding.latestRevision.evidence).toHaveLength(6);
|
||||
for (const evidence of finding.latestRevision.evidence) {
|
||||
const saved = await f.api.getRunResults(evidence.runId);
|
||||
if (!saved || !('kind' in saved) || saved.kind !== 'canonical-result/v1') {
|
||||
throw new Error('Missing native result');
|
||||
}
|
||||
expect(saved.strategyExecution).toBe('typescript-isolated-candidate/v1');
|
||||
expect(saved.request.strategy.versionId).toBe(outcome.versionId);
|
||||
expect(saved.request.strategy.package.artifact.sha256).toHaveLength(64);
|
||||
expect(evidence.datasetHash).toBe(saved.request.datasetHash);
|
||||
const metric = evidence.metricPath.slice('analytics.metrics.'.length) as
|
||||
| 'totalReturn'
|
||||
| 'maxDrawdown'
|
||||
| 'sharpeRatio';
|
||||
expect(evidence.value).toBe(saved.analytics.metrics[metric]);
|
||||
expect(evidence.availability).toBe(evidence.value === null ? 'unavailable' : 'available');
|
||||
if (evidence.value === null) {
|
||||
expect(evidence.unavailableReason).toBeTruthy();
|
||||
}
|
||||
}
|
||||
}
|
||||
const broken = result.outcomes[2]!;
|
||||
expect(broken.screening?.trials[0]?.status).toBe('failed');
|
||||
expect(broken.screening?.trials[0]?.metrics).toBeNull();
|
||||
expect(broken.screening?.trials[0]?.error).toContain('Deliberate research candidate failure');
|
||||
expect(broken.validation?.report).toBeNull();
|
||||
expect(broken.validation?.selection).toBeNull();
|
||||
expect(
|
||||
broken.validation?.phases.slice(1).every(phase => phase.status === 'not-admitted')
|
||||
).toBeTrue();
|
||||
expect(broken.findings).toEqual([]);
|
||||
expect(broken.stoppedReason).toContain('failed');
|
||||
expect(result.comparison?.rows).toHaveLength(4);
|
||||
expect(result.comparison?.selection.leftId).toBe(result.outcomes[0]!.costs!.id);
|
||||
expect(result.comparison?.selection.rightId).toBe(result.outcomes[1]!.costs!.id);
|
||||
expect(
|
||||
events.filter(event => event.phase === 'accepted' && event.operation === 'submit-training')
|
||||
).toHaveLength(3);
|
||||
const keyed = events.filter(event => event.phase === 'intent' && event.key);
|
||||
expect(new Set(keyed.map(event => event.key)).size).toBe(keyed.length);
|
||||
expect(
|
||||
keyed.every(
|
||||
event =>
|
||||
f.requests.some(
|
||||
request =>
|
||||
request.key === event.key &&
|
||||
JSON.stringify(request.body) === JSON.stringify(event.input)
|
||||
) || event.operation === 'publish-version'
|
||||
)
|
||||
).toBeTrue();
|
||||
expect(
|
||||
f.requests.some(request =>
|
||||
/\/(?:paper(?:-deployments)?|deployments|live|reviews)(?:\/|$)/.test(request.path)
|
||||
)
|
||||
).toBeFalse();
|
||||
expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(12);
|
||||
const accepted = events.find(
|
||||
event => event.operation === 'submit-training' && event.phase === 'intent'
|
||||
)!;
|
||||
const before = (await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count;
|
||||
const replay = await f.client.submitValidation(
|
||||
accepted.input as Parameters<ResearchClient['submitValidation']>[0],
|
||||
accepted.key!
|
||||
);
|
||||
expect(replay.id).toBe(result.outcomes[0]!.validation!.id);
|
||||
expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(
|
||||
before
|
||||
);
|
||||
const reopened = await f.client.validation(result.outcomes[0]!.validation!.id);
|
||||
expect(reopened.report).toEqual(result.outcomes[0]!.validation!.report);
|
||||
}, 180000);
|
||||
|
||||
test('real quota refusal and oversized search create no runs; nonmember evidence cannot become a finding', async () => {
|
||||
const f = await fixture(),
|
||||
plan = f.suggestions();
|
||||
const hypothesis = await f.client.createHypothesis(f.project.id, plan.hypothesis);
|
||||
const family = await f.client.createStrategy({
|
||||
name: 'Bounded candidate',
|
||||
description: 'Budget adversary',
|
||||
});
|
||||
const version = await f.client.publishVersion(
|
||||
family.id,
|
||||
plan.candidates[0]!.package,
|
||||
'bounded-version'
|
||||
);
|
||||
const input = {
|
||||
backtestId: plan.backtestId,
|
||||
name: 'Exceeds admission',
|
||||
candidate: { versionId: version.id, parameters: { fastPeriod: 2, slowPeriod: 10 } },
|
||||
grid: { fastPeriod: [1, 2, 3, 4, 5] },
|
||||
};
|
||||
const overBudget = await f.client.previewExperiment(input);
|
||||
await expect(
|
||||
f.client.submitExperiment(
|
||||
{ ...overBudget.input, previewHash: overBudget.previewHash },
|
||||
'over-budget'
|
||||
)
|
||||
).rejects.toMatchObject({
|
||||
status: 429,
|
||||
uncertain: false,
|
||||
});
|
||||
expect(() =>
|
||||
f.client.previewExperiment({
|
||||
...input,
|
||||
grid: { fastPeriod: Array.from({ length: 101 }, (_, i) => i + 1) },
|
||||
})
|
||||
).toThrow();
|
||||
expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(0);
|
||||
const good = await f.client.previewExperiment({ ...input, grid: {} });
|
||||
const admitted = await f.client.submitExperiment(
|
||||
{ ...good.input, previewHash: good.previewHash },
|
||||
'bounded-admitted'
|
||||
);
|
||||
const complete = await f.client.waitForExperiment(admitted.id, {
|
||||
timeoutMs: 60000,
|
||||
intervalMs: 20,
|
||||
});
|
||||
expect(complete.trials[0]?.status).toBe('completed');
|
||||
const evidence = {
|
||||
kind: 'finding' as const,
|
||||
title: 'Incorrect evidence',
|
||||
body: 'Must not be retained',
|
||||
hypothesisRevisionId: hypothesis.latestRevision.id,
|
||||
source: {
|
||||
kind: 'experiment/v1' as const,
|
||||
experimentId: admitted.id,
|
||||
previewHash: admitted.previewHash,
|
||||
},
|
||||
evidence: [
|
||||
{
|
||||
runId: randomUUID(),
|
||||
strategyVersionId: version.id,
|
||||
metricsVersion: 'canonical-analytics/v1' as const,
|
||||
metricPath: 'analytics.metrics.totalReturn' as const,
|
||||
},
|
||||
],
|
||||
};
|
||||
await expect(f.client.saveFinding(f.project.id, evidence)).rejects.toMatchObject({
|
||||
uncertain: false,
|
||||
});
|
||||
expect(
|
||||
(await f.pool.query('SELECT count(*)::int AS count FROM analysis_artifacts')).rows[0].count
|
||||
).toBe(0);
|
||||
const wrongVersion = {
|
||||
...evidence,
|
||||
evidence: [
|
||||
{
|
||||
...evidence.evidence[0]!,
|
||||
runId: complete.trials[0]!.runId!,
|
||||
strategyVersionId: f.version.id,
|
||||
},
|
||||
],
|
||||
};
|
||||
await expect(f.client.saveFinding(f.project.id, wrongVersion)).rejects.toMatchObject({
|
||||
uncertain: false,
|
||||
});
|
||||
}, 60000);
|
||||
});
|
||||
|
|
@ -219,7 +219,7 @@ describe.skipIf(!url)('canonical research admission and saved evidence', () => {
|
|||
expect(result.analytics.metrics.totalReturn).toBe(0);
|
||||
});
|
||||
|
||||
test('candidates, legacy settings, wrong asset/timeframe, multi-asset datasets and pacing never admit work', async () => {
|
||||
test('undeclared candidates, legacy settings, wrong asset/timeframe, multi-asset datasets and pacing never admit work', async () => {
|
||||
const f = await fixture();
|
||||
await f.approve();
|
||||
const clone = await f.catalog.cloneVersion(
|
||||
|
|
@ -237,7 +237,9 @@ describe.skipIf(!url)('canonical research admission and saved evidence', () => {
|
|||
{ ...f.definition, strategyVersionId: clone.version.id },
|
||||
{ autoStart: false }
|
||||
);
|
||||
await expect(f.api.createRun({ backtestId: candidate.id })).rejects.toThrow('candidates');
|
||||
await expect(f.api.createRun({ backtestId: candidate.id })).rejects.toThrow(
|
||||
'Candidate requires a retained isolated execution declaration'
|
||||
);
|
||||
await expect(f.api.createRun({ backtestId: f.draft.id, speedMultiplier: 2 })).rejects.toThrow(
|
||||
'maximum speed'
|
||||
);
|
||||
|
|
|
|||
537
test/postgres/isolated-candidates.test.ts
Normal file
537
test/postgres/isolated-candidates.test.ts
Normal file
|
|
@ -0,0 +1,537 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Pool } from 'pg';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { isResearchAgent, type ResearchActor } from '@stock-bot/types';
|
||||
import { canonicalRunRequestSchema } from '../../apps/stock/config/src/contracts/canonical-research';
|
||||
import { builtinStrategySelectionSchema } from '../../apps/stock/config/src/contracts/strategy';
|
||||
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||
import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
|
||||
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
|
||||
import { ChronologicalValidationService } from '../../apps/stock/web-api/src/services/chronological-validation.service';
|
||||
import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service';
|
||||
import { researchGrantPolicy } from '../../apps/stock/web-api/src/services/research-agent-budget';
|
||||
import { ResearchAgentsService } from '../../apps/stock/web-api/src/services/research-agents.service';
|
||||
import { WalkForwardService } from '../../apps/stock/web-api/src/services/walk-forward.service';
|
||||
import { retainResearchDataset } from '../../scripts/import-research-dataset';
|
||||
import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';
|
||||
import { walkForwardDataset } from '../fixtures/walk-forward';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('isolated-candidate-test');
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const cleanups: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanups.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
const migrations = [
|
||||
'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',
|
||||
'20-research-workspace.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
'26-cost-sensitivity.sql',
|
||||
'27-research-evidence-sources.sql',
|
||||
'28-research-agents.sql',
|
||||
];
|
||||
async function fixture() {
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Disposable safety database required');
|
||||
}
|
||||
const schema = 'stock_bot_safety_candidate_' + randomUUID().replaceAll('-', '');
|
||||
const admin = new Pool({ connectionString: url });
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
const pool = new Pool({
|
||||
connectionString: url,
|
||||
max: 4,
|
||||
options: `-c search_path=${schema} -c statement_timeout=10000`,
|
||||
});
|
||||
cleanups.push(async () => {
|
||||
await pool.end();
|
||||
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
||||
await admin.end();
|
||||
});
|
||||
for (const file of migrations) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${file}`, 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 });
|
||||
const base = await canonicalAdmissionFixture(pool, postgres, false);
|
||||
const container = { postgres, logger },
|
||||
experiments = new ExperimentsService(container),
|
||||
agents = new ResearchAgentsService(container);
|
||||
const apply = () =>
|
||||
pool.query(
|
||||
readFileSync(
|
||||
new URL('../../database/postgres/init/29-isolated-candidates.sql', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
);
|
||||
const candidate = async (principal: ResearchActor = 'operator', warmupBars = 0) => {
|
||||
const family = await base.catalog.createStrategy(
|
||||
{ name: 'Isolated SMA', description: 'Controlled parity fixture' },
|
||||
principal
|
||||
);
|
||||
const pkg = {
|
||||
...(await base.catalog.getVersionArtifact(base.version.id)),
|
||||
execution: { kind: 'isolated-candidate/v1' as const, warmupBars },
|
||||
};
|
||||
return base.catalog.publishVersion(family.id, pkg, null, principal, randomUUID());
|
||||
};
|
||||
const execute = async (runId: string) => {
|
||||
const engine = new RustBacktestAdapter({
|
||||
logger,
|
||||
storage: {
|
||||
async getHistoricalBars() {
|
||||
throw new Error('Candidate must use retained data only');
|
||||
},
|
||||
},
|
||||
});
|
||||
const runner = new BacktestRunner({
|
||||
engine,
|
||||
engineName: 'native',
|
||||
repository: new PostgresBacktestRunRepository(postgres),
|
||||
logger,
|
||||
});
|
||||
try {
|
||||
await runner.runQueued(runId);
|
||||
} finally {
|
||||
await runner.shutdown();
|
||||
await engine.shutdown();
|
||||
}
|
||||
return base.api.getRunResults(runId);
|
||||
};
|
||||
return { ...base, pool, postgres, container, experiments, agents, apply, candidate, execute };
|
||||
}
|
||||
const suite = url ? describe : describe.skip;
|
||||
suite('isolated candidate durable research', () => {
|
||||
test('SQL29 first upgrade/reapply preserves existing evidence and authoritative SQL28 resource guards', async () => {
|
||||
const f = await fixture();
|
||||
const before = (
|
||||
await f.pool.query(
|
||||
"SELECT pg_get_functiondef('guard_agent_run_budget()'::regprocedure) AS budget,pg_get_functiondef('require_agent_result_deadline()'::regprocedure) AS deadline"
|
||||
)
|
||||
).rows;
|
||||
const old = await f.experiments.preview({
|
||||
name: 'Old builtin',
|
||||
backtestId: f.draft.id,
|
||||
grid: {},
|
||||
});
|
||||
const admitted = await f.experiments.submit(
|
||||
{ ...old.input, previewHash: old.previewHash },
|
||||
{ principal: 'operator', key: 'before-upgrade' }
|
||||
);
|
||||
const pending = (
|
||||
await f.pool.query('SELECT request_snapshot FROM runs WHERE experiment_id=$1', [admitted.id])
|
||||
).rows[0];
|
||||
await new PostgresBacktestRunRepository(f.postgres).startCanonical(
|
||||
canonicalRunRequestSchema.parse(pending.request_snapshot)
|
||||
);
|
||||
const bytes = (
|
||||
await f.pool.query('SELECT to_jsonb(r) AS row FROM runs r WHERE experiment_id=$1', [
|
||||
admitted.id,
|
||||
])
|
||||
).rows;
|
||||
expect(bytes[0].row.status).toBe('running');
|
||||
expect(bytes[0].row.attempt_id).not.toBeNull();
|
||||
await f.apply();
|
||||
await f.apply();
|
||||
expect(
|
||||
(
|
||||
await f.pool.query(
|
||||
"SELECT pg_get_functiondef('guard_agent_run_budget()'::regprocedure) AS budget,pg_get_functiondef('require_agent_result_deadline()'::regprocedure) AS deadline"
|
||||
)
|
||||
).rows
|
||||
).toEqual(before);
|
||||
expect(
|
||||
(
|
||||
await f.pool.query('SELECT to_jsonb(r) AS row FROM runs r WHERE experiment_id=$1', [
|
||||
admitted.id,
|
||||
])
|
||||
).rows
|
||||
).toEqual(bytes);
|
||||
expect(
|
||||
(
|
||||
await f.experiments.submit(
|
||||
{ ...old.input, previewHash: old.previewHash },
|
||||
{ principal: 'operator', key: 'before-upgrade' }
|
||||
)
|
||||
).id
|
||||
).toBe(admitted.id);
|
||||
});
|
||||
test('unreviewed candidate admission runs the same Rust economics as the trusted controlled program', async () => {
|
||||
const f = await fixture();
|
||||
await f.apply();
|
||||
const candidate = await f.candidate();
|
||||
const input = {
|
||||
name: 'Candidate parity',
|
||||
backtestId: f.draft.id,
|
||||
grid: {},
|
||||
candidate: { versionId: candidate.id, parameters: { fastPeriod: 2, slowPeriod: 3 } },
|
||||
};
|
||||
const preview = await f.experiments.preview(input);
|
||||
expect(preview.request.strategy.origin).toBe('candidate');
|
||||
expect(preview.request.strategy.reviewId).toBeNull();
|
||||
const experiment = await f.experiments.submit(
|
||||
{ ...input, previewHash: preview.previewHash },
|
||||
{ principal: 'operator', key: 'candidate-once' }
|
||||
);
|
||||
const runId = experiment.trials[0]?.runId;
|
||||
if (!runId) {
|
||||
throw new Error('Missing candidate trial');
|
||||
}
|
||||
const result = await f.execute(runId);
|
||||
if (!result || !('kind' in result) || result.kind !== 'canonical-result/v1') {
|
||||
throw new Error('Missing canonical candidate result');
|
||||
}
|
||||
expect(result.strategyExecution).toBe('typescript-isolated-candidate/v1');
|
||||
const trusted = runStrategyReplay(
|
||||
prepareReplayLoad(f.dataset, result.request.policy),
|
||||
[
|
||||
createBuiltinStrategy(
|
||||
builtinStrategySelectionSchema.parse(result.request.strategy.selection)
|
||||
),
|
||||
],
|
||||
{ resultFormat: 'report' }
|
||||
);
|
||||
expect(result.financial).toEqual(trusted.result);
|
||||
expect(String(result.financial.view.equity)).toBe('9969.30000000');
|
||||
expect((await f.experiments.get(experiment.id)).trials[0]?.comparable).toBeTrue();
|
||||
expect(
|
||||
(
|
||||
await f.experiments.submit(
|
||||
{ ...input, previewHash: preview.previewHash },
|
||||
{ principal: 'operator', key: 'candidate-once' }
|
||||
)
|
||||
).id
|
||||
).toBe(experiment.id);
|
||||
}, 30000);
|
||||
test('agent own-candidate opt-in maps exactly to its frozen grant and rejects another principal/version or financial drift', async () => {
|
||||
const f = await fixture();
|
||||
await f.apply();
|
||||
const created = await f.agents.create({
|
||||
name: 'Candidate researcher',
|
||||
allowedProjectIds: [],
|
||||
allowedBacktestIds: [f.draft.id],
|
||||
limits: {
|
||||
maxActiveTrials: 2,
|
||||
maxTrialsPerExperiment: 10,
|
||||
maxBarEvaluationsPerExperiment: 10000,
|
||||
maxAttemptWallMs: 60000,
|
||||
maxAttempts: 2,
|
||||
},
|
||||
});
|
||||
const principal = created.agent.id;
|
||||
if (!isResearchAgent(principal)) {
|
||||
throw new Error('Expected agent identity');
|
||||
}
|
||||
const candidate = await f.candidate(principal);
|
||||
const input = {
|
||||
name: 'Own candidate',
|
||||
backtestId: f.draft.id,
|
||||
grid: {},
|
||||
candidate: { versionId: candidate.id, parameters: { fastPeriod: 2, slowPeriod: 3 } },
|
||||
};
|
||||
await expect(f.experiments.preview(input, principal)).rejects.toThrow('candidate permission');
|
||||
const before = (
|
||||
await f.pool.query('SELECT policy FROM research_agents WHERE id=$1', [principal])
|
||||
).rows[0].policy;
|
||||
await f.agents.update(principal, {
|
||||
expectedRevision: 1,
|
||||
allowOwnCandidateBacktestIds: [f.draft.id],
|
||||
});
|
||||
const preview = await f.experiments.preview(input, principal);
|
||||
expect(researchGrantPolicy(preview.request)).toEqual(before.grants[0].policy);
|
||||
expect(
|
||||
(await f.pool.query('SELECT research_grant_policy($1::jsonb) AS policy', [preview.request]))
|
||||
.rows[0].policy
|
||||
).toEqual(researchGrantPolicy(preview.request));
|
||||
const foreign = await f.candidate('operator');
|
||||
await expect(
|
||||
f.experiments.preview(
|
||||
{ ...input, candidate: { ...input.candidate, versionId: foreign.id } },
|
||||
principal
|
||||
)
|
||||
).rejects.toThrow('belong');
|
||||
const [experiment, duplicate] = await Promise.all([
|
||||
f.experiments.submit(
|
||||
{ ...input, previewHash: preview.previewHash },
|
||||
{ principal, key: 'agent-candidate' }
|
||||
),
|
||||
f.experiments.submit(
|
||||
{ ...input, previewHash: preview.previewHash },
|
||||
{ principal, key: 'agent-candidate' }
|
||||
),
|
||||
]);
|
||||
expect(duplicate.id).toBe(experiment.id);
|
||||
expect(experiment.trialCount).toBe(1);
|
||||
const after = (
|
||||
await f.pool.query('SELECT policy FROM research_agents WHERE id=$1', [principal])
|
||||
).rows[0].policy;
|
||||
expect(after.grants[0].policy).toEqual(before.grants[0].policy);
|
||||
expect(after.grants[0].policyHash).toBe(before.grants[0].policyHash);
|
||||
}, 30000);
|
||||
test('candidate retry and reproduction preserve the original package, null review, runtime and baseline after template edits', async () => {
|
||||
const f = await fixture();
|
||||
await f.apply();
|
||||
const candidate = await f.candidate();
|
||||
const input = {
|
||||
name: 'Retry candidate',
|
||||
backtestId: f.draft.id,
|
||||
grid: {},
|
||||
candidate: { versionId: candidate.id, parameters: { fastPeriod: 2, slowPeriod: 3 } },
|
||||
};
|
||||
const preview = await f.experiments.preview(input);
|
||||
const experiment = await f.experiments.submit(
|
||||
{ ...input, previewHash: preview.previewHash },
|
||||
{ principal: 'operator', key: 'create' }
|
||||
);
|
||||
const runId = experiment.trials[0]!.runId!;
|
||||
const repository = new PostgresBacktestRunRepository(f.postgres);
|
||||
await repository.rejectPending(runId, 'controlled preclaim failure');
|
||||
const original = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId]))
|
||||
.rows[0].request_snapshot;
|
||||
await f.api.updateBacktest(f.draft.id, {
|
||||
strategyParameters: { fastPeriod: 1, slowPeriod: 4 },
|
||||
});
|
||||
const retryBody = { expectedAttemptNumber: 0, expectedRetryCount: 0 },
|
||||
actor = { principal: 'operator', key: 'retry' };
|
||||
const retry = await f.experiments.retryTrial(experiment.id, runId, retryBody, actor);
|
||||
expect(retry.retry.reviewId).toBeNull();
|
||||
expect(
|
||||
(await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])).rows[0]
|
||||
.request_snapshot
|
||||
).toEqual(original);
|
||||
await f.execute(runId);
|
||||
expect((await f.experiments.retryTrial(experiment.id, runId, retryBody, actor)).retry.id).toBe(
|
||||
retry.retry.id
|
||||
);
|
||||
expect((await f.api.getReproductionPreview(runId)).available).toBeTrue();
|
||||
const reproduced = await f.api.reproduceRun(runId, {
|
||||
principal: 'operator',
|
||||
key: 'reproduction',
|
||||
});
|
||||
await f.execute(reproduced.id);
|
||||
expect((await f.api.getReproductionComparison(reproduced.id)).status).toBe('match');
|
||||
await f.catalog.reviewVersion(
|
||||
candidate.id,
|
||||
{ decision: 'revoke', reason: 'deny later admission' },
|
||||
'operator'
|
||||
);
|
||||
expect((await f.api.getReproductionPreview(runId)).available).toBeFalse();
|
||||
expect(
|
||||
(await f.api.reproduceRun(runId, { principal: 'operator', key: 'reproduction' })).id
|
||||
).toBe(reproduced.id);
|
||||
await expect(
|
||||
f.api.reproduceRun(runId, { principal: 'operator', key: 'after-revoke' })
|
||||
).rejects.toThrow();
|
||||
}, 30000);
|
||||
test('candidate declared warmup and original baseline propagate through two native walk-forward windows and sealed reports', async () => {
|
||||
const f = await fixture();
|
||||
await f.apply();
|
||||
const candidate = await f.candidate('operator', 4);
|
||||
const data = walkForwardDataset();
|
||||
await retainResearchDataset(f.pool, data.dataset);
|
||||
await f.api.updateBacktest(f.draft.id, {
|
||||
startDate: new Date(data.dataset.manifest.bounds.tradeStart).toISOString(),
|
||||
endDate: new Date(data.dataset.manifest.bounds.tradeEnd).toISOString(),
|
||||
config: { ...f.definition.config, datasetHash: data.dataset.manifest.hash },
|
||||
});
|
||||
const walks = new WalkForwardService(f.container),
|
||||
validations = new ChronologicalValidationService(f.container);
|
||||
const input = {
|
||||
name: 'Candidate rolling windows',
|
||||
backtestId: f.draft.id,
|
||||
grid: {},
|
||||
windows: data.windows,
|
||||
candidate: { versionId: candidate.id, parameters: { fastPeriod: 2, slowPeriod: 3 } },
|
||||
};
|
||||
const preview = await walks.preview(input);
|
||||
const walk = await walks.submit(
|
||||
{ ...input, previewHash: preview.previewHash },
|
||||
{ principal: 'operator', key: 'rolling' }
|
||||
);
|
||||
for (const member of walk.windows) {
|
||||
const initial = await validations.get(member.validationId);
|
||||
expect(initial.preview.policy.model).toBe('unverified-candidate');
|
||||
for (const trial of initial.phases[0]!.experiment!.trials) {
|
||||
await f.execute(trial.runId!);
|
||||
}
|
||||
const selected = await validations.select(
|
||||
initial.id,
|
||||
{ previewHash: initial.previewHash },
|
||||
{ principal: 'operator', key: randomUUID() }
|
||||
);
|
||||
expect(selected.validation.selection!.reviewId).toBeNull();
|
||||
const heldout = selected.validation.phases[1]!.experiment!.preview;
|
||||
for (const field of ['baselineVersionId', 'execution'] as const) {
|
||||
const forged = structuredClone(heldout);
|
||||
if (forged.request.strategy.origin !== 'candidate') {
|
||||
throw Error('candidate fixture');
|
||||
}
|
||||
if (field === 'baselineVersionId') {
|
||||
forged.request.strategy.baselineVersionId = randomUUID();
|
||||
} else {
|
||||
forged.request.strategy.execution.imageId = `sha256:${'0'.repeat(64)}`;
|
||||
}
|
||||
await expect(
|
||||
f.pool.query("SELECT assert_validation_phase_preview($1,$2,'validation',$3,NULL)", [
|
||||
forged,
|
||||
initial.preview,
|
||||
selected.validation.selection!.winner,
|
||||
])
|
||||
).rejects.toThrow();
|
||||
}
|
||||
for (const phase of selected.validation.phases.slice(1)) {
|
||||
expect(phase.experiment!.preview.request.strategy.origin).toBe('candidate');
|
||||
for (const trial of phase.experiment!.trials) {
|
||||
await f.execute(trial.runId!);
|
||||
}
|
||||
}
|
||||
await validations.finalize(
|
||||
initial.id,
|
||||
{
|
||||
previewHash: initial.previewHash,
|
||||
selectionHash: selected.validation.selection!.selectionHash,
|
||||
},
|
||||
{ principal: 'operator', key: randomUUID() }
|
||||
);
|
||||
}
|
||||
const sealed = await walks.finalize(
|
||||
walk.id,
|
||||
{ previewHash: preview.previewHash },
|
||||
{ principal: 'operator', key: 'seal' }
|
||||
);
|
||||
expect(sealed.walkForward.report!.segments).toHaveLength(2);
|
||||
const stored = (
|
||||
await f.pool.query(
|
||||
"SELECT request_snapshot#>>'{strategy,baselineVersionId}' AS baseline, request_snapshot#>'{strategy,reviewId}' AS review FROM runs"
|
||||
)
|
||||
).rows;
|
||||
expect(stored).toHaveLength(6);
|
||||
expect(stored.every(row => row.baseline === f.version.id && row.review === null)).toBeTrue();
|
||||
}, 60000);
|
||||
test('direct SQL refuses forged candidate ownership, baseline, execution profile and financial grant drift', async () => {
|
||||
const f = await fixture();
|
||||
await f.apply();
|
||||
const created = await f.agents.create({
|
||||
name: 'Direct guard',
|
||||
allowedProjectIds: [],
|
||||
allowedBacktestIds: [f.draft.id],
|
||||
allowOwnCandidateBacktestIds: [f.draft.id],
|
||||
limits: {
|
||||
maxActiveTrials: 2,
|
||||
maxTrialsPerExperiment: 10,
|
||||
maxBarEvaluationsPerExperiment: 10000,
|
||||
maxAttemptWallMs: 60000,
|
||||
maxAttempts: 2,
|
||||
},
|
||||
});
|
||||
const principal = created.agent.id;
|
||||
if (!isResearchAgent(principal)) {
|
||||
throw Error('agent identity');
|
||||
}
|
||||
const candidate = await f.candidate(principal);
|
||||
const input = {
|
||||
name: 'Guard candidate',
|
||||
backtestId: f.draft.id,
|
||||
grid: {},
|
||||
candidate: { versionId: candidate.id, parameters: { fastPeriod: 2, slowPeriod: 3 } },
|
||||
};
|
||||
const preview = await f.experiments.preview(input, principal);
|
||||
const admitted = await f.experiments.submit(
|
||||
{ ...input, previewHash: preview.previewHash },
|
||||
{ principal, key: 'admit' }
|
||||
);
|
||||
const row = (
|
||||
await f.pool.query('SELECT to_jsonb(e) AS value FROM research_experiments e WHERE id=$1', [
|
||||
admitted.id,
|
||||
])
|
||||
).rows[0].value;
|
||||
await f.pool.query(
|
||||
'SELECT validate_experiment_manifest(jsonb_populate_record(NULL::research_experiments,$1))',
|
||||
[row]
|
||||
);
|
||||
for (const [path, value] of [
|
||||
[['strategy', 'baselineVersionId'], randomUUID()],
|
||||
[['strategy', 'selection', 'ownerId'], 'strategy:' + randomUUID()],
|
||||
[['strategy', 'origin'], 'builtin'],
|
||||
[['strategy', 'execution', 'kind'], 'typescript-retained-builtin/v1'],
|
||||
[['strategy', 'execution', 'profile', 'limits', 'memoryBytes'], 1073741824],
|
||||
[['policy', 'matching', 'risk', 'maxGrossExposure'], '999999999'],
|
||||
] as const) {
|
||||
const forged = structuredClone(row);
|
||||
let parent = forged.preview.request;
|
||||
for (const key of path.slice(0, -1)) {
|
||||
parent = parent[key];
|
||||
}
|
||||
parent[path.at(-1)!] = value;
|
||||
await expect(
|
||||
f.pool.query(
|
||||
'SELECT validate_experiment_manifest(jsonb_populate_record(NULL::research_experiments,$1))',
|
||||
[forged]
|
||||
)
|
||||
).rejects.toThrow();
|
||||
}
|
||||
const drift = structuredClone(preview.request);
|
||||
drift.policy.matching.risk.maxGrossExposure =
|
||||
'999999999' as typeof drift.policy.matching.risk.maxGrossExposure;
|
||||
await expect(
|
||||
f.pool.query(
|
||||
'SELECT assert_research_agent_grant(a,$2,$3) FROM research_agents a WHERE id=$1',
|
||||
[principal, f.draft.id, drift]
|
||||
)
|
||||
).rejects.toThrow();
|
||||
const foreign = await f.candidate('operator');
|
||||
const foreignPreview = await f.experiments.preview({
|
||||
...input,
|
||||
candidate: { ...input.candidate, versionId: foreign.id },
|
||||
});
|
||||
await expect(
|
||||
f.pool.query(
|
||||
'SELECT assert_research_agent_grant(a,$2,$3) FROM research_agents a WHERE id=$1',
|
||||
[principal, f.draft.id, foreignPreview.request]
|
||||
)
|
||||
).rejects.toThrow();
|
||||
await f.agents.update(principal, { expectedRevision: 1, allowOwnCandidateBacktestIds: [] });
|
||||
await expect(
|
||||
f.pool.query(
|
||||
'SELECT assert_research_agent_grant(a,$2,$3) FROM research_agents a WHERE id=$1',
|
||||
[principal, f.draft.id, preview.request]
|
||||
)
|
||||
).rejects.toThrow();
|
||||
expect(
|
||||
(
|
||||
await f.experiments.submit(
|
||||
{ ...input, previewHash: preview.previewHash },
|
||||
{ principal, key: 'admit' }
|
||||
)
|
||||
).id
|
||||
).toBe(admitted.id);
|
||||
expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(1);
|
||||
}, 30000);
|
||||
});
|
||||
|
|
@ -31,6 +31,9 @@ const migrations = [
|
|||
'26-cost-sensitivity.sql',
|
||||
'27-research-evidence-sources.sql',
|
||||
'28-research-agents.sql',
|
||||
'29-isolated-candidates.sql',
|
||||
'30-paper-deployments.sql',
|
||||
'31-research-agent-project-links.sql',
|
||||
];
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
|
|
|
|||
573
test/postgres/paper-deployments.test.ts
Normal file
573
test/postgres/paper-deployments.test.ts
Normal file
|
|
@ -0,0 +1,573 @@
|
|||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { readdirSync, readFileSync } from 'node:fs';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Pool } from 'pg';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import type { PaperPromotionInput } from '@stock-bot/stock-config/paper-deployments';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
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 { PostgresCanonicalExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository';
|
||||
import {
|
||||
readPaperDeployment,
|
||||
verifyPaperEvidenceCustody,
|
||||
} from '../../apps/stock/orchestrator/src/paper/paper-deployment-custody';
|
||||
import { readPaperHostIdentity } from '../../apps/stock/orchestrator/src/paper/paper-host-identity';
|
||||
import { PaperDeploymentHost } from '../../apps/stock/orchestrator/src/paper/PaperDeploymentHost';
|
||||
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 { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service';
|
||||
import { PaperDeploymentsService } from '../../apps/stock/web-api/src/services/paper-deployments.service';
|
||||
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
|
||||
import { retainResearchDataset } from '../../scripts/import-research-dataset';
|
||||
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
|
||||
import { canonicalSettings } from '../fixtures/canonical-research';
|
||||
import { chronologicalDataset } from '../fixtures/chronological-validation';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('paper-promotion'),
|
||||
url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const closes: Array<() => Promise<void>> = [];
|
||||
afterEach(async () => {
|
||||
for (const close of closes.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
const actor = () => ({ principal: 'operator' as const, key: randomUUID() });
|
||||
async function fixture(max = 1, withPromotion = true, candidate = false) {
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Disposable database required');
|
||||
}
|
||||
const schema = 'stock_bot_safety_promotion_' + randomUUID().replaceAll('-', ''),
|
||||
admin = new Pool({ connectionString: url });
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
const pool = new Pool({
|
||||
connectionString: url,
|
||||
max,
|
||||
options: `-c search_path=${schema} -c statement_timeout=15000`,
|
||||
});
|
||||
closes.push(async () => {
|
||||
await pool.end();
|
||||
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
||||
await admin.end();
|
||||
});
|
||||
const directory = new URL('../../database/postgres/init/', import.meta.url);
|
||||
for (const file of readdirSync(directory)
|
||||
.filter(
|
||||
n =>
|
||||
/^\d\d-/.test(n) &&
|
||||
Number(n.slice(0, 2)) >= 6 &&
|
||||
Number(n.slice(0, 2)) <= 30 &&
|
||||
(withPromotion || Number(n.slice(0, 2)) !== 30)
|
||||
)
|
||||
.sort()) {
|
||||
await pool.query(readFileSync(new URL(file, directory), '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),
|
||||
validations = new ChronologicalValidationService(container),
|
||||
catalog = new StrategyCatalogService(container),
|
||||
service = new PaperDeploymentsService(container);
|
||||
const pkg = (await packageBuiltinStrategies())[0];
|
||||
if (!pkg) {
|
||||
throw new Error('Missing builtin');
|
||||
}
|
||||
const baseline = await catalog.seedBuiltin('Promotion SMA', pkg, 'seed');
|
||||
let version = baseline;
|
||||
await catalog.reviewVersion(
|
||||
version.id,
|
||||
{ decision: 'approve', reason: 'Disposable proof' },
|
||||
'operator'
|
||||
);
|
||||
if (candidate) {
|
||||
const family = await catalog.createStrategy(
|
||||
{ name: 'Generic retained paper candidate' },
|
||||
'operator'
|
||||
);
|
||||
const content = `export function createPaperCandidate(selection) {
|
||||
return { ownerId: selection.ownerId, strategyId: selection.strategyId, strategyVersion: selection.strategyVersion,
|
||||
seed: selection.seed, mode: 'target', initialState: {count:0, marker:'retained-candidate'},
|
||||
decide(context) { return { nextState:{count:context.state.count+1,marker:'retained-candidate'},
|
||||
intent:{mode:'target',targets:[{instrumentId:selection.instrumentId,quantity:'1.00000000'}]} }; }
|
||||
};
|
||||
}`;
|
||||
version = await catalog.publishVersion(
|
||||
family.id,
|
||||
{
|
||||
...pkg,
|
||||
program: {
|
||||
...pkg.program,
|
||||
strategyId: 'paper_fixture_candidate',
|
||||
strategyVersion: 'candidate/v1',
|
||||
checkpointVersion: 'candidate-state/v1',
|
||||
},
|
||||
artifact: {
|
||||
...pkg.artifact,
|
||||
entryExport: 'createPaperCandidate',
|
||||
content,
|
||||
sha256: createHash('sha256').update(content).digest('hex'),
|
||||
},
|
||||
execution: { kind: 'isolated-candidate/v1', warmupBars: 0 },
|
||||
},
|
||||
null,
|
||||
'operator',
|
||||
randomUUID()
|
||||
);
|
||||
}
|
||||
const candidateOverride = candidate
|
||||
? { candidate: { versionId: version.id, parameters: { fastPeriod: 2, slowPeriod: 3 } } }
|
||||
: {};
|
||||
const data = chronologicalDataset(),
|
||||
dataset = data.dataset;
|
||||
await retainResearchDataset(pool, dataset);
|
||||
const draft = await api.createBacktest(
|
||||
{
|
||||
name: 'Promotion template',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: baseline.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 repository = new PostgresBacktestRunRepository(postgres);
|
||||
const execute = async (id: string) => {
|
||||
const engine = new RustBacktestAdapter({
|
||||
logger,
|
||||
storage: {
|
||||
async getHistoricalBars() {
|
||||
throw new Error('No provider allowed');
|
||||
},
|
||||
},
|
||||
});
|
||||
const runner = new BacktestRunner({ engine, engineName: 'native', repository, logger });
|
||||
try {
|
||||
await runner.runQueued(id);
|
||||
} finally {
|
||||
await runner.shutdown();
|
||||
}
|
||||
};
|
||||
const input = {
|
||||
backtestId: draft.id,
|
||||
name: 'Frozen OOS',
|
||||
grid: {},
|
||||
recipe: data.recipe,
|
||||
...candidateOverride,
|
||||
},
|
||||
preview = await experiments.previewValidation(input),
|
||||
validation = await validations.submit({ ...input, previewHash: preview.previewHash }, actor());
|
||||
for (const trial of validation.phases[0]!.experiment!.trials) {
|
||||
await execute(trial.runId!);
|
||||
}
|
||||
const selected = await validations.select(
|
||||
validation.id,
|
||||
{ previewHash: preview.previewHash },
|
||||
actor()
|
||||
);
|
||||
for (const phase of selected.validation.phases.slice(1)) {
|
||||
for (const trial of phase.experiment!.trials) {
|
||||
await execute(trial.runId!);
|
||||
}
|
||||
}
|
||||
const finished = await validations.finalize(
|
||||
validation.id,
|
||||
{
|
||||
previewHash: preview.previewHash,
|
||||
selectionHash: selected.validation.selection!.selectionHash,
|
||||
},
|
||||
actor()
|
||||
),
|
||||
report = finished.validation.report!;
|
||||
const costInput = {
|
||||
backtestId: draft.id,
|
||||
name: 'Cost evidence',
|
||||
...candidateOverride,
|
||||
scenarios: [{ feeRate: '0.02', slippageRate: '0.01' }],
|
||||
},
|
||||
costPreview = await experiments.previewCosts(costInput),
|
||||
cost = await experiments.submitCosts(
|
||||
{ ...costInput, previewHash: costPreview.previewHash },
|
||||
actor()
|
||||
);
|
||||
for (const trial of cost.trials) {
|
||||
await execute(trial.runId!);
|
||||
}
|
||||
if (candidate) {
|
||||
const researchResult = await api.getRunResults(report.test.runId);
|
||||
expect(
|
||||
researchResult && 'strategyExecution' in researchResult
|
||||
? researchResult.strategyExecution
|
||||
: null
|
||||
).toBe('typescript-isolated-candidate/v1');
|
||||
await catalog.reviewVersion(
|
||||
version.id,
|
||||
{ decision: 'approve', reason: 'Separate human review for trusted paper promotion' },
|
||||
'operator'
|
||||
);
|
||||
}
|
||||
const start = Date.parse('2030-01-01T14:30:00Z'),
|
||||
ownerId = `strategy:${version.id}`;
|
||||
const promotion: PaperPromotionInput = {
|
||||
name: 'Reviewed paper trial',
|
||||
outOfSample: {
|
||||
kind: 'chronological-report/v1',
|
||||
validationId: validation.id,
|
||||
reportId: report.id,
|
||||
reportHash: report.reportHash,
|
||||
previewHash: report.previewHash,
|
||||
},
|
||||
testRunId: report.test.runId,
|
||||
costExperimentId: cost.id,
|
||||
costPreviewHash: cost.previewHash,
|
||||
costRunId: cost.trials[1]!.runId!,
|
||||
reason: 'Reviewed held-out results, costs and trusted-code limitations',
|
||||
acknowledgeTrustedCode: true,
|
||||
transport: {
|
||||
accountId: 'paper:' + randomUUID(),
|
||||
sessionId: 'paper:' + randomUUID(),
|
||||
quoteSeriesId: 'X0.US:quote',
|
||||
riskSession: {
|
||||
calendarId: 'paper-risk',
|
||||
calendarRevision: 'v1',
|
||||
sessionId: 'paper-day',
|
||||
startsAt: start,
|
||||
},
|
||||
policy: {
|
||||
version: 1,
|
||||
sourceId: 'disposable-producer',
|
||||
priceBasis: 'raw',
|
||||
maxFeedAgeMs: 300000,
|
||||
observations: [
|
||||
{ instrumentId: 'X0.US', seriesId: 'X0.US:1m', intervalMs: 60000, staleAfterMs: 300000 },
|
||||
],
|
||||
cadence: [{ ownerId, seriesIds: ['X0.US:1m'] }],
|
||||
calendars: [
|
||||
{
|
||||
instrumentId: 'X0.US',
|
||||
calendarId: 'explicit-venue',
|
||||
revision: 'v1',
|
||||
sessions: [{ sessionId: 'paper-day', opensAt: start, closesAt: start + 3600000 }],
|
||||
},
|
||||
],
|
||||
riskBoundaries: [],
|
||||
},
|
||||
},
|
||||
};
|
||||
return {
|
||||
pool,
|
||||
postgres,
|
||||
container,
|
||||
service,
|
||||
catalog,
|
||||
version,
|
||||
promotion,
|
||||
report,
|
||||
cost,
|
||||
preview,
|
||||
start,
|
||||
validation,
|
||||
api,
|
||||
draft,
|
||||
repository,
|
||||
};
|
||||
}
|
||||
const submit = async (
|
||||
f: Awaited<ReturnType<typeof fixture>>,
|
||||
input = f.promotion,
|
||||
key = randomUUID()
|
||||
) => {
|
||||
const preview = await f.service.preview(input);
|
||||
const body = { ...input, previewHash: preview.previewHash };
|
||||
return { deployment: await f.service.create(body, key), body, key };
|
||||
};
|
||||
|
||||
describe.skipIf(!url)('human-reviewed paper deployment', () => {
|
||||
for (const candidate of [false, true]) {
|
||||
test(`${candidate ? 'generic candidate' : 'builtin'} native OOS/cost promotion binds halted, fills through Rust, and restarts without resetting custody`, async () => {
|
||||
const f = await fixture(1, true, candidate),
|
||||
before = (await f.pool.query('SELECT count(*)::int AS n FROM simulation_accounts')).rows[0]
|
||||
.n;
|
||||
const saved = await submit(f),
|
||||
deployment = saved.deployment;
|
||||
expect(
|
||||
(await f.pool.query('SELECT count(*)::int AS n FROM simulation_accounts')).rows[0].n
|
||||
).toBe(before);
|
||||
expect(deployment.preview.evidence.test.fillCount).toBeGreaterThan(0);
|
||||
expect(deployment.preview.evidence.costs.every(e => e.fillCount > 0)).toBe(true);
|
||||
expect(deployment.preview.configuration.matching.risk.feeRate).toBe(
|
||||
parseFinancialDecimal('0.02')
|
||||
);
|
||||
let now = f.start + 60000;
|
||||
const repository = new PostgresCanonicalExecutionRepository(f.postgres),
|
||||
host = new PaperDeploymentHost({ database: f.postgres, repository, now: () => now });
|
||||
closes.push(() => host.shutdown());
|
||||
expect((await host.bind(deployment.id.toUpperCase())).readiness.active).toBe(false);
|
||||
expect((await host.status(deployment.id)).readiness.operatorHalted).toBe(true);
|
||||
await expect(host.activate(deployment.id)).rejects.toThrow('feed');
|
||||
const runtime = host.runtime(),
|
||||
connection = { sourceId: 'disposable-producer', connectionId: 'one' };
|
||||
await runtime.connect(connection);
|
||||
const send = async (sequence: number, price: number, bars = true) => {
|
||||
now = f.start + sequence * 60000;
|
||||
const decimal = parseFinancialDecimal(String(price));
|
||||
return runtime.ingest({
|
||||
version: 1,
|
||||
...connection,
|
||||
id: 'frame:' + sequence,
|
||||
sequence,
|
||||
availableAt: now,
|
||||
quotes: [
|
||||
{
|
||||
instrumentId: 'X0.US',
|
||||
seriesId: 'X0.US:quote',
|
||||
observedAt: now,
|
||||
sourceSequence: sequence,
|
||||
bid: decimal,
|
||||
ask: decimal,
|
||||
bidSize: parseFinancialDecimal('1000'),
|
||||
askSize: parseFinancialDecimal('1000'),
|
||||
},
|
||||
],
|
||||
observations: bars
|
||||
? [
|
||||
{
|
||||
series_id: 'X0.US:1m',
|
||||
instrument_id: 'X0.US',
|
||||
interval_start: now - 60000,
|
||||
interval_end: now,
|
||||
event_time: now,
|
||||
available_at: now,
|
||||
source_sequence: sequence,
|
||||
open: decimal,
|
||||
high: decimal,
|
||||
low: decimal,
|
||||
close: decimal,
|
||||
volume: parseFinancialDecimal('1000'),
|
||||
},
|
||||
]
|
||||
: [],
|
||||
});
|
||||
};
|
||||
await send(1, 3);
|
||||
await host.activate(deployment.id);
|
||||
await send(2, 3);
|
||||
await send(3, 2);
|
||||
await send(4, 1);
|
||||
await send(5, 4);
|
||||
await send(6, 5);
|
||||
await send(7, 5, false);
|
||||
const accountId = f.promotion.transport.accountId;
|
||||
const snapshot = async () => ({
|
||||
account: (
|
||||
await f.pool.query('SELECT state FROM simulation_accounts WHERE id=$1', [accountId])
|
||||
).rows[0].state,
|
||||
owners: (
|
||||
await f.pool.query(
|
||||
'SELECT payload FROM simulation_strategy_checkpoints WHERE account_id=$1 ORDER BY strategy_id',
|
||||
[accountId]
|
||||
)
|
||||
).rows,
|
||||
});
|
||||
const filled = await snapshot();
|
||||
expect(filled.account.view.portfolio.positions.length).toBeGreaterThan(0);
|
||||
expect(filled.account.host.deployment.deploymentId).toBe(deployment.id);
|
||||
expect(deployment.preview.strategy.origin).toBe(candidate ? 'candidate' : 'builtin');
|
||||
if (candidate) {
|
||||
expect(filled.owners[0].payload.definition.strategyId).toBe('paper_fixture_candidate');
|
||||
expect(filled.owners[0].payload.diagnostic.state.marker).toBe('retained-candidate');
|
||||
expect(filled.owners[0].payload.diagnostic.state.count).toBeGreaterThan(0);
|
||||
expect(filled.account.view.portfolio.positions[0].quantity).toBe('1.00000000');
|
||||
}
|
||||
|
||||
await host.halt(deployment.id, 'Review complete');
|
||||
await host.shutdown();
|
||||
const restarted = new PaperDeploymentHost({
|
||||
database: f.postgres,
|
||||
repository,
|
||||
now: () => now,
|
||||
});
|
||||
closes.push(() => restarted.shutdown());
|
||||
expect((await restarted.bind(deployment.id)).readiness.active).toBe(false);
|
||||
const restored = await snapshot();
|
||||
expect(restored.account.view).toEqual(filled.account.view);
|
||||
expect(restored.account.checkpoint).toEqual(filled.account.checkpoint);
|
||||
expect(restored.owners).toEqual(filled.owners);
|
||||
expect(restored.account.host.deployment).toEqual(filled.account.host.deployment);
|
||||
await f.catalog.reviewVersion(
|
||||
f.version.id,
|
||||
{ decision: 'revoke', reason: 'Stop new activation' },
|
||||
'operator'
|
||||
);
|
||||
await expect(restarted.activate(deployment.id)).rejects.toThrow('current operator approval');
|
||||
expect((await restarted.halt(deployment.id, 'Still allowed')).readiness.active).toBe(false);
|
||||
expect(await f.service.create(saved.body, saved.key)).toEqual(deployment);
|
||||
}, 60000);
|
||||
}
|
||||
test('exact receipts survive review changes; wrong evidence, cost drift, SQL tampering and custody reuse fail closed', async () => {
|
||||
const f = await fixture(4),
|
||||
saved = await submit(f);
|
||||
const race = await Promise.all([
|
||||
f.service.create(saved.body, saved.key),
|
||||
f.service.create(saved.body, saved.key),
|
||||
]);
|
||||
expect(race).toEqual([saved.deployment, saved.deployment]);
|
||||
await expect(f.service.create({ ...saved.body, name: 'different' }, saved.key)).rejects.toThrow(
|
||||
'another request'
|
||||
);
|
||||
await expect(
|
||||
f.service.preview({ ...f.promotion, testRunId: f.report.validation.runId })
|
||||
).rejects.toThrow('test run');
|
||||
await expect(
|
||||
f.service.preview({ ...f.promotion, costRunId: f.report.test.runId })
|
||||
).rejects.toThrow('cost scenario');
|
||||
await expect(f.service.create(saved.body, randomUUID())).rejects.toThrow('already');
|
||||
const original = saved.deployment;
|
||||
for (const mutate of [
|
||||
(d: typeof original) => {
|
||||
d.principal = 'service' as 'operator';
|
||||
},
|
||||
(d: typeof original) => {
|
||||
d.preview.configuration.matching.risk.maxGrossExposure = parseFinancialDecimal('999999');
|
||||
},
|
||||
(d: typeof original) => {
|
||||
d.preview.input.testRunId = f.report.validation.runId;
|
||||
},
|
||||
(d: typeof original) => {
|
||||
d.preview.evidence.costs = [];
|
||||
},
|
||||
(d: typeof original) => {
|
||||
d.preview.evidence.test.metrics.totalReturn = 999;
|
||||
},
|
||||
(d: typeof original) => {
|
||||
d.preview.host.engineBinarySha256 = 'f'.repeat(64);
|
||||
},
|
||||
]) {
|
||||
const d = structuredClone(original);
|
||||
d.id = randomUUID();
|
||||
d.preview.input.transport.accountId = 'other:' + randomUUID();
|
||||
d.preview.configuration.matching.risk.ledger.accountId = d.preview.input.transport.accountId;
|
||||
mutate(d);
|
||||
await expect(
|
||||
f.pool.query(
|
||||
'INSERT INTO paper_deployments(id,account_id,strategy_version_id,promotion_hash,idempotency_key,request_hash,document) VALUES($1,$2,$3,$4,$5,$6,$7)',
|
||||
[
|
||||
d.id,
|
||||
d.preview.configuration.matching.risk.ledger.accountId,
|
||||
d.preview.strategy.versionId,
|
||||
d.promotionHash,
|
||||
randomUUID(),
|
||||
'a'.repeat(64),
|
||||
d,
|
||||
]
|
||||
)
|
||||
).rejects.toThrow();
|
||||
}
|
||||
await expect(
|
||||
f.pool.query(
|
||||
'UPDATE paper_deployments SET document=document||\'{"principal":"service"}\' WHERE id=$1',
|
||||
[original.id]
|
||||
)
|
||||
).rejects.toThrow('immutable');
|
||||
await expect(
|
||||
f.pool.query('DELETE FROM paper_deployments WHERE id=$1', [original.id])
|
||||
).rejects.toThrow('immutable');
|
||||
expect((await f.service.get(original.id)).promotionHash).toBe(original.promotionHash);
|
||||
await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER');
|
||||
await f.pool.query(
|
||||
"UPDATE backtest_results SET canonical_result=jsonb_set(canonical_result,'{analytics,metrics,totalReturn}','999'::jsonb) WHERE run_id=$1",
|
||||
[f.promotion.testRunId]
|
||||
);
|
||||
await f.pool.query('ALTER TABLE backtest_results ENABLE TRIGGER USER');
|
||||
await expect(f.service.authorizeCommand(original.id)).rejects.toThrow();
|
||||
await expect(verifyPaperEvidenceCustody(f.pool, original)).rejects.toThrow('result identity');
|
||||
}, 60000);
|
||||
test('changed installed host and retained artifact cannot initialize or overwrite an account', async () => {
|
||||
const f = await fixture(),
|
||||
drifted = new PaperDeploymentsService(f.container, async () => ({
|
||||
...(await readPaperHostIdentity()),
|
||||
hostSha256: 'f'.repeat(64),
|
||||
}));
|
||||
const wrongNative = new PaperDeploymentsService(f.container, async () => ({
|
||||
...(await readPaperHostIdentity()),
|
||||
engineBinarySha256: 'f'.repeat(64),
|
||||
}));
|
||||
await expect(wrongNative.preview(f.promotion)).rejects.toThrow('same native');
|
||||
const preview = await drifted.preview(f.promotion),
|
||||
saved = await drifted.create(
|
||||
{ ...f.promotion, previewHash: preview.previewHash },
|
||||
randomUUID()
|
||||
);
|
||||
const host = new PaperDeploymentHost({
|
||||
database: f.postgres,
|
||||
repository: new PostgresCanonicalExecutionRepository(f.postgres),
|
||||
});
|
||||
closes.push(() => host.shutdown());
|
||||
await expect(host.bind(saved.id)).rejects.toThrow('differs');
|
||||
expect(
|
||||
(await f.pool.query('SELECT count(*)::int AS n FROM simulation_accounts')).rows[0].n
|
||||
).toBe(0);
|
||||
await f.postgres.transaction(async tx => {
|
||||
await tx.query('ALTER TABLE strategy_versions DISABLE TRIGGER USER');
|
||||
await tx.query(
|
||||
"UPDATE strategy_versions SET envelope=jsonb_set(envelope,'{artifact,content}',to_jsonb((envelope#>>'{artifact,content}')||' changed')) WHERE id=$1",
|
||||
[f.version.id]
|
||||
);
|
||||
await tx.query('ALTER TABLE strategy_versions ENABLE TRIGGER USER');
|
||||
});
|
||||
await expect(host.bind(saved.id)).rejects.toThrow('hash mismatch');
|
||||
await expect(f.service.preview(f.promotion)).rejects.toThrow();
|
||||
expect(
|
||||
(await f.pool.query('SELECT count(*)::int AS n FROM simulation_accounts')).rows[0].n
|
||||
).toBe(0);
|
||||
}, 60000);
|
||||
test('first migration/reapply preserves accepted research and leases, and archived evidence remains readable', async () => {
|
||||
const f = await fixture(1, false),
|
||||
pending = await f.api.createRun({ backtestId: f.draft.id }, actor()),
|
||||
request = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [pending.id]))
|
||||
.rows[0].request_snapshot;
|
||||
await f.repository.startCanonical(request);
|
||||
const snapshot = async () =>
|
||||
(await f.pool.query('SELECT to_jsonb(r) AS row FROM runs r ORDER BY id')).rows;
|
||||
const before = await snapshot();
|
||||
expect(
|
||||
before.some(
|
||||
item => item.row.status === 'running' && item.row.attempt_id && item.row.lease_expires_at
|
||||
)
|
||||
).toBe(true);
|
||||
const migration = readFileSync(
|
||||
new URL('../../database/postgres/init/30-paper-deployments.sql', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
await f.pool.query(migration);
|
||||
expect(await snapshot()).toEqual(before);
|
||||
const saved = await submit(f);
|
||||
await f.pool.query(migration);
|
||||
expect(await snapshot()).toEqual(before);
|
||||
expect(await readPaperDeployment(f.pool, saved.deployment.id)).toEqual(saved.deployment);
|
||||
await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [
|
||||
f.version.strategyId,
|
||||
]);
|
||||
expect(await f.service.get(saved.deployment.id)).toEqual(saved.deployment);
|
||||
await expect(f.service.authorizeCommand(saved.deployment.id)).rejects.toThrow('active family');
|
||||
expect(
|
||||
(await f.pool.query('SELECT count(*)::int AS n FROM simulation_accounts')).rows[0].n
|
||||
).toBe(0);
|
||||
}, 60000);
|
||||
});
|
||||
|
|
@ -236,6 +236,84 @@ function http(f: Fixture) {
|
|||
});
|
||||
}
|
||||
describe.skipIf(!url)('authoritative research principals and budgets', () => {
|
||||
test('owned project links advance only revision metadata after additive migration; project authority stays operator-only', async () => {
|
||||
const f = await fixture(),
|
||||
p = await provision(f);
|
||||
const actor = p.agent.id as `agent:${string}`;
|
||||
const clone = await f.catalog.cloneVersion(
|
||||
f.version.id,
|
||||
{ name: 'Owned link candidate' },
|
||||
actor,
|
||||
randomUUID()
|
||||
);
|
||||
const before = await f.research.getProject(p.project.id);
|
||||
await expect(f.research.linkStrategy(p.project.id, clone.strategy.id, actor)).rejects.toThrow(
|
||||
'Only an operator'
|
||||
);
|
||||
expect(await f.research.listProjectStrategies(p.project.id)).toEqual([]);
|
||||
const migration = readFileSync(
|
||||
new URL('../../database/postgres/init/31-research-agent-project-links.sql', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
await f.pool.query(migration);
|
||||
await f.research.linkStrategy(p.project.id, clone.strategy.id, actor);
|
||||
const after = await f.research.getProject(p.project.id);
|
||||
expect(after.revision).toBe(before.revision + 1);
|
||||
expect(after.updatedBy).toBe(actor);
|
||||
expect(after.ownerPrincipal).toBe(before.ownerPrincipal);
|
||||
expect(after.title).toBe(before.title);
|
||||
expect((await f.research.listProjectStrategies(p.project.id)).map(s => s.id)).toEqual([
|
||||
clone.strategy.id,
|
||||
]);
|
||||
await f.pool.query(migration);
|
||||
await f.research.linkStrategy(p.project.id, clone.strategy.id, actor);
|
||||
expect(await f.research.getProject(p.project.id)).toEqual(after);
|
||||
const update = (fragment: string, id = p.project.id) =>
|
||||
f.pool.query(
|
||||
`UPDATE research_projects SET revision=revision+1,updated_by=$2,updated_at=NOW(),${fragment} WHERE id=$1`,
|
||||
[id, actor]
|
||||
);
|
||||
for (const fragment of [
|
||||
"title='changed'",
|
||||
"description='changed'",
|
||||
"owner_principal='service'",
|
||||
'archived_at=NOW()',
|
||||
"created_at=created_at-INTERVAL '1 day'",
|
||||
]) {
|
||||
await expect(update(fragment)).rejects.toThrow('Only owned strategy links');
|
||||
}
|
||||
await expect(
|
||||
f.pool.query('UPDATE research_projects SET revision=revision+2,updated_by=$2 WHERE id=$1', [
|
||||
p.project.id,
|
||||
actor,
|
||||
])
|
||||
).rejects.toThrow('Only owned strategy links');
|
||||
await expect(
|
||||
f.research.createProject({ title: 'Unauthorized provisioning' }, actor)
|
||||
).rejects.toThrow('Only an operator');
|
||||
const foreign = await f.research.createProject({ title: 'Ungranted' }, 'operator');
|
||||
await expect(update('description=description', foreign.id)).rejects.toThrow(
|
||||
'Only owned strategy links'
|
||||
);
|
||||
await expect(f.research.linkStrategy(foreign.id, clone.strategy.id, actor)).rejects.toThrow(
|
||||
'not permitted'
|
||||
);
|
||||
await expect(
|
||||
f.research.linkStrategy(p.project.id, f.version.strategyId, actor)
|
||||
).rejects.toThrow('not permitted');
|
||||
expect(await f.research.getProject(p.project.id)).toEqual(after);
|
||||
expect(
|
||||
(
|
||||
await f.pool.query(
|
||||
"SELECT count(*)::int n FROM research_agent_audit WHERE agent_id=$1 AND operation='research_projects-link-revision'",
|
||||
[actor]
|
||||
)
|
||||
).rows[0].n
|
||||
).toBe(1);
|
||||
await f.agents.update(actor, { expectedRevision: 1, enabled: false });
|
||||
await expect(update('description=description')).rejects.toThrow('disabled');
|
||||
expect(await f.research.getProject(p.project.id)).toEqual(after);
|
||||
});
|
||||
test('operator provisioning stores only a hash; real mounted authentication, AI authorship and scoped writes', async () => {
|
||||
const f = await fixture(1),
|
||||
p = await provision(f);
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
import { asValue } from 'awilix';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { afterEach, describe, expect, spyOn, test } from 'bun:test';
|
||||
import { ServiceContainerBuilder } from '@stock-bot/di';
|
||||
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
|
||||
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
|
||||
import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';
|
||||
|
|
@ -38,14 +39,13 @@ async function fixture() {
|
|||
container.register({ serviceContainer: asValue(services) });
|
||||
await registerOrchestratorServices(container);
|
||||
const runtime = services.custom!,
|
||||
runner = runtime.BacktestRunner!,
|
||||
engine = runtime.BacktestEngine!;
|
||||
runner = runtime.BacktestRunner!;
|
||||
cleanup.push(async () => {
|
||||
await runner.shutdown();
|
||||
await paper.runtime.shutdown();
|
||||
await container.dispose();
|
||||
});
|
||||
return { paper, ...admitted, container, services, runtime, runner, engine };
|
||||
return { paper, ...admitted, container, services, runtime, runner };
|
||||
}
|
||||
describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)(
|
||||
'canonical research isolation from durable paper custody',
|
||||
|
|
@ -95,25 +95,29 @@ describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)(
|
|||
for (let index = 0; index < 2; index++) {
|
||||
const run = await accept();
|
||||
let stopped: Promise<void> | undefined;
|
||||
f.runner.once('progress', () => {
|
||||
const cancelOnProgress = () => {
|
||||
f.runner.off('progress', cancelOnProgress);
|
||||
stopped = f.runner.stopBacktest();
|
||||
});
|
||||
};
|
||||
f.runner.on('progress', cancelOnProgress);
|
||||
const cancelled = await f.runner.runQueued(run.id).catch(error => error);
|
||||
await stopped;
|
||||
expect(stopped).toBeDefined();
|
||||
expect(cancelled).toBeInstanceOf(BacktestCancelledError);
|
||||
await unchanged();
|
||||
const failed = await accept(),
|
||||
original = f.engine.runCanonical;
|
||||
f.engine.runCanonical = async () => {
|
||||
throw new Error('Injected canonical execution failure');
|
||||
};
|
||||
const failed = await accept();
|
||||
// The pool deliberately keeps engines private; inject only at the adapter seam.
|
||||
const failure = spyOn(RustBacktestAdapter.prototype, 'runCanonical').mockImplementationOnce(
|
||||
async () => {
|
||||
throw new Error('Injected canonical execution failure');
|
||||
}
|
||||
);
|
||||
try {
|
||||
await expect(f.runner.runQueued(failed.id)).rejects.toThrow(
|
||||
'Injected canonical execution failure'
|
||||
);
|
||||
} finally {
|
||||
f.engine.runCanonical = original;
|
||||
failure.mockRestore();
|
||||
}
|
||||
await unchanged();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -155,7 +155,7 @@ describe.skipIf(!url)('immutable strategy catalog on real PostgreSQL', () => {
|
|||
reviewStatus: 'pending',
|
||||
runnable: false,
|
||||
});
|
||||
expect(v.reason).toContain('A02');
|
||||
expect(v.reason).toContain('isolated execution declaration');
|
||||
expect(v.package.artifact).not.toHaveProperty('content');
|
||||
expect(v.package.dependencyLock).not.toHaveProperty('content');
|
||||
expect(await f.api.getVersionArtifact(v.id)).toEqual(pkg);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue