- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched) - Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations() - Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation - Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims - Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution - Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
383 lines
13 KiB
TypeScript
383 lines
13 KiB
TypeScript
/** Trusted launcher. Candidate code is never imported in this process. */
|
|
import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
|
|
import { mkdtemp, rm } from 'node:fs/promises';
|
|
import { tmpdir } from 'node:os';
|
|
import { join } from 'node:path';
|
|
import {
|
|
candidateSandboxLimits,
|
|
type CandidateExecution,
|
|
} from '@stock-bot/stock-config/candidate-execution';
|
|
import type { CanonicalRunRequest } from '@stock-bot/stock-config/canonical-research';
|
|
import {
|
|
daemon,
|
|
docker,
|
|
dockerRead,
|
|
environment,
|
|
readCandidateExecution,
|
|
verifyCandidateExecution,
|
|
} from '@stock-bot/trading-runtime/candidate-environment';
|
|
import { parseFinancialStrategyDecision } from '@stock-bot/types';
|
|
import type { ReplaySubmissionOutcome } from '@stock-bot/stock-config/canonical-replay';
|
|
import {
|
|
candidateResponseSchema,
|
|
readCandidateFrames,
|
|
writeCandidateFrame,
|
|
type CandidateResponse,
|
|
} from './candidate-protocol';
|
|
import type {
|
|
AsyncReplayController,
|
|
DecisionContext,
|
|
PublishedObservation,
|
|
ReplayIdentity,
|
|
} from './native-replay';
|
|
|
|
export {
|
|
candidateDescriptorPath,
|
|
CandidateSandboxUnavailable,
|
|
readCandidateExecution,
|
|
verifyCandidateExecution,
|
|
} from '@stock-bot/trading-runtime/candidate-environment';
|
|
|
|
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' }>;
|
|
};
|