diff --git a/apps/stock/config/src/schemas/stock-app.schema.ts b/apps/stock/config/src/schemas/stock-app.schema.ts index cd187800..274522fa 100644 --- a/apps/stock/config/src/schemas/stock-app.schema.ts +++ b/apps/stock/config/src/schemas/stock-app.schema.ts @@ -87,6 +87,8 @@ export const stockAppSchema = baseAppSchema.extend({ port: z.number().default(3002), defaultMode: z.enum(['backtest', 'paper', 'live']).default('paper'), paperTradingCapital: z.number().default(100000), + // Validated by the orchestrator's canonical contract before opening resources. + canonicalPaper: z.record(z.unknown()).optional(), enableWebSocket: z.boolean().default(true), backtesting: z .object({ diff --git a/apps/stock/orchestrator/src/api/rest/paper.ts b/apps/stock/orchestrator/src/api/rest/paper.ts new file mode 100644 index 00000000..7ff6d8bb --- /dev/null +++ b/apps/stock/orchestrator/src/api/rest/paper.ts @@ -0,0 +1,104 @@ +import { Hono } from 'hono'; +import { z } from 'zod'; +import { getVerifiedHttpPrincipal } from '@stock-bot/di'; +import { + paperActivationSchema, + paperConnectionSchema, + paperFrameSchema, + paperHaltSchema, + PaperRuntimeError, + type PaperReadiness, +} from '../../contracts/paper-runtime'; +import { ExecutionConflictError } from '../../execution/repository'; +import type { OrchestratorServices } from '../../types'; + +export function createPaperRoutes(services: OrchestratorServices): Hono { + const app = new Hono(); + const runtime = () => { + const value = services.custom?.CanonicalPaperRuntime; + if (!value) { + throw new PaperRuntimeError('not-ready', 'Canonical paper execution is not configured'); + } + return value; + }; + app.use('*', async (c, next) => { + c.header('Cache-Control', 'no-store'); + if (c.req.method !== 'GET') { + const principal = getVerifiedHttpPrincipal(c.req.raw); + const feed = c.req.path.includes('/feed/'); + if (principal !== 'operator' && !(feed && principal === 'service')) { + return c.json( + { error: feed ? 'Verified feed producer required' : 'Human operator required' }, + 403 + ); + } + } + await next(); + return undefined; + }); + app.onError((error, c) => { + if (error instanceof z.ZodError || error instanceof SyntaxError) { + return c.json({ error: 'Invalid paper request' }, 400); + } + if (error instanceof PaperRuntimeError) { + return c.json( + { error: error.message, code: error.kind }, + error.kind === 'invalid-input' ? 400 : 409 + ); + } + if (error instanceof ExecutionConflictError) { + return c.json({ error: error.message, code: 'conflict' }, 409); + } + services.logger.error('Canonical paper request failed', { error }); + return c.json({ error: 'Canonical paper runtime unavailable' }, 503); + }); + app.get('/readiness', async c => { + if (!services.custom?.CanonicalPaperRuntime) { + const unavailable: PaperReadiness = { + configured: false, + accountId: null, + sourceId: null, + active: false, + ready: false, + operatorHalted: true, + connected: false, + reasons: ['not-configured'], + lastReceivedAt: null, + lastAvailableAt: null, + requiresHistoricalRecovery: false, + pendingInput: null, + pendingBatch: null, + pendingDecisionSequence: null, + nativeStatus: null, + risk: null, + }; + return c.json(unavailable); + } + return c.json(await runtime().status()); + }); + app.post('/activate', async c => + c.json(await runtime().activate(paperActivationSchema.parse(await c.req.json()))) + ); + app.post('/halt', async c => + c.json(await runtime().halt(paperHaltSchema.parse(await c.req.json()).reason)) + ); + app.post('/feed/connect', async c => + c.json(await runtime().connect(paperConnectionSchema.parse(await c.req.json()))) + ); + app.post('/feed/disconnect', async c => + c.json(await runtime().disconnect(paperConnectionSchema.parse(await c.req.json()))) + ); + app.post('/feed/frames', async c => { + const input: unknown = await c.req.json(); + let frame; + try { + frame = paperFrameSchema.parse(input); + } catch { + // Decimal transforms can throw ordinary errors. Classify only input + // parsing here; storage/native failures must still surface as unavailable. + throw new PaperRuntimeError('invalid-input', 'Invalid paper frame'); + } + return c.json(await runtime().ingest(frame)); + }); + return app; +} diff --git a/apps/stock/orchestrator/src/container.ts b/apps/stock/orchestrator/src/container.ts index 2cba0c0f..5537faef 100644 --- a/apps/stock/orchestrator/src/container.ts +++ b/apps/stock/orchestrator/src/container.ts @@ -6,14 +6,19 @@ import type { BacktestExecutionEngine } from './backtest/execution-engine'; import { PostgresBacktestRunRepository } from './backtest/PostgresBacktestRunRepository'; import { UnavailableBacktestRunRepository } from './backtest/run-repository'; import { RustBacktestAdapter } from './backtest/RustBacktestAdapter'; +import type { PaperConfigurationInput, PaperRuntime } from './contracts/paper-runtime'; import { ModeManager } from './core/ModeManager'; +import { PostgresCanonicalExecutionRepository } from './execution/PostgresCanonicalExecutionRepository'; import { BacktestHandler } from './handlers/backtest/backtest.handler'; +import { CanonicalPaperRuntime } from './paper/CanonicalPaperRuntime'; +import { validatePaperConfiguration } from './paper/feed'; import { PaperTradingManager } from './paper/PaperTradingManager'; import { AnalyticsService } from './services/AnalyticsService'; import { ExecutionService } from './services/ExecutionService'; import { MarketDataService } from './services/MarketDataService'; import { StorageService } from './services/StorageService'; import { createBuiltinStrategyRegistry } from './strategies/builtin-strategies'; +import { createBuiltinStrategy } from './strategies/canonical-sma'; import { StrategyManager } from './strategies/StrategyManager'; import type { StrategyRegistry } from './strategies/StrategyRegistry'; import type { OrchestratorServices as IServiceContainer } from './types'; @@ -47,11 +52,20 @@ export async function registerOrchestratorServices( syntheticSeed?: number; nativeExecutionTimeoutMs?: number; strategyRegistry?: StrategyRegistry; + canonicalPaper?: PaperConfigurationInput; + paperTradingCapital?: number; } = {} ): Promise { const role = options.role === undefined ? 'paper' : options.role; const useRustEngine = options.useRustEngine === undefined ? true : options.useRustEngine; assertSupportedComposition(role, useRustEngine); + if (options.canonicalPaper !== undefined && role !== 'paper') { + throw new Error('Canonical paper configuration requires a paper composition'); + } + const canonicalPaper = + options.canonicalPaper === undefined + ? undefined + : validatePaperConfiguration(options.canonicalPaper); const allowedMode = role === 'research-only' ? 'backtest' : 'paper'; // Create a service adapter that provides the expected interface @@ -60,6 +74,24 @@ export async function registerOrchestratorServices( if (!services.custom) { Object.defineProperty(services, 'custom', { value: custom, enumerable: true }); } + if ( + custom.CanonicalPaperRuntime || + container.hasRegistration('CanonicalPaperRuntime') || + (canonicalPaper && + ( + [ + 'ModeManager', + 'ExecutionService', + 'MarketDataService', + 'StrategyManager', + 'PaperTradingManager', + 'BacktestEngine', + 'BacktestRunner', + ] as const + ).some(key => custom[key] || container.hasRegistration(key))) + ) { + throw new Error('Canonical paper requires a fresh runtime composition'); + } // Create storage service first as it's needed by other services const storageService = new StorageService( @@ -70,6 +102,67 @@ export async function registerOrchestratorServices( options ); + if (canonicalPaper) { + if (!services.postgres) { + throw new Error('Canonical paper requires durable PostgreSQL custody'); + } + const paper = new CanonicalPaperRuntime({ + repository: new PostgresCanonicalExecutionRepository(services.postgres), + programs: canonicalPaper.strategies.map(createBuiltinStrategy), + }); + const engine = new RustBacktestAdapter( + { logger: services.logger, storage: storageService }, + { timeoutMs: options.nativeExecutionTimeoutMs } + ); + const runner = new BacktestRunner({ + engine, + engineName: 'native', + repository: new PostgresBacktestRunRepository(services.postgres), + logger: services.logger, + }); + const analytics = new AnalyticsService(services); + // No legacy order gateway, feed listener or mode initializer is exposed in + // this composition. Research still runs in the existing isolated worker. + Object.assign(custom, { + StorageService: storageService, + AnalyticsService: analytics, + CanonicalPaperRuntime: paper, + BacktestEngine: engine, + BacktestRunner: runner, + }); + const canonicalContainer = container as AwilixContainer< + ServiceDefinitions & { + StorageService: StorageService; + AnalyticsService: AnalyticsService; + CanonicalPaperRuntime: PaperRuntime; + BacktestEngine: BacktestExecutionEngine; + BacktestRunner: BacktestRunner; + orchestratorServices: IServiceContainer; + } + >; + canonicalContainer.register({ + StorageService: asValue(storageService), + AnalyticsService: asValue(analytics), + CanonicalPaperRuntime: asValue(paper), + BacktestEngine: asValue(engine), + BacktestRunner: asValue(runner), + orchestratorServices: asValue(services), + }); + container + .resolve('handlerScanner') + .registerHandlerClass(BacktestHandler, { serviceName: 'orchestrator' }); + try { + if (options.initializeMode !== false) { + await paper.initialize(canonicalPaper); + } + services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: 1 }); + } catch (error) { + await paper.shutdown().catch(() => {}); + throw error; + } + return; + } + // Callbacks are invoked after composition: the feed drains the manager, and // factories receive the current mode without either service locating its peers. const marketDataService: MarketDataService = new MarketDataService({ @@ -174,7 +267,10 @@ export async function registerOrchestratorServices( // Initialize mode manager with default paper trading mode if (role === 'paper' && options.initializeMode !== false) { - await modeManager.initializeMode({ mode: 'paper', startingCapital: 100000 }); + await modeManager.initializeMode({ + mode: 'paper', + startingCapital: options.paperTradingCapital ?? 100000, + }); } // Start job consumption only after the shared graph and initial mode are ready. services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: 1 }); diff --git a/apps/stock/orchestrator/src/contracts/paper-runtime.ts b/apps/stock/orchestrator/src/contracts/paper-runtime.ts new file mode 100644 index 00000000..ff3a36f7 --- /dev/null +++ b/apps/stock/orchestrator/src/contracts/paper-runtime.ts @@ -0,0 +1,146 @@ +/** Explicit trusted producer boundary. No legacy timestamp repair or broker capabilities. */ +import { z } from 'zod'; +import { parseFinancialDecimal } from '@stock-bot/types'; +import { builtinStrategySelectionSchema } from './builtin-strategy'; +import { canonicalMatchingConfigSchema, matchingCommandSchema } from './canonical-execution'; +import { replayConfigSchema, stepSchema } from './native-replay'; + +const id = matchingCommandSchema.shape.key.shape.instrumentId; +const time = matchingCommandSchema.shape.key.shape.at; +const counter = matchingCommandSchema.shape.key.shape.sourceSequence; +const duration = counter.refine(value => value > 0, 'Duration must be positive'); +const decimal = z.string().transform(value => parseFinancialDecimal(value)); + +export const paperPolicySchema = z + .object({ + version: z.literal(1), + sourceId: id, + priceBasis: z.literal('raw'), + maxFeedAgeMs: duration, + observations: z.array( + z + .object({ + seriesId: id, + instrumentId: id, + intervalMs: duration, + staleAfterMs: counter, + }) + .strict() + ), + cadence: z.array(z.object({ ownerId: id, seriesIds: z.array(id).min(1) }).strict()), + calendars: z + .array( + z + .object({ + instrumentId: id, + calendarId: id, + revision: id, + sessions: z + .array(z.object({ sessionId: id, opensAt: time, closesAt: time }).strict()) + .min(1), + }) + .strict() + ) + .min(1), + riskBoundaries: z.array( + replayConfigSchema.shape.matching.shape.risk.shape.ledger.shape.riskSession + ), + }) + .strict(); + +export const paperConfigurationSchema = z + .object({ + version: z.literal(1), + matching: canonicalMatchingConfigSchema, + strategies: z.array(builtinStrategySelectionSchema).min(1), + policy: paperPolicySchema, + }) + .strict(); + +/** availableAt is the producer's atomic release time for the whole quote frame. + * Quotes retain their original physical timestamp and source sequence. The + * supplied completed bars were available by this release; quotes never synthesize bars. */ +export const paperFrameSchema = z + .object({ + version: z.literal(1), + sourceId: id, + connectionId: id, + id, + sequence: counter, + availableAt: time, + quotes: z + .array( + z + .object({ + instrumentId: id, + seriesId: id, + observedAt: time, + sourceSequence: counter, + bid: decimal, + ask: decimal, + bidSize: decimal, + askSize: decimal, + }) + .strict() + ) + .min(1), + observations: z.array(stepSchema.shape.observations.element), + }) + .strict(); + +export const paperConnectionSchema = z.object({ sourceId: id, connectionId: id }).strict(); +export const paperActivationSchema = z + .object({ recoverPending: z.boolean().default(false) }) + .strict(); +export const paperHaltSchema = z.object({ reason: z.string().trim().min(1) }).strict(); + +export type PaperConfigurationInput = z.input; +export type PaperConfiguration = z.output; +export type PaperPolicy = z.output; +export type PaperFrameInput = z.input; +export type PaperFrame = z.output; +export type PaperConnection = z.infer; + +export class PaperRuntimeError extends Error { + constructor( + readonly kind: 'invalid-input' | 'not-ready' | 'conflict', + message: string + ) { + super(message); + this.name = 'PaperRuntimeError'; + } +} + +export interface PaperReadiness { + configured: boolean; + accountId: string | null; + sourceId: string | null; + active: boolean; + ready: boolean; + operatorHalted: boolean; + connected: boolean; + reasons: string[]; + lastReceivedAt: number | null; + lastAvailableAt: number | null; + requiresHistoricalRecovery: boolean; + pendingInput: string | null; + pendingBatch: string | null; + pendingDecisionSequence: number | null; + nativeStatus: 'Running' | 'Complete' | { Failed: { diagnostic: string } } | null; + risk: { dailyHalted: boolean; drawdownHalted: boolean } | null; +} + +export interface PaperRuntime { + initialize(configuration: PaperConfigurationInput): Promise; + connect(connection: PaperConnection): Promise; + ingest(frame: PaperFrameInput): Promise<{ + duplicate: boolean; + disposition: 'health-only' | 'admitted'; + readiness: PaperReadiness; + }>; + disconnect(connection: PaperConnection): Promise; + activate(options: { recoverPending: boolean }): Promise; + halt(reason: string): Promise; + status(): Promise; + shutdown(): Promise; +} diff --git a/apps/stock/orchestrator/src/execution/CanonicalPaperExecution.ts b/apps/stock/orchestrator/src/execution/CanonicalPaperExecution.ts index 3fedce0b..8f0690b3 100644 --- a/apps/stock/orchestrator/src/execution/CanonicalPaperExecution.ts +++ b/apps/stock/orchestrator/src/execution/CanonicalPaperExecution.ts @@ -27,6 +27,7 @@ import { type CanonicalExecutionRepository, type CanonicalJournalEntry, type CanonicalOwner, + type CanonicalPaperHost, type CanonicalPaperInput, type CanonicalTransaction, } from './canonical-paper'; @@ -65,6 +66,8 @@ export class CanonicalPaperExecution { programs: readonly StrategyProgram[]; /** Best effort after SQL commit. Recover missed notifications using journal(sequence). */ publish?: (entries: readonly CanonicalJournalEntry[]) => void | Promise; + /** Only the trusted paper runtime owns this generation and operational gate. */ + control?: { generation: string; guard(account: CanonicalAccount): boolean }; } ) { this.programs = new Map(); @@ -95,12 +98,14 @@ export class CanonicalPaperExecution { pendingObservations: [], }; }) - .sort((a, b) => (a.definition.ownerId < b.definition.ownerId ? -1 : 1)); + .sort((a, b) => + Buffer.compare(Buffer.from(a.definition.ownerId), Buffer.from(b.definition.ownerId)) + ); // Program closures are trusted code. Metadata and state are detached now, before any await. freeze(this.initialOwners); } - initialize(configuration: CanonicalMatchingConfig): Promise { + initialize(configuration: CanonicalMatchingConfig, host?: CanonicalPaperHost): Promise { outsideCallback(); const config = canonicalMatchingConfigSchema.parse(configuration); const identity = { @@ -131,6 +136,7 @@ export class CanonicalPaperExecution { observed: 0, pendingDecisionSequence: null, latestObservations: [], + ...(host ? { host } : {}), }; return this.options.repository.initialize(initial, this.initialOwners).then(() => { this.identity = identity; @@ -149,6 +155,49 @@ export class CanonicalPaperExecution { enqueue(value: CanonicalPaperInput): Promise { outsideCallback(); const id = this.accountId(); + return this.options.repository.transact(id, async tx => { + if (tx.account.host) { + throw new ExecutionConflictError( + 'Controlled paper accounts accept only atomic producer frames' + ); + } + return this.enqueueInput(tx, value); + }); + } + + /** The runtime calls this while holding the account lock for the whole frame. */ + async enqueueFrame( + tx: CanonicalTransaction, + inputs: readonly CanonicalPaperInput[] + ): Promise { + outsideCallback(); + if ( + tx.account.identity.accountId !== this.accountId() || + !tx.account.host || + !this.allowed(tx.account) + ) { + throw new ExecutionConflictError('Paper frame admission requires an active owned runtime'); + } + for (const input of inputs) { + await this.enqueueInput(tx, input); + } + } + + private allowed(account: CanonicalAccount): boolean { + if (!account.host) { + return true; + } + const control = this.options.control; + if (!control || account.host.generation !== control.generation) { + throw new ExecutionConflictError('Canonical paper runtime generation is obsolete'); + } + return control.guard(account) && account.host.active && !account.host.operatorHalted; + } + + private async enqueueInput( + tx: CanonicalTransaction, + value: CanonicalPaperInput + ): Promise { const input = canonicalPaperInputSchema.parse(value); if (input.command.body.kind === 'submit') { throw new Error('Strategy submissions require a durable all-owner decision batch'); @@ -182,30 +231,28 @@ export class CanonicalPaperExecution { throw new Error('Observation is unavailable at its admitted input time'); } const fingerprint = createHash('sha256').update(canonicalJson(input)).digest('hex'); - return this.options.repository.transact(id, async tx => { - const old = await tx.getInput(input.command.commandId); - if (old) { - if (old.fingerprint !== fingerprint) { - throw new ExecutionConflictError('Conflicting canonical market input identity'); - } - return false; + const old = await tx.getInput(input.command.commandId); + if (old) { + if (old.fingerprint !== fingerprint) { + throw new ExecutionConflictError('Conflicting canonical market input identity'); } - if (tx.account.checkpoint.status !== 'Running') { - throw new Error( - `Canonical account is terminal: ${diagnosticFailure(tx.account) ?? tx.account.checkpoint.status}` - ); - } - tx.account.inputSequence = increment(tx.account.inputSequence); - await tx.putInput({ - version: 1, - id: input.command.commandId, - sequence: tx.account.inputSequence, - fingerprint, - status: 'pending', - input, - }); - return true; + return false; + } + if (tx.account.checkpoint.status !== 'Running') { + throw new Error( + `Canonical account is terminal: ${diagnosticFailure(tx.account) ?? tx.account.checkpoint.status}` + ); + } + tx.account.inputSequence = increment(tx.account.inputSequence); + await tx.putInput({ + version: 1, + id: input.command.commandId, + sequence: tx.account.inputSequence, + fingerprint, + status: 'pending', + input, }); + return true; } private async persist( @@ -357,7 +404,8 @@ export class CanonicalPaperExecution { tx: CanonicalTransaction, input: NonNullable ): DecisionContext { - const series = tx.account.checkpoint.config.series; + const series = + tx.account.host?.configuration.policy.observations ?? tx.account.checkpoint.config.series; if ( input.inputs.length !== series.length || new Set(input.inputs.map(item => item.series_id)).size !== series.length || @@ -372,7 +420,10 @@ export class CanonicalPaperExecution { const expected = !latest ? 'Missing' : { - [input.key.at - latest.event_time > tx.account.checkpoint.config.risk.maxMarkAgeMs + [input.key.at - latest.event_time > + (tx.account.host?.configuration.policy.observations.find( + series => series.seriesId === item.series_id + )?.staleAfterMs ?? tx.account.checkpoint.config.risk.maxMarkAgeMs) ? 'Stale' : 'Fresh']: { event_time: latest.event_time, available_at: latest.available_at }, }; @@ -389,7 +440,9 @@ export class CanonicalPaperExecution { barrier_id: input.barrierId, at: input.key.at, revision: tx.account.view.admissionRevision, - owner_ids: [...input.ownerIds].sort(), + owner_ids: [...input.ownerIds].sort((a, b) => + Buffer.compare(Buffer.from(a), Buffer.from(b)) + ), observation_count: tx.account.observed, inputs: input.inputs, }, @@ -410,7 +463,10 @@ export class CanonicalPaperExecution { const observations = input.input.observations; for (const observation of observations) { if ( - !tx.account.checkpoint.config.series.some( + !( + tx.account.host?.configuration.policy.observations ?? + tx.account.checkpoint.config.series + ).some( series => series.seriesId === observation.series_id && series.instrumentId === observation.instrument_id @@ -461,6 +517,9 @@ export class CanonicalPaperExecution { return (async () => { for (;;) { const step = await this.options.repository.transact(id, async tx => { + if (!this.allowed(tx.account)) { + return { worked: false, entries: [], failure: undefined }; + } const failure = diagnosticFailure(tx.account); if (failure) { return { worked: false, entries: [], failure }; diff --git a/apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository.ts b/apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository.ts index c68b60dc..b639cd00 100644 --- a/apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository.ts +++ b/apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository.ts @@ -35,6 +35,44 @@ function accountState(raw: unknown): CanonicalAccount { ) { throw new ExecutionConflictError('Canonical envelope identity or revision mismatch'); } + if ( + account.host && + canonicalJson(account.host.configuration.matching) !== canonicalJson(account.checkpoint.config) + ) { + throw new ExecutionConflictError( + 'Canonical host configuration differs from financial configuration' + ); + } + if (account.host) { + const { configuration, connection, quotes, quoteHighWater } = account.host; + if ( + configuration.strategies.length !== account.definitions.length || + configuration.strategies.some( + selection => + !account.definitions.some( + definition => + definition.ownerId === selection.ownerId && + definition.strategyId === selection.strategyId && + definition.strategyVersion === selection.strategyVersion && + definition.seed === selection.seed && + definition.mode === 'target' + ) + ) || + (connection && connection.sourceId !== configuration.policy.sourceId) || + [quotes, quoteHighWater].some( + clocks => + new Set(clocks.map(quote => quote.instrumentId)).size !== clocks.length || + clocks.some( + quote => + !configuration.matching.series.some( + series => series.instrumentId === quote.instrumentId + ) + ) + ) + ) { + throw new ExecutionConflictError('Canonical host strategy or feed binding mismatch'); + } + } return account; } @@ -59,11 +97,13 @@ export class PostgresCanonicalExecutionRepository implements CanonicalExecutionR identity: account.identity, config: account.checkpoint.config, definitions: account.definitions, + hostConfiguration: account.host?.configuration ?? null, }) !== canonicalJson({ identity: expected.identity, config: expected.checkpoint.config, definitions: expected.definitions, + hostConfiguration: expected.host?.configuration ?? null, }) ) { throw new ExecutionConflictError( diff --git a/apps/stock/orchestrator/src/execution/canonical-paper.ts b/apps/stock/orchestrator/src/execution/canonical-paper.ts index 99ae1152..d095bf1c 100644 --- a/apps/stock/orchestrator/src/execution/canonical-paper.ts +++ b/apps/stock/orchestrator/src/execution/canonical-paper.ts @@ -12,13 +12,44 @@ import { nativeManagedOrderSchema, stepSchema, } from '../contracts/native-replay'; +import { paperConfigurationSchema, paperConnectionSchema } from '../contracts/paper-runtime'; import { metadataSchema, stateCopy } from '../strategies/strategy-decision'; const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER); +const time = matchingCommandSchema.shape.key.shape.at; const json = z.unknown().transform(value => stateCopy(value)); const observation = stepSchema.shape.observations.element; const barrier = stepSchema.shape.step.options[1].shape.barrier; const definition = metadataSchema.extend({ initialState: json }).strict(); +const quoteClock = z + .object({ instrumentId: z.string(), observedAt: time, sourceSequence: counter }) + .strict(); +/** Host controls are deliberately outside the native financial checkpoint. */ +export const canonicalPaperHostSchema = z + .object({ + version: z.literal(1), + configuration: paperConfigurationSchema, + generation: z.string().min(1), + active: z.boolean(), + operatorHalted: z.boolean(), + haltReason: z.string().nullable(), + diagnostic: z.string().nullable(), + connection: paperConnectionSchema.nullable(), + lastReceivedAt: time.nullable(), + lastAvailableAt: time.nullable(), + lastSequence: counter.nullable(), + quotes: z.array(quoteClock), + quoteHighWater: z.array(quoteClock), + frames: z.record( + z + .object({ fingerprint: z.string(), disposition: z.enum(['health-only', 'admitted']) }) + .strict() + ), + observations: z.record(z.string()), + physicalQuotes: z.record(z.string()), + }) + .strict(); +export type CanonicalPaperHost = z.infer; const feedback = z .object({ decision: nativeManagedOrderSchema.shape.order.shape.decision, @@ -76,6 +107,7 @@ export const canonicalAccountSchema = z observed: counter, pendingDecisionSequence: counter.nullable(), latestObservations: z.array(observation), + host: canonicalPaperHostSchema.optional(), }) .strict(); export const canonicalPaperInputSchema = z @@ -170,7 +202,7 @@ export function compareEventKeys( return ( a.at - b.at || phases[a.phase] - phases[b.phase] || - (a.instrumentId < b.instrumentId ? -1 : a.instrumentId > b.instrumentId ? 1 : 0) || + Buffer.compare(Buffer.from(a.instrumentId), Buffer.from(b.instrumentId)) || a.sourceSequence - b.sourceSequence ); } diff --git a/apps/stock/orchestrator/src/index.ts b/apps/stock/orchestrator/src/index.ts index ad422b08..fefb8a72 100644 --- a/apps/stock/orchestrator/src/index.ts +++ b/apps/stock/orchestrator/src/index.ts @@ -151,10 +151,23 @@ async function main() { const stopped = server?.stop(); let exitCode = 0; try { - await services.custom?.BacktestRunner?.shutdown(); - await services.queueManager?.shutdown(); - await services.custom?.ModeManager?.shutdown(); - await stopped; + const failures: unknown[] = []; + for (const close of [ + () => services.custom?.CanonicalPaperRuntime?.shutdown(), + () => services.custom?.BacktestRunner?.shutdown(), + () => services.queueManager?.shutdown(), + () => services.custom?.ModeManager?.shutdown(), + () => stopped, + ]) { + try { + await close(); + } catch (error) { + failures.push(error); + } + } + if (failures.length) { + throw new AggregateError(failures, 'Orchestrator shutdown failed'); + } } catch (error) { exitCode = 1; services.logger.error('Orchestrator shutdown failed', { error }); diff --git a/apps/stock/orchestrator/src/paper/CanonicalPaperRuntime.ts b/apps/stock/orchestrator/src/paper/CanonicalPaperRuntime.ts new file mode 100644 index 00000000..1df6ce2e --- /dev/null +++ b/apps/stock/orchestrator/src/paper/CanonicalPaperRuntime.ts @@ -0,0 +1,498 @@ +import { createHash, randomUUID } from 'node:crypto'; +import type { StrategyProgram } from '../contracts/canonical-strategy'; +import { + paperActivationSchema, + paperConnectionSchema, + paperHaltSchema, + PaperRuntimeError, + type PaperConfiguration, + type PaperConfigurationInput, + type PaperConnection, + type PaperFrameInput, + type PaperReadiness, + type PaperRuntime, +} from '../contracts/paper-runtime'; +import type { + CanonicalAccount, + CanonicalExecutionRepository, + CanonicalJournalEntry, + CanonicalPaperHost, + CanonicalTransaction, +} from '../execution/canonical-paper'; +import { CanonicalPaperExecution } from '../execution/CanonicalPaperExecution'; +import { canonicalJson } from '../execution/strategy-recovery'; +import { planPaperFrame, validatePaperConfiguration, validatePaperFrame } from './feed'; + +const fingerprint = (value: unknown) => + createHash('sha256').update(canonicalJson(value)).digest('hex'); +function hostState(account: CanonicalAccount): CanonicalPaperHost { + if (!account.host) { + throw new PaperRuntimeError('conflict', 'Paper account has no host policy'); + } + return account.host; +} + +/** An operational gate around durable custody, never a second financial simulator. + * Each transaction releases the account lock so a halt can stop the next step. */ +export class CanonicalPaperRuntime implements PaperRuntime { + private readonly generation = randomUUID(); + private readonly execution: CanonicalPaperExecution; + private configuration?: PaperConfiguration; + private readonly now: () => number; + + constructor( + private readonly options: { + repository: CanonicalExecutionRepository; + programs: readonly StrategyProgram[]; + now?: () => number; + publish?: (entries: readonly CanonicalJournalEntry[]) => void | Promise; + } + ) { + this.now = options.now ?? Date.now; + this.execution = new CanonicalPaperExecution({ + repository: options.repository, + programs: options.programs, + publish: options.publish, + control: { generation: this.generation, guard: account => this.guard(account) }, + }); + } + + async initialize(input: PaperConfigurationInput): Promise { + if (this.configuration) { + throw new PaperRuntimeError('conflict', 'Paper runtime is already initialized'); + } + const configuration = validatePaperConfiguration(input); + if ( + configuration.strategies.length !== this.options.programs.length || + configuration.strategies.some( + selection => + !this.options.programs.some( + program => + program.ownerId === selection.ownerId && + program.strategyId === selection.strategyId && + program.strategyVersion === selection.strategyVersion && + program.seed === selection.seed && + program.mode === 'target' + ) + ) + ) { + throw new PaperRuntimeError( + 'conflict', + 'Paper programs must match immutable configured strategy selections' + ); + } + const host: CanonicalPaperHost = { + version: 1, + configuration, + generation: this.generation, + active: false, + operatorHalted: true, + haltReason: 'Initial operator activation required', + diagnostic: null, + connection: null, + lastReceivedAt: null, + lastAvailableAt: null, + lastSequence: null, + quotes: [], + quoteHighWater: [], + frames: {}, + observations: {}, + physicalQuotes: {}, + }; + await this.execution.initialize(configuration.matching, host); + await this.options.repository.transact( + configuration.matching.risk.ledger.accountId, + async tx => { + if (!tx.account.host) { + throw new PaperRuntimeError('conflict', 'Paper account has no host policy'); + } + tx.account.host.generation = this.generation; + tx.account.host.active = false; + tx.account.host.connection = null; + tx.account.host.lastReceivedAt = null; + tx.account.host.lastSequence = null; + tx.account.host.quotes = []; + } + ); + this.configuration = configuration; + } + + private transaction( + work: (tx: CanonicalTransaction, host: CanonicalPaperHost) => Promise + ): Promise { + if (!this.configuration) { + throw new PaperRuntimeError('not-ready', 'Paper runtime is not initialized'); + } + return this.options.repository.transact( + this.configuration.matching.risk.ledger.accountId, + async tx => { + const host = tx.account.host; + if (!host || host.generation !== this.generation) { + throw new PaperRuntimeError('conflict', 'Paper runtime generation is obsolete'); + } + return work(tx, host); + } + ); + } + + private health(account: CanonicalAccount, now: number): string[] { + const host = hostState(account); + const { policy, matching } = host.configuration; + const reasons: string[] = []; + if (!host.connection) { + reasons.push('feed-disconnected'); + } + if ( + host.lastReceivedAt === null || + host.lastAvailableAt === null || + now < host.lastReceivedAt || + now < host.lastAvailableAt || + now - host.lastReceivedAt > policy.maxFeedAgeMs || + now - host.lastAvailableAt > policy.maxFeedAgeMs + ) { + reasons.push('feed-stale'); + } + for (const series of matching.series) { + const quote = host.quotes.find(item => item.instrumentId === series.instrumentId); + if (!quote || now < quote.observedAt || now - quote.observedAt > matching.risk.maxMarkAgeMs) { + reasons.push(`quote-stale:${series.instrumentId}`); + } + const calendar = policy.calendars.find(item => item.instrumentId === series.instrumentId); + if (!calendar?.sessions.some(session => session.opensAt <= now && now < session.closesAt)) { + reasons.push(`calendar-uncovered:${series.instrumentId}`); + } + } + if (account.checkpoint.status !== 'Running') { + reasons.push('native-not-running'); + } + return reasons; + } + + private guard(account: CanonicalAccount): boolean { + const host = hostState(account); + if (this.health(account, this.now()).length && host.active) { + host.active = false; + host.diagnostic = + 'Operational readiness expired; fresh feed and operator activation required'; + } + return host.active && !host.operatorHalted; + } + + private async readiness(tx: CanonicalTransaction): Promise { + this.guard(tx.account); + const host = hostState(tx.account); + const reasons = this.health(tx.account, this.now()); + if (host.operatorHalted) { + reasons.push('operator-halted'); + } + if (host.diagnostic) { + reasons.push(host.diagnostic); + } + const pendingInput = (await tx.nextInput())?.id ?? null; + const pendingBatch = (await tx.nextBatch())?.id ?? null; + const pendingDecisionSequence = tx.account.pendingDecisionSequence; + const requiresHistoricalRecovery = + pendingInput !== null || pendingBatch !== null || pendingDecisionSequence !== null; + if (requiresHistoricalRecovery) { + reasons.push('historical-recovery-required'); + } + return { + configured: true, + accountId: tx.account.identity.accountId, + sourceId: host.configuration.policy.sourceId, + active: host.active, + ready: reasons.length === 0, + operatorHalted: host.operatorHalted, + connected: host.connection !== null, + reasons, + lastReceivedAt: host.lastReceivedAt, + lastAvailableAt: host.lastAvailableAt, + requiresHistoricalRecovery, + pendingInput, + pendingBatch, + pendingDecisionSequence, + nativeStatus: tx.account.checkpoint.status, + risk: { + dailyHalted: tx.account.view.risk.dailyHalted, + drawdownHalted: tx.account.view.risk.drawdownHalted, + }, + }; + } + + /** A rejected request rolls back its admission transaction. Persist ONLY the + * freshness latch separately, preserving the original failure if storage is down. */ + private async withFreshnessLatch(work: () => Promise): Promise { + try { + return await work(); + } catch (error) { + try { + await this.transaction(async tx => { + this.guard(tx.account); + }); + } catch { + // A replacement generation or unavailable repository must not mask the original error. + } + throw error; + } + } + + connect(input: PaperConnection): Promise { + const connection = paperConnectionSchema.parse(input); + return this.transaction(async (tx, host) => { + if (connection.sourceId !== host.configuration.policy.sourceId) { + throw new PaperRuntimeError( + 'invalid-input', + 'Paper source does not match its configured provider' + ); + } + this.guard(tx.account); + if (canonicalJson(connection) !== canonicalJson(host.connection)) { + host.connection = connection; + host.active = false; + host.lastReceivedAt = null; + host.lastSequence = null; + host.quotes = []; + } + return this.readiness(tx); + }); + } + + disconnect(input: PaperConnection): Promise { + const connection = paperConnectionSchema.parse(input); + return this.transaction(async (tx, host) => { + if (canonicalJson(connection) === canonicalJson(host.connection)) { + host.active = false; + host.connection = null; + } + return this.readiness(tx); + }); + } + + async ingest(input: PaperFrameInput): ReturnType { + return this.withFreshnessLatch(async () => { + if (!this.configuration) { + throw new PaperRuntimeError('not-ready', 'Paper runtime is not initialized'); + } + const frame = validatePaperFrame(this.configuration, input, this.now()); + const digest = fingerprint(frame); + const frameIdentity = fingerprint(frame.id); + const receipt = await this.transaction(async (tx, host) => { + const old = host.frames[frameIdentity]; + if (old) { + if (old.fingerprint !== digest) { + throw new PaperRuntimeError('conflict', 'Paper frame ID has conflicting content'); + } + this.guard(tx.account); + return { duplicate: true, disposition: old.disposition }; + } + if ( + !host.connection || + host.connection.sourceId !== frame.sourceId || + host.connection.connectionId !== frame.connectionId + ) { + throw new PaperRuntimeError('conflict', 'Paper frame belongs to an inactive connection'); + } + if ( + (host.lastSequence !== null && frame.sequence <= host.lastSequence) || + (host.lastAvailableAt !== null && frame.availableAt <= host.lastAvailableAt) + ) { + throw new PaperRuntimeError( + 'conflict', + 'Distinct paper frames require increasing sequence and availability time' + ); + } + // Compare the OLD health deadline before this fresh frame can change it. + this.guard(tx.account); + if ( + host.active && + ((await tx.nextInput()) || + (await tx.nextBatch()) || + tx.account.pendingDecisionSequence !== null) + ) { + throw new PaperRuntimeError( + 'not-ready', + 'Previously admitted paper work requires completion before another frame' + ); + } + const observations = frame.observations.filter(observation => { + const identity = fingerprint([ + observation.series_id, + observation.event_time, + observation.source_sequence, + ]); + const value = fingerprint(observation); + const known = host.observations[identity]; + if (known && known !== value) { + throw new PaperRuntimeError( + 'conflict', + 'Physical observation identity has conflicting content' + ); + } + return !known; + }); + for (const quote of frame.quotes) { + const latest = host.quoteHighWater.find(item => item.instrumentId === quote.instrumentId); + if ( + latest && + (quote.observedAt < latest.observedAt || + (quote.observedAt === latest.observedAt && + quote.sourceSequence < latest.sourceSequence)) + ) { + throw new PaperRuntimeError( + 'invalid-input', + 'Paper quote regresses the retained physical event time' + ); + } + if ( + host.active && + this.now() - quote.observedAt > host.configuration.matching.risk.maxMarkAgeMs + ) { + throw new PaperRuntimeError('invalid-input', 'Admitted paper quote is stale'); + } + const known = + host.physicalQuotes[ + fingerprint([quote.instrumentId, quote.observedAt, quote.sourceSequence]) + ]; + if (known) { + throw new PaperRuntimeError( + 'conflict', + known === fingerprint(quote) + ? 'New paper frame reuses known physical quote liquidity' + : 'Physical quote identity has conflicting content' + ); + } + } + const disposition = host.active ? ('admitted' as const) : ('health-only' as const); + host.lastReceivedAt = this.now(); + host.lastAvailableAt = frame.availableAt; + host.lastSequence = frame.sequence; + for (const quote of frame.quotes) { + for (const clocks of [host.quotes, host.quoteHighWater]) { + const oldQuote = clocks.find(item => item.instrumentId === quote.instrumentId); + if (!oldQuote) { + clocks.push({ + instrumentId: quote.instrumentId, + observedAt: quote.observedAt, + sourceSequence: quote.sourceSequence, + }); + } else if ( + quote.observedAt > oldQuote.observedAt || + (quote.observedAt === oldQuote.observedAt && + quote.sourceSequence > oldQuote.sourceSequence) + ) { + Object.assign(oldQuote, { + observedAt: quote.observedAt, + sourceSequence: quote.sourceSequence, + }); + } + } + } + if (disposition === 'admitted') { + await this.execution.enqueueFrame( + tx, + planPaperFrame(host.configuration, { ...frame, observations }, tx.account) + ); + } + for (const observation of frame.observations) { + host.observations[ + fingerprint([ + observation.series_id, + observation.event_time, + observation.source_sequence, + ]) + ] = fingerprint(observation); + } + for (const quote of frame.quotes) { + host.physicalQuotes[ + fingerprint([quote.instrumentId, quote.observedAt, quote.sourceSequence]) + ] = fingerprint(quote); + } + host.frames[frameIdentity] = { fingerprint: digest, disposition }; + return { duplicate: false, disposition }; + }); + // A retry retains its first disposition and never replays an inactive probe. + if (!receipt.duplicate && receipt.disposition === 'admitted') { + await this.drain(); + } + return { ...receipt, readiness: await this.status() }; + }); + } + + private async drain(): Promise { + try { + await this.execution.drain(); + } catch (error) { + await this.transaction(async (_tx, host) => { + host.active = false; + host.diagnostic = error instanceof Error ? error.message : String(error); + }).catch(() => { + /* A replacement generation alone controls its account. */ + }); + throw error; + } + } + + async activate(input: { recoverPending: boolean }): Promise { + return this.withFreshnessLatch(async () => { + const { recoverPending } = paperActivationSchema.parse(input); + await this.transaction(async (tx, host) => { + this.guard(tx.account); + const reasons = this.health(tx.account, this.now()); + if (reasons.length) { + throw new PaperRuntimeError( + 'not-ready', + `Paper activation unavailable: ${reasons.join(', ')}` + ); + } + if ( + !recoverPending && + ((await tx.nextInput()) || + (await tx.nextBatch()) || + tx.account.pendingDecisionSequence !== null) + ) { + throw new PaperRuntimeError( + 'not-ready', + 'Historical admitted work requires explicit recoverPending: true' + ); + } + host.active = true; + host.operatorHalted = false; + host.haltReason = null; + host.diagnostic = null; + }); + await this.drain(); + const result = await this.status(); + if (!result.active || !result.ready || result.requiresHistoricalRecovery) { + await this.transaction(async (_tx, host) => { + host.active = false; + }); + throw new PaperRuntimeError( + 'not-ready', + 'Paper activation stopped before recovery and fresh readiness completed' + ); + } + return result; + }); + } + + halt(reason: string): Promise { + const parsed = paperHaltSchema.parse({ reason }); + return this.transaction(async (tx, host) => { + host.active = false; + host.operatorHalted = true; + host.haltReason = parsed.reason; + return this.readiness(tx); + }); + } + + status(): Promise { + return this.transaction(tx => this.readiness(tx)); + } + + async shutdown(): Promise { + await this.transaction(async (_tx, host) => { + host.active = false; + host.connection = null; + }); + } +} diff --git a/apps/stock/orchestrator/src/paper/feed.ts b/apps/stock/orchestrator/src/paper/feed.ts new file mode 100644 index 00000000..fe46a567 --- /dev/null +++ b/apps/stock/orchestrator/src/paper/feed.ts @@ -0,0 +1,520 @@ +/** Pure trusted-feed validation and deterministic command planning. Rust alone + * matches orders and accounts for money; no feed clock or price is repaired here. */ +import { isDeepStrictEqual } from 'node:util'; +import { ZodError } from 'zod'; +import { + matchingCommandSchema, + type CanonicalMatchingCommand, +} from '../contracts/canonical-execution'; +import { + paperConfigurationSchema, + paperFrameSchema, + PaperRuntimeError, + type PaperConfiguration, + type PaperConfigurationInput, + type PaperFrame, + type PaperFrameInput, +} from '../contracts/paper-runtime'; +import type { CanonicalAccount, CanonicalPaperInput } from '../execution/canonical-paper'; + +type Observation = PaperFrame['observations'][number]; +type Quote = PaperFrame['quotes'][number]; +type Session = PaperConfiguration['policy']['calendars'][number]['sessions'][number]; +type Key = CanonicalMatchingCommand['key']; + +function invalid(message: string): never { + throw new PaperRuntimeError('invalid-input', message); +} +// Decimal wire transforms throw ordinary Errors. Classify only this synchronous +// input parsing boundary, never arbitrary storage/native errors, as bad input. +function parseInput(schema: { parse(input: unknown): T }, input: unknown): T { + try { + return schema.parse(input); + } catch (error) { + if (error instanceof ZodError) { + throw error; + } + invalid(error instanceof Error ? error.message : 'Malformed paper input'); + } +} +// UTF-8 ordering agrees with Rust Id/String ordering, including supplementary characters. +const compareText = (a: string, b: string) => Buffer.compare(Buffer.from(a), Buffer.from(b)); +const units = (value: string) => BigInt(value.replace('.', '')); +function unique(values: readonly string[], label: string): void { + if (new Set(values).size !== values.length) { + invalid(`Duplicate paper ${label}`); + } +} +function keyCompare(a: Key, b: Key): number { + const phase = { Observation: 0, Decision: 1, Execution: 2, SessionClose: 3 }; + return ( + a.at - b.at || + phase[a.phase] - phase[b.phase] || + compareText(a.instrumentId, b.instrumentId) || + a.sourceSequence - b.sourceSequence + ); +} +const observationId = (row: Observation) => + JSON.stringify([row.series_id, row.event_time, row.source_sequence]); +const physicalQuote = (instrumentId: string, observedAt: number, sourceSequence: number) => + JSON.stringify([instrumentId, observedAt, sourceSequence]); +const quoteId = (quote: Quote) => + physicalQuote(quote.instrumentId, quote.observedAt, quote.sourceSequence); +const quoteKey = (frame: PaperFrame, quote: Quote): Key => ({ + at: frame.availableAt, + phase: 'Execution', + instrumentId: quote.instrumentId, + sourceSequence: quote.sourceSequence, +}); +function sessions(config: PaperConfiguration, instrumentId: string): Session[] { + const calendar = config.policy.calendars.find(item => item.instrumentId === instrumentId); + if (!calendar) { + invalid('Paper instrument has no declared calendar'); + } + return calendar.sessions; +} +function activeSession(config: PaperConfiguration, instrumentId: string, at: number): Session { + const session = sessions(config, instrumentId).find( + item => item.opensAt <= at && at < item.closesAt + ); + if (!session) { + invalid('Paper quote is outside declared session coverage'); + } + return session; +} + +export function validatePaperConfiguration(input: PaperConfigurationInput): PaperConfiguration { + const config = parseInput(paperConfigurationSchema, input); + const { matching, policy, strategies } = config; + if (!matching.series.length || matching.series.some(series => series.mode !== 'Quote')) { + invalid('Canonical paper feed supports Quote execution only'); + } + unique( + matching.series.map(item => item.instrumentId), + 'execution instrument' + ); + unique( + matching.series.map(item => item.seriesId), + 'execution series' + ); + unique( + matching.owners.map(item => item.ownerId), + 'owner' + ); + unique(matching.risk.ledger.ownerIds, 'ledger owner'); + unique( + strategies.map(item => item.ownerId), + 'strategy owner' + ); + unique( + policy.observations.map(item => item.seriesId), + 'observation series' + ); + unique( + policy.cadence.map(item => item.ownerId), + 'cadence owner' + ); + unique( + policy.calendars.map(item => item.instrumentId), + 'calendar instrument' + ); + const owners = matching.owners.map(item => item.ownerId).sort(compareText); + if ( + matching.owners.some(item => item.mode !== 'Target') || + !isDeepStrictEqual(owners, [...matching.risk.ledger.ownerIds].sort(compareText)) || + !isDeepStrictEqual(owners, strategies.map(item => item.ownerId).sort(compareText)) || + !isDeepStrictEqual(owners, policy.cadence.map(item => item.ownerId).sort(compareText)) + ) { + invalid('Paper built-ins must exactly match the target owner and cadence cohort'); + } + const instruments = matching.series.map(item => item.instrumentId).sort(compareText); + if ( + !isDeepStrictEqual( + instruments, + policy.calendars.map(item => item.instrumentId).sort(compareText) + ) + ) { + invalid('Paper calendars must exactly cover execution instruments'); + } + for (const observation of policy.observations) { + if (!instruments.includes(observation.instrumentId)) { + invalid('Paper observation references an unknown instrument'); + } + } + for (const cadence of policy.cadence) { + unique(cadence.seriesIds, 'cadence series'); + if (cadence.seriesIds.some(id => !policy.observations.some(item => item.seriesId === id))) { + invalid('Paper cadence references an unknown observation series'); + } + cadence.seriesIds.sort(compareText); + } + for (const strategy of strategies) { + const series = policy.observations.find(item => item.seriesId === strategy.seriesId); + if ( + series?.instrumentId !== strategy.instrumentId || + !policy.cadence + .find(item => item.ownerId === strategy.ownerId) + ?.seriesIds.includes(strategy.seriesId) + ) { + invalid('Paper strategy requires its bound instrument/observation series in its cadence'); + } + } + const initial = matching.risk.ledger.riskSession; + for (const calendar of policy.calendars) { + unique( + calendar.sessions.map(item => item.sessionId), + 'venue session' + ); + calendar.sessions.sort((a, b) => a.opensAt - b.opensAt); + let previousClose = initial.startsAt; + for (const session of calendar.sessions) { + if (session.opensAt < previousClose || session.opensAt >= session.closesAt) { + invalid('Paper venue sessions overlap, are invalid, or precede the initial risk clock'); + } + previousClose = session.closesAt; + } + } + unique([initial.sessionId, ...policy.riskBoundaries.map(item => item.sessionId)], 'risk session'); + policy.riskBoundaries.sort((a, b) => a.startsAt - b.startsAt); + let previousRisk = initial.startsAt; + for (const boundary of policy.riskBoundaries) { + if ( + boundary.calendarId !== initial.calendarId || + boundary.calendarRevision !== initial.calendarRevision || + boundary.startsAt <= previousRisk + ) { + invalid('Paper risk boundaries must advance the declared account calendar revision'); + } + previousRisk = boundary.startsAt; + } + matching.owners.sort((a, b) => compareText(a.ownerId, b.ownerId)); + matching.series.sort((a, b) => compareText(a.instrumentId, b.instrumentId)); + matching.risk.ledger.ownerIds.sort(compareText); + strategies.sort((a, b) => compareText(a.ownerId, b.ownerId)); + policy.observations.sort((a, b) => compareText(a.seriesId, b.seriesId)); + policy.cadence.sort((a, b) => compareText(a.ownerId, b.ownerId)); + policy.calendars.sort((a, b) => compareText(a.instrumentId, b.instrumentId)); + return config; +} + +export function validatePaperFrame( + config: PaperConfiguration, + input: PaperFrameInput, + now: number +): PaperFrame { + const frame = parseInput(paperFrameSchema, input); + if ( + !Number.isSafeInteger(now) || + frame.sourceId !== config.policy.sourceId || + frame.availableAt > now + ) { + invalid('Paper frame source or availability time is invalid'); + } + unique(frame.quotes.map(quoteId), 'physical quote'); + unique( + frame.quotes.map(quote => JSON.stringify([quote.instrumentId, quote.sourceSequence])), + 'quote event key' + ); + for (const quote of frame.quotes) { + const series = config.matching.series.find(item => item.instrumentId === quote.instrumentId); + const session = activeSession(config, quote.instrumentId, frame.availableAt); + if ( + series?.seriesId !== quote.seriesId || + quote.observedAt > frame.availableAt || + quote.observedAt < session.opensAt || + units(quote.bid) <= 0n || + units(quote.ask) <= 0n || + units(quote.bid) > units(quote.ask) || + units(quote.bidSize) < 0n || + units(quote.askSize) < 0n + ) { + invalid('Paper quote identity, time, price or size is invalid'); + } + } + frame.quotes.sort((a, b) => keyCompare(quoteKey(frame, a), quoteKey(frame, b))); + for (let index = 1; index < frame.quotes.length; index++) { + const prior = frame.quotes[index - 1]; + const current = frame.quotes[index]; + if ( + prior && + current && + prior.instrumentId === current.instrumentId && + prior.observedAt > current.observedAt + ) { + invalid('Paper quote sequence reverses physical event time within a frame'); + } + } + const observations = new Map(); + for (const row of frame.observations) { + const series = config.policy.observations.find(item => item.seriesId === row.series_id); + if (!series || series.instrumentId !== row.instrument_id) { + invalid('Paper observation is outside the declared series manifest'); + } + const session = sessions(config, row.instrument_id).find( + item => item.opensAt <= row.interval_start && row.interval_start < item.closesAt + ); + const intervalEnd = BigInt(row.interval_start) + BigInt(series.intervalMs); + // Intervals start on a session-open grid and the final complete bar may be + // clipped at a half-day/session close. No synthetic partial prices or volume. + if ( + !session || + row.interval_end <= row.interval_start || + (BigInt(row.interval_start) - BigInt(session.opensAt)) % BigInt(series.intervalMs) !== 0n || + BigInt(row.interval_end) !== + (intervalEnd < BigInt(session.closesAt) ? intervalEnd : BigInt(session.closesAt)) || + row.event_time !== row.interval_end || + row.interval_end > row.available_at || + row.available_at > frame.availableAt || + units(row.open) <= 0n || + units(row.close) <= 0n || + units(row.low) <= 0n || + units(row.high) < units(row.low) || + units(row.high) < units(row.open) || + units(row.high) < units(row.close) || + units(row.low) > units(row.open) || + units(row.low) > units(row.close) || + units(row.volume) < 0n + ) { + invalid('Paper observation is incomplete, unaligned, unavailable or has invalid OHLCV'); + } + const prior = observations.get(observationId(row)); + if (prior && !isDeepStrictEqual(prior, row)) { + invalid('Conflicting physical paper observation'); + } + observations.set(observationId(row), row); + } + frame.observations = [...observations.values()]; + return frame; +} + +/** Caller atomically enqueues this complete plan under the same account lock. + * The runtime owns cross-frame observation fingerprints; this pure helper also + * deduplicates against the known latest observation while retaining delayed older bars. */ +export function planPaperFrame( + config: PaperConfiguration, + frame: PaperFrame, + account: Pick +): CanonicalPaperInput[] { + const { checkpoint } = account; + if (checkpoint.status !== 'Running' || !isDeepStrictEqual(checkpoint.config, config.matching)) { + throw new PaperRuntimeError( + 'not-ready', + 'Paper financial snapshot is incompatible or terminal' + ); + } + const retained = new Set(); + const physicalTime = new Map(); + for (const receipt of checkpoint.receipts) { + const input = receipt.input; + if (!input || typeof input !== 'object' || !('source' in input) || input.source !== 'Engine') { + continue; + } + const parsed = matchingCommandSchema.safeParse('command' in input ? input.command : undefined); + if (!parsed.success) { + invalid('Malformed retained paper execution receipt'); + } + const command = parsed.data; + const observedAt = + command.body.kind === 'mark' + ? command.body.observedAt + : command.body.kind === 'execute' && command.body.observation.kind === 'quote' + ? command.body.observation.observedAt + : undefined; + if (observedAt !== undefined) { + physicalTime.set( + command.key.instrumentId, + Math.max(physicalTime.get(command.key.instrumentId) ?? observedAt, observedAt) + ); + } + if (command.body.kind === 'execute' && command.body.observation.kind === 'quote') { + retained.add( + physicalQuote( + command.key.instrumentId, + command.body.observation.observedAt, + command.key.sourceSequence + ) + ); + } + } + if (frame.quotes.some(quote => retained.has(quoteId(quote)))) { + throw new PaperRuntimeError('conflict', 'Paper frame reuses retained physical quote liquidity'); + } + if ( + frame.quotes.some( + quote => quote.observedAt < (physicalTime.get(quote.instrumentId) ?? quote.observedAt) + ) + ) { + invalid('Paper quote regresses the retained physical event time'); + } + const commands: CanonicalMatchingCommand[] = []; + const add = (command: CanonicalMatchingCommand) => { + if ( + command.key.at <= frame.availableAt && + (!checkpoint.cursor || keyCompare(command.key, checkpoint.cursor) > 0) + ) { + commands.push(command); + } + }; + for (const calendar of config.policy.calendars) { + for (const session of calendar.sessions) { + const identity = [ + frame.sourceId, + calendar.instrumentId, + calendar.calendarId, + calendar.revision, + session.sessionId, + ]; + add({ + commandId: JSON.stringify(['paper-session-open', ...identity]), + key: { + at: session.opensAt, + phase: 'Observation', + instrumentId: calendar.instrumentId, + sourceSequence: 2, + }, + body: { kind: 'openSession', session }, + }); + add({ + commandId: JSON.stringify(['paper-session-close', ...identity]), + key: { + at: session.closesAt, + phase: 'Observation', + instrumentId: calendar.instrumentId, + sourceSequence: 0, + }, + body: { kind: 'closeSession', sessionId: session.sessionId }, + }); + } + } + const firstSeries = config.matching.series[0]; + if (!firstSeries) { + invalid('Paper configuration has no execution series'); + } + for (const boundary of config.policy.riskBoundaries) { + add({ + commandId: JSON.stringify([ + 'paper-risk-boundary', + frame.sourceId, + boundary.calendarId, + boundary.calendarRevision, + boundary.sessionId, + ]), + key: { + at: boundary.startsAt, + phase: 'Observation', + instrumentId: firstSeries.instrumentId, + sourceSequence: 1, + }, + body: { kind: 'riskSessionBoundary', riskSession: boundary }, + }); + } + const active = new Map(checkpoint.sessions); + commands.sort((a, b) => keyCompare(a.key, b.key)); + for (const command of commands) { + if (command.body.kind === 'openSession') { + if (active.has(command.key.instrumentId)) { + invalid('Paper venue session is already open at its declared boundary'); + } + active.set(command.key.instrumentId, command.body.session); + } else if (command.body.kind === 'closeSession') { + if (active.get(command.key.instrumentId)?.sessionId !== command.body.sessionId) { + invalid('Paper venue close does not match the retained open session'); + } + active.delete(command.key.instrumentId); + } + } + const quotes = [...frame.quotes].sort((a, b) => + keyCompare(quoteKey(frame, a), quoteKey(frame, b)) + ); + for (const quote of quotes) { + const key = quoteKey(frame, quote); + if ( + (checkpoint.cursor && keyCompare(key, checkpoint.cursor) <= 0) || + !isDeepStrictEqual( + active.get(quote.instrumentId), + activeSession(config, quote.instrumentId, frame.availableAt) + ) + ) { + invalid('Paper quote cannot advance the retained event cursor/session'); + } + commands.push({ + commandId: JSON.stringify([ + 'paper-quote', + frame.sourceId, + quote.instrumentId, + quote.seriesId, + quote.observedAt, + quote.sourceSequence, + ]), + key, + body: { + kind: 'execute', + seriesId: quote.seriesId, + observation: { + kind: 'quote', + observedAt: quote.observedAt, + bid: quote.bid, + ask: quote.ask, + bidSize: quote.bidSize, + askSize: quote.askSize, + }, + }, + }); + } + const observations = frame.observations.filter(row => { + const latest = account.latestObservations.find( + item => observationId(item) === observationId(row) + ); + if (latest && !isDeepStrictEqual(latest, row)) { + throw new PaperRuntimeError( + 'conflict', + 'Paper observation conflicts with its retained identity' + ); + } + return !latest; + }); + const latest = new Map(account.latestObservations.map(row => [row.series_id, row])); + for (const row of observations) { + const old = latest.get(row.series_id); + if ( + !old || + row.event_time > old.event_time || + (row.event_time === old.event_time && row.source_sequence > old.source_sequence) + ) { + latest.set(row.series_id, row); + } + } + const ownerIds = config.policy.cadence + .filter(cadence => observations.some(row => cadence.seriesIds.includes(row.series_id))) + .map(cadence => cadence.ownerId) + .sort(compareText); + const result: CanonicalPaperInput[] = commands.map(command => ({ command, observations: [] })); + const final = result.at(-1); + if (!final || final.command.body.kind !== 'execute') { + invalid('Paper frame requires a final execution quote'); + } + final.observations = observations; + if (ownerIds.length) { + const identity = [frame.sourceId, frame.id, frame.sequence]; + final.decision = { + commandId: JSON.stringify(['paper-decision', ...identity]), + key: { ...final.command.key }, + barrierId: JSON.stringify(['paper-barrier', ...identity]), + ownerIds, + inputs: config.policy.observations.map(series => { + const row = latest.get(series.seriesId); + const timing = row && { event_time: row.event_time, available_at: row.available_at }; + return { + series_id: series.seriesId, + availability: + !row || !timing + ? 'Missing' + : frame.availableAt - row.event_time > series.staleAfterMs + ? { Stale: timing } + : { Fresh: timing }, + }; + }), + }; + } + return result; +} diff --git a/apps/stock/orchestrator/src/routes/create-routes.ts b/apps/stock/orchestrator/src/routes/create-routes.ts index 3d510cfc..6f8229f4 100644 --- a/apps/stock/orchestrator/src/routes/create-routes.ts +++ b/apps/stock/orchestrator/src/routes/create-routes.ts @@ -3,6 +3,7 @@ import { Server as SocketIOServer } from 'socket.io'; import { createAnalyticsRoutes } from '../api/rest/analytics'; import { createBacktestRoutes } from '../api/rest/backtest'; import { createOrderRoutes } from '../api/rest/orders'; +import { createPaperRoutes } from '../api/rest/paper'; import { createPositionRoutes } from '../api/rest/positions'; import { setupWebSocketHandlers } from '../api/websocket'; import type { OrchestratorServices as IServiceContainer } from '../types'; @@ -20,7 +21,10 @@ export function createRoutes(services: IServiceContainer, io?: SocketIOServer): return c.json({ status: 'healthy', service: 'orchestrator', - mode: modeManager?.getCurrentMode() || 'unknown', + mode: services.custom?.CanonicalPaperRuntime + ? 'paper' + : modeManager?.getCurrentMode() || 'unknown', + execution: services.custom?.CanonicalPaperRuntime ? 'canonical-paper' : 'legacy', timestamp: new Date().toISOString(), }); }); @@ -28,6 +32,12 @@ export function createRoutes(services: IServiceContainer, io?: SocketIOServer): // Mount REST API routes app.get('/api/recovery', async c => { try { + if (services.custom?.CanonicalPaperRuntime) { + return c.json({ + engine: 'canonical-paper', + ...(await services.custom.CanonicalPaperRuntime.status()), + }); + } const execution = services.custom?.ExecutionService; if (!execution) { return c.json({ error: 'Execution gateway unavailable' }, 503); @@ -38,13 +48,23 @@ export function createRoutes(services: IServiceContainer, io?: SocketIOServer): return c.json({ error: 'Strategy recovery status unavailable' }, 503); } }); - app.route('/api/orders', createOrderRoutes(services)); - app.route('/api/positions', createPositionRoutes(services)); + app.route('/api/paper', createPaperRoutes(services)); + if (services.custom?.CanonicalPaperRuntime) { + // Legacy numeric gateways cannot operate on a controlled canonical account. + const unavailable = new Hono().all('*', c => + c.json({ error: 'Legacy account gateway unavailable in canonical paper mode' }, 409) + ); + app.route('/api/orders', unavailable); + app.route('/api/positions', unavailable); + } else { + app.route('/api/orders', createOrderRoutes(services)); + app.route('/api/positions', createPositionRoutes(services)); + } app.route('/api/analytics', createAnalyticsRoutes(services)); app.route('/api/backtest', createBacktestRoutes(services)); // Setup WebSocket handlers if Socket.IO is provided - if (io) { + if (io && !services.custom?.CanonicalPaperRuntime) { setupWebSocketHandlers(io, services); services.logger.info('WebSocket handlers configured'); } diff --git a/apps/stock/orchestrator/src/simple-container.ts b/apps/stock/orchestrator/src/simple-container.ts index 8c0df0ca..3bd81e49 100644 --- a/apps/stock/orchestrator/src/simple-container.ts +++ b/apps/stock/orchestrator/src/simple-container.ts @@ -1,5 +1,7 @@ import { ServiceContainerBuilder } from '@stock-bot/di'; import type { StockAppConfig } from '@stock-bot/stock-config'; +import { paperConfigurationSchema } from './contracts/paper-runtime'; +import { validatePaperConfiguration } from './paper/feed'; import { assertSupportedComposition, registerOrchestratorServices, @@ -12,11 +14,30 @@ export async function createContainer( config: StockAppConfig, options: { role?: OrchestratorRole } = {} ) { - const role = options.role === undefined ? 'paper' : options.role; + const settings = config.services?.orchestrator; + if (settings?.defaultMode === 'live') { + throw new Error('Live trading is disabled: no real broker adapter exists'); + } + const role = + options.role === undefined + ? settings?.defaultMode === 'backtest' + ? 'research-only' + : 'paper' + : options.role; const configuredEngine = config.services?.orchestrator?.backtesting?.useRustEngine; const useRustEngine = configuredEngine === undefined ? true : configuredEngine; // Fail before opening connections as well as before registering runtime services. assertSupportedComposition(role, useRustEngine); + if (settings?.canonicalPaper !== undefined && role !== 'paper') { + throw new Error('Canonical paper configuration requires a paper composition'); + } + const canonicalPaper = + settings?.canonicalPaper === undefined + ? undefined + : validatePaperConfiguration(paperConfigurationSchema.parse(settings.canonicalPaper)); + if (canonicalPaper && !config.database?.postgres?.enabled) { + throw new Error('Canonical paper requires durable PostgreSQL custody'); + } const container = await new ServiceContainerBuilder() .withConfig(config) .withOptions({ @@ -35,6 +56,8 @@ export async function createContainer( allowSyntheticData: config.services?.orchestrator?.backtesting?.allowSyntheticData ?? false, syntheticSeed: config.services?.orchestrator?.backtesting?.syntheticSeed ?? 42, nativeExecutionTimeoutMs: config.services?.orchestrator?.backtesting?.executionTimeoutMs, + canonicalPaper, + paperTradingCapital: settings?.paperTradingCapital, }); return container.resolve('serviceContainer') as OrchestratorServices; } diff --git a/apps/stock/orchestrator/src/types.ts b/apps/stock/orchestrator/src/types.ts index 36f31ac2..3fa0742b 100644 --- a/apps/stock/orchestrator/src/types.ts +++ b/apps/stock/orchestrator/src/types.ts @@ -56,6 +56,7 @@ export type OrchestratorServices = import('@stock-bot/services').IServiceContain BacktestEngine: import('./backtest/execution-engine').BacktestExecutionEngine; PaperTradingManager: import('./paper/PaperTradingManager').PaperTradingManager; ModeManager: import('./core/ModeManager').ModeManager; + CanonicalPaperRuntime: import('./contracts/paper-runtime').PaperRuntime; }>; }; export type { BacktestResult } from './backtest/RustBacktestAdapter'; diff --git a/docs/development/ROADMAP.md b/docs/development/ROADMAP.md index 7c3c4bf5..db38ba83 100644 --- a/docs/development/ROADMAP.md +++ b/docs/development/ROADMAP.md @@ -437,3 +437,17 @@ Rejected: competing TS/web simulators, wholesale Rust rewrite, hand-written deci Only [manifest.json](backlog/manifest.json) owns status/assignment/dependencies. [Task files](backlog/README.md) own scope/acceptance. Read the reusable [implementation](agents/implementation.md), [review](agents/review.md), [integration](agents/integration.md), [planning](agents/planning.md) briefs and [quality gates](QUALITY-GATES.md). Approval of planning artifacts is not permission to commit, push or create PRs. Historical planning-only statements refer to the original audit; later execution records and the canonical manifest identify actual implementation, authorization and validation evidence. + + +## Seventeenth-wave execution — 2026-10-23 + +S03 was accepted and committed as `c01e96e`, superseding its uncommitted status above. S04 is in progress under its [pinned execution contract](backlog/tasks/S04.md#execution-contract--2026-10-23). Isolated feed and custody owners work under `/tmp/stock-bot-wave17.JfETUx/`; root owns shared contracts, API/composition and integration, with independent review. Performance tasks remain deferred by owner instruction. + +The existing ingestion service has no working producer for its legacy paper Socket.IO client. This wave adds a validated trusted HTTP frame boundary and operator gate with deterministic feed-to-fill fixture coverage; it does not certify a vendor feed or activate paper/live trading. The canonical composition remains explicit and opt-in. Preserve S03 financial custody and financial semantics; retain paused work and require explicit historical recovery acknowledgement. + + +**Validated handoff:** S04 is `review` / `validated_uncommitted`. Twenty source/test files integrated; feed, custody and API-test slices match independently reviewed frozen hashes. Root supplied shared contracts, composition and HTTP/SQL SMA-to-fill/restart and research-isolation tests. New accounts start halted/disconnected. Exact frame receipts, retained physical quote ordering and generation fences prevent replay/reconnect from silently creating liquidity or resuming execution. Human halt stops the next locked step without discarding pending work. Historical recovery requires explicit acknowledgement and keeps original quote prices/times. Existing loopback auth bypass remains an explicit development exception, not authenticated-feed certification. + +Validation: `bun run check` passed build, source/contracts, 82 tooling, 43 utility, 44 calculation, 454 integration and 150 Rust tests (four manual tests ignored), plus lint. Full isolated PostgreSQL/Redis suite: **104 tests / 719 assertions**. Strict new-test TypeScript, scoped lint/format and diff checks passed. Final release addon matches this checkout's native library; **55 tests / 481 assertions** passed against it. No performance measurements were run. Exact commands, hashes and raw logs are in `manifest.json` → `seventeenth_wave_validation` and `/tmp/stock-bot-wave17.JfETUx/`. + +Sandbox-only connection/child-process restrictions were rerun with escalation; only the exact stalled test process was stopped. Both exact disposable fixture containers were stopped after validation. Development services, worktrees and logs were retained. No S04 commit, push, PR, default cutover or trading activation occurred. The current trusted HTTP feed boundary still needs a real provider producer and operational calendars. **Next after acceptance/commit: S05**, a small composable multi-signal/regime strategy example; performance remains deferred. R01/R11 still need ADR-006. diff --git a/docs/development/backlog/README.md b/docs/development/backlog/README.md index faabfcac..dafc39ff 100644 --- a/docs/development/backlog/README.md +++ b/docs/development/backlog/README.md @@ -1,6 +1,6 @@ # Canonical development backlog -**First fifteen waves committed; S03 is validated for review.** S02 is accepted as `ca5abdd`. The owner deferred performance work; P08 is on hold. S03 preserves durable execution/recovery on the canonical Rust kernel, with full repository and disposable-database checks passing. Its changes remain uncommitted. Consult manifest execution_scope and [current wave](../ROADMAP.md#sixteenth-wave-execution--2026-10-23). ADR-002/003/004/005 are approved; other policies/default cutovers remain gated. +**First sixteen waves committed; S04 is validated and awaiting acceptance/commit.** S03 is accepted as `c01e96e`. P08 remains deferred at the owner's request. S04 adds explicit canonical paper-feed custody, readiness and operator controls; the repository has no functioning vendor stream to claim as verified. Consult manifest execution_scope and [current wave](../ROADMAP.md#seventeenth-wave-execution--2026-10-23). ADR-002/003/004/005 are approved; other policies/default cutovers remain gated. ## One source of truth @@ -54,8 +54,8 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr | --- | --- | --- | --- | --- | | [S01 Run deterministic TypeScript decisions on Rust sessions](tasks/S01.md) | P0 / done | F07, ADR-004, ADR-005 | — | TypeScript trading infrastructure / M | | [S02 Adapt one SMA strategy for the first canonical path](tasks/S02.md) | P1 / done | S01 | — | TypeScript strategy/quant engineering / M | -| [S03 Adapt durable paper transactions to Rust financial reducers](tasks/S03.md) | P0 / review | S01, C06, ADR-005 | — | Durable execution/Rust integration / L | -| [S04 Establish a verified paper feed and operator safety gate](tasks/S04.md) | P1 / blocked | S02, S03 | — | TypeScript trading infrastructure / M | +| [S03 Adapt durable paper transactions to Rust financial reducers](tasks/S03.md) | P0 / done | S01, C06, ADR-005 | — | Durable execution/Rust integration / L | +| [S04 Establish a verified paper feed and operator safety gate](tasks/S04.md) | P1 / review | S02, S03 | — | TypeScript trading infrastructure / M | | [S05 Add a small composable multi-signal regime example](tasks/S05.md) | P2 / ready | S02, F08 | R08 | Quant strategy research / M | | [S06 Retire duplicate simulator paths after cutover proof](tasks/S06.md) | P2 / blocked | S03, S04, R05 | — | TypeScript trading infrastructure / M | @@ -118,4 +118,4 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr Before any wave: unique IDs; existing task/ADR references; acyclic implementation graph; no scheduled task dependent on merged/deferred work; approvals/readiness; actual file locks; isolated native build outputs/workspace dependencies and test databases. Release gates are checked separately at activation. -The first fifteen waves are committed. **S03 is authorized and in progress; performance work is deferred by the owner.** S05 is also code/ADR-ready but outside this wave. R01/R11 still need ADR-006; the multi-asset mark-policy gate still blocks default activation. No default/paper activation, push or PR is included in this continuation. +The first sixteen waves are committed. **S04 is validated and uncommitted; performance work is deferred by the owner.** S05 is also code/ADR-ready but outside this wave. R01/R11 still need ADR-006; the multi-asset mark-policy gate still blocks default activation. No default/paper activation, push or PR is included in this continuation. diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index 3d23c7e3..7dab33e7 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -1,16 +1,16 @@ { "schema_version": 1, - "plan_revision": "2026-10-23.36", + "plan_revision": "2026-10-23.38", "repository_base": "b7aeca4", - "plan_status": "sixteenth_wave_validated", + "plan_status": "seventeenth_wave_review", "execution_authorized": true, "execution_scope": { - "authorized_by": "User: commit and continue, then stop performance work for now and continue remaining backlog (2026-10-23). S02 accepted and committed ca5abdd. S03 is the highest-priority ready non-performance task under approved ADR-005.", + "authorized_by": "User: commit and continue after validated S03 handoff (2026-10-23). S03 accepted/committed c01e96e; S04 prerequisites satisfied. Performance work remains deferred.", "tasks": [ - "S03" + "S04" ], "permissions": [ - "accepted_wave15_commits", + "accepted_wave16_commits", "isolated_implementation", "local_correctness_tests", "local_integration_review", @@ -1037,7 +1037,7 @@ "epic": "E4", "priority": "P0", "severity": "Critical", - "status": "review", + "status": "done", "dependencies": [ "S01", "C06" @@ -1061,12 +1061,12 @@ "assignment": "/root/s03_durable", "branch": "wave16/s03-durable", "pull_request": null, - "completed_commit": null, + "completed_commit": "c01e96e4dd2879d0c728e57b48f5b6172adecd0f", "blocker": null, "release_gates": [], "worktree": "/tmp/stock-bot-wave16.kgaZm4/durable", "integration_base": "ca5abdde0e131ef4ec8c60ff9a4de4e277fc0820", - "integration_state": "validated_uncommitted", + "integration_state": "validated_committed", "implementation_slices": [ { "owner": "/root/s03_native", @@ -1091,7 +1091,7 @@ "epic": "E4", "priority": "P1", "severity": "High", - "status": "blocked", + "status": "review", "dependencies": [ "S02", "S03" @@ -1107,13 +1107,34 @@ "write_locks": [ "paper-runtime" ], - "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", - "assignment": null, - "branch": null, + "parallel_policy": "Feed translator and durable runtime/control owners use disjoint files and the root-owned public contract. Root owns configuration/composition/routes/integrated tests; independent review checks temporal and account-lock guarantees.", + "assignment": "/root/s04_controls_audit", + "branch": "wave17/s04-control", "pull_request": null, "completed_commit": null, "blocker": null, - "release_gates": [] + "release_gates": [], + "worktree": "/tmp/stock-bot-wave17.JfETUx/control", + "integration_base": "c01e96e4dd2879d0c728e57b48f5b6172adecd0f", + "integration_state": "validated_uncommitted", + "implementation_slices": [ + { + "owner": "/root/s04_feed_audit", + "branch": "wave17/s04-feed", + "worktree": "/tmp/stock-bot-wave17.JfETUx/feed", + "scope": "Strict normalized quote-frame validation, explicit calendar/feature/cadence translation and focused tests." + }, + { + "owner": "/root/s04_controls_audit", + "branch": "wave17/s04-control", + "worktree": "/tmp/stock-bot-wave17.JfETUx/control", + "scope": "Versioned host policy/control custody, atomic frame admission, persistent halt/runtime fencing, canonical runtime and real-PostgreSQL failure tests." + }, + { + "owner": "/root", + "scope": "Shared public contracts, opt-in configuration/composition, operator-authenticated REST routes and integrated tests/planning." + } + ] }, { "id": "S05", @@ -5904,7 +5925,7 @@ "After S03 acceptance/commit, S04 is the next non-performance task. S05 is independently code/ADR-ready; R01/R11 still require ADR-006. P08 remains deferred." ], "sixteenth_wave_validation": { - "state": "validated_uncommitted", + "state": "validated_committed", "work_root": "/tmp/stock-bot-wave16.kgaZm4", "committed_before_implementation": { "S02": "ca5abdde0e131ef4ec8c60ff9a4de4e277fc0820", @@ -6057,6 +6078,154 @@ "development_resources_untouched": true, "worktrees_and_logs_retained": true }, - "next": "Accept/commit S03, then S04 verified paper feed/operator readiness. S05 independently ready; research-product R01/R11 require ADR-006. P08 remains deferred by owner request." + "next": "Accept/commit S03, then S04 verified paper feed/operator readiness. S05 independently ready; research-product R01/R11 require ADR-006. P08 remains deferred by owner request.", + "completed_commit": "c01e96e4dd2879d0c728e57b48f5b6172adecd0f" + }, + "seventeenth_wave": [ + "S04" + ], + "seventeenth_wave_base": "c01e96e4dd2879d0c728e57b48f5b6172adecd0f", + "seventeenth_wave_notes": [ + "Actual vendor/socket feed is absent. Implement a strict normalized authenticated HTTP ingress and remain unready without a configured producer/current data/calendar; no invented provider certification.", + "Explicit canonical opt-in only; keep legacy execution intact for legacy accounts, skip legacy mutation/feed graph for canonical composition and reject canonical paper configuration in research-only composition.", + "Halt/feed/runtime-generation guards share the S03 account row lock; reconnect/restart/stale gap require renewed human activation. No native Finish/reset as a pause.", + "Inactive frames are health-only with immutable receipt disposition. Active frames enqueue complete derived command batches atomically. Preserve physical quote timestamps/sequences and one synchronized post-quote decision barrier.", + "Explicit recoverPending acknowledgement permits original-time replay of already-admitted work; activation succeeds only after recovery and final readiness. No silent skipping or restamping." + ], + "seventeenth_wave_validation": { + "state": "validated_uncommitted", + "work_root": "/tmp/stock-bot-wave17.JfETUx", + "committed_before_implementation": { + "S03": "c01e96e4dd2879d0c728e57b48f5b6172adecd0f" + }, + "scope": [ + "Explicit trusted quote-frame ingress with immutable calendars, completed-bar manifests and cadence", + "Generation-fenced durable host control under the canonical SQL account lock", + "Persistent operator halt, per-asset readiness and explicit historical recovery", + "Opt-in exclusive canonical composition and authenticated operator/feed REST routes", + "Actual SMA-to-Rust-to-SQL HTTP and research isolation regression tests" + ], + "source_integration": { + "files": 20, + "exact_hashes": { + "apps/stock/config/src/schemas/stock-app.schema.ts": "64bdc88949ebb872cf906d31725e36eeadae14db3cabed091630fa85d6dec6ab", + "apps/stock/orchestrator/src/api/rest/paper.ts": "a9235bcca32daadc4aa23348edcbbc1d958a643db9102fb225dcabcab242ee21", + "apps/stock/orchestrator/src/container.ts": "9db8987baa9f7e0fc462a8d47141123ed5087ad49d205d4b4c1c56679e3bdf31", + "apps/stock/orchestrator/src/contracts/paper-runtime.ts": "44ca90ab4b31bef527b084855b0d7b7bb6a259dd8bbcb8263307e96a22872467", + "apps/stock/orchestrator/src/execution/CanonicalPaperExecution.ts": "0f7c50df6c9ef27fe167ddf74296999e664ca7d1543653494215d0ac8dc9d60d", + "apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository.ts": "56912929fc1bea458cbcaae8125d2b98d7125e48784674a38c65c7c778539cd1", + "apps/stock/orchestrator/src/execution/canonical-paper.ts": "88e648ea345fd965fee5ddc1db787c41f55640d3009138df22e764d12daee409", + "apps/stock/orchestrator/src/index.ts": "efaa6bb761636988ea6f9c55d713766f28ce115c5234ea181e3ffe5616f2815c", + "apps/stock/orchestrator/src/paper/CanonicalPaperRuntime.ts": "b1f2315c03beead9031e779082415b4a1832f32ec98e67d882142d11137f93af", + "apps/stock/orchestrator/src/paper/feed.ts": "1ff4b9e46346f97e4e1bce4929f594cd885b4ee0dc598560adc704443f98f48a", + "apps/stock/orchestrator/src/routes/create-routes.ts": "6f9627ccd8b75819a757e7154b7f8020bbfc2235eb380b2747d97c1cdba68ff6", + "apps/stock/orchestrator/src/simple-container.ts": "8d7f51b87f8f5e2cba6298f3db67e79b1516a44da6db3610ee5fd319cca4282b", + "apps/stock/orchestrator/src/types.ts": "dc89de87a58eb50f865ef302bcb9108c7f9e6dfe82acd32c3228645efa871e11", + "test/fixtures/paper-feed.ts": "7321e4734c4a479bf49598401967da931f273bed29426cd5cc9950de1ad916fd", + "test/fixtures/paper-runtime.ts": "eb7821542290b1c3d7ed5673cb796143a18da82f87288d8cabab1ad0cde7d952", + "test/integration/paper-composition.test.ts": "880cc8996f0e89d088b75f2c215359f01fa88c7d9dd73593352015d6952a86f2", + "test/integration/paper-feed.test.ts": "a4d88a45bf275db365ef95d2d65e85bbad620b9e09819f3a896ddbb22f0953fe", + "test/integration/paper-routes.test.ts": "5a9f607ab756c3f1e5091575db63daee8ae97392f79535aaa3eb1b972c060ecb", + "test/postgres/paper-http.test.ts": "6df5064448b9d7897234c9786db2d197cfea3ef605bd6c300a8648e13c182f6b", + "test/postgres/paper-runtime.test.ts": "3a15bcba7ae0b423b5808a5906a342d9eea6a8f0f08aed9840471aef2fbb0780" + }, + "source_archive": "/tmp/stock-bot-wave17.JfETUx/s04-integrated-source.tar", + "source_archive_sha256": "6a0a38acea183444a3680b04650637aa10c6080fc25466e3ca7b0e6dc9304382", + "feed_archive_sha256": "0613896c3101ed27dfc1260d5da176368f50e22e5a9178e373529394a9ed1e11", + "control_archive_sha256": "da6e0195e5f102c13ca29ede7eb93a0bc0c36bcba51392ff0f8ab8e4f8fb1961", + "api_tests_archive_sha256": "d51c6c145f589590555f11318863cf9fd77a2af09016b57d40c18eba7299294c" + }, + "review": { + "reviewer": "/root/s03_review", + "result": "G1/G2 and scoped API/isolation accepted; all frozen hashes match; documentation auth-bypass caveat corrected", + "findings_resolved": [ + "Pending recovery cannot report ready", + "Fresh probe cannot hide stale executable quotes", + "Physical quote high-water persists across reconnect/restart", + "Rejected mutations preserve stale deactivation in a separate fenced transaction", + "Actual hour-old admitted quote recovers once at original price/time only with explicit acknowledgement", + "Malformed decimal HTTP inputs return400; unknown storage errors remain503", + "Canonical composition cannot expose or replace itself with legacy gateways" + ] + }, + "checks": [ + { + "command": "CARGO_BUILD_JOBS=2 bun run check", + "result": "passed outside sandbox", + "counts": { + "tooling": 82, + "utilities": 43, + "calculations": 44, + "integration": 454, + "rust": 150, + "rust_manual_ignored": 4 + }, + "log": "/tmp/stock-bot-wave17.JfETUx/integration-check-final.log" + }, + { + "command": "PIPELINE_TEST_DATABASE_URL=postgres://fixture:fixture@127.0.0.1:32817/stock_bot_safety BACKTEST_TEST_REDIS_URL=redis://127.0.0.1:32818/15 bun run test:postgres", + "result": "passed", + "tests": 104, + "assertions": 719, + "log": "/tmp/stock-bot-wave17.JfETUx/integration-postgres.log" + }, + { + "command": "bunx tsc --project /tmp/stock-bot-wave17.JfETUx/root-tests-tsconfig.json --noEmit", + "result": "passed", + "log": "/tmp/stock-bot-wave17.JfETUx/root-tests-typecheck-final.log" + }, + { + "command": "Scoped ESLint --no-ignore --max-warnings0 over all new tests/fixtures; scoped Prettier --check over all20 source/test files; git diff --check", + "result": "passed", + "logs": [ + "/tmp/stock-bot-wave17.JfETUx/root-test-lint.log", + "/tmp/stock-bot-wave17.JfETUx/integration-format.log" + ] + }, + { + "command": "CARGO_BUILD_JOBS=2 bun run --cwd apps/stock/engine build:release", + "result": "passed; final addon equals local target/release/libengine.so", + "log": "/tmp/stock-bot-wave17.JfETUx/integration-release-build.log" + }, + { + "command": "PIPELINE_TEST_DATABASE_URL=postgres://fixture:fixture@127.0.0.1:32817/stock_bot_safety bun test test/postgres/paper-runtime.test.ts test/postgres/paper-http.test.ts test/integration/paper-feed.test.ts test/integration/paper-routes.test.ts test/integration/paper-composition.test.ts scripts/test/native-bindings.test.ts", + "result": "passed against final release addon", + "tests": 55, + "assertions": 481, + "log": "/tmp/stock-bot-wave17.JfETUx/integration-release-focused.log" + } + ], + "native": { + "final_profile": "release", + "final_addon_sha256": "ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103", + "local_library_matches": true, + "rust_source_unchanged": true, + "performance_measurements": false + }, + "environment_notes": [ + "Sandbox PostgreSQL connection refusal required escalation; all disposable-fixture suites passed outside sandbox.", + "Sandbox native child tests timed out; only exact identified test process3655975 was terminated and full gate passed outside sandbox.", + "NAPI release build spawnSync EPERM required escalation.", + "Initial fixture issues corrected: generation test clock, exclusive research dataset end date, strict assertion types and formatting.", + "Browser E2E/Python analytics not rerun: no frontend or Python changes. No performance profiling or benchmark measurement." + ], + "limitations": [ + "No working external vendor quote producer was found; normalized HTTP fixture coverage verifies the boundary, not vendor connectivity. A real provider and declared operational calendars are still required.", + "Canonical composition is opt-in; no default change or paper/live activation. Live remains disabled.", + "Quote execution, raw prices, trusted built-in target strategies and explicit finite UTC session/cadence policies only. All configured assets require current quote/session readiness.", + "Existing explicit loopback auth-disabled mode remains supported and is not authenticated-feed certification.", + "Admitted historical recovery retains original prices/timestamps and needs explicit recoverPending; it does not pretend those fills use current quotes.", + "Metadata binding is not retained immutable code provenance; R01/R05 own artifacts. Invalid durable inputs remain pending; no auto-skip/capital reset." + ], + "cleanup": { + "status": "completed", + "development_resources_untouched": true, + "worktrees_and_logs_retained": true, + "stopped_container_ids": [ + "ebf9e7c2109562964d1367660f6c58cf46c4899d7c77740bf664674eb3dde124", + "d96d9a126e665226aeebc191b5b58e25eb29165cbabb4c099201f01e6364ef7f" + ] + }, + "next": "Accept/commit S04, then S05 composable multi-signal/regime example. R01/R11 still need ADR-006; performance remains deferred." } } diff --git a/docs/development/backlog/tasks/S04.md b/docs/development/backlog/tasks/S04.md index fadf18c9..3b79e2d9 100644 --- a/docs/development/backlog/tasks/S04.md +++ b/docs/development/backlog/tasks/S04.md @@ -6,8 +6,9 @@ Scheduling source of truth: [manifest entry S04](../manifest.json). No task is a ## Evidence and root cause -- **OPS-02 — Needs Investigation:** Paper/live operational readiness is not demonstrated end-to-end. Live is deliberately disabled; preserve that gate until feed, reconciliation and broker-specific recovery are verified. [apps/stock/orchestrator/src/core/ModeManager.ts:33](../../../../apps/stock/orchestrator/src/core/ModeManager.ts#L33); [apps/stock/orchestrator/src/container.ts:152](../../../../apps/stock/orchestrator/src/container.ts#L152). -- **FIN-06 — Verified:** Native simulation fills complete requested quantities at the latest price without bar-volume participation; current risk must be enforced at acceptance and fill, including pending exposure. [apps/stock/engine/src/backtest/engine.rs:374](../../../../apps/stock/engine/src/backtest/engine.rs#L374); [apps/stock/engine/src/backtest/engine.rs:414](../../../../apps/stock/engine/src/backtest/engine.rs#L414). +- **OPS-02 — Verified:** `MarketDataService.initialize()` creates a Socket.IO client, but `data-ingestion/src/routes/create-routes.ts` mounts no stream producer. The unmounted live route queues an absent handler. Connection logging is not feed readiness. +- **FIN-06 — Addressed by F04/F05/S03:** Canonical Rust already enforces quantity/cash/risk and quote capacity. S04 must connect that tested engine to explicit market-data timing and retain its durable recovery, rather than fix or duplicate financial arithmetic. See `execution/CanonicalPaperExecution.ts` and `PostgresCanonicalExecutionRepository.ts`. +- **OPS-02 composition evidence — Verified:** Existing composition constructs legacy execution/mode/order gateways; canonical activation requires an isolated graph and a persisted operator/feed gate, not just another boolean in a route. ## Intended behavior and implementation scope @@ -21,13 +22,13 @@ No unrelated refactor, new service or broker activation. ## Likely files and ownership -- apps/stock/orchestrator/src/paper/PaperTradingManager.ts -- apps/stock/orchestrator/src/services/MarketDataService.ts -- apps/stock/orchestrator/src/services/ExecutionService.ts -- apps/stock/orchestrator/src/api/rest/ -- apps/stock/data-ingestion/src/ +- apps/stock/orchestrator/src/paper/{feed,CanonicalPaperRuntime}.ts +- apps/stock/orchestrator/src/execution/{canonical-paper,CanonicalPaperExecution,PostgresCanonicalExecutionRepository}.ts +- apps/stock/orchestrator/src/{contracts/paper-runtime,api/rest/paper,container,simple-container,index,routes/create-routes,types}.ts +- apps/stock/config/src/schemas/stock-app.schema.ts +- test/{integration,postgres,fixtures}/paper-*.ts -Write locks: paper-runtime. One agent owns this change. Lock names do not override actual overlapping files. +Write locks: paper-runtime. Root owns shared contracts/composition/API; disjoint feed and custody slices have one owner each. Lock names do not override actual overlapping files. ## Dependencies and blockers @@ -58,3 +59,24 @@ Keep migrations additive and previous results readable. Do not add a switch that ## Handoff Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done. + +## Execution contract — 2026-10-23 + +Base `c01e96e` contains accepted S03. This wave implements an opt-in canonical composition; no default cutover or trading activation. Inspection found no usable quote producer behind the legacy Socket.IO client: ingestion does not serve that protocol, the live route is not mounted, and its queued handler is absent. Do not manufacture provider readiness. The implemented ingress is an authenticated normalized HTTP frame boundary; a real provider adapter and verified operational calendar remain prerequisites for running it. + +- Rust alone owns matching, financial state and risk. Host control state shares the existing SQL account row lock; no additional service/table. Immutable policy binds target-mode built-ins, explicit raw-price quote series, auxiliary completed-bar manifests/cadence, versioned UTC sessions and account risk boundaries. +- Each process generation fences prior hosts. Startup/reconnect disconnects or revokes activation. Initial and persisted human halt stop decisions, submissions and fills without finish/cancel/liquidation/reset. Every drain step rechecks controls under the account lock; old shutdown cannot stop a replacement. +- Feed frames carry original physical quote timestamps/sequences and explicit atomic release time. All quotes execute in native key order before the final synchronized decision; new intents cannot fill on those quotes. Completed bars are supplied, never synthesized. Session-open anchored bars may clip at declared session close. Auxiliary observations do not mark prices or create liquidity. +- Frame admission persists original receipt/disposition and every input atomically. Exact retries never change health-only/admitted meaning. Physical quote/bar receipts prevent conflicting or recycled observations, including inactive probes. New active frames cannot plan against pending recovery; producer retries after prior request drains. +- Fresh transport and every configured asset must be ready. Check the old deadline before refreshing health. Missing/stale/future/regressing/out-of-session data fail closed; no time repairs. A late fresh frame cannot silently resume execution. Native daily/drawdown risk remains authoritative and separate from the host pause. +- Previously admitted crash-recovery inputs retain their original times. Activation defaults to `recoverPending:false`; explicit `true` is required for pending historical work. Acknowledgement follows successful recovery and final fresh readiness. Invalid durable work remains pending with diagnostics; never skip/restamp/reset it. +- With HTTP authentication enabled, human operator credentials alone activate/halt; verified service credentials may submit feed frames. Existing explicit loopback development auth bypass maps to operator and remains supported; readiness in bypass mode is not authenticated-feed certification. Legacy order/position gateways and WebSocket controls are unavailable in canonical composition. Research uses its existing isolated worker. `/health` is liveness; `/api/paper/readiness` reports actual readiness or explicit unknown state. Live remains disabled. + +Mandatory added scenarios: actual HTTP → built-in SMA → later quote fill → SQL → restart; service activation denial; initial/persisted halt; locked halt race; stale generation/shutdown; idle-before-refresh; stale second asset; pending recovery status; old quote after fresh probe; immutable retry dispositions; explicit historical recovery; cross-session controls; physical observation conflicts; configured capital; canonical/research isolation. No performance work or benchmark is included. + + +## Validated handoff — 2026-10-23 + +Implementation and independent G1/G2/API isolation review accepted; manifest remains `review` until owner acceptance/commit. Full repository and PostgreSQL gates pass; the release-addon suite covers real SMA HTTP-to-fill restart, isolated research, all control regressions and native binding checks. See [wave17 validation](../manifest.json) and [roadmap](../../ROADMAP.md#seventeenth-wave-execution--2026-10-23) for exact commands, counts, hashes and limits. + +Canonical configuration is opt-in at `services.orchestrator.canonicalPaper`, validated before opening connections. `/api/paper/readiness` exposes state; operator `/activate` and `/halt` are separate from trusted producer `/feed/connect`, `/feed/frames`, `/feed/disconnect`. No provider connectivity is claimed and no account was operationally activated. All configured assets currently require covered sessions and fresh quotes; arbitrary callbacks, broker execution and automatic calendar/provider discovery remain outside this slice. diff --git a/test/fixtures/paper-feed.ts b/test/fixtures/paper-feed.ts new file mode 100644 index 00000000..c76348d8 --- /dev/null +++ b/test/fixtures/paper-feed.ts @@ -0,0 +1,88 @@ +import { parseFinancialDecimal } from '@stock-bot/types'; +import type { + PaperConfigurationInput, + PaperFrameInput, +} from '../../apps/stock/orchestrator/src/contracts/paper-runtime'; +import { canonicalConfig } from './canonical-paper'; + +export function paperFeedConfiguration(instruments = ['X']): PaperConfigurationInput { + const owners = instruments.map(instrument => `owner-${instrument}`); + const matching = canonicalConfig(owners); + matching.series = instruments.map(instrumentId => ({ + instrumentId, + seriesId: `${instrumentId}:quote`, + mode: 'Quote', + })); + return { + version: 1, + matching, + strategies: instruments.map(instrumentId => ({ + ownerId: `owner-${instrumentId}`, + strategyId: 'sma', + strategyVersion: 'sma-crossover-long-only/v1', + seed: 7, + instrumentId, + seriesId: `${instrumentId}:bar`, + ownerBudget: '100', + parameters: { fastPeriod: 1, slowPeriod: 2 }, + })), + policy: { + version: 1, + sourceId: 'trusted-fixture', + priceBasis: 'raw', + maxFeedAgeMs: 100, + observations: instruments.map(instrumentId => ({ + instrumentId, + seriesId: `${instrumentId}:bar`, + intervalMs: 1000, + staleAfterMs: 1000, + })), + cadence: instruments.map(instrumentId => ({ + ownerId: `owner-${instrumentId}`, + seriesIds: [`${instrumentId}:bar`], + })), + calendars: instruments.map(instrumentId => ({ + instrumentId, + calendarId: 'venue', + revision: '2026-10', + sessions: [{ sessionId: 'venue-1', opensAt: 0, closesAt: 10000 }], + })), + riskBoundaries: [], + }, + }; +} + +export function paperFeedFrame(at = 1000, instruments = ['X']): PaperFrameInput { + return { + version: 1, + sourceId: 'trusted-fixture', + connectionId: 'connection-1', + id: `frame-${at}`, + sequence: at, + availableAt: at, + quotes: instruments.map(instrumentId => ({ + instrumentId, + seriesId: `${instrumentId}:quote`, + observedAt: at, + sourceSequence: at, + bid: '10', + ask: '10', + bidSize: '100', + askSize: '100', + })), + observations: instruments.map(instrument_id => ({ + instrument_id, + series_id: `${instrument_id}:bar`, + interval_start: at - 1000, + interval_end: at, + event_time: at, + available_at: at, + source_sequence: at, + open: parseFinancialDecimal('10'), + high: parseFinancialDecimal('10'), + low: parseFinancialDecimal('10'), + close: parseFinancialDecimal('10'), + volume: parseFinancialDecimal('100'), + })), + }; +} diff --git a/test/fixtures/paper-runtime.ts b/test/fixtures/paper-runtime.ts new file mode 100644 index 00000000..c84e76f7 --- /dev/null +++ b/test/fixtures/paper-runtime.ts @@ -0,0 +1,183 @@ +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { Pool } from 'pg'; +import { PostgreSQLClient } from '@stock-bot/postgres'; +import { parseFinancialDecimal } from '@stock-bot/types'; +import type { StrategyProgram } from '../../apps/stock/orchestrator/src/contracts/canonical-strategy'; +import type { + PaperConfigurationInput, + PaperFrameInput, +} from '../../apps/stock/orchestrator/src/contracts/paper-runtime'; +import type { + CanonicalExecutionRepository, + CanonicalTransaction, +} from '../../apps/stock/orchestrator/src/execution/canonical-paper'; +import { PostgresCanonicalExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository'; +import { CanonicalPaperRuntime } from '../../apps/stock/orchestrator/src/paper/CanonicalPaperRuntime'; +import { canonicalConfig, counterProgram } from './canonical-paper'; +import { logger } from './execution'; + +export function paperConfig(): PaperConfigurationInput { + const matching = canonicalConfig(); + matching.risk.maxMarkAgeMs = 100; + return { + version: 1, + matching, + strategies: [ + { + ownerId: 'A', + strategyId: 'sma_crossover', + strategyVersion: 'sma-crossover-long-only/v1', + seed: 7, + instrumentId: 'X', + seriesId: 'X:bar', + ownerBudget: '500', + parameters: { fastPeriod: 1, slowPeriod: 2 }, + }, + ], + policy: { + version: 1, + sourceId: 'fixture', + priceBasis: 'raw', + maxFeedAgeMs: 100, + observations: [{ seriesId: 'X:bar', instrumentId: 'X', intervalMs: 10, staleAfterMs: 100 }], + cadence: [{ ownerId: 'A', seriesIds: ['X:bar'] }], + calendars: [ + { + instrumentId: 'X', + calendarId: 'venue', + revision: '1', + sessions: [{ sessionId: 'venue-1', opensAt: 0, closesAt: 10000 }], + }, + ], + riskBoundaries: [], + }, + }; +} + +export function paperFrame( + sequence: number, + at = sequence * 10, + connectionId = 'one' +): PaperFrameInput { + const price = parseFinancialDecimal('10'); + return { + version: 1, + sourceId: 'fixture', + connectionId, + id: `frame-${sequence}`, + sequence, + availableAt: at, + quotes: [ + { + instrumentId: 'X', + seriesId: 'X:quote', + observedAt: at, + sourceSequence: sequence, + bid: price, + ask: price, + bidSize: price, + askSize: price, + }, + ], + observations: [ + { + series_id: 'X:bar', + instrument_id: 'X', + interval_start: at - 10, + interval_end: at, + event_time: at, + available_at: at, + source_sequence: sequence, + open: price, + high: price, + low: price, + close: price, + volume: price, + }, + ], + }; +} + +export async function paperFixture( + configuration = paperConfig(), + program: StrategyProgram = counterProgram() +) { + const url = process.env.PIPELINE_TEST_DATABASE_URL; + if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { + throw new Error('Dedicated stock_bot_safety database required'); + } + const schema = 'stock_bot_safety_' + randomUUID().replaceAll('-', ''); + const admin = new Pool({ connectionString: url }); + await admin.query(`CREATE SCHEMA ${schema}`); + const pool = new Pool({ + connectionString: url, + options: `-c search_path=${schema} -c statement_timeout=10000`, + }); + for (const filename of [ + '11-simulation-execution-ledger.sql', + '13-strategy-recovery.sql', + '15-canonical-paper-intents.sql', + ]) { + await pool.query( + readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8') + ); + } + const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, + logger + ); + Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); + const repository = new PostgresCanonicalExecutionRepository(postgres); + let wrap = (tx: CanonicalTransaction): CanonicalTransaction => tx; + let afterCommit = () => {}; + const wrapped: CanonicalExecutionRepository = { + initialize: (account, owners) => repository.initialize(account, owners), + async transact(id, work) { + const result = await repository.transact(id, tx => work(wrap(tx))); + afterCommit(); + return result; + }, + }; + let now = 10; + const make = async (config = configuration) => { + const runtime = new CanonicalPaperRuntime({ + repository: wrapped, + programs: [ + { ...program, strategyId: 'sma_crossover', strategyVersion: 'sma-crossover-long-only/v1' }, + ], + now: () => now, + }); + await runtime.initialize(config); + return runtime; + }; + const accountId = configuration.matching.risk.ledger.accountId; + return { + pool, + postgres, + repository, + make, + runtime: await make(), + configuration, + clock(value: number) { + now = value; + }, + wrap(value: typeof wrap) { + wrap = value; + }, + afterCommit(value: typeof afterCommit) { + afterCommit = value; + }, + snapshot: () => + repository.transact(accountId, async tx => ({ + account: structuredClone(tx.account), + owners: await tx.owners(), + journal: await tx.journal(0), + })), + async close() { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }, + }; +} diff --git a/test/integration/paper-composition.test.ts b/test/integration/paper-composition.test.ts new file mode 100644 index 00000000..3eb47722 --- /dev/null +++ b/test/integration/paper-composition.test.ts @@ -0,0 +1,45 @@ +import { asFunction, createContainer as createDiContainer } from 'awilix'; +import { expect, test } from 'bun:test'; +import type { ServiceCradle } from '@stock-bot/di'; +import type { StockAppConfig } from '@stock-bot/stock-config'; +import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container'; +import { createContainer } from '../../apps/stock/orchestrator/src/simple-container'; +import { paperFeedConfiguration } from '../fixtures/paper-feed'; + +test('canonical paper rejects invalid role/configuration before resolving services', async () => { + let resolved = 0; + const container = createDiContainer(); + container.register({ + serviceContainer: asFunction(() => { + resolved++; + throw new Error('Unexpected service resolution'); + }), + }); + const config = paperFeedConfiguration(); + await expect( + registerOrchestratorServices(container, { + role: 'research-only', + canonicalPaper: config, + }) + ).rejects.toThrow('requires a paper composition'); + config.matching.series[0]!.mode = 'Open'; + await expect( + registerOrchestratorServices(container, { + canonicalPaper: config, + }) + ).rejects.toThrow('Quote execution only'); + expect(resolved).toBe(0); +}); + +test('live defaults, research canonical configuration and missing custody fail before connections', async () => { + const config = (orchestrator: unknown) => ({ services: { orchestrator } }) as StockAppConfig; + await expect(createContainer(config({ defaultMode: 'live' }))).rejects.toThrow( + 'Live trading is disabled' + ); + await expect( + createContainer(config({ defaultMode: 'backtest', canonicalPaper: paperFeedConfiguration() })) + ).rejects.toThrow('requires a paper composition'); + await expect( + createContainer(config({ canonicalPaper: paperFeedConfiguration() })) + ).rejects.toThrow('requires durable PostgreSQL'); +}); diff --git a/test/integration/paper-feed.test.ts b/test/integration/paper-feed.test.ts new file mode 100644 index 00000000..c4f4f241 --- /dev/null +++ b/test/integration/paper-feed.test.ts @@ -0,0 +1,467 @@ +import { describe, expect, test } from 'bun:test'; +import { stageFinancialTransaction } from '@stock-bot/engine'; +import { parseFinancialDecimal } from '@stock-bot/types'; +import { + parseFinancialTransactionResult, + type CanonicalMatchingCommand, +} from '../../apps/stock/orchestrator/src/contracts/canonical-execution'; +import { + PaperRuntimeError, + type PaperConfigurationInput, + type PaperFrameInput, +} from '../../apps/stock/orchestrator/src/contracts/paper-runtime'; +import type { CanonicalAccount } from '../../apps/stock/orchestrator/src/execution/canonical-paper'; +import { + planPaperFrame, + validatePaperConfiguration, + validatePaperFrame, +} from '../../apps/stock/orchestrator/src/paper/feed'; +import { paperFeedConfiguration, paperFeedFrame } from '../fixtures/paper-feed'; + +function fixture(input = paperFeedConfiguration()) { + const config = validatePaperConfiguration(input); + const identity = { + accountId: config.matching.risk.ledger.accountId, + sessionId: config.matching.risk.ledger.sessionId, + }; + let native = parseFinancialTransactionResult( + stageFinancialTransaction( + JSON.stringify({ version: 1, kind: 'initialize', identity, config: config.matching }) + ), + identity + ); + const account = (): Pick => ({ + checkpoint: native.checkpoint, + observed: 0, + latestObservations: [], + }); + return { + config, + identity, + account, + current: () => native, + plan: (frame = paperFeedFrame()) => + planPaperFrame(config, validatePaperFrame(config, frame, frame.availableAt), account()), + apply(command: CanonicalMatchingCommand) { + native = parseFinancialTransactionResult( + stageFinancialTransaction( + JSON.stringify({ + version: 1, + kind: 'apply', + identity, + checkpoint: native.checkpoint, + command, + }) + ), + identity + ); + expect(native.checkpoint.status).toBe('Running'); + return native; + }, + }; +} + +function invalidFrame( + change: (frame: PaperFrameInput) => void, + config = validatePaperConfiguration(paperFeedConfiguration()) +) { + const frame = paperFeedFrame(); + change(frame); + expect(() => validatePaperFrame(config, frame, 1000)).toThrow(); +} + +describe('trusted canonical paper feed policy', () => { + test('malformed decimal wire values remain input failures rather than server errors', () => { + const raw = paperFeedConfiguration(); + raw.matching.risk.ledger.initialCapital = 'bad'; + try { + validatePaperConfiguration(raw); + throw new Error('Malformed configuration was accepted'); + } catch (error) { + expect(error).toBeInstanceOf(PaperRuntimeError); + expect((error as PaperRuntimeError).kind).toBe('invalid-input'); + } + const config = validatePaperConfiguration(paperFeedConfiguration()); + const frame = paperFeedFrame(); + frame.quotes[0]!.bid = 'bad'; + try { + validatePaperFrame(config, frame, 1000); + throw new Error('Malformed frame was accepted'); + } catch (error) { + expect(error).toBeInstanceOf(PaperRuntimeError); + expect((error as PaperRuntimeError).kind).toBe('invalid-input'); + } + }); + + test('binds immutable built-in cohorts, observations and calendars without mutating caller input', () => { + const raw = paperFeedConfiguration(['Y', 'X']); + const before = JSON.stringify(raw); + const config = validatePaperConfiguration(raw); + expect(JSON.stringify(raw)).toBe(before); + expect(config.matching.series.map(series => series.instrumentId)).toEqual(['X', 'Y']); + expect(config.strategies.map(strategy => strategy.strategyId)).toEqual([ + 'sma_crossover', + 'sma_crossover', + ]); + expect(config.matching.risk.ledger.ownerIds).toEqual(['owner-X', 'owner-Y']); + const changes: ((raw: PaperConfigurationInput) => void)[] = [ + value => { + value.matching.series[0]!.mode = 'Open'; + }, + value => { + value.matching.owners[0]!.mode = 'Orders'; + }, + value => { + value.policy.cadence[0]!.ownerId = 'unknown'; + }, + value => { + value.policy.cadence[0]!.seriesIds = ['unknown']; + }, + value => { + value.strategies[0]!.instrumentId = 'unknown'; + }, + value => { + value.policy.observations[0]!.instrumentId = 'unknown'; + }, + value => { + value.matching.risk.ledger.ownerIds = []; + }, + value => { + value.policy.calendars[0]!.instrumentId = 'unknown'; + }, + value => { + value.policy.calendars[0]!.sessions.push({ + sessionId: 'overlap', + opensAt: 9000, + closesAt: 12000, + }); + }, + value => { + value.policy.riskBoundaries.push({ + ...value.matching.risk.ledger.riskSession, + sessionId: 'risk-2', + calendarRevision: 'other', + startsAt: 2000, + }); + }, + value => { + value.matching.series.push({ ...value.matching.series[0]!, seriesId: 'other' }); + }, + ]; + for (const change of changes) { + const candidate = paperFeedConfiguration(); + change(candidate); + expect(() => validatePaperConfiguration(candidate)).toThrow(); + } + }); + + test('rejects unknown, future, unaligned, crossed, impossible and observation-only frames', () => { + for (const change of [ + (value: PaperFrameInput) => { + value.sourceId = 'other'; + }, + (value: PaperFrameInput) => { + value.availableAt = 1001; + }, + (value: PaperFrameInput) => { + value.quotes = []; + }, + (value: PaperFrameInput) => { + value.quotes[0]!.instrumentId = 'unknown'; + }, + (value: PaperFrameInput) => { + value.quotes[0]!.seriesId = 'X:bar'; + }, + (value: PaperFrameInput) => { + value.quotes[0]!.observedAt = 1001; + }, + (value: PaperFrameInput) => { + value.quotes[0]!.bid = '11'; + }, + (value: PaperFrameInput) => { + value.quotes[0]!.ask = '0'; + }, + (value: PaperFrameInput) => { + value.quotes[0]!.bidSize = '-1'; + }, + (value: PaperFrameInput) => { + value.observations[0]!.series_id = 'unknown'; + }, + (value: PaperFrameInput) => { + value.observations[0]!.event_time = 999; + }, + (value: PaperFrameInput) => { + value.observations[0]!.interval_start = 1; + }, + (value: PaperFrameInput) => { + value.observations[0]!.interval_end = 999; + }, + (value: PaperFrameInput) => { + value.observations[0]!.available_at = 999; + }, + (value: PaperFrameInput) => { + value.observations[0]!.available_at = 1001; + }, + (value: PaperFrameInput) => { + value.observations[0]!.high = parseFinancialDecimal('9'); + }, + (value: PaperFrameInput) => { + value.observations[0]!.volume = parseFinancialDecimal('-1'); + }, + ]) { + invalidFrame(change); + } + const config = validatePaperConfiguration(paperFeedConfiguration()); + const exhausted = paperFeedFrame(10000); + expect(() => validatePaperFrame(config, exhausted, 10000)).toThrow('session coverage'); + const beforeOpen = paperFeedFrame(-1); + beforeOpen.sequence = 0; + beforeOpen.quotes[0]!.sourceSequence = 0; + beforeOpen.observations = []; + expect(() => validatePaperFrame(config, beforeOpen, 1000)).toThrow('session coverage'); + }); + + test('retains real timestamps and deduplicates only identical physical observations', () => { + const config = validatePaperConfiguration(paperFeedConfiguration()); + const raw = paperFeedFrame(); + raw.quotes[0]!.observedAt = 990; + raw.observations.push(structuredClone(raw.observations[0]!)); + const before = JSON.stringify(raw); + const frame = validatePaperFrame(config, raw, 1000); + expect(JSON.stringify(raw)).toBe(before); + expect(frame.quotes[0]!.observedAt).toBe(990); + expect(frame.observations).toHaveLength(1); + raw.observations[1]!.close = parseFinancialDecimal('9'); + raw.observations[1]!.low = parseFinancialDecimal('9'); + expect(() => validatePaperFrame(config, raw, 1000)).toThrow('Conflicting physical'); + raw.observations = []; + raw.quotes.push({ ...raw.quotes[0]! }); + expect(() => validatePaperFrame(config, raw, 1000)).toThrow('physical quote'); + raw.quotes[1]!.observedAt = 991; + expect(() => validatePaperFrame(config, raw, 1000)).toThrow('quote event key'); + }); +}); + +describe('paper frame deterministic native command planning', () => { + test('one multi-asset decision follows every quote and cannot fill until the next physical quotes', () => { + const f = fixture(paperFeedConfiguration(['Y', 'X'])); + const frame = paperFeedFrame(1000, ['Y', 'X']); + const plan = f.plan(frame); + expect(plan.map(input => input.command.body.kind)).toEqual([ + 'openSession', + 'openSession', + 'execute', + 'execute', + ]); + expect(plan.filter(input => input.decision)).toHaveLength(1); + expect(plan.slice(0, -1).every(input => !input.observations.length)).toBe(true); + const barrier = plan.at(-1)!.decision!; + expect(barrier.ownerIds).toEqual(['owner-X', 'owner-Y']); + expect(barrier.key).toEqual(plan.at(-1)!.command.key); + expect(barrier.key).toEqual({ + at: 1000, + phase: 'Execution', + instrumentId: 'Y', + sourceSequence: 1000, + }); + for (const input of plan) { + f.apply(input.command); + } + expect(f.current().view.portfolio.positions).toHaveLength(0); + f.apply({ + commandId: barrier.commandId, + key: barrier.key, + body: { + kind: 'submit', + decisions: ['X', 'Y'].map(instrumentId => ({ + version: 1, + sessionId: f.identity.sessionId, + barrierId: barrier.barrierId, + revision: f.current().checkpoint.revision, + decision: { + ownerId: `owner-${instrumentId}`, + decisionId: `decision-${instrumentId}`, + sequence: 0, + }, + intent: { + mode: 'target', + targets: [{ instrumentId, quantity: parseFinancialDecimal('2') }], + }, + })), + }, + }); + expect(f.current().view.portfolio.positions).toHaveLength(0); + expect(f.current().checkpoint.orders).toHaveLength(2); + const next = paperFeedFrame(1001, ['Y', 'X']); + next.observations = []; + const nextPlan = f.plan(next); + expect(nextPlan.every(input => !input.decision)).toBe(true); + for (const input of nextPlan) { + f.apply(input.command); + } + expect(f.current().view.portfolio.positions.map(position => position.quantity)).toEqual([ + parseFinancialDecimal('2'), + parseFinancialDecimal('2'), + ]); + expect(f.current().view.portfolio.cash).toBe('959.60000000'); + expect(f.current().view.portfolio.fees).toEqual([ + { ownerId: 'owner-X', amount: parseFinancialDecimal('0.2') }, + { ownerId: 'owner-Y', amount: parseFinancialDecimal('0.2') }, + ]); + }); + + test('quote identities survive frame/connection renaming and reject retimed reuse or backwards physical time', () => { + const f = fixture(); + const first = f.plan(); + const renamed = paperFeedFrame(); + renamed.id = 'renamed'; + renamed.connectionId = 'reconnected'; + renamed.sequence = 9; + expect(f.plan(renamed).at(-1)!.command.commandId).toBe(first.at(-1)!.command.commandId); + for (const input of first) { + f.apply(input.command); + } + const reused = paperFeedFrame(1001); + reused.observations = []; + reused.quotes[0]!.observedAt = 1000; + reused.quotes[0]!.sourceSequence = 1000; + expect(() => f.plan(reused)).toThrow('physical quote liquidity'); + reused.quotes[0]!.sourceSequence = 1001; + reused.quotes[0]!.observedAt = 999; + expect(() => f.plan(reused)).toThrow('regresses'); + reused.quotes[0]!.sourceSequence = 0; + reused.quotes[0]!.observedAt = 1001; + expect(f.plan(reused).at(-1)!.command.key.sourceSequence).toBe(0); + }); + + test('a newly published auxiliary series neither creates liquidity nor wakes unrelated cadence owners', () => { + const raw = paperFeedConfiguration(['X', 'Y']); + raw.policy.observations.push({ + seriesId: 'X:aux', + instrumentId: 'X', + intervalMs: 1000, + staleAfterMs: 50, + }); + const f = fixture(raw); + const frame = paperFeedFrame(1000, ['X', 'Y']); + frame.observations = [{ ...frame.observations[0]!, series_id: 'X:aux' }]; + const auxiliary = f.plan(frame); + expect(auxiliary.filter(input => input.command.body.kind === 'execute')).toHaveLength(2); + expect(auxiliary.filter(input => input.decision)).toHaveLength(0); + frame.observations.push(paperFeedFrame().observations[0]!); + const due = f.plan(frame).at(-1)!; + expect(due.decision!.ownerIds).toEqual(['owner-X']); + expect(due.decision!.inputs.find(input => input.series_id === 'Y:bar')!.availability).toBe( + 'Missing' + ); + expect(due.decision!.inputs.find(input => input.series_id === 'X:aux')!.availability).toEqual({ + Fresh: { event_time: 1000, available_at: 1000 }, + }); + }); + + test('accepts session-clipped complete bars and emits declared close/risk/open boundaries in native order', () => { + const raw = paperFeedConfiguration(); + raw.policy.calendars[0]!.sessions = [ + { sessionId: 'half-day', opensAt: 0, closesAt: 1500 }, + { sessionId: 'next-day', opensAt: 2000, closesAt: 3500 }, + ]; + raw.policy.riskBoundaries = [ + { ...raw.matching.risk.ledger.riskSession, sessionId: 'risk-2', startsAt: 2000 }, + ]; + raw.policy.observations[0]!.staleAfterMs = 500; + const f = fixture(raw); + for (const input of f.plan()) { + f.apply(input.command); + } + const frame = paperFeedFrame(2100); + frame.observations[0] = { + ...frame.observations[0]!, + interval_start: 1000, + interval_end: 1500, + event_time: 1500, + available_at: 2100, + }; + const plan = f.plan(frame); + expect( + plan.map(input => [ + input.command.body.kind, + input.command.key.at, + input.command.key.sourceSequence, + ]) + ).toEqual([ + ['closeSession', 1500, 0], + ['riskSessionBoundary', 2000, 1], + ['openSession', 2000, 2], + ['execute', 2100, 2100], + ]); + expect(plan.at(-1)!.decision!.inputs[0]!.availability).toEqual({ + Stale: { event_time: 1500, available_at: 2100 }, + }); + for (const input of plan) { + f.apply(input.command); + } + expect(f.current().checkpoint.sessions).toEqual([ + ['X', { sessionId: 'next-day', opensAt: 2000, closesAt: 3500 }], + ]); + const daily = structuredClone(raw); + daily.policy.observations[0]!.intervalMs = 86400000; + frame.observations[0]!.interval_start = 0; + expect( + validatePaperFrame(validatePaperConfiguration(daily), frame, 2100).observations[0]! + .interval_end + ).toBe(1500); + frame.quotes[0]!.observedAt = 1499; + expect(() => validatePaperFrame(f.config, frame, 2100)).toThrow('identity, time'); + }); + + test('keeps newly available older observations, while unchanged latest does not create decisions', () => { + const f = fixture(); + const newest = validatePaperFrame(f.config, paperFeedFrame(2000), 2000).observations[0]!; + const account = { ...f.account(), latestObservations: [newest], observed: 1 }; + const delayed = paperFeedFrame(3000); + delayed.observations = [{ ...paperFeedFrame().observations[0]!, available_at: 3000 }]; + const before = JSON.stringify(account); + const plan = planPaperFrame(f.config, validatePaperFrame(f.config, delayed, 3000), account); + expect(plan.at(-1)!.observations[0]!.event_time).toBe(1000); + expect(plan.at(-1)!.decision!.inputs[0]!.availability).toEqual({ + Fresh: { event_time: 2000, available_at: 2000 }, + }); + expect(JSON.stringify(account)).toBe(before); + delayed.observations = [newest]; + expect( + planPaperFrame(f.config, validatePaperFrame(f.config, delayed, 3000), account).at(-1)! + .decision + ).toBeUndefined(); + delayed.observations = [{ ...newest, volume: parseFinancialDecimal('101') }]; + expect(() => + planPaperFrame(f.config, validatePaperFrame(f.config, delayed, 3000), account) + ).toThrow('retained identity'); + }); + + test('atomic plan keys and physical sequence order are deterministic and fail closed behind the cursor', () => { + const f = fixture(); + const frame = paperFeedFrame(); + frame.quotes.push({ ...frame.quotes[0]!, observedAt: 999, sourceSequence: 999 }); + expect( + f + .plan(frame) + .filter(input => input.command.body.kind === 'execute') + .map(input => input.command.key.sourceSequence) + ).toEqual([999, 1000]); + frame.quotes[1]!.observedAt = 1000; + frame.quotes[0]!.observedAt = 999; + expect(() => f.plan(frame)).toThrow('reverses'); + for (const input of f.plan()) { + f.apply(input.command); + } + const behind = paperFeedFrame(999); + behind.observations = []; + behind.quotes[0]!.observedAt = 999; + expect(() => f.plan(behind)).toThrow(); + const snapshot = f.account(); + snapshot.checkpoint.status = 'Complete'; + expect(() => + planPaperFrame(f.config, validatePaperFrame(f.config, paperFeedFrame(2000), 2000), snapshot) + ).toThrow(PaperRuntimeError); + }); +}); diff --git a/test/integration/paper-routes.test.ts b/test/integration/paper-routes.test.ts new file mode 100644 index 00000000..d484fbf4 --- /dev/null +++ b/test/integration/paper-routes.test.ts @@ -0,0 +1,377 @@ +import { describe, expect, mock, test } from 'bun:test'; +import { Hono } from 'hono'; +import type { Server as SocketIOServer } from 'socket.io'; +import { createHttpSecurity } from '@stock-bot/di'; +import { createPaperRoutes } from '../../apps/stock/orchestrator/src/api/rest/paper'; +import { + PaperRuntimeError, + type PaperConfigurationInput, + type PaperConnection, + type PaperFrameInput, + type PaperReadiness, + type PaperRuntime, +} from '../../apps/stock/orchestrator/src/contracts/paper-runtime'; +import { ExecutionConflictError } from '../../apps/stock/orchestrator/src/execution/repository'; +import { createRoutes } from '../../apps/stock/orchestrator/src/routes/create-routes'; +import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types'; +import { paperFeedFrame } from '../fixtures/paper-feed'; + +const tokens = { + operator: 'paper-routes-admin-fixture-not-a-real-secret-1234', + service: 'paper-routes-service-fixture-not-a-real-secret-1234', + read: 'paper-routes-read-fixture-not-a-real-secret-1234', +}; +type Role = keyof typeof tokens; +const connection = { sourceId: 'trusted-fixture', connectionId: 'connection-1' }; +const readiness = (): PaperReadiness => ({ + configured: true, + accountId: 'paper-account', + sourceId: 'trusted-fixture', + active: false, + ready: true, + operatorHalted: true, + connected: true, + reasons: [], + lastReceivedAt: 1000, + lastAvailableAt: 1000, + requiresHistoricalRecovery: false, + pendingInput: null, + pendingBatch: null, + pendingDecisionSequence: null, + nativeStatus: 'Running', + risk: { dailyHalted: false, drawdownHalted: false }, +}); + +function runtimeFixture() { + return { + initialize: mock(async (_input: PaperConfigurationInput) => {}), + status: mock(async () => readiness()), + connect: mock(async (_input: PaperConnection) => readiness()), + disconnect: mock(async (_input: PaperConnection) => readiness()), + ingest: mock(async (_input: PaperFrameInput) => ({ + duplicate: false, + disposition: 'admitted' as const, + readiness: readiness(), + })), + activate: mock(async (_input: { recoverPending: boolean }) => readiness()), + halt: mock(async (_reason: string) => readiness()), + shutdown: mock(async () => {}), + } satisfies PaperRuntime; +} + +function fixture(runtime: PaperRuntime | null = runtimeFixture(), allRoutes = false) { + const logger = { + info: mock(() => {}), + warn: mock(() => {}), + debug: mock(() => {}), + error: mock(() => {}), + }; + const legacy = { + submitOrder: mock(async () => { + throw new Error('Legacy submit must be unreachable'); + }), + cancelOrder: mock(async () => { + throw new Error('Legacy cancel must be unreachable'); + }), + getPositions: mock(async () => { + throw new Error('Legacy positions must be unreachable'); + }), + getRecoveryStatus: mock(async () => { + throw new Error('Legacy recovery must be unreachable'); + }), + on: mock(() => {}), + }; + const services = { + logger, + custom: { + ...(runtime ? { CanonicalPaperRuntime: runtime } : {}), + ExecutionService: legacy, + BacktestRunner: {}, + ModeManager: { getCurrentMode: mock(() => 'live') }, + }, + } as unknown as OrchestratorServices; + const io = { on: mock(() => {}) }; + const app = new Hono(); + createHttpSecurity({ + adminToken: tokens.operator, + serviceToken: tokens.service, + readToken: tokens.read, + environment: 'test', + }).mount(app); + if (allRoutes) { + app.route('/', createRoutes(services, io as unknown as SocketIOServer)); + } else { + app.route('/api/paper', createPaperRoutes(services)); + } + return { + app, + logger, + legacy, + io, + request(path: string, role?: Role, body?: unknown, headers?: Record) { + return app.request(`/api/paper${path}`, { + method: body === undefined ? 'GET' : 'POST', + headers: { + ...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}), + 'Content-Type': 'application/json', + ...headers, + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }); + }, + }; +} + +const mutations = [ + { path: '/activate', method: 'activate', body: {}, feed: false }, + { path: '/halt', method: 'halt', body: { reason: 'operator-request' }, feed: false }, + { path: '/feed/connect', method: 'connect', body: connection, feed: true }, + { path: '/feed/disconnect', method: 'disconnect', body: connection, feed: true }, + { path: '/feed/frames', method: 'ingest', body: paperFeedFrame(), feed: true }, +] as const; + +describe('canonical paper HTTP authorization', () => { + test('real security distinguishes operator, service producer, reader and anonymous callers', async () => { + for (const role of ['operator', 'service', 'read', undefined] as const) { + const runtime = runtimeFixture(); + const f = fixture(runtime); + const response = await f.request('/readiness', role); + expect(response.status).toBe(role ? 200 : 401); + expect(runtime.status.mock.calls).toHaveLength(role ? 1 : 0); + for (const endpoint of mutations) { + const allowed = role === 'operator' || (role === 'service' && endpoint.feed); + const mutation = await f.request(endpoint.path, role, endpoint.body); + expect(mutation.status).toBe(allowed ? 200 : role ? 403 : 401); + expect(runtime[endpoint.method].mock.calls).toHaveLength(allowed ? 1 : 0); + } + } + }); + + test('caller actor headers, query strings and body fields cannot manufacture operator authority', async () => { + const runtime = runtimeFixture(); + const f = fixture(runtime); + const forged = { 'X-Actor': 'operator', 'X-Principal': 'operator', 'X-Role': 'admin' }; + for (const role of ['service', 'read', undefined] as const) { + const response = await f.request( + '/activate?principal=operator&actor=admin', + role, + {}, + forged + ); + expect(response.status).toBe(role ? 403 : 401); + } + expect((await f.request('/activate', 'operator', { actor: 'operator' }, forged)).status).toBe( + 400 + ); + expect(runtime.activate.mock.calls).toHaveLength(0); + expect((await f.request('/feed/connect', undefined, connection, forged)).status).toBe(401); + expect(runtime.connect.mock.calls).toHaveLength(0); + }); +}); + +describe('canonical paper HTTP input and readiness contracts', () => { + test('activation defaults to no historical recovery and accepts only the explicit strict option', async () => { + const runtime = runtimeFixture(); + const f = fixture(runtime); + expect((await f.request('/activate', 'operator', {})).status).toBe(200); + expect((await f.request('/activate', 'operator', { recoverPending: true })).status).toBe(200); + expect(runtime.activate.mock.calls).toEqual([ + [{ recoverPending: false }], + [{ recoverPending: true }], + ]); + for (const body of [ + { recoverPending: 'true' }, + { recoverPending: true, resetCapital: true }, + null, + [], + ]) { + expect((await f.request('/activate', 'operator', body)).status).toBe(400); + } + const malformed = await f.app.request('/api/paper/activate', { + method: 'POST', + headers: { Authorization: `Bearer ${tokens.operator}` }, + body: '{', + }); + expect(malformed.status).toBe(400); + expect(runtime.activate.mock.calls).toHaveLength(2); + }); + + test('halt and feed endpoints pass only validated normalized arguments to the runtime', async () => { + const runtime = runtimeFixture(); + const f = fixture(runtime); + expect((await f.request('/halt', 'operator', { reason: ' stop requested ' })).status).toBe( + 200 + ); + expect(runtime.halt.mock.calls).toEqual([['stop requested']]); + for (const body of [{ reason: '' }, { reason: ' ' }, { reason: 'stop', resetRisk: true }]) { + expect((await f.request('/halt', 'operator', body)).status).toBe(400); + } + for (const path of ['/feed/connect', '/feed/disconnect']) { + expect((await f.request(path, 'service', connection)).status).toBe(200); + expect((await f.request(path, 'service', { sourceId: connection.sourceId })).status).toBe( + 400 + ); + expect((await f.request(path, 'service', { ...connection, actor: 'operator' })).status).toBe( + 400 + ); + } + expect(runtime.connect.mock.calls).toEqual([[connection]]); + expect(runtime.disconnect.mock.calls).toEqual([[connection]]); + const frame = paperFeedFrame(); + const admitted = await f.request('/feed/frames', 'service', frame); + expect(admitted.status).toBe(200); + expect(await admitted.json()).toEqual({ + duplicate: false, + disposition: 'admitted', + readiness: readiness(), + }); + expect(runtime.ingest.mock.calls[0]![0].quotes[0]!.bid).toBe('10.00000000'); + for (const body of [ + { ...frame, unexpected: true }, + { ...frame, quotes: [] }, + { ...frame, quotes: [{ ...frame.quotes[0], brokerOrderId: 'forbidden' }] }, + { ...frame, observations: [{ ...frame.observations[0], futureFeature: 'forbidden' }] }, + ]) { + expect((await f.request('/feed/frames', 'service', body)).status).toBe(400); + } + expect(runtime.ingest.mock.calls).toHaveLength(1); + expect(runtime.initialize.mock.calls).toHaveLength(0); + }); + + test('malformed quote and observation decimals return400 before runtime admission', async () => { + const runtime = runtimeFixture(); + const f = fixture(runtime); + for (const malformed of ['bad', 'NaN', '1e5', '1.000000001']) { + const quote = paperFeedFrame(); + quote.quotes[0]!.bid = malformed; + expect((await f.request('/feed/frames', 'service', quote)).status).toBe(400); + const observation = paperFeedFrame(); + const body = { + ...observation, + observations: [{ ...observation.observations[0], close: malformed }], + }; + expect((await f.request('/feed/frames', 'service', body)).status).toBe(400); + } + expect(runtime.ingest.mock.calls).toHaveLength(0); + }); + + test('unconfigured readiness reports explicit unavailable state and never invents an account', async () => { + const f = fixture(null); + const response = await f.request('/readiness', 'read'); + expect(response.status).toBe(200); + expect(response.headers.get('Cache-Control')).toBe('no-store'); + expect(await response.json()).toEqual({ + configured: false, + accountId: null, + sourceId: null, + active: false, + ready: false, + operatorHalted: true, + connected: false, + reasons: ['not-configured'], + lastReceivedAt: null, + lastAvailableAt: null, + requiresHistoricalRecovery: false, + pendingInput: null, + pendingBatch: null, + pendingDecisionSequence: null, + nativeStatus: null, + risk: null, + }); + const activate = await f.request('/activate', 'operator', {}); + expect(activate.status).toBe(409); + expect(await activate.json()).toMatchObject({ code: 'not-ready' }); + }); + + test('configured readiness preserves recovery and risk diagnostics without claiming activation', async () => { + const runtime = runtimeFixture(); + const blocked: PaperReadiness = { + ...readiness(), + ready: false, + active: false, + connected: false, + reasons: ['disconnected', 'pending-financial-work'], + requiresHistoricalRecovery: true, + pendingInput: 'input-7', + pendingBatch: 'batch-3', + pendingDecisionSequence: 8, + risk: { dailyHalted: true, drawdownHalted: false }, + }; + runtime.status.mockImplementation(async () => blocked); + const response = await fixture(runtime).request('/readiness', 'read'); + expect(response.status).toBe(200); + expect(await response.json()).toEqual(blocked); + expect(response.headers.get('Cache-Control')).toBe('no-store'); + }); +}); + +describe('canonical paper HTTP failure and legacy gateway isolation', () => { + test('typed validation/readiness/conflict failures keep their public status classification', async () => { + const runtime = runtimeFixture(); + const f = fixture(runtime); + for (const [error, expectedStatus, code] of [ + [new PaperRuntimeError('invalid-input', 'Invalid physical quote'), 400, 'invalid-input'], + [new PaperRuntimeError('not-ready', 'Feed disconnected'), 409, 'not-ready'], + [new PaperRuntimeError('conflict', 'Frame conflicts'), 409, 'conflict'], + [new ExecutionConflictError('Account conflicts'), 409, 'conflict'], + ] as const) { + runtime.activate.mockImplementation(async () => { + throw error; + }); + const response = await f.request('/activate', 'operator', {}); + expect(response.status).toBe(expectedStatus); + expect(await response.json()).toEqual({ error: error.message, code }); + } + expect(f.logger.error.mock.calls).toHaveLength(0); + }); + + test('runtime failures return503 and never leak internal database or transport details', async () => { + const runtime = runtimeFixture(); + const f = fixture(runtime); + const failure = new Error('sensitive database driver details'); + runtime.status.mockImplementation(async () => { + throw failure; + }); + const failedStatus = await f.request('/readiness', 'read'); + expect(failedStatus.status).toBe(503); + expect(await failedStatus.json()).toEqual({ error: 'Canonical paper runtime unavailable' }); + for (const endpoint of mutations) { + runtime[endpoint.method].mockImplementation(async () => { + throw failure; + }); + const response = await f.request(endpoint.path, 'operator', endpoint.body); + expect(response.status).toBe(503); + expect(await response.json()).toEqual({ error: 'Canonical paper runtime unavailable' }); + expect(response.headers.get('Cache-Control')).toBe('no-store'); + } + expect(f.logger.error.mock.calls).toHaveLength(6); + }); + + test('canonical createRoutes blocks legacy account REST paths and does not register legacy WebSocket handlers', async () => { + const runtime = runtimeFixture(); + const f = fixture(runtime, true); + const headers = { Authorization: `Bearer ${tokens.operator}` }; + for (const path of [ + '/api/orders', + '/api/orders/order-1', + '/api/positions', + '/api/positions/X', + ]) { + for (const method of ['GET', 'POST', 'DELETE']) { + const response = await f.app.request(path, { method, headers }); + expect(response.status).toBe(409); + expect(await response.json()).toEqual({ + error: 'Legacy account gateway unavailable in canonical paper mode', + }); + } + } + const recovery = await f.app.request('/api/recovery', { headers }); + expect(await recovery.json()).toEqual({ engine: 'canonical-paper', ...readiness() }); + const health = await f.app.request('/health'); + expect(await health.json()).toMatchObject({ mode: 'paper', execution: 'canonical-paper' }); + expect(f.io.on.mock.calls).toHaveLength(0); + for (const call of Object.values(f.legacy)) { + expect(call.mock.calls).toHaveLength(0); + } + }); +}); diff --git a/test/postgres/paper-http.test.ts b/test/postgres/paper-http.test.ts new file mode 100644 index 00000000..ec7ed1e0 --- /dev/null +++ b/test/postgres/paper-http.test.ts @@ -0,0 +1,192 @@ +import { asValue } from 'awilix'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Hono } from 'hono'; +import { createHttpSecurity, ServiceContainerBuilder } from '@stock-bot/di'; +import { parseFinancialDecimal } from '@stock-bot/types'; +import { createPaperRoutes } from '../../apps/stock/orchestrator/src/api/rest/paper'; +import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container'; +import { builtinStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy'; +import type { PaperRuntime } from '../../apps/stock/orchestrator/src/contracts/paper-runtime'; +import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-sma'; +import { + BacktestConfigSchema, + type OrchestratorServices, +} from '../../apps/stock/orchestrator/src/types'; +import { logger } from '../fixtures/execution'; +import { paperConfig, paperFixture, paperFrame } from '../fixtures/paper-runtime'; + +const adminToken = 'paper-http-test-admin-token-not-real-123456'; +const serviceToken = 'paper-http-test-service-token-not-real-123456'; +const cleanup: (() => Promise)[] = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); +function api(runtime: PaperRuntime) { + const app = new Hono(); + createHttpSecurity({ adminToken, serviceToken }).mount(app); + app.route( + '/api/paper', + createPaperRoutes({ logger, custom: { CanonicalPaperRuntime: runtime } }) + ); + return async (path: string, body: unknown, producer = false) => { + const response = await app.request(`/api/paper/${path}`, { + method: 'POST', + headers: { + Authorization: `Bearer ${producer ? serviceToken : adminToken}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify(body), + }); + const result = await response.json(); + expect(response.status, JSON.stringify(result)).toBe(200); + return result; + }; +} + +describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)( + 'canonical paper HTTP and composition', + () => { + test('authenticated feed -> actual SMA -> next quote Rust fill -> durable restart without capital reset', async () => { + const config = paperConfig(); + config.matching.risk.ledger.initialCapital = '1234'; + config.strategies[0]!.ownerBudget = '20'; + const program = createBuiltinStrategy( + builtinStrategySelectionSchema.parse(config.strategies[0]) + ); + const f = await paperFixture(config, program); + cleanup.push(f.close); + let post = api(f.runtime); + const connection = { sourceId: 'fixture', connectionId: 'one' }; + await post('feed/connect', connection, true); + await post('feed/frames', paperFrame(1), true); + await post('activate', {}); + const send = async (sequence: number, price: string, bars = true) => { + f.clock(sequence * 10); + const frame = paperFrame(sequence); + frame.quotes[0]!.bid = frame.quotes[0]!.ask = parseFinancialDecimal(price); + frame.observations = bars + ? frame.observations.map(row => ({ + ...row, + open: parseFinancialDecimal(price), + high: parseFinancialDecimal(price), + low: parseFinancialDecimal(price), + close: parseFinancialDecimal(price), + })) + : []; + await post('feed/frames', frame, true); + }; + await send(2, '11'); + await send(3, '9'); + await send(4, '10'); + const decision = await f.snapshot(); + expect(decision.account.view.portfolio.positions).toHaveLength(0); + expect(decision.owners[0]!.diagnostic.nextDecisionSequence).toBe(3); + await send(5, '10', false); + const filled = await f.snapshot(); + expect(filled.account.view.portfolio.positions[0]!.quantity).toBe(parseFinancialDecimal('2')); + expect(filled.account.view.portfolio.cash).toBe(parseFinancialDecimal('1213.8')); + expect(filled.account.view.equity).toBe(parseFinancialDecimal('1233.8')); + expect(filled.journal.filter(row => row.payload.kind === 'effect')).not.toHaveLength(0); + await post('halt', { reason: 'restart fixture' }); + const restored = await f.make(); + post = api(restored); + expect(await restored.status()).toMatchObject({ + operatorHalted: true, + active: false, + connected: false, + }); + expect((await f.snapshot()).account.view).toEqual(filled.account.view); + expect((await f.snapshot()).account.checkpoint).toEqual(filled.account.checkpoint); + expect((await f.snapshot()).journal).toEqual(filled.journal); + expect((await f.snapshot()).owners).toEqual(filled.owners); + await post('feed/connect', { ...connection, connectionId: 'two' }, true); + f.clock(60); + await post('feed/frames', paperFrame(6, 60, 'two'), true); + await post('activate', {}); + expect((await f.snapshot()).account.view).toEqual(filled.account.view); + expect((await f.snapshot()).account.checkpoint).toEqual(filled.account.checkpoint); + expect((await f.snapshot()).journal).toEqual(filled.journal); + }); + + test('opt-in composition exposes canonical custody only and research cannot change its state', async () => { + const config = paperConfig(); + const f = await paperFixture( + config, + createBuiltinStrategy(builtinStrategySelectionSchema.parse(config.strategies[0])) + ); + cleanup.push(f.close); + const container = await new ServiceContainerBuilder() + .withOptions({ + enableCache: false, + enableQueue: false, + enableMongoDB: false, + enablePostgres: false, + enableQuestDB: false, + enableBrowser: false, + enableProxy: false, + }) + .build(); + const services: OrchestratorServices = { logger, postgres: f.postgres }; + container.register({ serviceContainer: asValue(services) }); + await registerOrchestratorServices(container, { + canonicalPaper: config, + nativeExecutionTimeoutMs: 10000, + }); + const custom = services.custom!; + cleanup.push(async () => { + await custom.CanonicalPaperRuntime!.shutdown(); + await custom.BacktestRunner!.shutdown(); + await container.dispose(); + }); + expect(custom.CanonicalPaperRuntime).toBeDefined(); + for (const key of [ + 'ExecutionService', + 'ModeManager', + 'StrategyManager', + 'MarketDataService', + 'PaperTradingManager', + ] as const) { + expect(custom[key]).toBeUndefined(); + expect(container.hasRegistration(key)).toBe(false); + } + expect((await custom.CanonicalPaperRuntime!.status()).active).toBe(false); + const before = await f.snapshot(); + const research = BacktestConfigSchema.parse({ + mode: 'backtest', + strategy: 'sma-crossover', + symbols: ['RESEARCH.TEST'], + startDate: '2024-01-01T00:00:00.000Z', + endDate: '2024-01-21T00:00:00.000Z', + initialCapital: 100000, + dataFrequency: '1d', + commission: 0, + slippage: 0, + config: { fastPeriod: 2, slowPeriod: 3 }, + }); + custom.StorageService!.getHistoricalBars = async () => + Array.from({ length: 20 }, (_, i) => { + const close = 100 + Math.sin(i) * 5; + return { + symbol: 'RESEARCH.TEST', + source: 'eod' as const, + timestamp: new Date(Date.parse(research.startDate) + i * 86400000), + open: close, + high: close + 1, + low: close - 1, + close, + volume: 1000000, + }; + }); + expect((await custom.BacktestEngine!.runBacktest(research)).status).toBe('completed'); + expect(await f.snapshot()).toEqual(before); + await expect( + registerOrchestratorServices(container, { canonicalPaper: config }) + ).rejects.toThrow('fresh runtime composition'); + await expect(registerOrchestratorServices(container)).rejects.toThrow( + 'fresh runtime composition' + ); + }); + } +); diff --git a/test/postgres/paper-runtime.test.ts b/test/postgres/paper-runtime.test.ts new file mode 100644 index 00000000..141cb196 --- /dev/null +++ b/test/postgres/paper-runtime.test.ts @@ -0,0 +1,543 @@ +import { afterEach, describe, expect, test } from 'bun:test'; +import { parseFinancialDecimal } from '@stock-bot/types'; +import { compareEventKeys } from '../../apps/stock/orchestrator/src/execution/canonical-paper'; +import { CanonicalPaperExecution } from '../../apps/stock/orchestrator/src/execution/CanonicalPaperExecution'; +import { counterProgram, quoteInput } from '../fixtures/canonical-paper'; +import { paperConfig, paperFixture, paperFrame } from '../fixtures/paper-runtime'; + +const connection = { sourceId: 'fixture', connectionId: 'one' }; +test('host event keys preserve Rust UTF-8 instrument ordering for supplementary Unicode', () => { + const key = { at: 1, phase: 'Execution' as const, sourceSequence: 1 }; + expect( + compareEventKeys({ ...key, instrumentId: '\u{10000}' }, { ...key, instrumentId: '\ue000' }) + ).toBeGreaterThan(0); +}); +const cleanup: (() => Promise)[] = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); +async function fixture(config = paperConfig(), program = counterProgram()) { + const f = await paperFixture(config, program); + cleanup.push(f.close); + return f; +} +async function start(f: Awaited>) { + await f.runtime.connect(connection); + expect((await f.runtime.ingest(paperFrame(1))).disposition).toBe('health-only'); + await f.runtime.activate({ recoverPending: false }); +} +function deferred() { + let resolve!: () => void; + const promise = new Promise(done => { + resolve = done; + }); + return { promise, resolve }; +} + +describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)( + 'controlled canonical paper on real PostgreSQL', + () => { + test('requires initial activation, retains inactive retry disposition, and freezes active retries after halt', async () => { + const f = await fixture(); + const initial = await f.runtime.status(); + expect(initial).toMatchObject({ + active: false, + ready: false, + connected: false, + operatorHalted: true, + }); + await start(f); + expect(await f.runtime.ingest(paperFrame(1))).toMatchObject({ + duplicate: true, + disposition: 'health-only', + }); + expect((await f.snapshot()).account.inputSequence).toBe(0); + f.clock(20); + const frame = paperFrame(2); + expect((await f.runtime.ingest(frame)).disposition).toBe('admitted'); + const before = await f.snapshot(); + expect(before.owners[0]!.diagnostic.nextDecisionSequence).toBe(1); + await f.runtime.halt('human stop'); + expect(await f.runtime.ingest(frame)).toMatchObject({ + duplicate: true, + disposition: 'admitted', + readiness: { active: false, operatorHalted: true }, + }); + expect((await f.snapshot()).account.checkpoint).toEqual(before.account.checkpoint); + f.clock(30); + expect((await f.runtime.ingest(paperFrame(3))).disposition).toBe('health-only'); + expect((await f.snapshot()).owners).toEqual(before.owners); + }); + + test('persists halt and fences all stale-generation controls, ingestion and shutdown after replacement', async () => { + const f = await fixture(); + await start(f); + await f.runtime.halt('persist me'); + const replacement = await f.make(); + expect(await replacement.status()).toMatchObject({ + active: false, + connected: false, + operatorHalted: true, + }); + f.clock(20); + await expect(f.runtime.ingest(paperFrame(2))).rejects.toThrow('generation'); + await expect(f.runtime.activate({ recoverPending: true })).rejects.toThrow('generation'); + await expect(f.runtime.shutdown()).rejects.toThrow('generation'); + await expect( + (f.runtime as unknown as { execution: CanonicalPaperExecution }).execution.drain() + ).rejects.toThrow('generation'); + await replacement.connect({ ...connection, connectionId: 'two' }); + f.clock(20); + await replacement.ingest(paperFrame(2, 20, 'two')); + await replacement.activate({ recoverPending: false }); + expect(await replacement.status()).toMatchObject({ + active: true, + connected: true, + operatorHalted: false, + }); + await replacement.disconnect(connection); + expect((await replacement.status()).active).toBe(true); + await replacement.connect({ ...connection, connectionId: 'two' }); + expect((await replacement.status()).active).toBe(true); + await replacement.connect({ ...connection, connectionId: 'three' }); + expect(await replacement.status()).toMatchObject({ + active: false, + connected: true, + ready: false, + }); + }); + + test('long idle then a fresh frame revokes activation without a preceding status poll', async () => { + const f = await fixture(); + await start(f); + f.clock(200); + const result = await f.runtime.ingest(paperFrame(2, 200)); + expect(result).toMatchObject({ disposition: 'health-only', readiness: { active: false } }); + expect((await f.snapshot()).account.inputSequence).toBe(0); + await f.runtime.activate({ recoverPending: false }); + expect((await f.runtime.status()).active).toBe(true); + }); + + test('frame inputs, health and receipts commit atomically and conflicting retries cannot alter them', async () => { + const f = await fixture(); + await start(f); + const before = await f.snapshot(); + let writes = 0; + f.wrap(tx => ({ + ...tx, + async putInput(input) { + if (++writes === 2) { + throw new Error('atomic enqueue failure'); + } + await tx.putInput(input); + }, + })); + f.clock(20); + await expect(f.runtime.ingest(paperFrame(2))).rejects.toThrow('atomic enqueue failure'); + expect((await f.snapshot()).account).toEqual(before.account); + f.wrap(tx => tx); + expect(await f.runtime.ingest(paperFrame(2))).toMatchObject({ + duplicate: false, + disposition: 'admitted', + }); + const saved = await f.snapshot(); + const conflict = paperFrame(2); + conflict.quotes[0]!.ask = parseFinancialDecimal('11'); + await expect(f.runtime.ingest(conflict)).rejects.toThrow('conflicting content'); + expect((await f.snapshot()).account).toEqual(saved.account); + }); + + test('new frame IDs cannot turn inactive probe quotes into later tradable liquidity', async () => { + const f = await fixture(); + await start(f); + f.clock(20); + const recycled = paperFrame(2); + recycled.quotes = paperFrame(1).quotes; + await expect(f.runtime.ingest(recycled)).rejects.toThrow('known physical quote'); + recycled.quotes[0]!.bidSize = parseFinancialDecimal('11'); + await expect(f.runtime.ingest(recycled)).rejects.toThrow('conflicting content'); + expect((await f.snapshot()).account.inputSequence).toBe(0); + }); + + test('new quote identities cannot regress a fresh inactive probe or hide stale executable quotes', async () => { + const f = await fixture(); + await start(f); + f.clock(20); + const old = paperFrame(2); + old.quotes[0]!.observedAt = 5; + await expect(f.runtime.ingest(old)).rejects.toThrow('regresses'); + expect((await f.snapshot()).account.inputSequence).toBe(0); + await f.runtime.halt('probe'); + f.clock(200); + await f.runtime.ingest(paperFrame(3, 200)); + await f.runtime.activate({ recoverPending: false }); + f.clock(210); + const stale = paperFrame(4, 210); + stale.quotes[0]!.observedAt = 100; + await expect(f.runtime.ingest(stale)).rejects.toThrow('regresses'); + expect((await f.snapshot()).account.inputSequence).toBe(0); + }); + + test('equal-time quotes require nonregressing physical sequence; a newer sequence remains admissible', async () => { + const f = await fixture(); + await start(f); + f.clock(20); + const newer = paperFrame(2); + newer.quotes[0]!.observedAt = 10; + expect((await f.runtime.ingest(newer)).disposition).toBe('admitted'); + const saved = await f.snapshot(); + f.clock(30); + const older = paperFrame(3); + older.quotes[0]!.observedAt = 10; + older.quotes[0]!.sourceSequence = 0; + await expect(f.runtime.ingest(older)).rejects.toThrow('regresses'); + expect((await f.snapshot()).account.checkpoint).toEqual(saved.account.checkpoint); + }); + + test.each(['reconnect', 'restart'] as const)( + '%s preserves quote highwater while requiring new connection health', + async kind => { + const f = await fixture(); + await f.runtime.connect(connection); + f.clock(30); + await f.runtime.ingest(paperFrame(3)); + const runtime = kind === 'restart' ? await f.make() : f.runtime; + await runtime.connect({ ...connection, connectionId: 'two' }); + expect((await runtime.status()).reasons).toContain('quote-stale:X'); + f.clock(40); + const old = paperFrame(4, 40, 'two'); + old.quotes[0]!.observedAt = 20; + old.quotes[0]!.sourceSequence = 2; + await expect(runtime.ingest(old)).rejects.toThrow('regresses'); + expect((await f.snapshot()).account.inputSequence).toBe(0); + await runtime.ingest(paperFrame(4, 40, 'two')); + expect((await runtime.activate({ recoverPending: false })).active).toBe(true); + } + ); + + test.each(['malformed', 'conflict', 'activation'] as const)( + 'a rejected %s request durably latches stale inactivity without polling or admitting its input', + async kind => { + const f = await fixture(); + await start(f); + const before = await f.snapshot(); + f.clock(200); + if (kind === 'activation') { + await expect(f.runtime.activate({ recoverPending: false })).rejects.toThrow( + 'unavailable' + ); + } else { + const rejected = kind === 'conflict' ? paperFrame(1) : paperFrame(2, 200); + if (kind === 'conflict') { + rejected.quotes[0]!.ask = parseFinancialDecimal('11'); + } else { + rejected.quotes[0]!.ask = parseFinancialDecimal('0'); + } + await expect(f.runtime.ingest(rejected)).rejects.toThrow(); + } + // Read persisted custody directly: status() must not be what latches the halt. + const stopped = await f.snapshot(); + expect(stopped.account.host?.active).toBe(false); + expect(stopped.account.checkpoint).toEqual(before.account.checkpoint); + expect(stopped.account.inputSequence).toBe(0); + expect(stopped.account.host!.frames).toEqual(before.account.host!.frames); + expect(stopped.account.host!.lastAvailableAt).toBe(before.account.host!.lastAvailableAt); + } + ); + + test('fresh transport and asset A cannot certify a stale required asset B or exhausted calendars', async () => { + const config = paperConfig(); + config.matching.series.push({ instrumentId: 'Y', seriesId: 'Y:quote', mode: 'Quote' }); + config.policy.calendars.push({ ...config.policy.calendars[0]!, instrumentId: 'Y' }); + const f = await fixture(config); + await f.runtime.connect(connection); + await f.runtime.ingest(paperFrame(1)); + await expect(f.runtime.activate({ recoverPending: false })).rejects.toThrow('quote-stale:Y'); + f.clock(20); + const frame = paperFrame(2); + frame.quotes.push({ ...frame.quotes[0]!, instrumentId: 'Y', seriesId: 'Y:quote' }); + await f.runtime.ingest(frame); + await f.runtime.activate({ recoverPending: false }); + f.clock(110); + await f.runtime.ingest(paperFrame(3, 110)); + f.clock(121); + expect(await f.runtime.status()).toMatchObject({ active: false, ready: false }); + expect((await f.runtime.status()).reasons).toContain('quote-stale:Y'); + f.clock(10000); + expect((await f.runtime.status()).reasons).toContain('calendar-uncovered:X'); + }); + + test('binds configured capital and policy and refuses uncontrolled reopening or direct enqueue', async () => { + const f = await fixture(); + expect((await f.snapshot()).account.view.portfolio.cash).toBe(parseFinancialDecimal('1000')); + const changed = paperConfig(); + changed.matching.risk.ledger.initialCapital = '2000'; + await expect(f.make(changed)).rejects.toThrow('configuration'); + const plain = new CanonicalPaperExecution({ + repository: f.repository, + programs: [ + { + ...counterProgram(), + strategyId: 'sma_crossover', + strategyVersion: 'sma-crossover-long-only/v1', + }, + ], + }); + await expect(plain.initialize(f.configuration.matching)).rejects.toThrow('configuration'); + const privileged = (f.runtime as unknown as { execution: CanonicalPaperExecution }).execution; + await expect(privileged.enqueue(quoteInput(1))).rejects.toThrow('atomic producer frames'); + expect((await f.snapshot()).account.inputSequence).toBe(0); + }); + + test('requires explicit historical recovery, preserves original times, and retains poisoned decisions', async () => { + let fail = true; + const base = counterProgram(); + const f = await fixture(paperConfig(), { + ...base, + decide: context => { + if (fail) { + throw new Error('poisoned strategy'); + } + return base.decide(context); + }, + }); + await start(f); + f.clock(20); + await expect(f.runtime.ingest(paperFrame(2))).rejects.toThrow('poisoned strategy'); + const pending = await f.runtime.status(); + expect(pending).toMatchObject({ active: false, requiresHistoricalRecovery: true }); + f.clock(200); + await f.runtime.ingest(paperFrame(3, 200)); + await f.repository.transact(f.configuration.matching.risk.ledger.accountId, async tx => { + if (tx.account.host) { + tx.account.host.diagnostic = null; + } + }); + expect(await f.runtime.status()).toMatchObject({ + ready: false, + reasons: ['historical-recovery-required'], + }); + await expect(f.runtime.activate({ recoverPending: false })).rejects.toThrow('recoverPending'); + await expect(f.runtime.activate({ recoverPending: true })).rejects.toThrow( + 'poisoned strategy' + ); + expect(await f.runtime.status()).toMatchObject({ + active: false, + requiresHistoricalRecovery: true, + }); + fail = false; + expect(await f.runtime.activate({ recoverPending: true })).toMatchObject({ + active: true, + ready: true, + requiresHistoricalRecovery: false, + }); + const snapshot = await f.snapshot(); + const decisions = snapshot.journal.filter(row => row.payload.kind === 'decision'); + expect(decisions).toHaveLength(1); + expect(decisions[0]!.payload.kind === 'decision' && decisions[0]!.payload.key.at).toBe(20); + expect(snapshot.owners[0]!.diagnostic.observationCount).toBe(1); + }); + + test('explicit recovery after an hour fills an already admitted quote at its original price/time exactly once', async () => { + const config = paperConfig(); + config.policy.calendars[0]!.sessions[0]!.closesAt = 7_200_000; + const f = await fixture(config); + await start(f); + f.clock(20); + await f.runtime.ingest(paperFrame(2)); + let armed = true; + f.wrap(tx => ({ + ...tx, + async appendJournal(payload) { + if (armed) { + armed = false; + throw new Error('crash before quote commit'); + } + return tx.appendJournal(payload); + }, + })); + f.clock(30); + const admitted = paperFrame(3); + await expect(f.runtime.ingest(admitted)).rejects.toThrow('crash before quote commit'); + expect((await f.snapshot()).account.view.portfolio.positions).toHaveLength(0); + const restored = await f.make(); + await restored.connect({ ...connection, connectionId: 'two' }); + f.clock(3_600_030); + const probe = paperFrame(4, 3_600_030, 'two'); + probe.quotes[0]!.bid = parseFinancialDecimal('99'); + probe.quotes[0]!.ask = parseFinancialDecimal('99'); + expect((await restored.ingest(probe)).disposition).toBe('health-only'); + await expect(restored.activate({ recoverPending: false })).rejects.toThrow('recoverPending'); + expect(await restored.activate({ recoverPending: true })).toMatchObject({ + active: true, + ready: true, + requiresHistoricalRecovery: false, + }); + const recovered = await f.snapshot(); + expect(recovered.account.view.portfolio.cash).toBe(parseFinancialDecimal('979.8')); + expect(recovered.account.view.portfolio.positions[0]!.quantity).toBe( + parseFinancialDecimal('2') + ); + expect(recovered.account.view.portfolio.fees[0]!.amount).toBe(parseFinancialDecimal('0.2')); + const quotes = recovered.journal.filter( + row => + row.payload.kind === 'command' && + row.payload.command.key.at === 30 && + row.payload.command.body.kind === 'execute' + ); + expect(quotes).toHaveLength(1); + const payload = quotes[0]!.payload; + if (payload.kind !== 'command' || payload.command.body.kind !== 'execute') { + throw new Error('Missing quote command'); + } + expect(payload.command.body.observation).toMatchObject({ + kind: 'quote', + observedAt: 30, + ask: parseFinancialDecimal('10'), + }); + expect(await restored.ingest(admitted)).toMatchObject({ + duplicate: true, + disposition: 'admitted', + }); + expect((await f.snapshot()).account.checkpoint).toEqual(recovered.account.checkpoint); + }); + + test('a halt waiting on the real account lock stops the next financial step without discarding work', async () => { + const f = await fixture(); + await start(f); + const reached = deferred(); + const release = deferred(); + let armed = true; + f.wrap(tx => ({ + ...tx, + async appendJournal(payload) { + if (armed && payload.kind === 'decision') { + armed = false; + reached.resolve(); + await release.promise; + } + return tx.appendJournal(payload); + }, + })); + f.clock(20); + const ingest = f.runtime.ingest(paperFrame(2)); + await reached.promise; + const halt = f.runtime.halt('race stop'); + // Verify PostgreSQL sees a lock waiter before allowing the financial step to commit. + let waiting = false; + for (let attempt = 0; attempt < 100; attempt++) { + const rows = await f.pool.query( + "SELECT 1 FROM pg_stat_activity WHERE datname=current_database() AND wait_event_type='Lock' AND query LIKE 'SELECT state FROM simulation_accounts%' " + ); + if (rows.rowCount) { + waiting = true; + break; + } + await new Promise(resolve => setTimeout(resolve, 5)); + } + release.resolve(); + expect(waiting).toBe(true); + expect(await halt).toMatchObject({ active: false, operatorHalted: true }); + await ingest; + const snapshot = await f.snapshot(); + expect(snapshot.account.pendingDecisionSequence).not.toBeNull(); + expect(snapshot.owners[0]!.diagnostic.nextDecisionSequence).toBe(0); + expect(snapshot.account.view.orders).toHaveLength(0); + }); + + test.each(['input', 'batch'] as const)( + 'explicit recovery retains %s work across transient SQL or acknowledgement failures', + async stage => { + const f = await fixture(); + await start(f); + let armed = true; + let lostAcknowledgement = false; + f.wrap(tx => ({ + ...tx, + async appendJournal(payload) { + if (stage === 'input' && armed) { + armed = false; + throw new Error('transient SQL failure'); + } + return tx.appendJournal(payload); + }, + async putBatch(batch) { + await tx.putBatch(batch); + if (stage === 'batch' && armed) { + armed = false; + lostAcknowledgement = true; + } + }, + })); + f.afterCommit(() => { + if (lostAcknowledgement) { + lostAcknowledgement = false; + throw new Error('lost batch acknowledgement'); + } + }); + f.clock(20); + await expect(f.runtime.ingest(paperFrame(2))).rejects.toThrow(); + const stopped = await f.runtime.status(); + expect(stopped.active).toBe(false); + expect(stage === 'input' ? stopped.pendingInput : stopped.pendingBatch).not.toBeNull(); + f.clock(200); + await f.runtime.ingest(paperFrame(3, 200)); + await expect(f.runtime.activate({ recoverPending: false })).rejects.toThrow( + 'recoverPending' + ); + expect(await f.runtime.activate({ recoverPending: true })).toMatchObject({ + active: true, + requiresHistoricalRecovery: false, + }); + expect((await f.snapshot()).owners[0]!.diagnostic.nextDecisionSequence).toBe(1); + } + ); + + test('auxiliary cadence survives restart; known old physical bars dedup while new delayed bars remain visible', async () => { + const config = paperConfig(); + config.policy.observations.push({ + seriesId: 'X:slow', + instrumentId: 'X', + intervalMs: 10, + staleAfterMs: 100, + }); + config.policy.cadence[0]!.seriesIds = ['X:slow']; + config.strategies[0]!.seriesId = 'X:slow'; + const f = await fixture(config); + await start(f); + f.clock(20); + const fast = paperFrame(2); + await f.runtime.ingest(fast); + expect((await f.snapshot()).owners[0]!.pendingObservations).toHaveLength(1); + const restored = await f.make(); + await restored.connect({ ...connection, connectionId: 'two' }); + f.clock(30); + await restored.ingest(paperFrame(3, 30, 'two')); + await restored.activate({ recoverPending: false }); + f.clock(40); + const slow = paperFrame(4, 40, 'two'); + slow.observations = [ + fast.observations[0]!, + { + ...fast.observations[0]!, + series_id: 'X:slow', + event_time: 20, + available_at: 40, + source_sequence: 99, + }, + ]; + await restored.ingest(slow); + const snapshot = await f.snapshot(); + expect(snapshot.owners[0]!.diagnostic.observationCount).toBe(2); + expect(snapshot.owners[0]!.diagnostic.nextDecisionSequence).toBe(1); + expect(snapshot.owners[0]!.diagnostic.state).toMatchObject({ seen: [2, 99] }); + f.clock(50); + const conflict = paperFrame(5, 50, 'two'); + conflict.observations = [{ ...fast.observations[0]!, volume: parseFinancialDecimal('11') }]; + await expect(restored.ingest(conflict)).rejects.toThrow('conflicting content'); + expect((await f.snapshot()).account.checkpoint).toEqual(snapshot.account.checkpoint); + }); + } +);