stock-bot/apps/stock/orchestrator/src/backtest/candidate-protocol.ts
Boki 4cd6038063 refactor: pre-M0 cleanup, core library hardening, and isolated dev/QA Docker stack
- 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
2026-11-27 00:11:50 -05:00

89 lines
3.5 KiB
TypeScript

/** 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 '@stock-bot/stock-config/canonical-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');
}
}