diff --git a/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts b/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts index c6b03e02..261dd7c8 100644 --- a/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts +++ b/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts @@ -8,6 +8,10 @@ import { replayIdentitySchema, replayResultFormatSchema, } from '../contracts/native-replay'; +import { + parseStrategyReplayResult, + strategyReplayRequestSchema, +} from '../contracts/strategy-replay'; import { nativeWorkerMessageSchema, type NativeWorkerRequest } from './native-worker-protocol'; import { BacktestConflictError } from './run-repository'; @@ -31,18 +35,25 @@ export class NativeBacktestWorker { if (this.active) { throw new BacktestConflictError('A native backtest worker is already running'); } + // Detach the entire normalized strategy request, including the frozen-data + // payload. The caller must not mutate what is sent or what counts as success. + const strategyRequest = + request.type === 'runStrategyReplay' + ? structuredClone(strategyReplayRequestSchema.parse(request)) + : undefined; + const submitted = strategyRequest ?? request; // Capture expected identity/policy before asynchronous execution. A caller // mutating its request cannot change which completed child result is valid. const expectedReplay = - request.type === 'runReplayTrace' + submitted.type === 'runReplayTrace' || submitted.type === 'runStrategyReplay' ? { identity: replayIdentitySchema.parse({ version: 1, - sessionId: request.config.matching.risk.ledger.sessionId, - datasetHash: (request.dataset as { manifest?: { hash?: unknown } })?.manifest?.hash, + sessionId: submitted.config.matching.risk.ledger.sessionId, + datasetHash: (submitted.dataset as { manifest?: { hash?: unknown } })?.manifest?.hash, }), - policy: replayConfigSchema.parse(request.config), - format: replayResultFormatSchema.parse(request.resultFormat ?? 'trace'), + policy: replayConfigSchema.parse(submitted.config), + format: replayResultFormatSchema.parse(submitted.resultFormat ?? 'trace'), } : undefined; const child = fork(fileURLToPath(this.workerUrl), [], { @@ -85,13 +96,20 @@ export class NativeBacktestWorker { } else if (message.type === 'result') { if (expectedReplay) { try { - const parse = - expectedReplay.format === 'report' - ? parseReplayReportResult - : expectedReplay.format === 'projection' - ? parseReplayProjectionResult - : parseReplayResult; - parse(message.result, expectedReplay.identity, expectedReplay.policy); + if (strategyRequest) { + parseStrategyReplayResult(message.result, { + ...expectedReplay, + strategies: strategyRequest.strategies, + }); + } else { + const parse = + expectedReplay.format === 'report' + ? parseReplayReportResult + : expectedReplay.format === 'projection' + ? parseReplayProjectionResult + : parseReplayResult; + parse(message.result, expectedReplay.identity, expectedReplay.policy); + } } catch (error) { terminate(error instanceof Error ? error : new Error(String(error))); return; @@ -144,7 +162,7 @@ export class NativeBacktestWorker { return; } try { - child.send(request, error => { + child.send(submitted, error => { if (error) { terminate(error); } diff --git a/apps/stock/orchestrator/src/backtest/native-worker-protocol.ts b/apps/stock/orchestrator/src/backtest/native-worker-protocol.ts index 2ac401a0..27a891d9 100644 --- a/apps/stock/orchestrator/src/backtest/native-worker-protocol.ts +++ b/apps/stock/orchestrator/src/backtest/native-worker-protocol.ts @@ -1,5 +1,6 @@ import { z } from 'zod'; import { replayTraceSchema } from '../contracts/native-replay'; +import { strategyReplayRequestSchema } from '../contracts/strategy-replay'; import { BacktestConfigSchema } from '../types'; const finite = z.number().finite(); @@ -21,7 +22,11 @@ const legacyRequestSchema = z.object({ ), }); -export const nativeWorkerRequestSchema = z.union([legacyRequestSchema, replayTraceSchema]); +export const nativeWorkerRequestSchema = z.union([ + legacyRequestSchema, + replayTraceSchema, + strategyReplayRequestSchema, +]); export const nativeWorkerMessageSchema = z.discriminatedUnion('type', [ z.object({ type: z.literal('progress'), progress: finite.min(0).max(100), message: z.string() }), @@ -29,5 +34,5 @@ export const nativeWorkerMessageSchema = z.discriminatedUnion('type', [ z.object({ type: z.literal('error'), message: z.string() }), ]); -export type NativeWorkerRequest = z.infer; +export type NativeWorkerRequest = z.input; export type NativeWorkerMessage = z.infer; diff --git a/apps/stock/orchestrator/src/backtest/native-worker.ts b/apps/stock/orchestrator/src/backtest/native-worker.ts index ad6cdf0a..a0a8bf8a 100644 --- a/apps/stock/orchestrator/src/backtest/native-worker.ts +++ b/apps/stock/orchestrator/src/backtest/native-worker.ts @@ -1,7 +1,13 @@ import { BacktestEngine } from '@stock-bot/engine'; -import { executeReplayTrace } from './native-replay'; +import type { StrategyReplayResult } from '../contracts/strategy-replay'; +import { + createBuiltinStrategy, + validateBuiltinStrategyBindings, +} from '../strategies/canonical-sma'; +import { executeReplayTrace, prepareReplayLoad } from './native-replay'; import { resolveNativeStrategies } from './native-strategies'; import { nativeWorkerRequestSchema, type NativeWorkerMessage } from './native-worker-protocol'; +import { runStrategyReplay } from './strategy-runtime'; /** One process, one native engine, one request. No database or service-container access. */ function send(message: NativeWorkerMessage): Promise { @@ -17,6 +23,36 @@ function send(message: NativeWorkerMessage): Promise { process.once('message', async (input: unknown) => { try { const request = nativeWorkerRequestSchema.parse(input); + if (request.type === 'runStrategyReplay') { + const load = prepareReplayLoad(request.dataset, request.config); + validateBuiltinStrategyBindings(request.strategies, load); + const programs = request.strategies.map(selection => { + const program = createBuiltinStrategy(selection); + if ( + program.ownerId !== selection.ownerId || + program.strategyId !== selection.strategyId || + program.strategyVersion !== selection.strategyVersion || + program.seed !== selection.seed || + program.mode !== 'target' + ) { + throw new Error('Trusted strategy constructor identity mismatch'); + } + return program; + }); + await send({ type: 'progress', progress: 0, message: 'Canonical strategy replay started' }); + const { result } = runStrategyReplay(load, programs, { + eventBudget: request.eventBudget, + resultFormat: request.resultFormat, + }); + const envelope: StrategyReplayResult = { + type: 'strategyReplayResult', + version: 1, + strategies: request.strategies, + result, + }; + await send({ type: 'result', result: JSON.stringify(envelope) }); + return; + } if (request.type === 'runReplayTrace') { await send({ type: 'progress', progress: 0, message: 'Canonical replay trace started' }); // One load and a local pull loop; no per-observation IPC. The supervisor diff --git a/apps/stock/orchestrator/src/contracts/builtin-strategy.ts b/apps/stock/orchestrator/src/contracts/builtin-strategy.ts new file mode 100644 index 00000000..6802780b --- /dev/null +++ b/apps/stock/orchestrator/src/contracts/builtin-strategy.ts @@ -0,0 +1,51 @@ +/** Trusted built-in selection only. No callbacks, code paths or checkpoint transport. */ +import { z } from 'zod'; +import { parseFinancialDecimal } from '@stock-bot/types'; +import { maxStrategyPeriod } from './strategies'; +import { builtinStrategy } from './strategy-names'; + +const identity = z + .string() + .min(1) + .refine(value => + [...value].every(character => { + const code = character.charCodeAt(0); + return ( + code >= 32 && code !== 127 && !(character.length === 1 && code >= 0xd800 && code <= 0xdfff) + ); + }) + ); +const period = z.number().int().min(1).max(maxStrategyPeriod); + +export const builtinStrategySelectionSchema = z + .object({ + ownerId: identity, + strategyId: z + .string() + .refine(value => builtinStrategy(value) === 'sma_crossover', 'Unsupported canonical strategy') + .transform(() => 'sma_crossover' as const), + strategyVersion: z.literal('sma-crossover-long-only/v1'), + seed: z.number().int().min(0).max(0xffffffff), + instrumentId: identity, + seriesId: identity, + ownerBudget: z + .string() + .transform(value => parseFinancialDecimal(value)) + .refine( + value => !value.startsWith('-') && value !== '0.00000000', + 'Owner budget must be positive' + ), + parameters: z + .object({ + fastPeriod: period.default(5), + slowPeriod: period.min(2).default(15), + }) + .strict() + .refine( + value => value.fastPeriod < value.slowPeriod, + 'SMA fastPeriod must be below slowPeriod' + ), + }) + .strict(); + +export type BuiltinStrategySelection = z.infer; diff --git a/apps/stock/orchestrator/src/contracts/strategy-replay.ts b/apps/stock/orchestrator/src/contracts/strategy-replay.ts new file mode 100644 index 00000000..872fce7b --- /dev/null +++ b/apps/stock/orchestrator/src/contracts/strategy-replay.ts @@ -0,0 +1,72 @@ +/** Data-only trusted built-in execution protocol; no strategy code or native imports. */ +import { z } from 'zod'; +import { builtinStrategySelectionSchema, type BuiltinStrategySelection } from './builtin-strategy'; +import { + parseReplayProjectionValue, + parseReplayReportValue, + parseReplayResultValue, + replayConfigSchema, + replayResultFormatSchema, + type ReplayConfig, + type ReplayIdentity, + type ReplayOutput, + type ReplayResultFormat, +} from './native-replay'; + +export const strategyReplayRequestSchema = z + .object({ + type: z.literal('runStrategyReplay'), + version: z.literal(1), + dataset: z.unknown(), + config: replayConfigSchema, + eventBudget: z.number().int().positive().max(Number.MAX_SAFE_INTEGER), + resultFormat: replayResultFormatSchema.optional(), + strategies: z.array(builtinStrategySelectionSchema).min(1), + }) + .strict(); + +export type StrategyReplayRequest = z.input; + +const strategyReplayResultSchema = z + .object({ + type: z.literal('strategyReplayResult'), + version: z.literal(1), + strategies: z.array(builtinStrategySelectionSchema).min(1), + result: z.unknown(), + }) + .strict(); + +export interface StrategyReplayResult { + type: 'strategyReplayResult'; + version: 1; + strategies: BuiltinStrategySelection[]; + result: ReplayOutput; +} + +export interface StrategyReplayExpectation { + strategies: readonly BuiltinStrategySelection[]; + identity: ReplayIdentity; + policy: ReplayConfig; + format: ReplayResultFormat; +} + +/** Strategy selection is additional provenance; Rust remains the only result authority. */ +export function parseStrategyReplayResult( + input: string, + expected: StrategyReplayExpectation +): StrategyReplayResult { + const envelope = strategyReplayResultSchema.parse(JSON.parse(input)); + if (JSON.stringify(envelope.strategies) !== JSON.stringify(expected.strategies)) { + throw new Error('Native strategy replay selection mismatch'); + } + const parse = + expected.format === 'report' + ? parseReplayReportValue + : expected.format === 'projection' + ? parseReplayProjectionValue + : parseReplayResultValue; + return { + ...envelope, + result: parse(envelope.result, expected.identity, expected.policy), + }; +} diff --git a/apps/stock/orchestrator/src/strategies/canonical-sma.ts b/apps/stock/orchestrator/src/strategies/canonical-sma.ts new file mode 100644 index 00000000..aa262f8a --- /dev/null +++ b/apps/stock/orchestrator/src/strategies/canonical-sma.ts @@ -0,0 +1,200 @@ +import { z } from 'zod'; +import { movingAverageCrossover } from '@stock-bot/calculations/indicators'; +import { + parseFinancialDecimal, + type FinancialDecimal, + type HistoricalDatasetManifestV2, +} from '@stock-bot/types'; +import { + builtinStrategySelectionSchema, + type BuiltinStrategySelection, +} from '../contracts/builtin-strategy'; +import type { StrategyProgram } from '../contracts/canonical-strategy'; +import type { ReplayConfig } from '../contracts/native-replay'; + +const time = z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER); +const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER); +const decimal = z.string().transform(value => parseFinancialDecimal(value)); +const nonnegative = decimal.refine(value => !value.startsWith('-')); +const positive = nonnegative.refine(value => value !== '0.00000000'); + +export interface SmaStrategyState { + version: 1; + selectionKey: string; + closes: number[]; + lastObservation: { + eventTime: number; + availableAt: number; + sourceSequence: number; + close: FinancialDecimal; + } | null; + lastCrossover: 'golden' | 'death' | null; + targetQuantity: FinancialDecimal | null; +} + +/** Validate dataset/cadence membership before opening the native session. */ +export function validateBuiltinStrategyBindings( + selections: readonly BuiltinStrategySelection[], + load: { config: ReplayConfig; manifest: Pick } +): void { + const parsed = selections.map(selection => builtinStrategySelectionSchema.parse(selection)); + const owners = load.config.matching.owners; + if ( + new Set(parsed.map(selection => selection.ownerId)).size !== parsed.length || + parsed.length !== owners.length || + owners.some(owner => owner.mode !== 'Target' || !parsed.some(s => s.ownerId === owner.ownerId)) + ) { + throw new Error('Canonical built-ins must exactly match target-mode owners'); + } + for (const selection of parsed) { + const series = load.manifest.series.find(item => item.id === selection.seriesId); + const cadence = load.config.cadence.filter(item => item.owner_id === selection.ownerId); + if ( + series?.instrumentId !== selection.instrumentId || + !load.config.matching.series.some(item => item.instrumentId === selection.instrumentId) || + cadence.length !== 1 || + !cadence[0]?.series_ids.includes(selection.seriesId) + ) { + throw new Error('Canonical SMA requires its instrument/series in its owner cadence'); + } + } +} + +/** Whole-share intent sizing only. Rust remains authoritative for all financial effects. */ +function desiredShares(budget: FinancialDecimal, price: FinancialDecimal): FinancialDecimal { + const units = (value: FinancialDecimal) => BigInt(value.replace('.', '')); + return parseFinancialDecimal((units(budget) / units(price)).toString()); +} + +/** One explicitly versioned long-only program; legacy factories remain unchanged. */ +export function createBuiltinStrategy( + selectionInput: BuiltinStrategySelection +): StrategyProgram { + const selection = builtinStrategySelectionSchema.parse(selectionInput); + const { fastPeriod, slowPeriod } = selection.parameters; + const selectionKey = JSON.stringify(selection); + const stateSchema = z + .object({ + version: z.literal(1), + selectionKey: z.literal(selectionKey), + closes: z.array(z.number().finite().positive()).max(slowPeriod + 1), + lastObservation: z + .object({ + eventTime: time, + availableAt: time, + sourceSequence: counter, + close: positive, + }) + .strict() + .refine(value => value.availableAt >= value.eventTime) + .nullable(), + lastCrossover: z.enum(['golden', 'death']).nullable(), + targetQuantity: nonnegative.refine(value => value.endsWith('.00000000')).nullable(), + }) + .strict() + .refine(state => { + if (!state.lastObservation) { + return ( + state.closes.length === 0 && state.lastCrossover === null && state.targetQuantity === null + ); + } + if (state.closes.at(-1) !== Number(state.lastObservation.close)) { + return false; + } + if (state.lastCrossover === null) { + return state.targetQuantity === null; + } + if (state.closes.length !== slowPeriod + 1) { + return false; + } + return state.lastCrossover !== 'death' || state.targetQuantity === '0.00000000'; + }, 'Inconsistent SMA checkpoint'); + + return { + ownerId: selection.ownerId, + strategyId: selection.strategyId, + strategyVersion: selection.strategyVersion, + seed: selection.seed, + mode: 'target', + initialState: { + version: 1, + selectionKey, + closes: [], + lastObservation: null, + lastCrossover: null, + targetQuantity: null, + }, + decide(context) { + const nextState = stateSchema.parse(context.state); + let advanced = false; + for (const observation of context.observations) { + if (observation.series_id !== selection.seriesId) { + continue; + } + if ( + observation.instrument_id !== selection.instrumentId || + observation.available_at > context.now + ) { + throw new Error('Canonical SMA observation binding or availability mismatch'); + } + const previous = nextState.lastObservation; + // Arrival order is authoritative. A delayed older event cannot rewrite evaluated history. + if ( + previous && + (observation.event_time < previous.eventTime || + (observation.event_time === previous.eventTime && + observation.source_sequence <= previous.sourceSequence)) + ) { + continue; + } + const close = positive.parse(observation.close); + nextState.closes.push(Number(close)); + if (nextState.closes.length > slowPeriod + 1) { + nextState.closes.shift(); + } + nextState.lastObservation = { + eventTime: observation.event_time, + availableAt: observation.available_at, + sourceSequence: observation.source_sequence, + close, + }; + advanced = true; + const cross = movingAverageCrossover(nextState.closes, fastPeriod, slowPeriod); + if (cross?.goldenCross && nextState.lastCrossover !== 'golden') { + nextState.lastCrossover = 'golden'; + nextState.targetQuantity = null; + } else if (cross?.deathCross) { + nextState.lastCrossover = 'death'; + nextState.targetQuantity = parseFinancialDecimal('0'); + } + } + const input = context.barrier.inputs.find(item => item.series_id === selection.seriesId); + const availability = input?.availability; + const last = nextState.lastObservation; + const fresh = + typeof availability === 'object' && 'Fresh' in availability ? availability.Fresh : null; + if ( + !advanced || + !last || + !fresh || + fresh.event_time !== last.eventTime || + fresh.available_at !== last.availableAt + ) { + return { nextState, intent: { mode: 'target', targets: [] } }; + } + if (nextState.lastCrossover === 'golden' && nextState.targetQuantity === null) { + nextState.targetQuantity = desiredShares(selection.ownerBudget, last.close); + } + return { + nextState, + intent: { + mode: 'target', + targets: + nextState.targetQuantity === null + ? [] + : [{ instrumentId: selection.instrumentId, quantity: nextState.targetQuantity }], + }, + }; + }, + }; +} diff --git a/docs/development/ROADMAP.md b/docs/development/ROADMAP.md index 02d0a0ea..626cdfc6 100644 --- a/docs/development/ROADMAP.md +++ b/docs/development/ROADMAP.md @@ -8,7 +8,7 @@ Authorization update: the owner accepted F08 and requested “commit all of it a Use TypeScript for strategies, research and the web product; one Rust kernel owns money, risk, matching and replay. Preserve durable decisions/checkpoints, transactional execution, frozen datasets, reviewed calculations and failure-oriented tests. -The skeptical review established 43 scheduled tasks, 5 conditional tasks and 4 merged redirects. The measured F09/P07 additions bring the current plan to **45 scheduled + 5 conditional + 4 merged = 54 retained IDs**. See [review findings and dispositions](REVIEW.md), [complete index](backlog/README.md) and [canonical manifest](backlog/manifest.json). +The skeptical review established 43 scheduled tasks, 5 conditional tasks and 4 merged redirects. The measured F09/P07/P08 additions bring the current plan to **46 scheduled + 5 conditional + 4 merged = 55 retained IDs**. See [review findings and dispositions](REVIEW.md), [complete index](backlog/README.md) and [canonical manifest](backlog/manifest.json). The existing web workbench improves during engine migration. Legacy results remain labelled; fixing controls or terminal valuation does not make same-bar economics trustworthy. C06 blocks shared-runtime legacy research rather than building another soon-to-be-retired simulator runtime. @@ -379,6 +379,29 @@ S01 is accepted and committed as `2bcadbd`, superseding its uncommitted handoff S03 is code/ADR-ready but outside this wave. R05 retains durable canonical/default activation and its multi-asset policy gate; R01/R11 require ADR-006. No pending policy was implicitly approved. +**Validated handoff:** S02 is `review` / `validated_uncommitted`. Ten integrated source/test files match the independently reviewed hashes. `sma-crossover-long-only/v1` uses the existing aliases and reviewed crossover helper, exact whole-share budget sizing, bounded JSON state and explicit availability/freshness rules. The legacy long/short strategy stays intact. The existing child worker locally runs trusted programs over the canonical Rust session; the parent detaches input and checks exact effective selections plus native identity/policy/format. No callback source, module path, TS financial engine or default/paper activation was added. + +The independent next-open fixture buys ten shares at5 and sells at2, with0.7 total fees and9969.3 terminal equity from10000. Further tests cover warmup entry sizing, delayed older bars, equality, stale inputs, unaffordable fees/gaps, same-order partial fills, owner attribution, JSON reconstruction and full retry. Worker tests reject altered provenance/economics, malformed/duplicate output and crashes, and preserve hard cancellation even after a result arrives before child close. + +`CARGO_BUILD_JOBS=2 bun run check` passed build/types/contracts/audit/lint plus **78 tooling, 43 utility, 44 calculation, 432 integration and 144 Rust tests**; four existing manual Rust measurements remain ignored. Dedicated test/fixture strict TypeScript and scoped lint/format/diff checks passed. Disposable PostgreSQL/Redis: **58 tests /345 assertions**. Final release tests: **48 /175**. Built `dist/native-worker.js` matches direct execution in trace, projection and report formats. Browser/Python boundaries did not change and were not rerun. + +The worker owner's second elevated test run waited for approval and was aborted; root took over final validation after an explicit handoff. Root's restricted IPC run also stalled and was stopped, then passed unrestricted. Fixture correction uses a mutable detached dataset for the mutation test; schema `.min(1)` retains runtime nonempty validation without requiring a tuple input type. No economic failure was hidden by those environment/type corrections. Only the two exact disposable test containers were stopped. + +The unchanged release addon is `6fe9dae…`. A paired benchmark compares actual SMA programs with replay of their **exact captured decisions**, including IDs. All **48 timed sessions** preserve complete financial hashes; repeated/reversed program order preserves diagnostics. + +| 10,000 total bars | Recorded decisions | SMA callbacks | Added wall time | +| --- | ---: | ---: | ---: | +| SMA5/15, 1 asset /1 owner | 1,091 ms | 1,467 ms | 376 ms /34.5% | +| SMA5/15, 10 assets /2 owners | 410 ms | 478 ms | 69 ms /16.8% | +| SMA5/15, 10 assets /10 owners | 624 ms | 916 ms | 292 ms /46.8% | +| SMA15/252, 1 asset /1 owner | 1,018 ms | 2,351 ms | 1,333 ms /130.9% | +| SMA15/252, 10 assets /2 owners | 409 ms | 636 ms | 227 ms /55.5% | +| SMA15/252, 10 assets /10 owners | 594 ms | 1,681 ms | 1,087 ms /183.1% | + +Each median has four samples across two processes, after an untimed reference capture. Imports/preparation are separate. Ten-assets/two-owners trades only two assets; the other eight still replay. Single-asset runs have9999 decisions and10000 advance calls; ten-assets/two-owners has1998 decisions/1000 calls, and ten-owners has9990 decisions/1000 calls. Warmup proportions and fills also differ. Cross-shape ratios do not isolate scaling. This is warmed direct-runtime throughput, not durable jobs, worker IPC, pure callbacks or NAPI cost; no speedup is claimed for S02. + +The long-window decision/state phase accounts for roughly51–62% of wall time in the owner-dense cases, but cloning, freezing, schema validation, trailing calculation and allocation costs are not yet separated. [P08](backlog/tasks/P08.md) is the recommended next task **after S02 acceptance**, to profile and reduce that measured cost while preserving all strict-state and financial invariants. It is planned, not started. Immutable code artifacts remain R01/R05 work; no label-only reproduction guarantee is claimed. All raw evidence, exact commands, source archive and hashes are in `manifest.json` → `fifteenth_wave_validation` and `/tmp/stock-bot-wave15.zi3GmP/`. No new implementation commit, push, PR or trading operation occurred. + ## Deferred and rejected Conditional: shared feature cache D04; cross-trial resident datasets P03; large-detail pagination/storage P05; tiny DSL P06; expanded cross-service monitoring O02. Each has a measured/real-need trigger and is not a prerequisite for scheduled work. diff --git a/docs/development/backlog/README.md b/docs/development/backlog/README.md index 33f8b220..0534a708 100644 --- a/docs/development/backlog/README.md +++ b/docs/development/backlog/README.md @@ -1,12 +1,12 @@ # Canonical development backlog -**First fourteen waves committed; S02 is in progress.** S01 is accepted as `2bcadbd`. S02 adds one explicit long-only SMA version and trusted selection through the existing native worker. Consult manifest execution_scope and [current wave](../ROADMAP.md#fifteenth-wave-execution--2026-10-23). ADR-002/003/004/005 are approved; other policies/default cutovers remain gated. +**First fourteen waves committed; S02 is validated and awaiting acceptance.** S01 is accepted as `2bcadbd`; `4f6e44a` records acceptance and the S02 contract. S02 adds one explicit long-only SMA version and trusted selection through the existing native worker. Consult manifest execution_scope and [current wave](../ROADMAP.md#fifteenth-wave-execution--2026-10-23). ADR-002/003/004/005 are approved; other policies/default cutovers remain gated. ## One source of truth [manifest.json](manifest.json) owns scheduling metadata: status, priorities, dependencies, ADR approvals, assignments and write locks. Task Markdown owns implementation scope/evidence/acceptance. This index and the [graph](dependencies.mmd) are derived views. Only the planning/integration owner updates scheduling state. -**45 scheduled + 5 deferred + 4 merged IDs = 54 retained IDs.** F09/P07 add the measured projection/profiling work. Merged records preserve traceability; never execute them separately. Deferred work requires its stated trigger and explicit activation. +**46 scheduled + 5 deferred + 4 merged IDs = 55 retained IDs.** F09/P07 add projection/profiling work; P08 follows measured TypeScript strategy overhead. Merged records preserve traceability; never execute them separately. Deferred work requires its stated trigger and explicit activation. States: ready, claimed, in_progress, review, done, blocked, deferred, merged. “Ready” means no code/ADR prerequisite, not execution authority. Implementation dependencies require accepted integration. `release_gates` govern enabling an end-to-end feature, not component coding or integration; conditional gates apply only to the named capability. F05 may integrate before F06, but its replay behavior is not released until F06 proves it. @@ -53,7 +53,7 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr | Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size | | --- | --- | --- | --- | --- | | [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 / in_progress | S01 | — | TypeScript strategy/quant engineering / M | +| [S02 Adapt one SMA strategy for the first canonical path](tasks/S02.md) | P1 / review | S01 | — | TypeScript strategy/quant engineering / M | | [S03 Adapt durable paper transactions to Rust financial reducers](tasks/S03.md) | P0 / ready | 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 | | [S05 Add a small composable multi-signal regime example](tasks/S05.md) | P2 / blocked | S02, F08 | R08 | Quant strategy research / M | @@ -96,6 +96,7 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr | [P05 Separate result summaries from paged detail payloads](tasks/P05.md) | P2 / deferred | R06, P01 | — | Performance/infrastructure engineering / M | | [P06 Conditionally add a minimal Rust-executed strategy plan](tasks/P06.md) | P2 / deferred | P04, S01, ADR-008 | — | Rust/TS performance compiler boundary / M | | [P07 Profile representative canonical replay workloads](tasks/P07.md) | P1 / done | F07, P01 | F09 for compact comparisons | Performance/test infrastructure / M | +| [P08 Reduce measured TypeScript strategy decision overhead](tasks/P08.md) | P1 / blocked | S02, P07 | — | TypeScript performance/runtime engineering / M | ### E8 — Authorized, isolated AI research @@ -117,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 thirteen waves are committed. **S01 is independently reviewed and validated, with new implementation changes uncommitted.** Next after acceptance: S02, one real SMA program and trusted native-worker composition on the new runtime. R01/R11 still need ADR-006; the multi-asset mark-policy gate still blocks default activation. New S01 commits, other tasks, push, PR or trading operations are outside this continuation. +The first fourteen waves are committed. **S02 is independently reviewed and validated, with new implementation changes uncommitted.** Recommended next after acceptance: P08, profile and reduce the measured TypeScript strategy decision/state overhead. S03 is also code/ADR-ready. R01/R11 still need ADR-006; the multi-asset mark-policy gate still blocks default activation. No P08 implementation, new S02 commit, push, PR or trading operation is included in this continuation. diff --git a/docs/development/backlog/dependencies.mmd b/docs/development/backlog/dependencies.mmd index 0a20c959..168e6013 100644 --- a/docs/development/backlog/dependencies.mmd +++ b/docs/development/backlog/dependencies.mmd @@ -57,6 +57,7 @@ flowchart TD P05["P05: Separate result summaries from paged detail payloads (conditional)"] P06["P06: Conditionally add a minimal Rust-executed strategy plan (conditional)"] P07["P07: Profile representative canonical replay workloads"] + P08["P08: Reduce measured TypeScript strategy decision overhead"] end subgraph E8["E8: Authorized, isolated AI research"] A01["A01: Add research-only principals and durable job budgets"] @@ -179,6 +180,8 @@ flowchart TD F07 --> P07 P01 --> P07 F09 -. compact comparisons only .-> P07 + S02 --> P08 + P07 --> P08 R06 --> A01 O01 --> A01 ADR007 --> A01 diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index 44dc1e42..101306e2 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -1,8 +1,8 @@ { "schema_version": 1, - "plan_revision": "2026-10-23.33", + "plan_revision": "2026-10-23.34", "repository_base": "b7aeca4", - "plan_status": "fifteenth_wave_in_progress", + "plan_status": "fifteenth_wave_in_review", "execution_authorized": true, "execution_scope": { "authorized_by": "User: commit and continue (2026-10-23), after S01 validated handoff named S02. S01 accepted and committed as 2bcadbd. Continue only S02 under approved ADR-002/003/004/005.", @@ -969,7 +969,7 @@ "epic": "E4", "priority": "P1", "severity": "High", - "status": "in_progress", + "status": "review", "dependencies": [ "S01" ], @@ -994,7 +994,7 @@ "release_gates": [], "worktree": "/tmp/stock-bot-wave15.zi3GmP/strategy", "integration_base": "2bcadbd117c288577a26615e6d132cf49ea074e4", - "integration_state": "isolated_implementation", + "integration_state": "validated_uncommitted", "implementation_slices": [ { "owner": "/root/s02_strategy", @@ -1006,8 +1006,27 @@ "owner": "/root/s02_worker", "scope": "Additive trusted worker request/result supervision with dedicated tests", "worktree": "/tmp/stock-bot-wave15.zi3GmP/worker", - "branch": "wave15/s02-worker" + "branch": "wave15/s02-worker", + "integration_handoff": "Root imported six-file draft after explicit takeover authorization, corrected nonempty-array input typing and readonly expected test arrays, and completed all validation. Worker owner made no concurrent edits." } + ], + "reviewed_by": [ + "/root/s02_review", + "/root" + ], + "verification_reference": "ROADMAP.md#fifteenth-wave-execution--2026-10-23", + "review_notes": "All ten source/test files independently approved with exact hashes. Full repository, strict test types/lint/format, disposable recovery, release and built-worker parity gates passed. Long-only policy differs explicitly from legacy; R01/R05 retain artifact and durable/public cutover. Paired 48-session exact-decision benchmark identifies aggregate strategy/state overhead; P08 planned only. Root finished worker validation after owner tool approval stalled; no new source semantics changed during takeover.", + "concrete_write_scope": [ + "apps/stock/orchestrator/src/contracts/builtin-strategy.ts", + "apps/stock/orchestrator/src/strategies/canonical-sma.ts", + "apps/stock/orchestrator/src/contracts/strategy-replay.ts", + "apps/stock/orchestrator/src/backtest/native-worker-protocol.ts", + "apps/stock/orchestrator/src/backtest/native-worker.ts", + "apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts", + "test/fixtures/canonical-sma.ts", + "test/integration/canonical-sma.test.ts", + "test/integration/canonical-strategy-worker.test.ts", + "test/fixtures/canonical-strategy-worker.ts" ] }, { @@ -1972,6 +1991,37 @@ "review_notes": "Independent financial-normalizer and measurement/provenance reviews passed; final 72-tooling gate and strict test types/lint passed. Paired final-source release benchmarks cover all three 10k profiles and sparse/turnover at 100k. Historical baseline source-retention limitation is explicit; measured final source is archived. Owner accepted and authorized commit e3bd722 on 2026-10-23.", "verification_reference": "ROADMAP.md#twelfth-wave-handoff--2026-10-23" }, + { + "id": "P08", + "title": "Reduce measured TypeScript strategy decision overhead", + "epic": "E7", + "priority": "P1", + "severity": "High", + "status": "blocked", + "dependencies": [ + "S02", + "P07" + ], + "decision_dependencies": [], + "task_file": "backlog/tasks/P08.md", + "findings": [ + "PER-02" + ], + "complexity": "M", + "specialization": "TypeScript performance/deterministic runtime engineering", + "write_locks": [ + "strategy-contract", + "strategy-builtins", + "benchmark-harness" + ], + "parallel_policy": "One runtime/strategy optimization owner. Disjoint review may proceed; actual file overlap with S03/S05 or benchmark work blocks concurrency. Scope exact files before edits.", + "assignment": null, + "branch": null, + "pull_request": null, + "completed_commit": null, + "blocker": "Requires S02 acceptance/commit and explicit next-wave authorization. Profile subphase costs before choosing a local optimization; preserve current contracts and all invariants.", + "release_gates": [] + }, { "id": "A01", "title": "Add research-only principals and durable job budgets", @@ -5481,6 +5531,339 @@ "S01 accepted after frozen-hash and diff verification. No new-wave implementation commit yet.", "Pinned S02 explicit long-only version, reviewed crossover arithmetic, exact owner-budget whole-share sizing, monotonic available observations and native Fresh gating; legacy semantics unchanged.", "Minimal trusted worker selection/result envelope binds exact strategy provenance and native identity/policy/format. No callback/source/path or checkpoint transport.", - "S03 is code/ADR-ready but not authorized in this wave. R05 owns durable/default/public result cutover; ADR-006/007/008 remain pending." - ] + "S03 is code/ADR-ready but not authorized in this wave. R05 owns durable/default/public result cutover; ADR-006/007/008 remain pending.", + "Paired S02 benchmark demonstrates aggregate TS strategy/state overhead, especially 252-bar windows. P08 is a narrow planned follow-up, recommended after S02 acceptance; no optimization or extra task implementation in this wave." + ], + "fifteenth_wave_validation": { + "state": "validated_uncommitted", + "work_root": "/tmp/stock-bot-wave15.zi3GmP", + "committed_before_implementation": [ + "2bcadbd117c288577a26615e6d132cf49ea074e4", + "4f6e44a85395929a16a0d7ba622f7ae7986e4afe" + ], + "scope": "One explicitly versioned long-only SMA and strict trusted selection through existing native worker. No Rust financial semantics, legacy registry, SQL, web/default or paper migration.", + "source_integration": { + "owner_files": 10, + "exact_hashes": { + "apps/stock/orchestrator/src/contracts/builtin-strategy.ts": "bd648e863f00419a7210b17ccc796ab72ba4e72edf5c04cd61af9e61527bc4d2", + "apps/stock/orchestrator/src/strategies/canonical-sma.ts": "d76ba01e40f3eed073bcada2b40078bba6f0f1702fb9e7fcdca0278775d4b01b", + "apps/stock/orchestrator/src/contracts/strategy-replay.ts": "fccba629266524c4e2a79dc95d5a89f4eea3e64b5790ea7a1c38c8121360528b", + "apps/stock/orchestrator/src/backtest/native-worker-protocol.ts": "43b0e01fd59cb6bbd483e4858555e0cdc4666c3e4835786d01442ab86520f1e5", + "apps/stock/orchestrator/src/backtest/native-worker.ts": "0f5583d72aad6841962d017565fadcecb6be775ff6b8abacbb54da9a5e0f95e1", + "apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts": "fdfa65d61b22c959ec83c83a19e6e9acbaee7d8d855b950ab30306b65b65565c", + "test/fixtures/canonical-sma.ts": "138aa061225a8d6340c788c1e914fc6eb9649234718eb273ffe5139cc6f3acb1", + "test/integration/canonical-sma.test.ts": "18d523784e5f7b3ad81729cc04de0c2af27e804e8cb0b30cda0b94551403c15b", + "test/integration/canonical-strategy-worker.test.ts": "5b0410932e96d5091e19761fba7cc3d6a2e3944cad796f55fe369fd4d0553942", + "test/fixtures/canonical-strategy-worker.ts": "546a6fc502a53260ece4361177bc4e784e97ec3f2423f65193d231eba06149bc" + }, + "reviewed_hash_list_sha256": "44780f2b0f276e74c4e1b28b7297ac37a51537942e97e9595686b77ab46bb662", + "source_archive": "/tmp/stock-bot-wave15.zi3GmP/integrated-source.tar", + "source_archive_sha256": "660604296a75dc148e82622e92d8459e7d795b672ff8d4644dc6ae9a408ae948", + "measured_source": { + "root": "/home/boki/repos/stock-bot", + "commit": "4f6e44a85395929a16a0d7ba622f7ae7986e4afe", + "dirty": true, + "sha256": "8c5cd9d17e3870ebe21e95f2013b39ef00d7aa981245471f6a801fa162c42696", + "files": 1179 + }, + "note": "Only planning records changed after measurement; all ten source hashes remain independently reviewed and validated. Reconstruct measured source from planning commit4f6e44a plus the ten-file archive." + }, + "review": { + "reviewer": "/root/s02_review", + "disposition": "Approved frozen strategy and worker integration, no blocking findings; read-only review. Reviewed measurements and supports narrow P08 follow-up; no reviewer tests/builds.", + "root_takeover": "Worker owner approval request stalled about415s and aborted with no test session; explicit ownership handoff permitted root final corrections/validation.", + "corrections": [ + "Mutation test now starts with a detached mutable dataset rather than mutating the intentionally frozen fixture.", + "Schema min(1) preserves nonempty arrays without unnecessary input tuples; request author type uses schema input; readonly expectations copied for Bun strict types." + ] + }, + "checks": [ + { + "command": "CARGO_BUILD_JOBS=2 bun run check", + "result": "passed", + "counts": { + "tooling": 78, + "utilities": 43, + "calculations": 44, + "integration": 432, + "rust": 144, + "rust_manual_ignored": 4 + }, + "log": "/tmp/stock-bot-wave15.zi3GmP/integration-check.log" + }, + { + "command": "bunx tsc --project /tmp/stock-bot-wave15.zi3GmP/tsconfig.integration.json --noEmit", + "result": "passed", + "log": "/tmp/stock-bot-wave15.zi3GmP/integration-test-types.log" + }, + { + "command": "Scoped ESLint --no-ignore --max-warnings 0 and Prettier --check over all ten integrated TypeScript files; git diff --check", + "result": "passed" + }, + { + "command": "PIPELINE_TEST_DATABASE_URL=postgres://fixture:fixture@127.0.0.1:32814/stock_bot_safety BACKTEST_TEST_REDIS_URL=redis://127.0.0.1:32813/15 bun run test:postgres", + "result": "passed", + "tests": 58, + "assertions": 345, + "log": "/tmp/stock-bot-wave15.zi3GmP/integration-postgres.log" + }, + { + "command": "CARGO_BUILD_JOBS=2 bun run --cwd apps/stock/engine build:release", + "result": "passed", + "log": "/tmp/stock-bot-wave15.zi3GmP/integration-native-release.log" + }, + { + "command": "bun test test/integration/canonical-sma.test.ts test/integration/canonical-strategy-worker.test.ts scripts/test/native-bindings.test.ts", + "result": "passed against release addon", + "tests": 48, + "assertions": 175, + "log": "/tmp/stock-bot-wave15.zi3GmP/integration-release-focused.log" + }, + { + "command": "bun /tmp/stock-bot-wave15.zi3GmP/packaged-worker-smoke.ts", + "result": "built dist/native-worker.js matches direct native trace/projection/report", + "evidence": { + "verified": true, + "summaries": [ + { + "resultFormat": "trace", + "sha256": "73bc6b6c195547ad32df76613e25195c806e66d4f81e7e4ee4034d4200561055" + }, + { + "resultFormat": "projection", + "sha256": "1ea0bc7ceb82d7cf70ab40a597cea9963e65303a92fead25ef04f69f313009e0" + }, + { + "resultFormat": "report", + "sha256": "643a06a8824134f7cbf2a1c1b981c7bebfabe3ce86ba0ac3312ac0ad02a6a00e" + } + ] + }, + "harness_sha256": "fef64af8f6f38870a8470a168c19e0b9d9ee5bad59371f0a7aed00ae9927c2de" + } + ], + "environment_notes": [ + "Root restricted IPC test stalled and was interrupted, then unrestricted focused tests passed42/160; full/release gates used required subprocess permissions.", + "Dedicated worker test typing initially exposed array-tuple/readonly expectation issues; corrected before final strict pass.", + "Browser and Python boundaries unchanged; those suites not rerun." + ], + "financial_fixture": { + "fast": 2, + "slow": 3, + "closes": [ + 3, + 2, + 1, + 4, + 5, + 1, + 1 + ], + "ownerBudget": "40", + "initialCapital": "10000", + "quantity": "10", + "entryNextOpen": "5", + "exitNextOpen": "2", + "feeRate": "0.01", + "totalFees": "0.7", + "terminalEquity": "9969.3" + }, + "native": { + "path": "/home/boki/repos/stock-bot/apps/stock/engine/dist/engine.node", + "sha256": "6fe9dae546b4fc1d50b064b2ad50b0a3d08a0208ede3c568bf0f95e549c57b9e", + "artifact": "/home/boki/repos/stock-bot/target/release/libengine.so", + "buildProfile": "release", + "generated_types_sha256": "62c0338e9909e6bfe3feb713949fb3b063bf2b5831044763bdbdb9cf87f9f703", + "note": "Same native release artifact as S01/F08; no Rust change." + }, + "performance": { + "command": "bun /tmp/stock-bot-wave15.zi3GmP/sma-benchmark.ts", + "harness": { + "path": "/tmp/stock-bot-wave15.zi3GmP/sma-benchmark.ts", + "sha256": "f0f6ec1957c752635597d6c91c725ae1ab55287fb1b445bc6095f93cde106b0c" + }, + "raw_file": "/tmp/stock-bot-wave15.zi3GmP/sma-release.json", + "raw_sha256": "0e0231722401933564e4ea390146c71615a6e96241f4472c3d801d96f7923485", + "log": "/tmp/stock-bot-wave15.zi3GmP/sma-release.log", + "host": { + "platform": "linux", + "arch": "x64", + "kernel": "6.8.0-146-generic", + "cpu": "AMD Ryzen 9 9950X3D 16-Core Processor", + "logicalCpus": 32, + "memoryBytes": 98683457536, + "loadAverage": [ + 1.24, + 2.03, + 3.06 + ] + }, + "host_load_at_finish": [ + 2.8, + 2.38, + 3.09 + ], + "runtime": { + "bun": "1.2.17", + "nodeCompatibility": "v22.6.0", + "executableSha256": "6cd2f181c30d3cb1497b0b9d4bc9d63eb1ec4a9142f809183fed18fcc4e1051b", + "rustc": "rustc 1.88.0 (6b00bc388 2025-06-23)", + "bunLockSha256": "1a2b653bbaaeb5075785b860487557b8fc379f0c50cbe8f2554c90e4a3ac4514", + "cargoLockSha256": "8f2ecaa4f1790f14e1650326f78fbf246f454dad6139dc4cb0d61383b9e301e8" + }, + "timed_sessions": 48, + "untimed_reference_sessions": 24, + "smoke": "passed all three short-period shapes; raw sma-smoke.json retained", + "summary": [ + { + "workload": { + "totalBars": 10000, + "assets": 1, + "owners": 1, + "fastPeriod": 5, + "slowPeriod": 15, + "untradedAssets": 0 + }, + "verified": true, + "samples_per_mode": 4, + "recorded_ms": 1091.0554985, + "sma_ms": 1466.9523095, + "added_ms": 375.89681099999984, + "added_percent": 34.45258389850825, + "sma_decision_phase_ms": 326.81869449997794, + "sma_bars_per_second": 6816.854191673367, + "decisions": 9999, + "fills": 997, + "full_financial_hash": "25fadb03424da2ab9c7e405358332ae89de492a83c71882e8bbef04b1d7f318e" + }, + { + "workload": { + "totalBars": 10000, + "assets": 10, + "owners": 2, + "fastPeriod": 5, + "slowPeriod": 15, + "untradedAssets": 8 + }, + "verified": true, + "samples_per_mode": 4, + "recorded_ms": 409.59593200000006, + "sma_ms": 478.2034970000001, + "added_ms": 68.60756500000002, + "added_percent": 16.750060154406032, + "sma_decision_phase_ms": 66.50624600000037, + "sma_bars_per_second": 20911.599481674217, + "decisions": 1998, + "fills": 194, + "full_financial_hash": "02afdf4e00a589bdae0c66ab4416a6d8cbb130543deb4ff5b4a8e18421a7250e" + }, + { + "workload": { + "totalBars": 10000, + "assets": 10, + "owners": 10, + "fastPeriod": 5, + "slowPeriod": 15, + "untradedAssets": 0 + }, + "verified": true, + "samples_per_mode": 4, + "recorded_ms": 624.1090814999999, + "sma_ms": 916.3397714999999, + "added_ms": 292.23069, + "added_percent": 46.82365609832904, + "sma_decision_phase_ms": 275.0971249999985, + "sma_bars_per_second": 10912.982619569733, + "decisions": 9990, + "fills": 970, + "full_financial_hash": "3616bfd9c6061abb217bd5b8451650c68e0167c9830b3b8cf0143323c6513526" + }, + { + "workload": { + "totalBars": 10000, + "assets": 1, + "owners": 1, + "fastPeriod": 15, + "slowPeriod": 252, + "untradedAssets": 0 + }, + "verified": true, + "samples_per_mode": 4, + "recorded_ms": 1018.2021005000001, + "sma_ms": 2350.8183565, + "added_ms": 1332.6162559999998, + "added_percent": 130.87934658017332, + "sma_decision_phase_ms": 1201.672781500027, + "sma_bars_per_second": 4253.837806034675, + "decisions": 9999, + "fills": 975, + "full_financial_hash": "056f9253b2b2c9ce00aab6fa6776534e931e87273b7c1ea75e345ff57e999971" + }, + { + "workload": { + "totalBars": 10000, + "assets": 10, + "owners": 2, + "fastPeriod": 15, + "slowPeriod": 252, + "untradedAssets": 8 + }, + "verified": true, + "samples_per_mode": 4, + "recorded_ms": 409.37107850000007, + "sma_ms": 636.4676205, + "added_ms": 227.09654199999989, + "added_percent": 55.47449586133864, + "sma_decision_phase_ms": 223.09511149999656, + "sma_bars_per_second": 15711.718362269776, + "decisions": 1998, + "fills": 150, + "full_financial_hash": "99f624549deb03d41a9ca47030ef5f39bdb98f497063af6c4bf8adc5fee013af" + }, + { + "workload": { + "totalBars": 10000, + "assets": 10, + "owners": 10, + "fastPeriod": 15, + "slowPeriod": 252, + "untradedAssets": 0 + }, + "verified": true, + "samples_per_mode": 4, + "recorded_ms": 593.9949515000001, + "sma_ms": 1681.4738735, + "added_ms": 1087.478922, + "added_percent": 183.07881561178553, + "sma_decision_phase_ms": 1042.1618619999977, + "sma_bars_per_second": 5947.163472236965, + "decisions": 9990, + "fills": 750, + "full_financial_hash": "fb8024de3c4a710d5e7773575d59ad4904a4955ef14a15d6122bf7284526e98c" + } + ], + "limitations": [ + "10,000 TOTAL bars in full workloads, not per asset. Synthetic sawtooth fixture unchanged; one owner per selected asset. Ten-assets/two-owners explicitly leaves eight assets untraded while all ten replay/mark.", + "No database, durable queue, public-result mapping, real native-worker IPC, or production wall-clock throughput measurement. Each child imports modules and directly executes the canonical runtime.", + "Each fresh child first runs an untimed SMA reference to capture exact submitted financial identities. Timed fresh sessions therefore run in warmed processes; imports, preparation, reference capture and process wall time are separate.", + "Actual versioned SMA code uses bounded slow+1 JSON history and reviewed trailing calculations. Both 5/15 and 15/252 are measured; large-period copying/scanning costs remain included.", + "Recorded control replays exact captured decisions through the same Rust/native pull loop. Complete financial projection hashes including all IDs must match; there is no TypeScript accounting oracle or financial normalization.", + "executionWallMs includes native-session construction, replay, state copying/strategy/staging/feedback where applicable, finalization and disposal. Benchmark verification/hashing is measured separately.", + "decisionMs includes host validation/state copying/strategy execution/admission feedback for SMA and tape lookup/checks for recorded control. Difference is not pure callback or NAPI crossing cost.", + "Both modes retain reference decision tapes; RSS includes reference activity and tape memory. No allocation attribution or resident-dataset caching claim.", + "Two separate processes per mode, two fresh timed sessions each, counterbalanced mode order. Second SMA session reverses owner callback order and must preserve financial and diagnostic hashes. This checks fresh whole-attempt recomputation, not native checkpoint resume.", + "Shared host, no timing assertion, confidence interval, cold-start SLA, or cross-artifact performance attribution. Root must freeze source and use the matching release addon before execution." + ], + "interpretation": "Verified aggregate host/strategy/state overhead, not per-function attribution. Long-window decision phase is about51\u201362%of total owner-dense wall. Profiles in P08 must distinguish schema parsing, copying/freezing, trailing calculations and allocation before optimization. No cross-shape scaling or S02 speedup claim." + }, + "cleanup": { + "stopped_exact_containers": [ + "d42bc73629ccfc7d816ad6d603a0131b3cd95fe53be0cc68d0bafadbf0bf2407", + "6333a832a853e86a35b7a646e96ede511e9a22fcc90ff58643f70ad702dd8db2" + ], + "development_resources_touched": false, + "worktrees_and_evidence_retained": true + }, + "next": "Accept/commit S02; recommended next P08 measured local TS decision/state optimization. S03 also code/ADR-ready; R01/R11 still require ADR-006. No extra task/default/paper approval inferred." + } } diff --git a/docs/development/backlog/tasks/P08.md b/docs/development/backlog/tasks/P08.md new file mode 100644 index 00000000..8801b32c --- /dev/null +++ b/docs/development/backlog/tasks/P08.md @@ -0,0 +1,38 @@ +# P08 — Reduce measured TypeScript strategy decision overhead + +Parent epic: E7. Priority/severity: P1 / High. Complexity: M. Specialist: TypeScript performance and deterministic runtime engineering. + +Story: As a researcher, I can run realistic window-based TypeScript strategies without repeatedly paying avoidable state-validation or copying costs. + +Scheduling source of truth: [manifest P08](../manifest.json). This story is planned, not authorized for implementation in S02's wave. + +## Evidence and root cause + +**PER-02 — Verified aggregate cost; individual causes need profiling.** S02's release comparison replays exactly the same financial decisions and IDs. For 10,000 total bars, recorded decisions versus SMA callbacks took 1,091→1,467 ms (5/15, one owner) and 1,018→2,351 ms (15/252, one owner). With ten assets/ten owners, 15/252 took 594→1,681 ms. All 48 timed sessions preserve complete financial hashes; repeat/reversed-owner runs preserve diagnostics. These are warmed synthetic workloads, not durable-job throughput or pure callback/NAPI measurements. + +Potential contributors are the [host staging boundary](../../../../apps/stock/orchestrator/src/backtest/strategy-runtime.ts#L205), strict JSON copying/freezing, [per-callback SMA state parsing](../../../../apps/stock/orchestrator/src/strategies/canonical-sma.ts#L128), bounded history and [reviewed trailing calculations](../../../../libs/calculations/src/indicators/window-statistics.ts#L50). The aggregate difference does not attribute cost among them. Larger windows also change decisions and fills; compare each strategy with its own exact recorded control, not the two periods as identical economics. + +Raw evidence/harness/source identity: `manifest.json` → `fifteenth_wave_validation.performance`; [roadmap](../../ROADMAP.md#fifteenth-wave-execution--2026-10-23). Retained local harness: `/tmp/stock-bot-wave15.zi3GmP/sma-benchmark.ts`. + +## Scope and exclusions + +1. Extend the existing research benchmark entrypoint with the S02 paired strategy/recorded workload; incorporate the useful temporary harness logic into existing tooling, not another benchmark framework. Preserve cold import/preparation versus warmed-session boundaries, source/addon hashes, raw samples, counts and exact comparisons. +2. Profile actual calculation, schema parsing, state copy/freezing, host admission feedback and allocations. Measure instrumentation separately; a residual is not a named subsystem cost. +3. Implement the smallest evidenced local optimization in `backtest/strategy-runtime.ts`, `strategies/canonical-sma.ts` or their private helpers. Avoid changing public contracts. Publish a proposed exact file scope before editing shared runtime/strategy files. +4. Preserve strict JSON state validation, detached immutable contexts, per-owner isolation, staged commit-after-native-ack, failure diagnostics, scoped RNG, whole-attempt retry, reviewed crossover arithmetic, financial decisions and result provenance. Do not special-case away validation for trusted built-ins or change strategy semantics to make the benchmark faster. + +No Rust financial changes, DSL, worker pool, resident dataset/feature framework, shared mutable checkpoints, public/default cutover, weakened validation, arbitrary input limits or general cleanup. Incremental indicator arithmetic or a new state contract needs a separately reviewed proposal; neither is assumed necessary. + +## Dependencies, ownership and parallelism + +Code prerequisites: S02 accepted/integrated, P07 complete. No additional policy approval for profiling/local semantics-preserving optimization. One owner holds strategy-contract, strategy-builtins and benchmark-harness locks for the minimal patch; disjoint review may run in parallel. Do not overlap S03/S05 or another worker using those actual files. Root alone updates task state. No native rebuild during measurements or artifact review. + +## Acceptance and mandatory tests + +- `sma_benchmark_modes` validates selection/period/topology arguments, labels ten-assets/two-owners as eight untraded assets, and reports actual decisions/fills rather than inferring equal work from bar count. +- `sma_recorded_decision_parity` compares identical captured decision IDs and complete financial outputs for 5/15 and 15/252, with 1/1, 10/2 and 10/10 asset/owner shapes. Fresh retries and reversed program order preserve diagnostic/RNG/state hashes. Retain raw repeated measurements and the exact baseline/candidate artifacts. +- Profile identifies the removed cost. Counterbalance baseline/candidate runs on the same host/release addon and configurations; show repeatable end-to-end improvement larger than observed run-to-run variation on both 15/252 owner-dense workloads, with the smaller workloads checked for regression. Do not claim an optimization from changed economics, instrumentation overhead or host drift. If no safe local improvement is demonstrated, hand off the blocker/proposal rather than mark implementation complete. +- Preserve all `canonical-sma`, `strategy-runtime`, `native-replay`, worker and runtime tooling regression tests. Add a focused regression for each changed state/validation path, including retained mutable references, malformed JSON, callback failure after prior owners staged, native rejection and malformed/ambiguous admission feedback as relevant. Accessors must not execute; prototype/cycle/symbol/sparse/non-finite/negative-zero rejection and future-information isolation remain intact. No unstable wall-time assertions in unit tests. +- Strict TypeScript for new test/tooling sources, scoped lint/format, full `bun run check`, final release verification and G2 recovery if worker/durable boundaries change. Independent reviewer signs off both invariants and measurement methodology. + +Risks: accidental mutable aliasing, skipped validation, changed floating-point crossover arithmetic, committing partial owner state, misleading benchmark attribution. Revert a failed optimization without weakening economic policy or deleting reviewed helpers. Definition of done: focused reviewed patch, passing gates and repeatable exact-economics measurements; root acceptance and explicit commit authorization remain separate. diff --git a/docs/development/backlog/tasks/S02.md b/docs/development/backlog/tasks/S02.md index ab668d21..44fe15f4 100644 --- a/docs/development/backlog/tasks/S02.md +++ b/docs/development/backlog/tasks/S02.md @@ -74,3 +74,9 @@ Keep finite plain JSON indicator state; validate reconstruction without exposing Add strict `runStrategyReplay` version1 requests with existing dataset/config/eventBudget/resultFormat and trusted selections only. Return a versioned `strategyReplayResult` envelope containing normalized selections actually executed and the unchanged native result. The parent captures detached normalized inputs before fork and binds selections, native identity, policy and format on return. No callbacks, source, arbitrary paths, checkpoint transport or second worker infrastructure. Existing legacy/conformance requests remain supported. Required additions: warmup/tie/delayed-bar/freshness cases; exact budget and native fee/gap rejection; separate owners; whole retry and JSON reconstruction; real worker/direct equality in all formats; malformed/tampered responses, crashes and cancellation (including result-before-close); legacy worker regressions. Full repository and disposable recovery gates follow integration. Measure representative release SMA replay without calling it pure callback cost or claiming a performance improvement. + +## Validated handoff — 2026-10-23 + +The new schema and `createBuiltinStrategy`/`validateBuiltinStrategyBindings` implement the pinned contract; the legacy registry and built-ins are unchanged. `runStrategyReplay` requests carry only trusted selections. `parseStrategyReplayResult` validates the versioned envelope and all native result formats. New tests and existing gates pass; exact source hashes, commands and measurements are in the manifest's fifteenth-wave validation and roadmap handoff. Implementation remains uncommitted pending acceptance. + +Worker provenance identifies the reviewed built-in/version/configuration. R01/R05 still own immutable code-artifact retention, durable/public results and default activation. Whole-attempt retry remains the recovery model. [P08](P08.md) records the measured state/decision overhead; optimization and financial-policy changes are outside S02. diff --git a/test/fixtures/canonical-sma.ts b/test/fixtures/canonical-sma.ts new file mode 100644 index 00000000..64a0a9e2 --- /dev/null +++ b/test/fixtures/canonical-sma.ts @@ -0,0 +1,63 @@ +import { builtinStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy'; +import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2'; +import { nativeReplayFixture } from './native-replay'; + +/** Reviewed oracle: buy ten at next open 5, sell ten at next open 2; fees 0.70. */ +export function canonicalSmaFixture( + owners = ['A'], + options: { + tradeStartStep?: number; + volume?: number; + opens?: number[]; + closes?: number[]; + availabilitySteps?: number[]; + } = {} +) { + const fixture = nativeReplayFixture(7, 1, owners); + const { calendars, series, executionSeries, bounds, universe, corporateActions } = + fixture.dataset.manifest; + const closes = options.closes ?? [3, 2, 1, 4, 5, 1, 1]; + const opens = options.opens ?? [3, 3, 2, 1, 5, 5, 2]; + const dataset = createDatasetV2({ + metadata: { + calendars, + series, + executionSeries, + bounds: { + ...bounds, + tradeStart: fixture.start + (options.tradeStartStep ?? 1) * fixture.minute, + }, + universe, + corporateActions, + }, + bars: fixture.dataset.bars.map((bar, index) => { + const open = opens[index]!, + close = closes[index]!; + return { + seriesId: bar.seriesId, + timestamp: bar.intervalStart, + availableAt: + fixture.start + (options.availabilitySteps?.[index] ?? index + 1) * fixture.minute, + sourceSequence: bar.sourceSequence, + open, + close, + high: Math.max(open, close), + low: Math.min(open, close), + volume: options.volume ?? 1000, + }; + }), + }); + const selections = owners.map(ownerId => + builtinStrategySelectionSchema.parse({ + ownerId, + strategyId: 'sma', + strategyVersion: 'sma-crossover-long-only/v1', + seed: 42, + instrumentId: 'X0.US', + seriesId: 'X0.US:1m', + ownerBudget: '40', + parameters: { fastPeriod: 2, slowPeriod: 3 }, + }) + ); + return { ...fixture, dataset, selections }; +} diff --git a/test/fixtures/canonical-strategy-worker.ts b/test/fixtures/canonical-strategy-worker.ts new file mode 100644 index 00000000..b1f70fc2 --- /dev/null +++ b/test/fixtures/canonical-strategy-worker.ts @@ -0,0 +1,111 @@ +import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay'; +import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime'; +import { strategyReplayRequestSchema } from '../../apps/stock/orchestrator/src/contracts/strategy-replay'; +import { + createBuiltinStrategy, + validateBuiltinStrategyBindings, +} from '../../apps/stock/orchestrator/src/strategies/canonical-sma'; + +function send(message: unknown): Promise { + return new Promise((resolve, reject) => + process.send!(message, (error: Error | null) => (error ? reject(error) : resolve())) + ); +} + +process.once('message', async (input: unknown) => { + const request = strategyReplayRequestSchema.parse(input); + const mode = request.config.matching.risk.ledger.accountId; + const load = prepareReplayLoad(request.dataset, request.config); + validateBuiltinStrategyBindings(request.strategies, load); + const { result } = runStrategyReplay(load, request.strategies.map(createBuiltinStrategy), { + eventBudget: request.eventBudget, + resultFormat: + mode === 'wrong-format' + ? request.resultFormat === 'projection' + ? 'trace' + : 'projection' + : request.resultFormat, + }); + const envelope = { + type: 'strategyReplayResult', + version: 1, + strategies: structuredClone(request.strategies), + result, + }; + const selection = envelope.strategies[0]!; + await send({ type: 'progress', progress: 0, message: 'Fixture ready' }); + switch (mode) { + case 'wrong-envelope-version': + envelope.version = 2; + break; + case 'wrong-envelope-type': + envelope.type = 'result'; + break; + case 'wrong-strategy': + Object.assign(selection, { strategyId: 'mean_reversion' }); + break; + case 'wrong-version': + Object.assign(selection, { strategyVersion: 'sma-crossover-long-only/v2' }); + break; + case 'wrong-owner': + selection.ownerId = 'other'; + break; + case 'wrong-seed': + selection.seed++; + break; + case 'wrong-parameters': + selection.parameters.slowPeriod++; + break; + case 'wrong-budget': + Object.assign(selection, { ownerBudget: '101.00000000' }); + break; + case 'wrong-series': + selection.seriesId = 'X0.US:5m'; + break; + case 'wrong-instrument': + selection.instrumentId = 'OTHER.US'; + break; + case 'reordered': + envelope.strategies.reverse(); + break; + case 'missing-selection': + envelope.strategies.pop(); + break; + case 'wrong-session': + result.identity.sessionId = 'other'; + break; + case 'wrong-dataset': + result.identity.datasetHash = '0'.repeat(64); + break; + case 'wrong-policy': + Object.assign(result.policy.matching.risk, { feeRate: '0.5' }); + break; + case 'invalid-result': + Object.assign(envelope, { result: {} }); + break; + case 'malformed': + await send({ nonsense: true }); + process.disconnect?.(); + return; + case 'reported-error': + await send({ type: 'error', message: 'Fixture strategy failure' }); + process.disconnect?.(); + return; + case 'crash': + process.kill(process.pid, 'SIGKILL'); + return; + case 'no-result': + process.disconnect?.(); + return; + } + await send({ type: 'result', result: JSON.stringify(envelope) }); + if (mode === 'duplicate') { + await send({ type: 'result', result: JSON.stringify(envelope) }); + } + if (mode === 'result-then-block') { + while (true) { + Math.sqrt(Math.random()); + } + } + process.disconnect?.(); +}); diff --git a/test/integration/canonical-sma.test.ts b/test/integration/canonical-sma.test.ts new file mode 100644 index 00000000..e2fb6a8c --- /dev/null +++ b/test/integration/canonical-sma.test.ts @@ -0,0 +1,406 @@ +import { expect, test } from 'bun:test'; +import { parseFinancialDecimal } from '@stock-bot/types'; +import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay'; +import { + runStrategyReplay, + StrategyReplayError, +} from '../../apps/stock/orchestrator/src/backtest/strategy-runtime'; +import { + builtinStrategySelectionSchema, + type BuiltinStrategySelection, +} from '../../apps/stock/orchestrator/src/contracts/builtin-strategy'; +import type { + StrategyContext, + StrategyProgram, +} from '../../apps/stock/orchestrator/src/contracts/canonical-strategy'; +import type { PublishedObservation } from '../../apps/stock/orchestrator/src/contracts/native-replay'; +import { strategyAliases } from '../../apps/stock/orchestrator/src/contracts/strategy-names'; +import { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies'; +import { + createBuiltinStrategy, + validateBuiltinStrategyBindings, + type SmaStrategyState, +} from '../../apps/stock/orchestrator/src/strategies/canonical-sma'; +import { canonicalSmaFixture } from '../fixtures/canonical-sma'; + +const d = parseFinancialDecimal; +function selection(overrides: Partial = {}) { + return builtinStrategySelectionSchema.parse({ + ...canonicalSmaFixture().selections[0], + ...overrides, + }); +} +function observation( + close: string, + sequence: number, + overrides: Partial = {} +): PublishedObservation { + return { + series_id: 'X0.US:1m', + instrument_id: 'X0.US', + interval_start: sequence, + interval_end: sequence + 1, + event_time: sequence + 1, + available_at: sequence + 1, + source_sequence: sequence, + open: d(close), + high: d(close), + low: d(close), + close: d(close), + volume: d('1000'), + ...overrides, + }; +} +function context( + state: SmaStrategyState, + observations: PublishedObservation[], + now = observations.at(-1)?.available_at ?? 0 +): StrategyContext { + const last = observations.at(-1); + const riskSession = { calendarId: 'test', calendarRevision: '1', sessionId: 'test', startsAt: 0 }; + return { + ownerId: 'A', + strategyId: 'sma_crossover', + strategyVersion: 'sma-crossover-long-only/v1', + decisionSequence: 0, + now, + barrier: { + barrier_id: 'test', + at: now, + revision: 0, + owner_ids: ['A'], + observation_count: observations.length, + inputs: [ + { + series_id: 'X0.US:1m', + availability: last + ? { Fresh: { event_time: last.event_time, available_at: last.available_at } } + : 'Missing', + }, + ], + }, + portfolio: { + admissionRevision: 0, + equity: d('10000'), + availableCash: d('10000'), + orders: [], + reservations: [], + portfolio: { + version: 1, + sessionId: 'test', + accountId: 'test', + revision: 0, + baseCurrency: 'USD', + reserveOwnerId: 'reserve', + cash: d('10000'), + positions: [], + fees: [], + riskSession, + }, + risk: { + dailyBaseline: d('10000'), + peakEquity: d('10000'), + dailyHalted: false, + drawdownHalted: false, + riskSession, + lastEventTime: now, + }, + }, + positions: [], + observations, + previousAdmission: null, + state, + random: () => { + throw new Error('SMA must not consume random'); + }, + }; +} +function decide( + program: StrategyProgram, + closes: string[], + state = program.initialState, + offset = 0 +) { + return program.decide( + context( + state, + closes.map((close, i) => observation(close, offset + i)) + ) + ); +} + +test('sma_registry_alias selects only the explicit canonical version and leaves legacy factories available', () => { + for (const strategyId of [...strategyAliases.sma_crossover, 'sma_crossover', ' SMA Crossover ']) { + expect(builtinStrategySelectionSchema.parse({ ...selection(), strategyId }).strategyId).toBe( + 'sma_crossover' + ); + } + for (const patch of [ + { strategyId: 'momentum' }, + { strategyVersion: 'sma-crossover-fixed/v2' }, + { source: 'code' }, + { parameters: { fastPeriod: 2, slowPeriod: 3, quantity: 10 } }, + { parameters: { fastPeriod: 3, slowPeriod: 3 } }, + { ownerBudget: '0' }, + ]) { + expect(() => builtinStrategySelectionSchema.parse({ ...selection(), ...patch })).toThrow(); + } + expect(typeof createBuiltinStrategyRegistry().create).toBe('function'); +}); + +test('binding validation rejects wrong owners, mode, cadence, instrument and unknown series before replay', () => { + const fixture = canonicalSmaFixture(); + const load = prepareReplayLoad(fixture.dataset, fixture.config); + expect(() => validateBuiltinStrategyBindings(fixture.selections, load)).not.toThrow(); + for (const changed of [ + selection({ ownerId: 'B' }), + selection({ seriesId: 'missing' }), + selection({ instrumentId: 'X1.US' }), + ]) { + expect(() => validateBuiltinStrategyBindings([changed], load)).toThrow(); + } + expect(() => + validateBuiltinStrategyBindings([...fixture.selections, ...fixture.selections], load) + ).toThrow(); + const wrongMode = structuredClone(load); + wrongMode.config.matching.owners[0]!.mode = 'Orders'; + expect(() => validateBuiltinStrategyBindings(fixture.selections, wrongMode)).toThrow(); + const wrongCadence = structuredClone(load); + wrongCadence.config.cadence[0]!.series_ids = []; + expect(() => validateBuiltinStrategyBindings(fixture.selections, wrongCadence)).toThrow(); +}); + +test('owner_budget_sizing uses exact decimal whole shares, never account equity or a forced minimum', () => { + for (const [budget, prices, expected] of [ + ['0.3', ['0.2', '0.01', '0.1'], '3'], + ['0.09', ['0.2', '0.01', '0.1'], '0'], + ['9007199254740993', ['2', '0.5', '1'], '9007199254740993'], + ] as const) { + const program = createBuiltinStrategy( + selection({ ownerBudget: d(budget), parameters: { fastPeriod: 1, slowPeriod: 2 } }) + ); + const result = decide(program, [...prices]); + expect(result.intent).toEqual({ + mode: 'target', + targets: [{ instrumentId: 'X0.US', quantity: d(expected) }], + }); + expect(JSON.stringify(result.nextState)).not.toContain('BigInt'); + } +}); + +test('warmup requires a real crossover; target survives equality and a repeated golden cross until death', () => { + const program = createBuiltinStrategy( + selection({ parameters: { fastPeriod: 1, slowPeriod: 2 } }) + ); + expect(decide(program, ['1', '2']).intent).toEqual({ mode: 'target', targets: [] }); + expect(decide(program, ['1', '2', '3']).intent).toEqual({ mode: 'target', targets: [] }); + let result = decide(program, ['3', '1', '2']); + expect(result.nextState.targetQuantity).toBe(d('20')); + result = decide(program, ['2'], result.nextState, 3); // equality retains long + expect(result.nextState.targetQuantity).toBe(d('20')); + result = decide(program, ['4'], result.nextState, 4); // golden after equality must not resize to10 + expect(result.nextState.targetQuantity).toBe(d('20')); + result = decide(program, ['1'], result.nextState, 5); + expect(result.nextState.targetQuantity).toBe(d('0')); +}); + +test('stale, missing, mismatched freshness and no-new inputs preserve GTC intent without new targets', () => { + const program = createBuiltinStrategy(selection()); + const initial = decide(program, ['3', '2', '1', '4']); + for (const availability of [ + 'Missing', + { Stale: { event_time: 5, available_at: 5 } }, + { Fresh: { event_time: 4, available_at: 4 } }, + ] as const) { + const input = context(initial.nextState, [observation('5', 4)]); + const result = program.decide({ + ...input, + barrier: { ...input.barrier, inputs: [{ series_id: 'X0.US:1m', availability }] }, + }); + expect(result.intent).toEqual({ mode: 'target', targets: [] }); + expect(result.nextState.targetQuantity).toBe(d('10')); + } + expect(program.decide(context(initial.nextState, [])).intent).toEqual({ + mode: 'target', + targets: [], + }); + const delayed = observation('0.01', 1, { available_at: 10 }); + const input = context(initial.nextState, [delayed], 10); + const result = program.decide({ + ...input, + barrier: { + ...input.barrier, + inputs: [ + { series_id: 'X0.US:1m', availability: { Fresh: { event_time: 4, available_at: 4 } } }, + ], + }, + }); + expect(result.nextState).toEqual(initial.nextState); + expect(result.intent).toEqual({ mode: 'target', targets: [] }); + expect(() => program.decide(context(initial.nextState, [observation('5', 4)], 4))).toThrow( + 'availability' + ); +}); + +test('sma_checkpoint_restore validates JSON state and reconstructs identical indicator decisions', () => { + const selected = selection(); + const first = createBuiltinStrategy(selected); + const before = decide(first, ['3', '2', '1', '4']); + const restored = JSON.parse(JSON.stringify(before.nextState)) as SmaStrategyState; + expect(decide(createBuiltinStrategy(selected), ['5', '1'], restored, 4)).toEqual( + decide(first, ['5', '1'], before.nextState, 4) + ); + expect(() => decide(first, ['5'], { ...restored, closes: [] }, 4)).toThrow(); + expect(() => + decide(createBuiltinStrategy(selection({ ownerId: 'B' })), ['5'], restored, 4) + ).toThrow(); + expect(() => decide(first, ['5'], { ...restored, targetQuantity: d('1.5') }, 4)).toThrow(); +}); + +test('sma_next_open_trace buys and closes at eligible next opens with authoritative fees and exact equity', () => { + const fixture = canonicalSmaFixture(); + const load = prepareReplayLoad(fixture.dataset, fixture.config); + validateBuiltinStrategyBindings(fixture.selections, load); + const run = (eventBudget: number) => + runStrategyReplay(load, fixture.selections.map(createBuiltinStrategy), { + resultFormat: 'report', + eventBudget, + }); + const first = run(1); + expect(run(64)).toEqual({ ...first, metrics: expect.anything() }); + expect(first.result.projection.valuation.equity).toBe(d('9969.3')); + expect(first.result.projection.valuation.fees).toBe(d('0.7')); + expect( + first.result.projection.fills.map(fill => ({ + price: fill.price, + quantityDelta: fill.quantityDelta, + })) + ).toEqual([ + { price: d('5'), quantityDelta: d('10') }, + { price: d('2'), quantityDelta: d('-10') }, + ]); +}); + +test('warmup crossover sizes once at the first eligible fresh trading close and cannot fill during warmup', () => { + const fixture = canonicalSmaFixture(['A'], { tradeStartStep: 5 }); + const load = prepareReplayLoad(fixture.dataset, fixture.config); + const run = runStrategyReplay(load, fixture.selections.map(createBuiltinStrategy), { + resultFormat: 'report', + }); + expect(run.result.projection.fills.map(fill => [fill.eventTime, fill.quantityDelta])).toEqual([ + [fixture.start + 5 * fixture.minute, d('8')], + [fixture.start + 6 * fixture.minute, d('-8')], + ]); + expect(run.result.projection.valuation.equity).toBe(d('9975.44')); +}); + +test('canonical SMA cannot bypass native fee-inclusive funding or adverse-gap fill checks', () => { + for (const capital of ['40', '45']) { + const fixture = canonicalSmaFixture(); + fixture.config.matching.risk.ledger.initialCapital = capital; + const run = runStrategyReplay( + prepareReplayLoad(fixture.dataset, fixture.config), + fixture.selections.map(createBuiltinStrategy), + { resultFormat: 'report' } + ); + expect(run.result.projection.fills).toEqual([]); + expect(run.result.projection.valuation.cash).toBe(d(capital)); + const trace = runStrategyReplay( + prepareReplayLoad(fixture.dataset, fixture.config), + fixture.selections.map(createBuiltinStrategy), + { resultFormat: 'trace' } + ); + expect(JSON.stringify(trace.result.receipts)).toContain('InsufficientCash'); + expect(run.diagnostics.strategies[0]!.state).toMatchObject({ + lastCrossover: 'death', + targetQuantity: d('0'), + }); + } +}); + +test('late older native observations cannot rewrite SMA history or alter its targets', () => { + const run = (lateClose: number) => { + const fixture = canonicalSmaFixture(['A'], { + closes: [3, lateClose, 1, 4, 5, 1, 1], + availabilitySteps: [1, 6, 3, 4, 5, 6, 7], + }); + return runStrategyReplay( + prepareReplayLoad(fixture.dataset, fixture.config), + fixture.selections.map(createBuiltinStrategy), + { resultFormat: 'report', eventBudget: 1 } + ); + }; + const first = run(2), + changed = run(200); + expect(changed.result.projection).toEqual(first.result.projection); + expect(changed.diagnostics.strategies).toEqual(first.diagnostics.strategies); + expect(first.result.projection.fills.map(fill => fill.quantityDelta)).toEqual([d('8'), d('-8')]); +}); + +test('repeating the desired target preserves the partially filled native order before a death closes owned inventory', () => { + const fixture = canonicalSmaFixture(['A'], { volume: 3 }); + const run = runStrategyReplay( + prepareReplayLoad(fixture.dataset, fixture.config), + fixture.selections.map(createBuiltinStrategy), + { resultFormat: 'report' } + ); + const fills = run.result.projection.fills; + expect(fills.map(fill => fill.quantityDelta)).toEqual([d('3'), d('3'), d('-3')]); + expect(fills[0]!.orderId).toBe(fills[1]!.orderId); + expect(run.result.view.portfolio.positions[0]!.quantity).toBe(d('3')); + expect(run.result.projection.valuation.cash).toBe(d('9975.64')); + expect(run.result.projection.valuation.equity).toBe(d('9978.64')); +}); + +test('two owners sharing an asset keep independent targets, fills and P&L', () => { + const fixture = canonicalSmaFixture(['B', 'A']); + fixture.selections = fixture.selections.map(item => + selection({ ...item, ownerBudget: d(item.ownerId === 'A' ? '40' : '20') }) + ); + const load = prepareReplayLoad(fixture.dataset, fixture.config); + validateBuiltinStrategyBindings(fixture.selections, load); + const run = runStrategyReplay(load, fixture.selections.map(createBuiltinStrategy), { + resultFormat: 'report', + }); + expect(run.result.projection.fills.map(fill => [fill.ownerId, fill.quantityDelta])).toEqual([ + ['A', d('10')], + ['B', d('5')], + ['A', d('-10')], + ['B', d('-5')], + ]); + expect( + run.result.projection.valuation.owners + .filter(owner => owner.ownerId !== 'reserve') + .map(owner => [owner.ownerId, owner.realizedGrossPnl, owner.fees]) + ).toEqual([ + ['A', d('-30'), d('0.7')], + ['B', d('-15'), d('0.35')], + ]); + expect(run.result.projection.valuation.equity).toBe(d('9953.95')); +}); + +test('sma_checkpoint_restore whole-attempt retry after strategy failure recomputes identical decisions and economics', () => { + const fixture = canonicalSmaFixture(); + const load = prepareReplayLoad(fixture.dataset, fixture.config); + const original = createBuiltinStrategy(fixture.selections[0]!); + const failing: StrategyProgram = { + ...original, + decide(input) { + if (input.decisionSequence === 4) { + throw new Error('injected strategy failure'); + } + return original.decide(input); + }, + }; + expect(() => runStrategyReplay(load, [failing], { resultFormat: 'report' })).toThrow( + StrategyReplayError + ); + const baseline = runStrategyReplay(load, [createBuiltinStrategy(fixture.selections[0]!)], { + resultFormat: 'report', + eventBudget: 1, + }); + const retried = runStrategyReplay(load, [original], { resultFormat: 'report', eventBudget: 7 }); + expect(retried.result).toEqual(baseline.result); + expect(retried.diagnostics).toEqual(baseline.diagnostics); + expect(original.initialState.closes).toEqual([]); +}); diff --git a/test/integration/canonical-strategy-worker.test.ts b/test/integration/canonical-strategy-worker.test.ts new file mode 100644 index 00000000..9e94f567 --- /dev/null +++ b/test/integration/canonical-strategy-worker.test.ts @@ -0,0 +1,238 @@ +import type { ChildProcess } from 'node:child_process'; +import { describe, expect, test } from 'bun:test'; +import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay'; +import { nativeWorkerRequestSchema } from '../../apps/stock/orchestrator/src/backtest/native-worker-protocol'; +import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker'; +import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime'; +import { + replayIdentitySchema, + type ReplayResultFormat, +} from '../../apps/stock/orchestrator/src/contracts/native-replay'; +import { + parseStrategyReplayResult, + strategyReplayRequestSchema, + type StrategyReplayExpectation, + type StrategyReplayRequest, +} from '../../apps/stock/orchestrator/src/contracts/strategy-replay'; +import { + createBuiltinStrategy, + validateBuiltinStrategyBindings, +} from '../../apps/stock/orchestrator/src/strategies/canonical-sma'; +import { nativeReplayFixture } from '../fixtures/native-replay'; + +function request(resultFormat: ReplayResultFormat = 'trace', owners = ['A']) { + const { dataset, config } = nativeReplayFixture(24, 1, owners); + return { + type: 'runStrategyReplay' as const, + version: 1 as const, + dataset, + config, + eventBudget: 3, + resultFormat, + strategies: owners.map((ownerId, index) => ({ + ownerId, + strategyId: 'SMA', + strategyVersion: 'sma-crossover-long-only/v1' as const, + seed: index + 7, + instrumentId: 'X0.US', + seriesId: 'X0.US:1m', + ownerBudget: '100', + parameters: { fastPeriod: 1, slowPeriod: 2 }, + })), + } satisfies StrategyReplayRequest; +} + +function expected(input: StrategyReplayRequest): StrategyReplayExpectation { + const normalized = strategyReplayRequestSchema.parse(input); + return { + strategies: normalized.strategies, + identity: replayIdentitySchema.parse({ + version: 1, + sessionId: normalized.config.matching.risk.ledger.sessionId, + datasetHash: (normalized.dataset as { manifest: { hash: string } }).manifest.hash, + }), + policy: normalized.config, + format: normalized.resultFormat ?? 'trace', + }; +} + +function direct(input: StrategyReplayRequest) { + const normalized = strategyReplayRequestSchema.parse(input); + const load = prepareReplayLoad(normalized.dataset, normalized.config); + validateBuiltinStrategyBindings(normalized.strategies, load); + return runStrategyReplay(load, normalized.strategies.map(createBuiltinStrategy), { + eventBudget: normalized.eventBudget, + resultFormat: normalized.resultFormat, + }).result; +} + +describe('trusted built-in strategy worker', () => { + test.each(['trace', 'projection', 'report'] as const)( + '%s real child matches direct SMA replay and repeated frozen-input attempts', + async resultFormat => { + const input = request(resultFormat, ['B', 'A']); + const captured = expected(input); + const worker = new NativeBacktestWorker(); + const raw = await worker.execute(input, new AbortController().signal, () => {}); + const envelope = parseStrategyReplayResult(raw, captured); + expect(envelope.result).toEqual(direct(input)); + expect(envelope.strategies).toEqual([...captured.strategies]); + expect(envelope.strategies.map(selection => selection.strategyId)).toEqual([ + 'sma_crossover', + 'sma_crossover', + ]); + expect(envelope.result.view.portfolio.positions).toHaveLength(2); + expect(Object.keys(envelope).sort()).toEqual(['result', 'strategies', 'type', 'version']); + expect(await worker.execute(input, new AbortController().signal, () => {})).toBe(raw); + } + ); + + test('schema normalizes built-in aliases/defaults but rejects code and unsupported versions', () => { + const defaults = request(); + const parsed = strategyReplayRequestSchema.parse({ + ...defaults, + strategies: [{ ...defaults.strategies[0], parameters: {} }], + }); + expect(parsed.strategies[0]).toMatchObject({ + strategyId: 'sma_crossover', + ownerBudget: '100.00000000', + parameters: { fastPeriod: 5, slowPeriod: 15 }, + }); + for (const extra of [ + { source: 'return buy()' }, + { module: './candidate.ts' }, + { initialState: {} }, + { decide: () => ({}) }, + ]) { + expect(() => nativeWorkerRequestSchema.parse({ ...request(), ...extra })).toThrow(); + const input = request(); + expect(() => + nativeWorkerRequestSchema.parse({ + ...input, + strategies: [{ ...input.strategies[0], ...extra }], + }) + ).toThrow(); + } + for (const changes of [ + { strategyId: 'momentum' }, + { strategyVersion: 'legacy' }, + { parameters: { fastPeriod: 1, slowPeriod: 2, quantity: 10 } }, + ]) { + const input = request(); + expect(() => + nativeWorkerRequestSchema.parse({ + ...input, + strategies: [{ ...input.strategies[0], ...changes }], + }) + ).toThrow(); + } + }); + + test('captures the entire normalized request before caller mutation', async () => { + const input = structuredClone(request('report')); + const captured = expected(input); + const reference = direct(structuredClone(input)); + const worker = new NativeBacktestWorker(); + const running = worker.execute(input, new AbortController().signal, () => {}); + input.strategies[0]!.seed = 999; + input.strategies[0]!.parameters.slowPeriod = 20; + input.strategies[0]!.ownerBudget = '5000'; + input.strategies[0]!.ownerId = 'mutated'; + input.config.matching.risk.ledger.sessionId = 'mutated'; + (input.dataset.manifest as { hash: string }).hash = '0'.repeat(64); + (input.dataset.bars as unknown[]).length = 0; + input.resultFormat = 'projection'; + input.eventBudget = 0; + const envelope = parseStrategyReplayResult(await running, captured); + expect(envelope.result).toEqual(reference); + expect(envelope.strategies).toEqual([...captured.strategies]); + }); + + test('actual child rejects invalid owner, cadence and series bindings', async () => { + const worker = new NativeBacktestWorker(); + for (const change of ['owner', 'cadence', 'series', 'instrument'] as const) { + const input = request(); + if (change === 'owner') { + input.strategies[0]!.ownerId = 'unknown'; + } + if (change === 'cadence') { + input.config.cadence[0]!.series_ids = []; + } + if (change === 'series') { + input.strategies[0]!.seriesId = 'X0.US:unknown'; + } + if (change === 'instrument') { + input.strategies[0]!.instrumentId = 'OTHER.US'; + } + await expect(worker.execute(input, new AbortController().signal, () => {})).rejects.toThrow(); + } + expect( + JSON.parse(await worker.execute(request(), new AbortController().signal, () => {})).type + ).toBe('strategyReplayResult'); + }); + + test.each([ + 'wrong-envelope-version', + 'wrong-envelope-type', + 'wrong-strategy', + 'wrong-version', + 'wrong-owner', + 'wrong-seed', + 'wrong-parameters', + 'wrong-budget', + 'wrong-series', + 'wrong-instrument', + 'reordered', + 'missing-selection', + 'wrong-session', + 'wrong-dataset', + 'wrong-policy', + 'wrong-format', + 'invalid-result', + 'malformed', + 'reported-error', + 'crash', + 'no-result', + 'duplicate', + ])('%s child cannot publish a successful result', async mode => { + const worker = new NativeBacktestWorker( + new URL('../fixtures/canonical-strategy-worker.ts', import.meta.url) + ); + const input = request('trace', ['B', 'A']); + input.config.matching.risk.ledger.accountId = mode; + await expect(worker.execute(input, new AbortController().signal, () => {})).rejects.toThrow(); + expect( + JSON.parse(await worker.execute(request(), new AbortController().signal, () => {})).type + ).toBe('strategyReplayResult'); + }); + + test('hard cancellation discards pending success and releases the worker', async () => { + const actual = new NativeBacktestWorker(); + const beforeResult = new AbortController(); + await expect( + actual.execute(request(), beforeResult.signal, () => { + beforeResult.abort(new Error('cancel strategy work')); + }) + ).rejects.toThrow('cancel strategy work'); + const worker = new NativeBacktestWorker( + new URL('../fixtures/canonical-strategy-worker.ts', import.meta.url) + ); + const input = request(); + input.config.matching.risk.ledger.accountId = 'result-then-block'; + const afterResult = new AbortController(); + let observed = false; + const running = worker.execute(input, afterResult.signal, () => {}); + const child = (worker as unknown as { active: ChildProcess }).active; + child.on('message', (message: { type: string }) => { + if (message.type === 'result') { + observed = true; + afterResult.abort(new Error('cancel pending strategy success')); + } + }); + await expect(running).rejects.toThrow('cancel pending strategy success'); + expect(observed).toBe(true); + expect( + JSON.parse(await worker.execute(request(), new AbortController().signal, () => {})).type + ).toBe('strategyReplayResult'); + }); +});