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
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('');
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue