From 6055aeeee9fa993ca0d83fb5a1f5eee80a0ab19a Mon Sep 17 00:00:00 2001 From: Boki Date: Mon, 26 Oct 2026 20:33:56 -0400 Subject: [PATCH] refactor(orchestrator): share pure strategy bookkeeping (CL19) --- apps/stock/orchestrator/src/canonical-json.ts | 23 +++++ .../src/contracts/canonical-execution.ts | 14 +++ .../src/execution/CanonicalPaperExecution.ts | 32 ++----- .../PostgresCanonicalExecutionRepository.ts | 2 +- .../src/execution/canonical-paper.ts | 14 +-- .../src/execution/strategy-recovery.ts | 25 +---- .../src/paper/CanonicalPaperRuntime.ts | 2 +- apps/stock/orchestrator/src/paper/feed.ts | 20 ++-- .../src/strategies/strategy-controller.ts | 32 ++----- .../src/strategies/strategy-decision.ts | 44 ++++++++- docs/development/backlog/README.md | 2 +- docs/development/backlog/manifest.json | 21 ++-- .../orchestrator-engine-cleanup.md | 9 ++ test/integration/paper-feed.test.ts | 40 +++++++- test/integration/strategy-recovery.test.ts | 11 +++ test/integration/strategy-runtime.test.ts | 95 ++++++++++--------- test/postgres/canonical-paper.test.ts | 68 ++++++++++++- 17 files changed, 297 insertions(+), 157 deletions(-) create mode 100644 apps/stock/orchestrator/src/canonical-json.ts diff --git a/apps/stock/orchestrator/src/canonical-json.ts b/apps/stock/orchestrator/src/canonical-json.ts new file mode 100644 index 00000000..a0fcdccc --- /dev/null +++ b/apps/stock/orchestrator/src/canonical-json.ts @@ -0,0 +1,23 @@ +/** Only JSON values are checkpointable; reject lossy JSON.stringify conversions. */ +export function canonicalJson(value: unknown): string { + const visit = (input: unknown): unknown => { + if (input === null || typeof input === 'string' || typeof input === 'boolean') { + return input; + } + if (typeof input === 'number' && Number.isFinite(input)) { + return input; + } + if (Array.isArray(input)) { + return Array.from(input, visit); + } + if (input && typeof input === 'object' && Object.getPrototypeOf(input) === Object.prototype) { + return Object.fromEntries( + Object.entries(input) + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) + .map(([key, item]) => [key, visit(item)]) + ); + } + throw new Error('Strategy checkpoints require finite, plain JSON values'); + }; + return JSON.stringify(visit(value)); +} diff --git a/apps/stock/orchestrator/src/contracts/canonical-execution.ts b/apps/stock/orchestrator/src/contracts/canonical-execution.ts index 719da74c..c1877b9c 100644 --- a/apps/stock/orchestrator/src/contracts/canonical-execution.ts +++ b/apps/stock/orchestrator/src/contracts/canonical-execution.ts @@ -94,6 +94,20 @@ export const matchingCommandSchema = z .strict(); export type CanonicalMatchingCommand = z.input; +/** Event ordering must agree with Rust, including UTF-8 instrument identity ties. */ +export function compareEventKeys( + a: CanonicalMatchingCommand['key'], + b: CanonicalMatchingCommand['key'] +): number { + const phases = { Observation: 0, Decision: 1, Execution: 2, SessionClose: 3 }; + return ( + a.at - b.at || + phases[a.phase] - phases[b.phase] || + Buffer.compare(Buffer.from(a.instrumentId), Buffer.from(b.instrumentId)) || + a.sourceSequence - b.sourceSequence + ); +} + /** Metadata and shapes only. Rust restores and validates all nested receipts, * reservations, accounting and indexes before any transition. */ export const canonicalExecutionCheckpointSchema = z diff --git a/apps/stock/orchestrator/src/execution/CanonicalPaperExecution.ts b/apps/stock/orchestrator/src/execution/CanonicalPaperExecution.ts index 8f0690b3..10234bae 100644 --- a/apps/stock/orchestrator/src/execution/CanonicalPaperExecution.ts +++ b/apps/stock/orchestrator/src/execution/CanonicalPaperExecution.ts @@ -1,6 +1,7 @@ import { AsyncLocalStorage } from 'node:async_hooks'; import { createHash } from 'node:crypto'; import { stageFinancialTransaction } from '@stock-bot/engine'; +import { canonicalJson } from '../canonical-json'; import { canonicalMatchingConfigSchema, financialTransactionRequestSchema, @@ -15,7 +16,9 @@ import { nativeAdmissionOrders, type DecisionContext } from '../contracts/native import { freeze, increment, + initialStrategyDiagnostic, metadataSchema, + ownerAdmissionFeedback, stageStrategyDecision, stateCopy, type Metadata, @@ -32,7 +35,6 @@ import { type CanonicalTransaction, } from './canonical-paper'; import { ExecutionConflictError } from './repository'; -import { canonicalJson } from './strategy-recovery'; const callback = new AsyncLocalStorage(); function outsideCallback() { @@ -85,16 +87,7 @@ export class CanonicalPaperExecution { version: 1, definition: { ...metadata, initialState }, cursor: 0, - diagnostic: { - ownerId, - strategyId, - strategyVersion, - nextDecisionSequence: 0, - state: stateCopy(initialState), - rng: { algorithm: 'lcg32-v1', seed, state: seed, draws: 0 }, - observationCount: 0, - previousAdmission: null, - }, + diagnostic: initialStrategyDiagnostic(metadata, initialState), pendingObservations: [], }; }) @@ -327,18 +320,11 @@ export class CanonicalPaperExecution { if (!decision) { continue; } - owner.diagnostic.previousAdmission = { - decision: decision.decision, - revision: result.outcome.revision, - orders: orders - .filter(order => order.order.decision.ownerId === owner.definition.ownerId) - .map(order => ({ - orderId: order.order.orderId, - instrumentId: order.order.instrumentId, - decision: order.order.decision, - status: order.status, - })), - }; + owner.diagnostic.previousAdmission = ownerAdmissionFeedback( + decision.decision, + result.outcome.revision, + orders + ); await tx.putOwner(owner); } } diff --git a/apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository.ts b/apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository.ts index 50d6ab79..7677b9f2 100644 --- a/apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository.ts +++ b/apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository.ts @@ -1,3 +1,4 @@ +import { canonicalJson } from '../canonical-json'; import { increment } from '../strategies/strategy-decision'; import { canonicalAccountSchema, @@ -12,7 +13,6 @@ import { type CanonicalTransaction, } from './canonical-paper'; import { ExecutionConflictError } from './repository'; -import { canonicalJson } from './strategy-recovery'; function accountState(raw: unknown): CanonicalAccount { const result = canonicalAccountSchema.safeParse(raw); diff --git a/apps/stock/orchestrator/src/execution/canonical-paper.ts b/apps/stock/orchestrator/src/execution/canonical-paper.ts index ebd5e541..7d865147 100644 --- a/apps/stock/orchestrator/src/execution/canonical-paper.ts +++ b/apps/stock/orchestrator/src/execution/canonical-paper.ts @@ -6,7 +6,6 @@ import { canonicalExecutionCheckpointSchema, financialTransactionResultSchema, matchingCommandSchema, - type CanonicalMatchingCommand, } from '../contracts/canonical-execution'; import { nativeFinancialViewSchema, @@ -196,18 +195,7 @@ export interface CanonicalExecutionRepository { transact(accountId: string, work: (tx: CanonicalTransaction) => Promise): Promise; } export type CanonicalPostgres = Pick; -export function compareEventKeys( - a: CanonicalMatchingCommand['key'], - b: CanonicalMatchingCommand['key'] -): number { - const phases = { Observation: 0, Decision: 1, Execution: 2, SessionClose: 3 }; - return ( - a.at - b.at || - phases[a.phase] - phases[b.phase] || - Buffer.compare(Buffer.from(a.instrumentId), Buffer.from(b.instrumentId)) || - a.sourceSequence - b.sourceSequence - ); -} +export { compareEventKeys } from '../contracts/canonical-execution'; /** Legacy callers must never reinterpret any version of a canonical envelope. */ export function refuseCanonicalAccount(state: unknown): void { if (state && typeof state === 'object' && 'kind' in state) { diff --git a/apps/stock/orchestrator/src/execution/strategy-recovery.ts b/apps/stock/orchestrator/src/execution/strategy-recovery.ts index 2844f2af..508d4642 100644 --- a/apps/stock/orchestrator/src/execution/strategy-recovery.ts +++ b/apps/stock/orchestrator/src/execution/strategy-recovery.ts @@ -1,30 +1,9 @@ import { createHash } from 'node:crypto'; +import { canonicalJson } from '../canonical-json'; import type { MarketData, OrderRequest, StrategyConfig } from '../types'; import type { Account, ExecutionReport, Fill } from './model'; -/** Only JSON values are checkpointable; reject lossy JSON.stringify conversions. */ -export function canonicalJson(value: unknown): string { - const visit = (input: unknown): unknown => { - if (input === null || typeof input === 'string' || typeof input === 'boolean') { - return input; - } - if (typeof input === 'number' && Number.isFinite(input)) { - return input; - } - if (Array.isArray(input)) { - return Array.from(input, visit); - } - if (input && typeof input === 'object' && Object.getPrototypeOf(input) === Object.prototype) { - return Object.fromEntries( - Object.entries(input) - .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) - .map(([key, item]) => [key, visit(item)]) - ); - } - throw new Error('Strategy checkpoints require finite, plain JSON values'); - }; - return JSON.stringify(visit(value)); -} +export { canonicalJson } from '../canonical-json'; export function strategyConfigHash(config: StrategyConfig, version: string): string { const { enabled: _enabled, ...definition } = config; return createHash('sha256').update(canonicalJson({ definition, version })).digest('hex'); diff --git a/apps/stock/orchestrator/src/paper/CanonicalPaperRuntime.ts b/apps/stock/orchestrator/src/paper/CanonicalPaperRuntime.ts index 0348f223..becb267a 100644 --- a/apps/stock/orchestrator/src/paper/CanonicalPaperRuntime.ts +++ b/apps/stock/orchestrator/src/paper/CanonicalPaperRuntime.ts @@ -1,5 +1,6 @@ import { createHash, randomUUID } from 'node:crypto'; import type { PaperDeploymentBinding } from '@stock-bot/stock-config/paper-deployments'; +import { canonicalJson } from '../canonical-json'; import type { StrategyProgram } from '../contracts/canonical-strategy'; import { paperActivationSchema, @@ -21,7 +22,6 @@ import type { 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) => diff --git a/apps/stock/orchestrator/src/paper/feed.ts b/apps/stock/orchestrator/src/paper/feed.ts index fe46a567..54ab6715 100644 --- a/apps/stock/orchestrator/src/paper/feed.ts +++ b/apps/stock/orchestrator/src/paper/feed.ts @@ -3,6 +3,7 @@ import { isDeepStrictEqual } from 'node:util'; import { ZodError } from 'zod'; import { + compareEventKeys, matchingCommandSchema, type CanonicalMatchingCommand, } from '../contracts/canonical-execution'; @@ -45,15 +46,6 @@ function unique(values: readonly string[], label: string): void { 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) => @@ -231,7 +223,7 @@ export function validatePaperFrame( invalid('Paper quote identity, time, price or size is invalid'); } } - frame.quotes.sort((a, b) => keyCompare(quoteKey(frame, a), quoteKey(frame, b))); + frame.quotes.sort((a, b) => compareEventKeys(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]; @@ -350,7 +342,7 @@ export function planPaperFrame( const add = (command: CanonicalMatchingCommand) => { if ( command.key.at <= frame.availableAt && - (!checkpoint.cursor || keyCompare(command.key, checkpoint.cursor) > 0) + (!checkpoint.cursor || compareEventKeys(command.key, checkpoint.cursor) > 0) ) { commands.push(command); } @@ -409,7 +401,7 @@ export function planPaperFrame( }); } const active = new Map(checkpoint.sessions); - commands.sort((a, b) => keyCompare(a.key, b.key)); + commands.sort((a, b) => compareEventKeys(a.key, b.key)); for (const command of commands) { if (command.body.kind === 'openSession') { if (active.has(command.key.instrumentId)) { @@ -424,12 +416,12 @@ export function planPaperFrame( } } const quotes = [...frame.quotes].sort((a, b) => - keyCompare(quoteKey(frame, a), quoteKey(frame, b)) + compareEventKeys(quoteKey(frame, a), quoteKey(frame, b)) ); for (const quote of quotes) { const key = quoteKey(frame, quote); if ( - (checkpoint.cursor && keyCompare(key, checkpoint.cursor) <= 0) || + (checkpoint.cursor && compareEventKeys(key, checkpoint.cursor) <= 0) || !isDeepStrictEqual( active.get(quote.instrumentId), activeSession(config, quote.instrumentId, frame.availableAt) diff --git a/apps/stock/orchestrator/src/strategies/strategy-controller.ts b/apps/stock/orchestrator/src/strategies/strategy-controller.ts index d9614638..801eef08 100644 --- a/apps/stock/orchestrator/src/strategies/strategy-controller.ts +++ b/apps/stock/orchestrator/src/strategies/strategy-controller.ts @@ -3,7 +3,6 @@ import type { FinancialStrategyDecision } from '@stock-bot/types'; import type { DeepReadonly, - StrategyAdmissionFeedback, StrategyDiagnostic, StrategyDiagnosticSnapshot, StrategyProgram, @@ -18,9 +17,10 @@ import { import { freeze, increment, + initialStrategyDiagnostic, metadataSchema, + ownerAdmissionFeedback, stageStrategyDecision, - stateCopy, type Metadata, } from '../strategies/strategy-decision'; @@ -64,16 +64,7 @@ export class StrategyController { if (typeof decide !== 'function') { throw new Error('Strategy decide must be synchronous callable code'); } - const diagnostic = freeze({ - ownerId, - strategyId, - strategyVersion, - nextDecisionSequence: 0, - state: stateCopy(program.initialState), - rng: { algorithm: 'lcg32-v1' as const, seed, state: seed, draws: 0 }, - observationCount: 0, - previousAdmission: null, - }); + const diagnostic = freeze(initialStrategyDiagnostic(metadata, program.initialState)); return [ownerId, { program: { ...metadata, decide }, diagnostic, pendingObservations: [] }]; }) ); @@ -183,18 +174,11 @@ export class StrategyController { if (!slot) { throw new Error('Staged strategy owner is missing'); } - const previousAdmission: StrategyAdmissionFeedback = { - decision: owner.decision.decision, - revision: outcome.revision, - orders: orders - .filter(order => order.order.decision.ownerId === owner.ownerId) - .map(order => ({ - orderId: order.order.orderId, - instrumentId: order.order.instrumentId, - decision: order.order.decision, - status: order.status, - })), - }; + const previousAdmission = ownerAdmissionFeedback( + owner.decision.decision, + outcome.revision, + orders + ); next.set(owner.ownerId, { program: slot.program, diagnostic: freeze({ ...owner.diagnostic, previousAdmission }), diff --git a/apps/stock/orchestrator/src/strategies/strategy-decision.ts b/apps/stock/orchestrator/src/strategies/strategy-decision.ts index 69cc3cf9..9f952b1b 100644 --- a/apps/stock/orchestrator/src/strategies/strategy-decision.ts +++ b/apps/stock/orchestrator/src/strategies/strategy-decision.ts @@ -4,10 +4,15 @@ import { z } from 'zod'; import { parseFinancialStrategyDecision, type FinancialStrategyDecision } from '@stock-bot/types'; import type { DeepReadonly, + StrategyAdmissionFeedback, StrategyDiagnostic, StrategyProgram, } from '../contracts/canonical-strategy'; -import type { DecisionContext, PublishedObservation } from '../contracts/native-replay'; +import type { + DecisionContext, + nativeAdmissionOrders, + PublishedObservation, +} from '../contracts/native-replay'; export function freeze(value: T): DeepReadonly { if (value && typeof value === 'object' && !Object.isFrozen(value)) { @@ -83,6 +88,43 @@ export const metadataSchema = z .strict(); export type Metadata = z.infer; +/** Fresh detached diagnostics; each host retains its own commit/freeze boundary. */ +export function initialStrategyDiagnostic( + { ownerId, strategyId, strategyVersion, seed }: Metadata, + initialState: unknown +): StrategyDiagnostic { + return { + ownerId, + strategyId, + strategyVersion, + nextDecisionSequence: 0, + state: stateCopy(initialState), + rng: { algorithm: 'lcg32-v1', seed, state: seed, draws: 0 }, + observationCount: 0, + previousAdmission: null, + }; +} + +/** Project already-validated batch admission into this decision owner's feedback. */ +export function ownerAdmissionFeedback( + decision: FinancialStrategyDecision['decision'], + revision: number, + orders: ReturnType +): StrategyAdmissionFeedback { + return { + decision, + revision, + orders: orders + .filter(order => order.order.decision.ownerId === decision.ownerId) + .map(order => ({ + orderId: order.order.orderId, + instrumentId: order.order.instrumentId, + decision: order.order.decision, + status: order.status, + })), + }; +} + export function increment(value: number, amount = 1): number { const next = value + amount; if (!Number.isSafeInteger(next) || next < 0) { diff --git a/docs/development/backlog/README.md b/docs/development/backlog/README.md index 86715ec2..f822844e 100644 --- a/docs/development/backlog/README.md +++ b/docs/development/backlog/README.md @@ -144,7 +144,7 @@ R06/R08/R09 and the R07 comparison/measurement are complete. The default support ## E11 — Orchestrator and engine cleanup -Owner authorized planning and per-task implementation commits. [Execution plan and validation](../orchestrator-engine-cleanup.md). First wave CL14/CL15/CL16 is completed and committed. CL17/CL18 are completed; CL19/CL20 are in progress; CL21 remains conditional. Earlier cleanup reviews and the six original conditional tasks remain unchanged. +Owner authorized planning and per-task implementation commits. [Execution plan and validation](../orchestrator-engine-cleanup.md). First wave CL14/CL15/CL16 is completed and committed. CL17–CL19 are completed; CL20 is in progress; CL21 remains conditional. Earlier cleanup reviews and the six original conditional tasks remain unchanged. | Task | Priority | Dependencies | | --- | --- | --- | diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index 88c84e36..f7a4758a 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -1,6 +1,6 @@ { "schema_version": 1, - "plan_revision": "2026-10-26.83", + "plan_revision": "2026-10-26.84", "repository_base": "b7aeca4", "plan_status": "orchestrator_engine_cleanup_remaining_wave", "execution_authorized": true, @@ -2877,10 +2877,10 @@ ], "assignment": "/root/implement_cl17", "branch": "cleanup/cl17-historical-reader", - "completed_commit": null, + "completed_commit": "984dc1a9", "blocker": null, "release_gates": [], - "integration_state": "validated_pending_commit", + "integration_state": "validated_committed", "integration_base": "580a6de7", "completion_evidence": "orchestrator-engine-cleanup.md", "reviewer": "/root", @@ -2888,7 +2888,8 @@ "integration": "Root 60 passed, 519 assertions; implementer expanded103 plus architecture17", "postgres": "12 passed, 92 assertions: stored preparation and strategy recovery on disposable database", "review": "Root independently accepted; normalization bodies and baseline frozen hashes unchanged" - } + }, + "implementation_commit": "984dc1a9" }, { "id": "CL18", @@ -2940,7 +2941,7 @@ "epic": "E11", "priority": "P2", "severity": "Medium", - "status": "in_progress", + "status": "done", "dependencies": [], "decision_dependencies": [], "task_file": "backlog/tasks/CL19.md", @@ -2967,9 +2968,15 @@ "completed_commit": null, "blocker": null, "release_gates": [], - "integration_state": "implementing", + "integration_state": "validated_pending_commit", "integration_base": "580a6de7", - "completion_evidence": "orchestrator-engine-cleanup.md" + "completion_evidence": "orchestrator-engine-cleanup.md", + "reviewer": "/root/review_cl19", + "validation": { + "integration": "Root 60 passed, 6959 assertions; application types passed", + "postgres": "Root 35 passed, 275 assertions: canonical paper, crash and strategy recovery", + "review": "Independent reviewer accepted; canonicalJson bytes verified against baseline" + } }, { "id": "CL20", diff --git a/docs/development/orchestrator-engine-cleanup.md b/docs/development/orchestrator-engine-cleanup.md index c1343c3d..b03bdadc 100644 --- a/docs/development/orchestrator-engine-cleanup.md +++ b/docs/development/orchestrator-engine-cleanup.md @@ -66,3 +66,12 @@ CL18 implementation commit: `03518c8a`. Historical storage now borrows only its logger, MongoDB and QuestDB readers. Removed uncalled market/performance writes, ad hoc DDL, PostgreSQL injection, mode state and empty shutdown; retained ModeManager/examples no longer give this reader a resource lifecycle. Provider routing, decoding, validation and synthetic calculations stay unchanged. Pinned baseline V1/V2 hashes and malformed-volume negatives protect retained data semantics. Implemented by `/root/implement_cl17`, independently reviewed/integrated by `/root`. Root scoped historical/dataset/mode suite: 60 passed, 519 assertions; application types passed. Expanded implementer suite: 103 passed, 895 assertions; architecture rerun: 17 passed. Root disposable stored-dataset preparation plus strategy recovery: 12 passed, 92 assertions. Authored-test types/lint and diff checks passed. Three obsolete parameterized storage-lifecycle cases were removed with the nonexistent stages; actual execution/feed/strategy rollback cases remain. Initial worktree browser bundling read errors cleared on architecture rerun. Nine pre-existing lint findings in other historical test bodies and the already-broken no-argument legacy example were not widened into this task. Logs: `/tmp/stock-bot-engine-cleanup-20261026/cl17-{root-tests,root-types,postgres}.log`. + + +CL17 implementation commit: `984dc1a9`. + +### CL19 — accepted + +Research and paper share pure diagnostic initialization and owner-feedback projection, keeping their separate confirmation/SQL commit boundaries. Feed planning and paper admission share the existing timestamp/phase/UTF-8/source comparator. `canonicalJson` moved unchanged to a neutral module with its legacy re-export; canonical consumers no longer depend on legacy recovery. + +Implemented by `/root/implement_cl19`, independently accepted by `/root/review_cl19`, integrated by `/root`. Root runtime/feed/recovery/architecture suite: 60 passed, 6,959 assertions; application types passed. Root disposable canonical-paper, crash and strategy-recovery suite: 35 passed, 275 assertions. Root also compared the entire canonicalJson function/comment against baseline bytes. Tests cover research/paper state/RNG/feedback parity and detached initial state, malformed-owner atomicity, native-accepted Unicode ordering and historical serialization. Explicit authored-test types/lint/format passed. Worktree Bun browser-bundle errors cleared on separate architecture rerun; root combined focused invocation passed. Logs: `/tmp/stock-bot-engine-cleanup-20261026/cl19-root-{tests,types,postgres}.log`. diff --git a/test/integration/paper-feed.test.ts b/test/integration/paper-feed.test.ts index c4f4f241..ba17a895 100644 --- a/test/integration/paper-feed.test.ts +++ b/test/integration/paper-feed.test.ts @@ -2,6 +2,7 @@ import { describe, expect, test } from 'bun:test'; import { stageFinancialTransaction } from '@stock-bot/engine'; import { parseFinancialDecimal } from '@stock-bot/types'; import { + compareEventKeys, parseFinancialTransactionResult, type CanonicalMatchingCommand, } from '../../apps/stock/orchestrator/src/contracts/canonical-execution'; @@ -145,7 +146,11 @@ describe('trusted canonical paper feed policy', () => { }); }, value => { - value.matching.series.push({ ...value.matching.series[0]!, seriesId: 'other' }); + value.matching.series.push({ + ...value.matching.series[0]!, + seriesId: 'other', + mode: 'Quote', + }); }, ]; for (const change of changes) { @@ -465,3 +470,36 @@ describe('paper frame deterministic native command planning', () => { ).toThrow(PaperRuntimeError); }); }); + +test('paper planning and admission use Rust-compatible phase, UTF-8 and sequence ordering', () => { + const instruments = ['𐀀', '\ue000', 'A']; + const f = fixture(paperFeedConfiguration(instruments)); + const frame = paperFeedFrame(1000, instruments); + const plan = f.plan(frame); + expect(plan.map(input => input.command.key)).toEqual( + plan.map(input => input.command.key).sort(compareEventKeys) + ); + expect( + plan + .filter(input => input.command.body.kind === 'openSession') + .map(input => input.command.key.instrumentId) + ).toEqual(['A', '\ue000', '𐀀']); + expect( + plan + .filter(input => input.command.body.kind === 'execute') + .map(input => input.command.key.instrumentId) + ).toEqual(['A', '\ue000', '𐀀']); + for (const input of plan) { + f.apply(input.command); + } + const keys: CanonicalMatchingCommand['key'][] = [ + { at: 10, phase: 'SessionClose', instrumentId: 'A', sourceSequence: 0 }, + { at: 10, phase: 'Execution', instrumentId: 'A', sourceSequence: 0 }, + { at: 10, phase: 'Decision', instrumentId: 'A', sourceSequence: 0 }, + { at: 10, phase: 'Observation', instrumentId: '𐀀', sourceSequence: 2 }, + { at: 10, phase: 'Observation', instrumentId: '𐀀', sourceSequence: 1 }, + { at: 10, phase: 'Observation', instrumentId: '\ue000', sourceSequence: 9 }, + { at: 9, phase: 'SessionClose', instrumentId: '𐀀', sourceSequence: 9 }, + ]; + expect([...keys].sort(compareEventKeys)).toEqual([...keys].reverse()); +}); diff --git a/test/integration/strategy-recovery.test.ts b/test/integration/strategy-recovery.test.ts index 99daefca..987db1e5 100644 --- a/test/integration/strategy-recovery.test.ts +++ b/test/integration/strategy-recovery.test.ts @@ -1,4 +1,5 @@ import { afterEach, describe, expect, test } from 'bun:test'; +import { canonicalJson as neutralCanonicalJson } from '../../apps/stock/orchestrator/src/canonical-json'; import { BacktestExecutionRepository } from '../../apps/stock/orchestrator/src/execution/BacktestExecutionRepository'; import { canonicalJson } from '../../apps/stock/orchestrator/src/execution/strategy-recovery'; import { config, makeExecution, order, quote, start } from '../fixtures/execution'; @@ -167,6 +168,16 @@ describe('transactional strategy recovery', () => { } expect(canonicalJson({ b: 1, a: [2] })).toBe(canonicalJson({ a: [2], b: 1 })); }); + test('canonical serialization retains historical bytes and the compatibility export', () => { + expect(canonicalJson).toBe(neutralCanonicalJson); + const value = JSON.parse( + '{"z":-0,"𐀀":3,"a":[{"z":2,"a":1},null,true],"\\ue000":4,"__proto__":{"b":2,"a":1},"10":10,"2":2}' + ); + const expected = + '{"2":2,"10":10,"__proto__":{"a":1,"b":2},"a":[{"a":1,"z":2},null,true],"z":0,"𐀀":3,"\ue000":4}'; + expect(canonicalJson(value)).toBe(expected); + expect(neutralCanonicalJson(value)).toBe(expected); + }); test('a callback cannot open a nested repository transaction and deadlock its account', async () => { const f = await fixture(); f.strategy.onDecision = async () => { diff --git a/test/integration/strategy-runtime.test.ts b/test/integration/strategy-runtime.test.ts index c4420944..84df6d83 100644 --- a/test/integration/strategy-runtime.test.ts +++ b/test/integration/strategy-runtime.test.ts @@ -272,51 +272,60 @@ test('post-native-submit failure never publishes unconfirmed strategy state or r expect(retry.diagnostics).toEqual(baseline.diagnostics); }); -test('malformed second-owner feedback after real native admission cannot partially commit diagnostic state', () => { - const f = fixture(['A', 'B']); - const programs = ['A', 'B'].map(id => - program(id, context => ({ - nextState: { - count: context.state.count + 1, - samples: [...context.state.samples, context.random()], - }, - intent: target(String(context.state.count + 1)), - })) - ); - const originalSubmit = NativeReplaySession.prototype.submit; - let submissions = 0; - let failedSession: NativeReplaySession | undefined; - NativeReplaySession.prototype.submit = function (...args) { - const output = originalSubmit.apply(this, args); - failedSession = this; - if (++submissions !== 2) { - return output; +test.each(['status', 'owner'] as const)( + 'malformed second-owner %s feedback cannot partially commit diagnostic state', + field => { + const f = fixture(['A', 'B']); + const programs = ['A', 'B'].map(id => + program(id, context => ({ + nextState: { + count: context.state.count + 1, + samples: [...context.state.samples, context.random()], + }, + intent: target(String(context.state.count + 1)), + })) + ); + const originalSubmit = NativeReplaySession.prototype.submit; + let submissions = 0; + let failedSession: NativeReplaySession | undefined; + NativeReplaySession.prototype.submit = function (...args) { + const output = originalSubmit.apply(this, args); + failedSession = this; + if (++submissions !== 2) { + return output; + } + const malformed = structuredClone(output); + const secondOwner = malformed.effects.find(effect => { + const order = effect.Order as { order: { decision: { ownerId: string } } } | undefined; + return order?.order.decision.ownerId === 'B'; + }); + expect(secondOwner).toBeDefined(); + if (field === 'status') { + (secondOwner!.Order as { status: unknown }).status = 'InventedStatus'; + } else { + ( + secondOwner!.Order as { order: { decision: { ownerId: string } } } + ).order.decision.ownerId = 'outside-the-barrier'; + } + return malformed; + }; + let failure: StrategyReplayError; + try { + failure = captureFailure(() => runStrategyReplay(f.load, programs)); + } finally { + NativeReplaySession.prototype.submit = originalSubmit; } - const malformed = structuredClone(output); - const secondOwner = malformed.effects.find(effect => { - const order = effect.Order as { order: { decision: { ownerId: string } } } | undefined; - return order?.order.decision.ownerId === 'B'; - }); - expect(secondOwner).toBeDefined(); - (secondOwner!.Order as { status: unknown }).status = 'InventedStatus'; - return malformed; - }; - let failure: StrategyReplayError; - try { - failure = captureFailure(() => runStrategyReplay(f.load, programs)); - } finally { - NativeReplaySession.prototype.submit = originalSubmit; + expect(submissions).toBe(2); + expect(failure.diagnostics.committedBarriers).toBe(1); + for (const saved of failure.diagnostics.strategies) { + expect(saved.nextDecisionSequence).toBe(1); + expect(saved.rng.draws).toBe(1); + expect((saved.state as CountState).count).toBe(1); + expect(saved.previousAdmission?.decision.sequence).toBe(0); + } + expect(() => failedSession!.project()).toThrow('disposed'); } - expect(submissions).toBe(2); - expect(failure.diagnostics.committedBarriers).toBe(1); - for (const saved of failure.diagnostics.strategies) { - expect(saved.nextDecisionSequence).toBe(1); - expect(saved.rng.draws).toBe(1); - expect((saved.state as CountState).count).toBe(1); - expect(saved.previousAdmission?.decision.sequence).toBe(0); - } - expect(() => failedSession!.project()).toThrow('disposed'); -}); +); test('risk rejection commits state and cursors and returns the actual rejection at the next decision', () => { const f = fixture(); diff --git a/test/postgres/canonical-paper.test.ts b/test/postgres/canonical-paper.test.ts index 95fa0cd1..8fa8a88b 100644 --- a/test/postgres/canonical-paper.test.ts +++ b/test/postgres/canonical-paper.test.ts @@ -11,16 +11,18 @@ import { type CanonicalMatchingConfig, } from '../../apps/stock/orchestrator/src/contracts/canonical-execution'; import type { StrategyProgram } from '../../apps/stock/orchestrator/src/contracts/canonical-strategy'; -import type { - CanonicalExecutionRepository, - CanonicalJournalEntry, - CanonicalPaperInput, - CanonicalTransaction, +import { + canonicalPaperInputSchema, + type CanonicalExecutionRepository, + type CanonicalJournalEntry, + type CanonicalPaperInput, + type CanonicalTransaction, } from '../../apps/stock/orchestrator/src/execution/canonical-paper'; import { CanonicalPaperExecution } from '../../apps/stock/orchestrator/src/execution/CanonicalPaperExecution'; import { PostgresCanonicalExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository'; import { PostgresExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository'; import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins'; +import { StrategyController } from '../../apps/stock/orchestrator/src/strategies/strategy-controller'; import { canonicalConfig, counterProgram, @@ -175,6 +177,62 @@ function ordersConfig(): CanonicalMatchingConfig { } describe.skipIf(!url)('canonical paper custody on real PostgreSQL', () => { + test('research and durable paper retain identical owned state, RNG and admission feedback', async () => { + const config = canonicalConfig(['A', 'B']); + const programs = [counterProgram('B'), counterProgram('A')]; + const f = await fixture(config, programs); + const controller = new StrategyController( + { version: 1, sessionId: config.risk.ledger.sessionId, datasetHash: '0'.repeat(64) }, + programs, + { matching: config } + ); + const diagnostics = async () => (await f.host.snapshot()).owners.map(owner => owner.diagnostic); + const initial = controller.snapshot().strategies; + expect(initial).toEqual(await diagnostics()); + programs[0]!.initialState.samples.push(999); + expect(initial).toEqual(await diagnostics()); + expect(controller.snapshot().strategies).toEqual(initial); + let cursor = 0; + for (const input of [ + openInput(), + markInput(1, ['A', 'B']), + quoteInput(1, '1'), + markInput(2, ['A', 'B']), + ]) { + await send(f.host, input); + const entries = await f.host.journal(cursor); + cursor = entries.at(-1)?.sequence ?? cursor; + const context = entries.find(entry => entry.payload.kind === 'decision')?.payload; + const admitted = entries.find( + entry => entry.payload.kind === 'command' && entry.payload.command.body.kind === 'submit' + )?.payload; + if (context?.kind === 'decision') { + if ( + admitted?.kind !== 'command' || + admitted.command.body.kind !== 'submit' || + !admitted.outcome + ) { + throw new Error('Missing native decision admission in paper journal'); + } + expect( + controller + .stage(context.context, canonicalPaperInputSchema.parse(input).observations) + .sort((a, b) => + Buffer.compare(Buffer.from(a.decision.ownerId), Buffer.from(b.decision.ownerId)) + ) + ).toEqual(admitted.command.body.decisions); + controller.committed(admitted.outcome); + } + expect(controller.snapshot().strategies).toEqual(await diagnostics()); + } + for (const owner of controller.snapshot().strategies) { + expect(owner.rng.draws).toBe(2); + expect( + owner.previousAdmission?.orders.every(order => order.decision.ownerId === owner.ownerId) + ).toBe(true); + } + }); + test('real strategy state/RNG and economic postings match uninterrupted replacement and the direct Rust command tape', async () => { const f = await fixture(); await send(f.host, openInput());