stock-bot/apps/stock/orchestrator/src/backtest/native-worker-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

98 lines
3.7 KiB
TypeScript

import { z } from 'zod';
import {
candidateExecutionSchema,
type CandidateExecution,
} from '@stock-bot/stock-config/candidate-execution';
import {
canonicalBuildIdentitySchema,
canonicalRunRequestSchema,
parseCanonicalFinancialResult,
type CanonicalBuildIdentity,
type CanonicalRunRequest,
} from '@stock-bot/stock-config/canonical-research';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import type { CanonicalBacktestAnalytics } from '@stock-bot/types';
import { replayTraceSchema } from '@stock-bot/stock-config/canonical-replay';
import type { ReplayReportResult } from '@stock-bot/stock-config/canonical-replay';
import { strategyReplayRequestSchema } from '../contracts/strategy-replay';
import { buildCanonicalBacktestReport } from '@stock-bot/research/results';
const finite = z.number().finite();
export const retainedStrategyRequestSchema = z
.object({
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();
export const nativeWorkerRequestSchema = z.union([
replayTraceSchema,
strategyReplayRequestSchema,
retainedStrategyRequestSchema,
]);
export interface RetainedStrategyResult {
type: 'retainedStrategyResult';
version: 1;
build: CanonicalBuildIdentity;
artifactHash: string;
execution?: CandidateExecution;
financial: ReplayReportResult;
analytics: CanonicalBacktestAnalytics;
}
const retainedStrategyResultSchema = z
.object({
type: z.literal('retainedStrategyResult'),
version: z.literal(1),
build: canonicalBuildIdentitySchema,
artifactHash: z.string().regex(/^[a-f0-9]{64}$/),
execution: candidateExecutionSchema.optional(),
financial: z.unknown(),
analytics: z.unknown(),
})
.strict();
/** Financial facts are validated, never recalculated. F08 alone owns statistical reporting. */
export function parseRetainedStrategyResult(
input: string,
request: CanonicalRunRequest
): RetainedStrategyResult {
const envelope = retainedStrategyResultSchema.parse(JSON.parse(input));
if (
canonicalStrategyJson(envelope.build) !== canonicalStrategyJson(request.build) ||
envelope.artifactHash !== request.strategy.package.artifact.sha256
) {
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)) {
throw new Error('Retained strategy result analytics do not match the frozen policy');
}
return { ...envelope, financial, analytics };
}
export const nativeWorkerMessageSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('progress'), progress: finite.min(0).max(100), message: z.string() }),
z.object({ type: z.literal('result'), result: z.string() }),
z.object({ type: z.literal('error'), message: z.string() }),
]);
export type NativeWorkerRequest = z.input<typeof nativeWorkerRequestSchema>;
export type RetainedStrategyRequest = z.input<typeof retainedStrategyRequestSchema>;
export type NativeWorkerMessage = z.infer<typeof nativeWorkerMessageSchema>;