refactor(runtime): expose shared admission and artifact boundaries (CL26)

This commit is contained in:
Boki 2026-10-28 14:02:03 -04:00
parent 2165a2efa8
commit b4589d5af1
49 changed files with 1790 additions and 1565 deletions

View file

@ -92,12 +92,12 @@ export class NativeBacktestWorker {
retainedRequest &&
this.workerUrl &&
realpathSync(fileURLToPath(this.workerUrl)) !==
realpathSync(fileURLToPath(canonicalWorkerUrl))
realpathSync(fileURLToPath(canonicalWorkerUrl()))
) {
throw new Error('Retained strategy execution requires the canonical bundled worker');
}
const workerUrl = retainedRequest
? canonicalWorkerUrl
? canonicalWorkerUrl()
: (this.workerUrl ??
new URL(
import.meta.url.endsWith('.ts') ? './native-worker.ts' : './native-worker.js',

View file

@ -1,18 +1,21 @@
/** 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 { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
import { mkdtemp, 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 { join } from 'node:path';
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 {
daemon,
docker,
dockerRead,
environment,
readCandidateExecution,
verifyCandidateExecution,
} from '@stock-bot/trading-runtime/candidate-environment';
import { parseFinancialStrategyDecision } from '@stock-bot/types';
import type { ReplaySubmissionOutcome } from '../contracts/native-replay';
import {
@ -28,100 +31,13 @@ import type {
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';
}
export {
candidateDescriptorPath,
CandidateSandboxUnavailable,
readCandidateExecution,
verifyCandidateExecution,
} from '@stock-bot/trading-runtime/candidate-environment';
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');

View file

@ -1,79 +1,2 @@
/** Read-only build identity. This module never imports the native addon or strategy code. */
import { createHash } from 'node:crypto';
import { realpathSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { dirname, isAbsolute, relative, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import {
canonicalBuildIdentitySchema,
type CanonicalBuildIdentity,
} from '@stock-bot/stock-config/canonical-research';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
const engineWrapper = realpathSync(fileURLToPath(import.meta.resolve('@stock-bot/engine')));
const repositoryRoot = resolve(dirname(engineWrapper), '../../..');
const ownPath = relative(repositoryRoot, realpathSync(fileURLToPath(import.meta.url)));
if (isAbsolute(ownPath) || ownPath === '..' || ownPath.startsWith('../')) {
throw new Error('Canonical engine resolves outside this checkout');
}
if (engineWrapper !== resolve(repositoryRoot, 'apps/stock/engine/index.mjs')) {
throw new Error('Unsupported canonical engine wrapper location');
}
export const canonicalWorkerUrl = pathToFileURL(
resolve(repositoryRoot, 'apps/stock/orchestrator/dist/native-worker.js')
);
async function hashLocalFile(path: string): Promise<string> {
if (realpathSync(path) !== path) {
throw new Error('Canonical build artifacts must belong to this checkout');
}
return createHash('sha256')
.update(await readFile(path))
.digest('hex');
}
/** Capture all executable worker/native bytes and the runtime that interprets them. */
export async function readCanonicalBuildIdentity(): Promise<CanonicalBuildIdentity> {
if (typeof Bun === 'undefined') {
throw new Error('Canonical research requires the Bun runtime');
}
const [workerSha256, engineWrapperSha256, engineBinarySha256, dependencyLockSha256] =
await Promise.all([
hashLocalFile(fileURLToPath(canonicalWorkerUrl)),
hashLocalFile(engineWrapper),
hashLocalFile(resolve(repositoryRoot, 'apps/stock/engine/dist/engine.node')),
hashLocalFile(resolve(repositoryRoot, 'bun.lock')),
]);
return canonicalBuildIdentitySchema.parse({
version: 1,
workerSha256,
engineWrapperSha256,
engineBinarySha256,
dependencyLockSha256,
runtime: 'bun',
runtimeVersion: Bun.version,
platform: process.platform,
arch: process.arch,
});
}
/** The running child supplies its own module URL, never a URL from the request. */
export async function verifyCanonicalWorkerBuild(
expected: CanonicalBuildIdentity,
actualWorkerUrl: string
): Promise<CanonicalBuildIdentity> {
if (
realpathSync(fileURLToPath(actualWorkerUrl)) !== realpathSync(fileURLToPath(canonicalWorkerUrl))
) {
throw new Error('Canonical research requires the bundled worker from this checkout');
}
const actual = await readCanonicalBuildIdentity();
if (
canonicalStrategyJson(actual) !==
canonicalStrategyJson(canonicalBuildIdentitySchema.parse(expected))
) {
throw new Error('Canonical worker/native/runtime build identity mismatch');
}
return actual;
}
/** Shared read-only artifact inspection. */
export * from '@stock-bot/trading-runtime/canonical-build';