feat(research): isolate candidates and add reviewed paper promotion

This commit is contained in:
Boki 2026-10-24 18:46:55 -04:00
parent 26b97265c6
commit 25b5cbf481
128 changed files with 13038 additions and 1388 deletions

View file

@ -3,6 +3,7 @@ import type { Logger } from '@stock-bot/services';
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
import {
canonicalRunRequestSchema,
canonicalStrategyExecution,
type CanonicalRunRequest,
type CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
@ -260,14 +261,17 @@ export class BacktestRunner extends EventEmitter {
throw new Error('Canonical execution capabilities are unavailable');
}
const claim = this.active;
const report = await engine.runCanonical(executionConfig, signal =>
loadCanonicalDataset.call(
repository,
claim.runId,
claim.attemptId,
executionConfig.datasetHash,
signal
)
const report = await engine.runCanonical(
executionConfig,
signal =>
loadCanonicalDataset.call(
repository,
claim.runId,
claim.attemptId,
executionConfig.datasetHash,
signal
),
{ executionDeadlineAt: claim.executionDeadlineAt }
);
if (this.cancelled) {
throw new BacktestCancelledError();
@ -280,7 +284,7 @@ export class BacktestRunner extends EventEmitter {
completedAt: new Date().toISOString(),
executionTime: performance.now() - started,
financialEngine: 'rust',
strategyExecution: 'typescript-retained-builtin/v1',
strategyExecution: canonicalStrategyExecution(executionConfig),
request: executionConfig,
...report,
};

View file

@ -1,4 +1,5 @@
import { fork, type ChildProcess } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { realpathSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import {
@ -13,6 +14,7 @@ import {
parseStrategyReplayResult,
strategyReplayRequestSchema,
} from '../contracts/strategy-replay';
import { removeCandidateContainer } from './candidate-sandbox';
import { canonicalWorkerUrl } from './canonical-build';
import {
nativeWorkerMessageSchema,
@ -49,6 +51,16 @@ export class NativeBacktestWorker {
request.type === 'runStrategyReplay'
? structuredClone(strategyReplayRequestSchema.parse(request))
: undefined;
const candidateContainerName =
retainedRequest?.request.strategy.origin === 'candidate'
? `stock-bot-candidate-${randomUUID()}`
: undefined;
if (retainedRequest) {
delete retainedRequest.candidateContainerName;
if (candidateContainerName) {
retainedRequest.candidateContainerName = candidateContainerName;
}
}
const submitted = retainedRequest ?? strategyRequest ?? request;
if (
retainedRequest &&
@ -155,7 +167,7 @@ export class NativeBacktestWorker {
}
}
};
const finish = (code: number | null, exitSignal: NodeJS.Signals | null) => {
const finish = async (code: number | null, exitSignal: NodeJS.Signals | null) => {
if (settled) {
return;
}
@ -163,6 +175,13 @@ export class NativeBacktestWorker {
signal.removeEventListener('abort', onAbort);
child.off('message', onMessage);
child.stderr?.off('data', onStderr);
if (candidateContainerName) {
try {
await removeCandidateContainer(candidateContainerName);
} catch (error) {
failure ??= error instanceof Error ? error : new Error(String(error));
}
}
this.active = undefined;
if (failure) {
reject(failure);

View file

@ -8,6 +8,7 @@ import {
} from '@stock-bot/stock-config/backtest';
import {
canonicalRunRequestSchema,
canonicalStrategyExecution,
parseCanonicalFinancialResult,
type CanonicalRunRequest,
type CanonicalRunResult,
@ -414,7 +415,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
result.runId !== request.runId ||
result.backtestId !== request.backtestId ||
result.financialEngine !== 'rust' ||
result.strategyExecution !== 'typescript-retained-builtin/v1'
result.strategyExecution !== canonicalStrategyExecution(request)
) {
throw new BacktestConflictError('Canonical result identity mismatch');
}

View file

@ -58,7 +58,8 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
async runCanonical(
input: CanonicalRunRequest,
resolveDataset: (signal: AbortSignal) => Promise<HistoricalDatasetV2>
resolveDataset: (signal: AbortSignal) => Promise<HistoricalDatasetV2>,
controls: { executionDeadlineAt?: number } = {}
): Promise<Pick<CanonicalRunResult, 'financial' | 'analytics'>> {
const request = canonicalRunRequestSchema.parse(input);
return this.runOwned(
@ -67,7 +68,14 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
const dataset = await Promise.race([resolveDataset(signal), aborted]);
signal.throwIfAborted();
const raw = await this.worker.execute(
{ type: 'runRetainedStrategy', request, dataset },
{
type: 'runRetainedStrategy',
request,
dataset,
...(controls.executionDeadlineAt === undefined
? {}
: { executionDeadlineAt: controls.executionDeadlineAt }),
},
signal,
progress => {
this.progress = progress.progress;

View file

@ -0,0 +1,99 @@
/** This entrypoint runs ONLY inside the restricted image; never the API/native supervisor. */
import { sameIdentity } from '../contracts/native-replay';
import { importRetainedProgram } from '../strategies/retained-program';
import { StrategyController } from '../strategies/strategy-controller';
import { freeze } from '../strategies/strategy-decision';
import {
candidateRequestSchema,
readCandidateFrames,
writeCandidateFrame,
} from './candidate-protocol';
// Ordinary logs are diagnostics, not protocol. Deliberate raw stdout forgery remains untrusted.
// eslint-disable-next-line no-console -- stdout belongs exclusively to the framed protocol.
console.log = console.info = console.debug = (...values: unknown[]) => console.error(...values);
let controller: StrategyController | undefined;
let identity: ConstructorParameters<typeof StrategyController>[0] | undefined;
let sequence = 0;
try {
for await (const raw of readCandidateFrames(process.stdin)) {
const request = candidateRequestSchema.parse(raw);
if (request.sequence !== sequence) {
throw new Error('Candidate protocol sequence mismatch');
}
const response = { version: 1, sequence };
if (request.type === 'transpile') {
if (sequence !== 0 || controller) {
throw new Error('Packaging must be the first and only host operation');
}
const compiler = new Bun.Transpiler({ loader: 'ts', target: 'browser' });
if (
compiler.scanImports(request.source).length ||
/\b(?:import|require)\s*\(/.test(request.source)
) {
throw new Error(
'Candidate packaging accepts self-contained TypeScript without import/require edges'
);
}
// Transformation only: top-level statements are data and are never imported or evaluated.
const content = compiler.transformSync(request.source);
if (compiler.scanImports(content).length) {
throw new Error('Packaged candidate retained an import edge');
}
await writeCandidateFrame(process.stdout, {
...response,
type: 'transpiled',
content,
runtimeVersion: Bun.version,
});
process.exit(0);
} else if (request.type === 'init') {
if (controller || sequence !== 0) {
throw new Error('Candidate host already initialized');
}
identity = freeze(request.identity);
const program = await importRetainedProgram(
request.package as Parameters<typeof importRetainedProgram>[0],
request.selection
);
controller = new StrategyController(identity, [program], {
matching: { owners: [{ ownerId: request.selection.ownerId, mode: 'Target' }] },
});
await writeCandidateFrame(process.stdout, { ...response, type: 'ready' });
} else {
if (!controller || !identity) {
throw new Error('Candidate host is not initialized');
}
if (request.type === 'stage') {
sameIdentity(request.published.identity, identity);
if (request.published.step.type !== 'decisionBatch') {
throw new Error('Candidate requires a decision barrier');
}
freeze(request.published);
const decisions = controller.stage(request.published.step, request.published.observations);
await writeCandidateFrame(process.stdout, { ...response, type: 'decisions', decisions });
} else if (request.type === 'committed') {
sameIdentity(request.admitted.identity, identity);
freeze(request.admitted.outcome);
controller.committed(request.admitted.outcome);
await writeCandidateFrame(process.stdout, { ...response, type: 'ack' });
} else {
await writeCandidateFrame(process.stdout, { ...response, type: 'finished' });
process.exit(0);
}
}
sequence++;
}
throw new Error('Candidate supervisor disconnected before finish');
} catch (error) {
try {
await writeCandidateFrame(process.stdout, {
version: 1,
sequence,
type: 'error',
message: String(error).slice(0, 4096),
});
} finally {
process.exit(1);
}
}

View file

@ -0,0 +1,89 @@
/** Bounded transport, shared by the restricted host and its untrusted-output supervisor. */
import { Readable, Writable } from 'node:stream';
import { z } from 'zod';
import {
candidateSandboxLimits,
retainedProgramSelectionSchema,
} from '@stock-bot/stock-config/candidate-execution';
import { parseFinancialStrategyDecision } from '@stock-bot/types';
import { replayIdentitySchema, stepSchema, submissionSchema } from '../contracts/native-replay';
const base = {
version: z.literal(1),
sequence: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
};
export const candidateRequestSchema = z.discriminatedUnion('type', [
z.object({ ...base, type: z.literal('transpile'), source: z.string().min(1) }).strict(),
z
.object({
...base,
type: z.literal('init'),
identity: replayIdentitySchema,
package: z.unknown(),
selection: retainedProgramSelectionSchema,
})
.strict(),
z.object({ ...base, type: z.literal('stage'), published: stepSchema }).strict(),
z.object({ ...base, type: z.literal('committed'), admitted: submissionSchema }).strict(),
z.object({ ...base, type: z.literal('finish') }).strict(),
]);
export const candidateResponseSchema = z.discriminatedUnion('type', [
z.object({ ...base, type: z.literal('ready') }).strict(),
z
.object({
...base,
type: z.literal('transpiled'),
content: z.string(),
runtimeVersion: z.string().min(1),
})
.strict(),
z
.object({
...base,
type: z.literal('decisions'),
decisions: z.array(z.unknown().transform(parseFinancialStrategyDecision)).length(1),
})
.strict(),
z.object({ ...base, type: z.literal('ack') }).strict(),
z.object({ ...base, type: z.literal('finished') }).strict(),
z.object({ ...base, type: z.literal('error'), message: z.string().max(4096) }).strict(),
]);
export type CandidateResponse = z.infer<typeof candidateResponseSchema>;
export async function writeCandidateFrame(stream: Writable, value: unknown): Promise<void> {
const body = Buffer.from(JSON.stringify(value));
if (body.length > candidateSandboxLimits.frameBytes) {
throw new Error('Candidate protocol frame exceeds its retained resource limit');
}
const header = Buffer.alloc(4);
header.writeUInt32BE(body.length);
await new Promise<void>((resolve, reject) =>
stream.write(Buffer.concat([header, body]), error => (error ? reject(error) : resolve()))
);
}
export async function* readCandidateFrames(stream: Readable): AsyncGenerator<unknown> {
let buffer = Buffer.alloc(0);
for await (const raw of stream) {
const chunk = Buffer.isBuffer(raw) ? raw : Buffer.from(raw as string);
// Readable chunks are bounded by stream buffering; reject oversized buffered input before parsing.
if (buffer.length + chunk.length > candidateSandboxLimits.frameBytes + 4) {
throw new Error('Candidate protocol buffer exceeds its retained resource limit');
}
buffer = Buffer.concat([buffer, chunk]);
while (buffer.length >= 4) {
const length = buffer.readUInt32BE(0);
if (length === 0 || length > candidateSandboxLimits.frameBytes) {
throw new Error('Invalid or oversized candidate protocol frame');
}
if (buffer.length < length + 4) {
break;
}
const content = buffer.subarray(4, length + 4);
buffer = buffer.subarray(length + 4);
yield JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(content));
}
}
if (buffer.length) {
throw new Error('Truncated candidate protocol frame');
}
}

View file

@ -0,0 +1,467 @@
/** Trusted launcher. Candidate code is never imported in this process. */
import { execFile, spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
import { createHash } from 'node:crypto';
import { mkdtemp, readFile, realpath, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { promisify } from 'node:util';
import {
candidateExecutionSchema,
candidateSandboxLimits,
type CandidateExecution,
} from '@stock-bot/stock-config/candidate-execution';
import type { CanonicalRunRequest } from '@stock-bot/stock-config/canonical-research';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import { parseFinancialStrategyDecision } from '@stock-bot/types';
import type { ReplaySubmissionOutcome } from '../contracts/native-replay';
import {
candidateResponseSchema,
readCandidateFrames,
writeCandidateFrame,
type CandidateResponse,
} from './candidate-protocol';
import type {
AsyncReplayController,
DecisionContext,
PublishedObservation,
ReplayIdentity,
} from './native-replay';
const runFile = promisify(execFile);
const docker = '/usr/bin/docker';
const daemon = ['--host', 'unix:///var/run/docker.sock'];
const environment = (config: string) => ({ PATH: '/usr/bin:/bin', DOCKER_CONFIG: config });
const root = resolve(dirname(fileURLToPath(import.meta.resolve('@stock-bot/engine'))), '../../..');
export const candidateDescriptorPath = resolve(
root,
'apps/stock/orchestrator/dist/candidate-sandbox.json'
);
export class CandidateSandboxUnavailable extends Error {
readonly code = 'candidate_sandbox_unavailable';
}
async function dockerRead(args: string[]) {
const config = await mkdtemp(join(tmpdir(), 'stock-bot-docker-client-'));
try {
return (
await runFile(docker, [...daemon, ...args], {
env: environment(config),
timeout: 10000,
maxBuffer: 65536,
})
).stdout.trim();
} finally {
await rm(config, { recursive: true, force: true });
}
}
export async function readCandidateExecution(): Promise<CandidateExecution> {
try {
if (process.platform !== 'linux' || process.arch !== 'x64') {
throw new Error('Unsupported candidate platform');
}
const execution = candidateExecutionSchema.parse(
JSON.parse(await readFile(candidateDescriptorPath, 'utf8'))
);
const files = [
resolve(root, 'apps/stock/orchestrator/dist/candidate-host.js'),
resolve(root, 'apps/stock/orchestrator/dist/candidate-guardian'),
await realpath(process.execPath),
];
const hashes = await Promise.all(
files.map(async path =>
createHash('sha256')
.update(await readFile(path))
.digest('hex')
)
);
if (
hashes[0] !== execution.profile.hostSha256 ||
hashes[1] !== execution.profile.guardianSha256 ||
hashes[2] !== execution.profile.bunSha256
) {
throw new Error('Candidate installed host/runtime bytes differ');
}
const info = JSON.parse(await dockerRead(['info', '--format', '{{json .}}'])) as Record<
string,
unknown
>;
if (
info.OSType !== 'linux' ||
info.CgroupVersion !== '2' ||
info.MemoryLimit !== true ||
info.SwapLimit !== true ||
info.CpuCfsQuota !== true ||
info.PidsLimit !== true ||
!Array.isArray(info.SecurityOptions) ||
!info.SecurityOptions.some(v => String(v).startsWith('name=seccomp')) ||
!info.SecurityOptions.some(v => String(v).startsWith('name=apparmor'))
) {
throw new Error('Candidate cgroup/seccomp/AppArmor isolation is unavailable');
}
if (
(await dockerRead(['image', 'inspect', execution.imageId, '--format', '{{.Id}}'])) !==
execution.imageId
) {
throw new Error('Candidate exact image is unavailable');
}
return execution;
} catch (cause) {
throw new CandidateSandboxUnavailable('The exact isolated candidate runtime is unavailable', {
cause,
});
}
}
export async function verifyCandidateExecution(expected: CandidateExecution): Promise<void> {
if (
canonicalStrategyJson(await readCandidateExecution()) !==
canonicalStrategyJson(candidateExecutionSchema.parse(expected))
) {
throw new CandidateSandboxUnavailable(
'The retained isolated candidate runtime is not installed'
);
}
}
export function validateCandidateContainerName(value: string): string {
if (!/^stock-bot-candidate-[0-9a-f-]{36}$/.test(value)) {
throw new Error('Invalid owned candidate container name');
}
return value;
}
/** Removal is exact-name only; never touches other research or operator containers. */
export async function removeCandidateContainer(name: string): Promise<void> {
validateCandidateContainerName(name);
try {
await dockerRead(['rm', '--force', name]);
} catch (cause) {
// A successful --rm exit races explicit cancellation cleanup. Confirm absence.
if ((await dockerRead(['ps', '--all', '--quiet', '--filter', `name=^/${name}$`])) !== '') {
throw cause;
}
}
}
export class IsolatedCandidateController implements AsyncReplayController {
private readonly child: ChildProcessWithoutNullStreams;
private readonly closed: Promise<{ code: number | null; signal: NodeJS.Signals | null }>;
private failure: Error | undefined;
private pending:
| {
sequence: number;
type: CandidateResponse['type'];
resolve(value: CandidateResponse): void;
reject(error: Error): void;
}
| undefined;
private sequence = 0;
private decisionSequence = 0;
private stderr = Buffer.alloc(0);
private readonly timer: ReturnType<typeof setTimeout>;
private disposed = false;
private expectedExit = false;
private hasClosed = false;
private readonly identity: ReplayIdentity | undefined;
private constructor(
private readonly request: CandidateRequest | null,
private readonly name: string,
deadlineAt: number,
private readonly dockerConfig: string,
execution: CandidateExecution
) {
this.identity = request
? { version: 1, sessionId: request.runId, datasetHash: request.datasetHash }
: undefined;
const limits = candidateSandboxLimits;
this.child = spawn(
docker,
[
...daemon,
'run',
'--rm',
'--interactive',
'--pull=never',
'--name',
name,
'--network',
'none',
'--ipc',
'none',
'--read-only',
'--tmpfs',
`/tmp:rw,nosuid,nodev,noexec,size=${limits.tmpBytes}`,
'--memory',
String(limits.memoryBytes),
'--memory-swap',
String(limits.memoryBytes),
'--cpus',
String(limits.cpuQuota),
'--pids-limit',
String(limits.pids),
'--cap-drop',
'ALL',
'--cap-add',
'SETUID',
'--cap-add',
'SETGID',
'--cap-add',
'KILL',
'--security-opt',
'no-new-privileges=true',
'--log-driver',
'none',
execution.imageId,
String(deadlineAt),
],
{ env: environment(dockerConfig), stdio: ['pipe', 'pipe', 'pipe'] }
);
this.child.stdin.on('error', cause => this.fail(cause));
this.child.stderr.on('data', (chunk: Buffer) => {
this.stderr = Buffer.concat([this.stderr, chunk]).subarray(-limits.stderrBytes);
});
this.closed = new Promise(resolveClosed => {
this.child.once('error', cause => this.fail(cause));
this.child.once('close', (code, signal) => {
this.hasClosed = true;
if (!this.disposed && (!this.expectedExit || this.pending)) {
this.fail(
new Error(`Candidate host exited before completion (code ${code}, signal ${signal})`)
);
}
resolveClosed({ code, signal });
});
});
this.timer = setTimeout(
() => this.fail(new Error('Candidate host exceeded its wall deadline')),
Math.max(1, deadlineAt - Date.now())
);
void this.readResponses();
}
static async start(
request: CanonicalRunRequest,
name: string,
suppliedDeadline?: number
): Promise<IsolatedCandidateController> {
if (request.strategy.origin !== 'candidate') {
throw new Error('Only candidates may use the isolated controller');
}
validateCandidateContainerName(name);
await verifyCandidateExecution(request.strategy.execution);
const deadlineAt = Math.min(
Date.now() + candidateSandboxLimits.wallMs,
suppliedDeadline ?? Infinity
);
if (!Number.isSafeInteger(deadlineAt) || deadlineAt <= Date.now()) {
throw new Error('Candidate execution deadline is expired or invalid');
}
const config = await mkdtemp(join(tmpdir(), 'stock-bot-docker-client-'));
const controller = new IsolatedCandidateController(
request as CandidateRequest,
name,
deadlineAt,
config,
request.strategy.execution
);
try {
await controller.exchange('ready', {
type: 'init',
identity: controller.identity,
package: request.strategy.package,
selection: request.strategy.selection,
});
return controller;
} catch (cause) {
try {
await controller.dispose();
} catch (cleanup) {
throw new AggregateError([cause, cleanup], 'Candidate initialization and cleanup failed');
}
throw cause;
}
}
static async transpile(
source: string,
name: string
): Promise<{ content: string; runtimeVersion: string; execution: CandidateExecution }> {
validateCandidateContainerName(name);
const execution = await readCandidateExecution();
const config = await mkdtemp(join(tmpdir(), 'stock-bot-docker-client-'));
const controller = new IsolatedCandidateController(
null,
name,
Date.now() + candidateSandboxLimits.wallMs,
config,
execution
);
try {
const response = await controller.exchange('transpiled', { type: 'transpile', source });
const status = await controller.closed;
if (response.type !== 'transpiled' || controller.failure || status.code !== 0) {
throw controller.failure ?? new Error('Candidate packaging failed');
}
return { content: response.content, runtimeVersion: response.runtimeVersion, execution };
} finally {
await controller.dispose();
}
}
private fail(error: Error) {
this.failure ??= error;
const pending = this.pending;
this.pending = undefined;
pending?.reject(this.failure);
this.child.stdin.destroy();
}
private async readResponses() {
try {
for await (const raw of readCandidateFrames(this.child.stdout)) {
const response = candidateResponseSchema.parse(raw);
const pending = this.pending;
if (
!pending ||
response.sequence !== pending.sequence ||
(response.type !== pending.type && response.type !== 'error')
) {
throw new Error('Unsolicited or mismatched candidate response');
}
if (response.type === 'error') {
throw new Error(`Candidate strategy failed: ${response.message}`);
}
if (response.type === 'finished' || response.type === 'transpiled') {
this.expectedExit = true;
}
this.pending = undefined;
pending.resolve(response);
}
if (!this.disposed && !this.expectedExit) {
this.fail(new Error('Candidate protocol closed before completion'));
}
} catch (cause) {
this.fail(cause instanceof Error ? cause : new Error(String(cause)));
}
}
private async exchange(
type: CandidateResponse['type'],
message: Record<string, unknown>
): Promise<CandidateResponse> {
if (this.failure) {
throw this.failure;
}
if (this.pending || this.disposed || this.hasClosed || this.expectedExit) {
throw new Error('Candidate controller is unavailable or busy');
}
const sequence = this.sequence++;
const response = new Promise<CandidateResponse>((resolveResponse, reject) => {
this.pending = { sequence, type, resolve: resolveResponse, reject };
});
void response.catch(() => undefined);
try {
await writeCandidateFrame(this.child.stdin, { version: 1, sequence, ...message });
} catch (cause) {
this.fail(cause instanceof Error ? cause : new Error(String(cause)));
}
return response;
}
async stage(context: DecisionContext, observations: readonly PublishedObservation[]) {
const response = await this.exchange('decisions', {
type: 'stage',
published: { identity: this.identity, step: context, observations },
});
if (response.type !== 'decisions') {
throw new Error('Expected candidate decisions');
}
const decision = parseFinancialStrategyDecision(response.decisions[0]);
if (!this.request || !this.identity) {
throw new Error('Packaging host cannot make decisions');
}
const selected = this.request.strategy.selection;
const expectedId = JSON.stringify([
'strategy',
selected.ownerId,
selected.strategyId,
selected.strategyVersion,
this.decisionSequence,
]);
if (
context.barrier.owner_ids.length !== 1 ||
context.barrier.owner_ids[0] !== selected.ownerId ||
decision.sessionId !== this.identity.sessionId ||
decision.barrierId !== context.barrier.barrier_id ||
decision.revision !== context.barrier.revision ||
decision.decision.ownerId !== selected.ownerId ||
decision.decision.sequence !== this.decisionSequence ||
decision.decision.decisionId !== expectedId ||
decision.intent.mode !== 'target'
) {
throw new Error('Candidate returned a forged decision identity or mode');
}
return [decision];
}
async committed(outcome: ReplaySubmissionOutcome): Promise<void> {
if (!this.identity) {
throw new Error('Packaging host cannot accept financial acknowledgements');
}
await this.exchange('ack', {
type: 'committed',
admitted: { identity: this.identity, outcome },
});
this.decisionSequence++;
}
async finish(): Promise<void> {
await this.exchange('finished', { type: 'finish' });
const status = await this.closed;
if (this.failure || status.code !== 0) {
throw this.failure ?? new Error(`Candidate host did not exit successfully: ${this.stderr}`);
}
}
async dispose(): Promise<void> {
if (this.disposed) {
return;
}
this.disposed = true;
if (this.pending) {
this.fail(new Error('Candidate controller disposed before acknowledgement'));
}
clearTimeout(this.timer);
this.child.stdin.destroy();
const errors: unknown[] = [];
// Always attempt every cleanup stage, including when the daemon is unavailable.
// The independent guardian still enforces its frozen wall deadline in that case.
try {
await removeCandidateContainer(this.name);
} catch (error) {
errors.push(error);
}
if (!this.hasClosed) {
this.child.kill('SIGKILL');
}
let timer: ReturnType<typeof setTimeout> | undefined;
try {
await Promise.race([
this.closed,
new Promise<never>((_, reject) => {
timer = setTimeout(
() => reject(new Error('Candidate Docker client did not close during cleanup')),
10000
);
}),
]);
} catch (error) {
errors.push(error);
} finally {
clearTimeout(timer);
}
try {
await rm(this.dockerConfig, { recursive: true, force: true });
} catch (error) {
errors.push(error);
}
if (errors.length) {
throw new AggregateError(
this.failure ? [this.failure, ...errors] : errors,
'Candidate cleanup failed'
);
}
}
}
type CandidateRequest = CanonicalRunRequest & {
strategy: Extract<CanonicalRunRequest['strategy'], { origin: 'candidate' }>;
};

View file

@ -17,7 +17,8 @@ export interface BacktestExecutionEngine extends Pick<EventEmitter, 'on' | 'off'
): Promise<BacktestResult | NativeBacktestResult>;
runCanonical?(
request: CanonicalRunRequest,
resolveDataset: (signal: AbortSignal) => Promise<HistoricalDatasetV2>
resolveDataset: (signal: AbortSignal) => Promise<HistoricalDatasetV2>,
controls?: { executionDeadlineAt?: number }
): Promise<Pick<CanonicalRunResult, 'financial' | 'analytics'>>;
stopBacktest(): Promise<void>;
pauseBacktest(): Promise<void>;

View file

@ -1,4 +1,8 @@
import { z } from 'zod';
import {
candidateExecutionSchema,
type CandidateExecution,
} from '@stock-bot/stock-config/candidate-execution';
import {
canonicalBuildIdentitySchema,
canonicalRunRequestSchema,
@ -19,6 +23,11 @@ export const retainedStrategyRequestSchema = z
type: z.literal('runRetainedStrategy'),
request: canonicalRunRequestSchema,
dataset: z.unknown(),
executionDeadlineAt: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
candidateContainerName: z
.string()
.regex(/^stock-bot-candidate-[0-9a-f-]{36}$/)
.optional(),
})
.strict();
@ -33,6 +42,7 @@ export interface RetainedStrategyResult {
version: 1;
build: CanonicalBuildIdentity;
artifactHash: string;
execution?: CandidateExecution;
financial: ReplayReportResult;
analytics: CanonicalBacktestAnalytics;
}
@ -43,6 +53,7 @@ const retainedStrategyResultSchema = z
version: z.literal(1),
build: canonicalBuildIdentitySchema,
artifactHash: z.string().regex(/^[a-f0-9]{64}$/),
execution: candidateExecutionSchema.optional(),
financial: z.unknown(),
analytics: z.unknown(),
})
@ -60,6 +71,14 @@ export function parseRetainedStrategyResult(
) {
throw new Error('Retained strategy result build/artifact identity mismatch');
}
if (
request.strategy.origin === 'candidate'
? canonicalStrategyJson(envelope.execution) !==
canonicalStrategyJson(request.strategy.execution)
: envelope.execution !== undefined
) {
throw new Error('Retained strategy result execution identity mismatch');
}
const financial = parseCanonicalFinancialResult(envelope.financial, request);
const analytics = buildCanonicalBacktestReport(financial, request.analyticsPolicy).analytics;
if (canonicalStrategyJson(envelope.analytics) !== canonicalStrategyJson(analytics)) {

View file

@ -1,14 +1,21 @@
import { createHash } from 'node:crypto';
import type { StrategyProgram } from '../contracts/canonical-strategy';
import type { StrategyReplayResult } from '../contracts/strategy-replay';
import {
createBuiltinStrategy,
validateBuiltinStrategyBindings,
} from '../strategies/canonical-builtins';
import { freeze } from '../strategies/strategy-decision';
import {
importRetainedProgram,
verifyRetainedProgramPackage,
} from '../strategies/retained-program';
import { IsolatedCandidateController } from './candidate-sandbox';
import { verifyCanonicalWorkerBuild } from './canonical-build';
import { buildCanonicalBacktestReport } from './canonical-result';
import { executeReplayTrace, prepareReplayLoad } from './native-replay';
import {
executeReplayTrace,
NativeReplaySession,
prepareReplayLoad,
runReplaySessionAsync,
} from './native-replay';
import {
nativeWorkerRequestSchema,
type NativeWorkerMessage,
@ -34,17 +41,7 @@ process.once('message', async (input: unknown) => {
const admitted = request.request;
// Identity checks precede bundle import, including any top-level module side effects.
const build = await verifyCanonicalWorkerBuild(admitted.build, import.meta.url);
const pkg = admitted.strategy.package;
const hash = (content: string) => createHash('sha256').update(content, 'utf8').digest('hex');
if (
hash(pkg.artifact.content) !== pkg.artifact.sha256 ||
hash(pkg.dependencyLock.content) !== pkg.dependencyLock.sha256
) {
throw new Error('Retained strategy artifact or dependency lock hash mismatch');
}
if (pkg.program.apiVersion !== 'canonical-ts/v1') {
throw new Error('Unsupported retained strategy API version');
}
const pkg = verifyRetainedProgramPackage(admitted.strategy.package);
const load = prepareReplayLoad(request.dataset, admitted.policy);
if (
load.identity.datasetHash !== admitted.datasetHash ||
@ -53,50 +50,48 @@ process.once('message', async (input: unknown) => {
) {
throw new Error('Retained strategy requires its exact eligible single-series dataset');
}
const selection = admitted.strategy.selection;
validateBuiltinStrategyBindings([selection], load);
// Only server-admitted built-ins reach this trusted worker path. Candidate
// execution requires separate isolation; import is never performed by an API.
// Bun's data-URL loader rejects real bundle-sized specifiers. A Blob keeps
// these exact UTF-8 bytes in memory without temporary files surviving SIGKILL.
const moduleUrl = URL.createObjectURL(
new Blob([pkg.artifact.content], { type: 'text/javascript' })
);
let module: Record<string, unknown>;
try {
module = await import(moduleUrl);
} finally {
URL.revokeObjectURL(moduleUrl);
}
const factory = module[pkg.artifact.entryExport];
if (typeof factory !== 'function') {
throw new Error('Retained strategy factory export is missing');
}
const program = factory(freeze(structuredClone(selection))) as StrategyProgram;
if (
!program ||
typeof program !== 'object' ||
program.ownerId !== selection.ownerId ||
program.strategyId !== selection.strategyId ||
program.strategyVersion !== selection.strategyVersion ||
program.seed !== selection.seed ||
program.mode !== 'target' ||
typeof program.decide !== 'function'
) {
throw new Error('Retained strategy factory identity or API mismatch');
}
await send({
type: 'progress',
progress: 0,
message: 'Retained canonical strategy replay started',
});
const { result } = runStrategyReplay(load, [program], { resultFormat: 'report' });
let result;
if (admitted.strategy.origin === 'candidate') {
if (!request.candidateContainerName) {
throw new Error('Isolated candidate lacks its owned container identity');
}
const controller = await IsolatedCandidateController.start(
admitted,
request.candidateContainerName,
request.executionDeadlineAt
);
try {
result = (
await runReplaySessionAsync(new NativeReplaySession(load), controller, {
resultFormat: 'report',
})
).result;
await controller.finish();
} finally {
await controller.dispose();
}
} else {
validateBuiltinStrategyBindings([admitted.strategy.selection], load);
const program = await importRetainedProgram(pkg, admitted.strategy.selection);
result = runStrategyReplay(load, [program], { resultFormat: 'report' }).result;
}
if (!('format' in result) || result.format !== 'report') {
throw new Error('Retained replay requires the canonical report format');
}
const report = buildCanonicalBacktestReport(result, admitted.analyticsPolicy);
const envelope: RetainedStrategyResult = {
type: 'retainedStrategyResult',
version: 1,
build,
artifactHash: pkg.artifact.sha256,
...(admitted.strategy.origin === 'candidate'
? { execution: admitted.strategy.execution }
: {}),
financial: report.financial,
analytics: report.analytics,
};

View file

@ -0,0 +1,218 @@
//! Minimal Linux x86_64 PID1. This executable contains no strategy/data logic.
use std::{
os::{fd::FromRawFd, unix::process::CommandExt},
process::{Command, Stdio},
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
#[repr(C)]
struct Filter {
code: u16,
jt: u8,
jf: u8,
k: u32,
}
#[repr(C)]
struct Program {
len: u16,
filter: *const Filter,
}
#[repr(C)]
struct PollFd {
fd: i32,
events: i16,
revents: i16,
}
#[repr(C)]
struct Limit {
current: u64,
maximum: u64,
}
unsafe extern "C" {
fn prctl(option: i32, ...) -> i32;
fn setgid(gid: u32) -> i32;
fn setuid(uid: u32) -> i32;
fn setgroups(size: usize, list: *const u32) -> i32;
fn setrlimit(resource: i32, limit: *const Limit) -> i32;
fn poll(fds: *mut PollFd, nfds: usize, timeout: i32) -> i32;
fn kill(pid: i32, signal: i32) -> i32;
}
fn stmt(code: u16, k: u32) -> Filter {
Filter {
code,
jt: 0,
jf: 0,
k,
}
}
fn equal(k: u32, jt: u8, jf: u8) -> Filter {
Filter {
code: 0x15,
jt,
jf,
k,
}
}
fn error() -> std::io::Error {
std::io::Error::last_os_error()
}
fn main() {
if !cfg!(all(target_os = "linux", target_arch = "x86_64")) {
std::process::exit(126);
}
let deadline: u128 = std::env::args()
.nth(1)
.and_then(|s| s.parse().ok())
.unwrap_or(0);
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system clock")
.as_millis();
if deadline <= now || deadline - now > 300_000 {
std::process::exit(124);
}
let remaining = Duration::from_millis((deadline - now) as u64);
let clock = Instant::now();
let mut command = Command::new("/usr/bin/bun");
command
.arg("/app/candidate-host.js")
.current_dir("/tmp")
.env_clear()
.stdin(Stdio::inherit())
.stdout(Stdio::piped())
.stderr(Stdio::inherit());
unsafe {
command.pre_exec(|| {
if setgroups(0, std::ptr::null()) != 0 || setgid(65534) != 0 || setuid(65534) != 0 {
return Err(error());
}
if setrlimit(
0,
&Limit {
current: 300,
maximum: 300,
},
) != 0
|| setrlimit(
4,
&Limit {
current: 0,
maximum: 0,
},
) != 0
{
return Err(error());
}
if prctl(38, 1, 0, 0, 0) != 0 {
return Err(error());
}
// Check architecture and reject x32 syscall-number aliases before any allow rule.
let mut filter = vec![
stmt(0x20, 4),
equal(0xc000003e, 1, 0),
stmt(0x06, 0x80000000),
stmt(0x20, 0),
Filter {
code: 0x35,
jt: 0,
jf: 1,
k: 0x40000000,
},
stmt(0x06, 0x00050001),
];
// fork, vfork, socket, ptrace, mount, umount2, unshare, setns, bpf, perf_event_open.
for nr in [57, 58, 41, 101, 165, 166, 272, 308, 321, 298] {
filter.push(equal(nr, 0, 1));
filter.push(stmt(0x06, 0x00050001));
}
// clone3 cannot inspect the pointed-to flags; make libc use checked clone instead.
filter.push(equal(435, 0, 1));
filter.push(stmt(0x06, 0x00050026));
filter.push(equal(56, 0, 4));
filter.push(stmt(0x20, 16));
filter.push(Filter {
code: 0x45,
jt: 0,
jf: 1,
k: 0x00010000,
});
filter.push(stmt(0x06, 0x7fff0000));
filter.push(stmt(0x06, 0x00050001));
filter.push(stmt(0x06, 0x7fff0000));
let program = Program {
len: filter.len() as u16,
filter: filter.as_ptr(),
};
if prctl(22, 2, &program as *const Program) != 0 {
return Err(error());
}
Ok(())
});
}
let mut child = command
.spawn()
.expect("restricted host initialization failed");
let mut output = child.stdout.take().expect("restricted host stdout missing");
let output_closed = Arc::new(AtomicBool::new(false));
let relay_closed = Arc::clone(&output_closed);
// A bounded std::io::copy buffer relays bytes only. A separate watchdog remains
// responsive even if the child floods stdout or the consumer stops reading.
// Direct File writes avoid line-buffering the binary protocol.
std::thread::spawn(move || {
let mut destination = unsafe { std::fs::File::from_raw_fd(1) };
let _ = std::io::copy(&mut output, &mut destination);
relay_closed.store(true, Ordering::Release);
});
let mut exit_status = None;
let mut stdout_closed_at = None;
loop {
if exit_status.is_none() {
if let Some(status) = child.try_wait().expect("restricted host wait failed") {
exit_status = Some(status.code().unwrap_or(125));
}
}
if output_closed.load(Ordering::Acquire) {
if let Some(code) = exit_status {
// Drain the complete final frame before ending a normal finish/transpile.
std::process::exit(code);
}
stdout_closed_at.get_or_insert_with(Instant::now);
}
// EOF can precede the child's normal exit by a few scheduler turns.
let protocol_closed =
stdout_closed_at.is_some_and(|at| at.elapsed() >= Duration::from_millis(100));
let mut input = PollFd {
fd: 0,
events: 0,
revents: 0,
};
let ready = unsafe { poll(&mut input, 1, 0) };
let disconnected = ready < 0 || input.revents & (0x10 | 0x08 | 0x20) != 0;
if disconnected || protocol_closed || clock.elapsed() >= remaining {
unsafe {
kill(child.id() as i32, 9);
}
let _ = child.wait();
eprintln!(
"Candidate host {}",
if disconnected {
"supervisor disconnected"
} else if protocol_closed {
"protocol stdout closed"
} else {
"wall deadline exceeded"
}
);
// Exiting namespace PID1 kills remaining threads/processes independently of JS.
std::process::exit(if disconnected || protocol_closed {
125
} else {
124
});
}
std::thread::sleep(Duration::from_millis(10));
}
}