refactor(orchestrator): share pure strategy bookkeeping (CL19)
This commit is contained in:
parent
984dc1a9cc
commit
6055aeeee9
17 changed files with 297 additions and 157 deletions
23
apps/stock/orchestrator/src/canonical-json.ts
Normal file
23
apps/stock/orchestrator/src/canonical-json.ts
Normal file
|
|
@ -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));
|
||||
}
|
||||
|
|
@ -94,6 +94,20 @@ export const matchingCommandSchema = z
|
|||
.strict();
|
||||
export type CanonicalMatchingCommand = z.input<typeof matchingCommandSchema>;
|
||||
|
||||
/** 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
|
||||
|
|
|
|||
|
|
@ -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<boolean>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@ import {
|
|||
canonicalExecutionCheckpointSchema,
|
||||
financialTransactionResultSchema,
|
||||
matchingCommandSchema,
|
||||
type CanonicalMatchingCommand,
|
||||
} from '../contracts/canonical-execution';
|
||||
import {
|
||||
nativeFinancialViewSchema,
|
||||
|
|
@ -196,18 +195,7 @@ export interface CanonicalExecutionRepository {
|
|||
transact<T>(accountId: string, work: (tx: CanonicalTransaction) => Promise<T>): Promise<T>;
|
||||
}
|
||||
export type CanonicalPostgres = Pick<PostgresClient, 'transaction'>;
|
||||
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) {
|
||||
|
|
|
|||
|
|
@ -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');
|
||||
|
|
|
|||
|
|
@ -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) =>
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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 }),
|
||||
|
|
|
|||
|
|
@ -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<T>(value: T): DeepReadonly<T> {
|
||||
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
|
||||
|
|
@ -83,6 +88,43 @@ export const metadataSchema = z
|
|||
.strict();
|
||||
export type Metadata = z.infer<typeof metadataSchema>;
|
||||
|
||||
/** 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<typeof nativeAdmissionOrders>
|
||||
): 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) {
|
||||
|
|
|
|||
|
|
@ -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 |
|
||||
| --- | --- | --- |
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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`.
|
||||
|
|
|
|||
|
|
@ -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());
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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 () => {
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -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());
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue