feat(paper): gate canonical execution on durable feed readiness
This commit is contained in:
parent
c01e96e4dd
commit
75abae2cfc
24 changed files with 3720 additions and 66 deletions
88
test/fixtures/paper-feed.ts
vendored
Normal file
88
test/fixtures/paper-feed.ts
vendored
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import type {
|
||||
PaperConfigurationInput,
|
||||
PaperFrameInput,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/paper-runtime';
|
||||
import { canonicalConfig } from './canonical-paper';
|
||||
|
||||
export function paperFeedConfiguration(instruments = ['X']): PaperConfigurationInput {
|
||||
const owners = instruments.map(instrument => `owner-${instrument}`);
|
||||
const matching = canonicalConfig(owners);
|
||||
matching.series = instruments.map(instrumentId => ({
|
||||
instrumentId,
|
||||
seriesId: `${instrumentId}:quote`,
|
||||
mode: 'Quote',
|
||||
}));
|
||||
return {
|
||||
version: 1,
|
||||
matching,
|
||||
strategies: instruments.map(instrumentId => ({
|
||||
ownerId: `owner-${instrumentId}`,
|
||||
strategyId: 'sma',
|
||||
strategyVersion: 'sma-crossover-long-only/v1',
|
||||
seed: 7,
|
||||
instrumentId,
|
||||
seriesId: `${instrumentId}:bar`,
|
||||
ownerBudget: '100',
|
||||
parameters: { fastPeriod: 1, slowPeriod: 2 },
|
||||
})),
|
||||
policy: {
|
||||
version: 1,
|
||||
sourceId: 'trusted-fixture',
|
||||
priceBasis: 'raw',
|
||||
maxFeedAgeMs: 100,
|
||||
observations: instruments.map(instrumentId => ({
|
||||
instrumentId,
|
||||
seriesId: `${instrumentId}:bar`,
|
||||
intervalMs: 1000,
|
||||
staleAfterMs: 1000,
|
||||
})),
|
||||
cadence: instruments.map(instrumentId => ({
|
||||
ownerId: `owner-${instrumentId}`,
|
||||
seriesIds: [`${instrumentId}:bar`],
|
||||
})),
|
||||
calendars: instruments.map(instrumentId => ({
|
||||
instrumentId,
|
||||
calendarId: 'venue',
|
||||
revision: '2026-10',
|
||||
sessions: [{ sessionId: 'venue-1', opensAt: 0, closesAt: 10000 }],
|
||||
})),
|
||||
riskBoundaries: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function paperFeedFrame(at = 1000, instruments = ['X']): PaperFrameInput {
|
||||
return {
|
||||
version: 1,
|
||||
sourceId: 'trusted-fixture',
|
||||
connectionId: 'connection-1',
|
||||
id: `frame-${at}`,
|
||||
sequence: at,
|
||||
availableAt: at,
|
||||
quotes: instruments.map(instrumentId => ({
|
||||
instrumentId,
|
||||
seriesId: `${instrumentId}:quote`,
|
||||
observedAt: at,
|
||||
sourceSequence: at,
|
||||
bid: '10',
|
||||
ask: '10',
|
||||
bidSize: '100',
|
||||
askSize: '100',
|
||||
})),
|
||||
observations: instruments.map(instrument_id => ({
|
||||
instrument_id,
|
||||
series_id: `${instrument_id}:bar`,
|
||||
interval_start: at - 1000,
|
||||
interval_end: at,
|
||||
event_time: at,
|
||||
available_at: at,
|
||||
source_sequence: at,
|
||||
open: parseFinancialDecimal('10'),
|
||||
high: parseFinancialDecimal('10'),
|
||||
low: parseFinancialDecimal('10'),
|
||||
close: parseFinancialDecimal('10'),
|
||||
volume: parseFinancialDecimal('100'),
|
||||
})),
|
||||
};
|
||||
}
|
||||
183
test/fixtures/paper-runtime.ts
vendored
Normal file
183
test/fixtures/paper-runtime.ts
vendored
Normal file
|
|
@ -0,0 +1,183 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { Pool } from 'pg';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import type { StrategyProgram } from '../../apps/stock/orchestrator/src/contracts/canonical-strategy';
|
||||
import type {
|
||||
PaperConfigurationInput,
|
||||
PaperFrameInput,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/paper-runtime';
|
||||
import type {
|
||||
CanonicalExecutionRepository,
|
||||
CanonicalTransaction,
|
||||
} from '../../apps/stock/orchestrator/src/execution/canonical-paper';
|
||||
import { PostgresCanonicalExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository';
|
||||
import { CanonicalPaperRuntime } from '../../apps/stock/orchestrator/src/paper/CanonicalPaperRuntime';
|
||||
import { canonicalConfig, counterProgram } from './canonical-paper';
|
||||
import { logger } from './execution';
|
||||
|
||||
export function paperConfig(): PaperConfigurationInput {
|
||||
const matching = canonicalConfig();
|
||||
matching.risk.maxMarkAgeMs = 100;
|
||||
return {
|
||||
version: 1,
|
||||
matching,
|
||||
strategies: [
|
||||
{
|
||||
ownerId: 'A',
|
||||
strategyId: 'sma_crossover',
|
||||
strategyVersion: 'sma-crossover-long-only/v1',
|
||||
seed: 7,
|
||||
instrumentId: 'X',
|
||||
seriesId: 'X:bar',
|
||||
ownerBudget: '500',
|
||||
parameters: { fastPeriod: 1, slowPeriod: 2 },
|
||||
},
|
||||
],
|
||||
policy: {
|
||||
version: 1,
|
||||
sourceId: 'fixture',
|
||||
priceBasis: 'raw',
|
||||
maxFeedAgeMs: 100,
|
||||
observations: [{ seriesId: 'X:bar', instrumentId: 'X', intervalMs: 10, staleAfterMs: 100 }],
|
||||
cadence: [{ ownerId: 'A', seriesIds: ['X:bar'] }],
|
||||
calendars: [
|
||||
{
|
||||
instrumentId: 'X',
|
||||
calendarId: 'venue',
|
||||
revision: '1',
|
||||
sessions: [{ sessionId: 'venue-1', opensAt: 0, closesAt: 10000 }],
|
||||
},
|
||||
],
|
||||
riskBoundaries: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function paperFrame(
|
||||
sequence: number,
|
||||
at = sequence * 10,
|
||||
connectionId = 'one'
|
||||
): PaperFrameInput {
|
||||
const price = parseFinancialDecimal('10');
|
||||
return {
|
||||
version: 1,
|
||||
sourceId: 'fixture',
|
||||
connectionId,
|
||||
id: `frame-${sequence}`,
|
||||
sequence,
|
||||
availableAt: at,
|
||||
quotes: [
|
||||
{
|
||||
instrumentId: 'X',
|
||||
seriesId: 'X:quote',
|
||||
observedAt: at,
|
||||
sourceSequence: sequence,
|
||||
bid: price,
|
||||
ask: price,
|
||||
bidSize: price,
|
||||
askSize: price,
|
||||
},
|
||||
],
|
||||
observations: [
|
||||
{
|
||||
series_id: 'X:bar',
|
||||
instrument_id: 'X',
|
||||
interval_start: at - 10,
|
||||
interval_end: at,
|
||||
event_time: at,
|
||||
available_at: at,
|
||||
source_sequence: sequence,
|
||||
open: price,
|
||||
high: price,
|
||||
low: price,
|
||||
close: price,
|
||||
volume: price,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
export async function paperFixture(
|
||||
configuration = paperConfig(),
|
||||
program: StrategyProgram = counterProgram()
|
||||
) {
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Dedicated stock_bot_safety database required');
|
||||
}
|
||||
const schema = 'stock_bot_safety_' + randomUUID().replaceAll('-', '');
|
||||
const admin = new Pool({ connectionString: url });
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
const pool = new Pool({
|
||||
connectionString: url,
|
||||
options: `-c search_path=${schema} -c statement_timeout=10000`,
|
||||
});
|
||||
for (const filename of [
|
||||
'11-simulation-execution-ledger.sql',
|
||||
'13-strategy-recovery.sql',
|
||||
'15-canonical-paper-intents.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
);
|
||||
}
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
const repository = new PostgresCanonicalExecutionRepository(postgres);
|
||||
let wrap = (tx: CanonicalTransaction): CanonicalTransaction => tx;
|
||||
let afterCommit = () => {};
|
||||
const wrapped: CanonicalExecutionRepository = {
|
||||
initialize: (account, owners) => repository.initialize(account, owners),
|
||||
async transact(id, work) {
|
||||
const result = await repository.transact(id, tx => work(wrap(tx)));
|
||||
afterCommit();
|
||||
return result;
|
||||
},
|
||||
};
|
||||
let now = 10;
|
||||
const make = async (config = configuration) => {
|
||||
const runtime = new CanonicalPaperRuntime({
|
||||
repository: wrapped,
|
||||
programs: [
|
||||
{ ...program, strategyId: 'sma_crossover', strategyVersion: 'sma-crossover-long-only/v1' },
|
||||
],
|
||||
now: () => now,
|
||||
});
|
||||
await runtime.initialize(config);
|
||||
return runtime;
|
||||
};
|
||||
const accountId = configuration.matching.risk.ledger.accountId;
|
||||
return {
|
||||
pool,
|
||||
postgres,
|
||||
repository,
|
||||
make,
|
||||
runtime: await make(),
|
||||
configuration,
|
||||
clock(value: number) {
|
||||
now = value;
|
||||
},
|
||||
wrap(value: typeof wrap) {
|
||||
wrap = value;
|
||||
},
|
||||
afterCommit(value: typeof afterCommit) {
|
||||
afterCommit = value;
|
||||
},
|
||||
snapshot: () =>
|
||||
repository.transact(accountId, async tx => ({
|
||||
account: structuredClone(tx.account),
|
||||
owners: await tx.owners(),
|
||||
journal: await tx.journal(0),
|
||||
})),
|
||||
async close() {
|
||||
await pool.end();
|
||||
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
||||
await admin.end();
|
||||
},
|
||||
};
|
||||
}
|
||||
45
test/integration/paper-composition.test.ts
Normal file
45
test/integration/paper-composition.test.ts
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
import { asFunction, createContainer as createDiContainer } from 'awilix';
|
||||
import { expect, test } from 'bun:test';
|
||||
import type { ServiceCradle } from '@stock-bot/di';
|
||||
import type { StockAppConfig } from '@stock-bot/stock-config';
|
||||
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
|
||||
import { createContainer } from '../../apps/stock/orchestrator/src/simple-container';
|
||||
import { paperFeedConfiguration } from '../fixtures/paper-feed';
|
||||
|
||||
test('canonical paper rejects invalid role/configuration before resolving services', async () => {
|
||||
let resolved = 0;
|
||||
const container = createDiContainer<ServiceCradle>();
|
||||
container.register({
|
||||
serviceContainer: asFunction(() => {
|
||||
resolved++;
|
||||
throw new Error('Unexpected service resolution');
|
||||
}),
|
||||
});
|
||||
const config = paperFeedConfiguration();
|
||||
await expect(
|
||||
registerOrchestratorServices(container, {
|
||||
role: 'research-only',
|
||||
canonicalPaper: config,
|
||||
})
|
||||
).rejects.toThrow('requires a paper composition');
|
||||
config.matching.series[0]!.mode = 'Open';
|
||||
await expect(
|
||||
registerOrchestratorServices(container, {
|
||||
canonicalPaper: config,
|
||||
})
|
||||
).rejects.toThrow('Quote execution only');
|
||||
expect(resolved).toBe(0);
|
||||
});
|
||||
|
||||
test('live defaults, research canonical configuration and missing custody fail before connections', async () => {
|
||||
const config = (orchestrator: unknown) => ({ services: { orchestrator } }) as StockAppConfig;
|
||||
await expect(createContainer(config({ defaultMode: 'live' }))).rejects.toThrow(
|
||||
'Live trading is disabled'
|
||||
);
|
||||
await expect(
|
||||
createContainer(config({ defaultMode: 'backtest', canonicalPaper: paperFeedConfiguration() }))
|
||||
).rejects.toThrow('requires a paper composition');
|
||||
await expect(
|
||||
createContainer(config({ canonicalPaper: paperFeedConfiguration() }))
|
||||
).rejects.toThrow('requires durable PostgreSQL');
|
||||
});
|
||||
467
test/integration/paper-feed.test.ts
Normal file
467
test/integration/paper-feed.test.ts
Normal file
|
|
@ -0,0 +1,467 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { stageFinancialTransaction } from '@stock-bot/engine';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import {
|
||||
parseFinancialTransactionResult,
|
||||
type CanonicalMatchingCommand,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/canonical-execution';
|
||||
import {
|
||||
PaperRuntimeError,
|
||||
type PaperConfigurationInput,
|
||||
type PaperFrameInput,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/paper-runtime';
|
||||
import type { CanonicalAccount } from '../../apps/stock/orchestrator/src/execution/canonical-paper';
|
||||
import {
|
||||
planPaperFrame,
|
||||
validatePaperConfiguration,
|
||||
validatePaperFrame,
|
||||
} from '../../apps/stock/orchestrator/src/paper/feed';
|
||||
import { paperFeedConfiguration, paperFeedFrame } from '../fixtures/paper-feed';
|
||||
|
||||
function fixture(input = paperFeedConfiguration()) {
|
||||
const config = validatePaperConfiguration(input);
|
||||
const identity = {
|
||||
accountId: config.matching.risk.ledger.accountId,
|
||||
sessionId: config.matching.risk.ledger.sessionId,
|
||||
};
|
||||
let native = parseFinancialTransactionResult(
|
||||
stageFinancialTransaction(
|
||||
JSON.stringify({ version: 1, kind: 'initialize', identity, config: config.matching })
|
||||
),
|
||||
identity
|
||||
);
|
||||
const account = (): Pick<CanonicalAccount, 'checkpoint' | 'observed' | 'latestObservations'> => ({
|
||||
checkpoint: native.checkpoint,
|
||||
observed: 0,
|
||||
latestObservations: [],
|
||||
});
|
||||
return {
|
||||
config,
|
||||
identity,
|
||||
account,
|
||||
current: () => native,
|
||||
plan: (frame = paperFeedFrame()) =>
|
||||
planPaperFrame(config, validatePaperFrame(config, frame, frame.availableAt), account()),
|
||||
apply(command: CanonicalMatchingCommand) {
|
||||
native = parseFinancialTransactionResult(
|
||||
stageFinancialTransaction(
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
kind: 'apply',
|
||||
identity,
|
||||
checkpoint: native.checkpoint,
|
||||
command,
|
||||
})
|
||||
),
|
||||
identity
|
||||
);
|
||||
expect(native.checkpoint.status).toBe('Running');
|
||||
return native;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function invalidFrame(
|
||||
change: (frame: PaperFrameInput) => void,
|
||||
config = validatePaperConfiguration(paperFeedConfiguration())
|
||||
) {
|
||||
const frame = paperFeedFrame();
|
||||
change(frame);
|
||||
expect(() => validatePaperFrame(config, frame, 1000)).toThrow();
|
||||
}
|
||||
|
||||
describe('trusted canonical paper feed policy', () => {
|
||||
test('malformed decimal wire values remain input failures rather than server errors', () => {
|
||||
const raw = paperFeedConfiguration();
|
||||
raw.matching.risk.ledger.initialCapital = 'bad';
|
||||
try {
|
||||
validatePaperConfiguration(raw);
|
||||
throw new Error('Malformed configuration was accepted');
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(PaperRuntimeError);
|
||||
expect((error as PaperRuntimeError).kind).toBe('invalid-input');
|
||||
}
|
||||
const config = validatePaperConfiguration(paperFeedConfiguration());
|
||||
const frame = paperFeedFrame();
|
||||
frame.quotes[0]!.bid = 'bad';
|
||||
try {
|
||||
validatePaperFrame(config, frame, 1000);
|
||||
throw new Error('Malformed frame was accepted');
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(PaperRuntimeError);
|
||||
expect((error as PaperRuntimeError).kind).toBe('invalid-input');
|
||||
}
|
||||
});
|
||||
|
||||
test('binds immutable built-in cohorts, observations and calendars without mutating caller input', () => {
|
||||
const raw = paperFeedConfiguration(['Y', 'X']);
|
||||
const before = JSON.stringify(raw);
|
||||
const config = validatePaperConfiguration(raw);
|
||||
expect(JSON.stringify(raw)).toBe(before);
|
||||
expect(config.matching.series.map(series => series.instrumentId)).toEqual(['X', 'Y']);
|
||||
expect(config.strategies.map(strategy => strategy.strategyId)).toEqual([
|
||||
'sma_crossover',
|
||||
'sma_crossover',
|
||||
]);
|
||||
expect(config.matching.risk.ledger.ownerIds).toEqual(['owner-X', 'owner-Y']);
|
||||
const changes: ((raw: PaperConfigurationInput) => void)[] = [
|
||||
value => {
|
||||
value.matching.series[0]!.mode = 'Open';
|
||||
},
|
||||
value => {
|
||||
value.matching.owners[0]!.mode = 'Orders';
|
||||
},
|
||||
value => {
|
||||
value.policy.cadence[0]!.ownerId = 'unknown';
|
||||
},
|
||||
value => {
|
||||
value.policy.cadence[0]!.seriesIds = ['unknown'];
|
||||
},
|
||||
value => {
|
||||
value.strategies[0]!.instrumentId = 'unknown';
|
||||
},
|
||||
value => {
|
||||
value.policy.observations[0]!.instrumentId = 'unknown';
|
||||
},
|
||||
value => {
|
||||
value.matching.risk.ledger.ownerIds = [];
|
||||
},
|
||||
value => {
|
||||
value.policy.calendars[0]!.instrumentId = 'unknown';
|
||||
},
|
||||
value => {
|
||||
value.policy.calendars[0]!.sessions.push({
|
||||
sessionId: 'overlap',
|
||||
opensAt: 9000,
|
||||
closesAt: 12000,
|
||||
});
|
||||
},
|
||||
value => {
|
||||
value.policy.riskBoundaries.push({
|
||||
...value.matching.risk.ledger.riskSession,
|
||||
sessionId: 'risk-2',
|
||||
calendarRevision: 'other',
|
||||
startsAt: 2000,
|
||||
});
|
||||
},
|
||||
value => {
|
||||
value.matching.series.push({ ...value.matching.series[0]!, seriesId: 'other' });
|
||||
},
|
||||
];
|
||||
for (const change of changes) {
|
||||
const candidate = paperFeedConfiguration();
|
||||
change(candidate);
|
||||
expect(() => validatePaperConfiguration(candidate)).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
test('rejects unknown, future, unaligned, crossed, impossible and observation-only frames', () => {
|
||||
for (const change of [
|
||||
(value: PaperFrameInput) => {
|
||||
value.sourceId = 'other';
|
||||
},
|
||||
(value: PaperFrameInput) => {
|
||||
value.availableAt = 1001;
|
||||
},
|
||||
(value: PaperFrameInput) => {
|
||||
value.quotes = [];
|
||||
},
|
||||
(value: PaperFrameInput) => {
|
||||
value.quotes[0]!.instrumentId = 'unknown';
|
||||
},
|
||||
(value: PaperFrameInput) => {
|
||||
value.quotes[0]!.seriesId = 'X:bar';
|
||||
},
|
||||
(value: PaperFrameInput) => {
|
||||
value.quotes[0]!.observedAt = 1001;
|
||||
},
|
||||
(value: PaperFrameInput) => {
|
||||
value.quotes[0]!.bid = '11';
|
||||
},
|
||||
(value: PaperFrameInput) => {
|
||||
value.quotes[0]!.ask = '0';
|
||||
},
|
||||
(value: PaperFrameInput) => {
|
||||
value.quotes[0]!.bidSize = '-1';
|
||||
},
|
||||
(value: PaperFrameInput) => {
|
||||
value.observations[0]!.series_id = 'unknown';
|
||||
},
|
||||
(value: PaperFrameInput) => {
|
||||
value.observations[0]!.event_time = 999;
|
||||
},
|
||||
(value: PaperFrameInput) => {
|
||||
value.observations[0]!.interval_start = 1;
|
||||
},
|
||||
(value: PaperFrameInput) => {
|
||||
value.observations[0]!.interval_end = 999;
|
||||
},
|
||||
(value: PaperFrameInput) => {
|
||||
value.observations[0]!.available_at = 999;
|
||||
},
|
||||
(value: PaperFrameInput) => {
|
||||
value.observations[0]!.available_at = 1001;
|
||||
},
|
||||
(value: PaperFrameInput) => {
|
||||
value.observations[0]!.high = parseFinancialDecimal('9');
|
||||
},
|
||||
(value: PaperFrameInput) => {
|
||||
value.observations[0]!.volume = parseFinancialDecimal('-1');
|
||||
},
|
||||
]) {
|
||||
invalidFrame(change);
|
||||
}
|
||||
const config = validatePaperConfiguration(paperFeedConfiguration());
|
||||
const exhausted = paperFeedFrame(10000);
|
||||
expect(() => validatePaperFrame(config, exhausted, 10000)).toThrow('session coverage');
|
||||
const beforeOpen = paperFeedFrame(-1);
|
||||
beforeOpen.sequence = 0;
|
||||
beforeOpen.quotes[0]!.sourceSequence = 0;
|
||||
beforeOpen.observations = [];
|
||||
expect(() => validatePaperFrame(config, beforeOpen, 1000)).toThrow('session coverage');
|
||||
});
|
||||
|
||||
test('retains real timestamps and deduplicates only identical physical observations', () => {
|
||||
const config = validatePaperConfiguration(paperFeedConfiguration());
|
||||
const raw = paperFeedFrame();
|
||||
raw.quotes[0]!.observedAt = 990;
|
||||
raw.observations.push(structuredClone(raw.observations[0]!));
|
||||
const before = JSON.stringify(raw);
|
||||
const frame = validatePaperFrame(config, raw, 1000);
|
||||
expect(JSON.stringify(raw)).toBe(before);
|
||||
expect(frame.quotes[0]!.observedAt).toBe(990);
|
||||
expect(frame.observations).toHaveLength(1);
|
||||
raw.observations[1]!.close = parseFinancialDecimal('9');
|
||||
raw.observations[1]!.low = parseFinancialDecimal('9');
|
||||
expect(() => validatePaperFrame(config, raw, 1000)).toThrow('Conflicting physical');
|
||||
raw.observations = [];
|
||||
raw.quotes.push({ ...raw.quotes[0]! });
|
||||
expect(() => validatePaperFrame(config, raw, 1000)).toThrow('physical quote');
|
||||
raw.quotes[1]!.observedAt = 991;
|
||||
expect(() => validatePaperFrame(config, raw, 1000)).toThrow('quote event key');
|
||||
});
|
||||
});
|
||||
|
||||
describe('paper frame deterministic native command planning', () => {
|
||||
test('one multi-asset decision follows every quote and cannot fill until the next physical quotes', () => {
|
||||
const f = fixture(paperFeedConfiguration(['Y', 'X']));
|
||||
const frame = paperFeedFrame(1000, ['Y', 'X']);
|
||||
const plan = f.plan(frame);
|
||||
expect(plan.map(input => input.command.body.kind)).toEqual([
|
||||
'openSession',
|
||||
'openSession',
|
||||
'execute',
|
||||
'execute',
|
||||
]);
|
||||
expect(plan.filter(input => input.decision)).toHaveLength(1);
|
||||
expect(plan.slice(0, -1).every(input => !input.observations.length)).toBe(true);
|
||||
const barrier = plan.at(-1)!.decision!;
|
||||
expect(barrier.ownerIds).toEqual(['owner-X', 'owner-Y']);
|
||||
expect(barrier.key).toEqual(plan.at(-1)!.command.key);
|
||||
expect(barrier.key).toEqual({
|
||||
at: 1000,
|
||||
phase: 'Execution',
|
||||
instrumentId: 'Y',
|
||||
sourceSequence: 1000,
|
||||
});
|
||||
for (const input of plan) {
|
||||
f.apply(input.command);
|
||||
}
|
||||
expect(f.current().view.portfolio.positions).toHaveLength(0);
|
||||
f.apply({
|
||||
commandId: barrier.commandId,
|
||||
key: barrier.key,
|
||||
body: {
|
||||
kind: 'submit',
|
||||
decisions: ['X', 'Y'].map(instrumentId => ({
|
||||
version: 1,
|
||||
sessionId: f.identity.sessionId,
|
||||
barrierId: barrier.barrierId,
|
||||
revision: f.current().checkpoint.revision,
|
||||
decision: {
|
||||
ownerId: `owner-${instrumentId}`,
|
||||
decisionId: `decision-${instrumentId}`,
|
||||
sequence: 0,
|
||||
},
|
||||
intent: {
|
||||
mode: 'target',
|
||||
targets: [{ instrumentId, quantity: parseFinancialDecimal('2') }],
|
||||
},
|
||||
})),
|
||||
},
|
||||
});
|
||||
expect(f.current().view.portfolio.positions).toHaveLength(0);
|
||||
expect(f.current().checkpoint.orders).toHaveLength(2);
|
||||
const next = paperFeedFrame(1001, ['Y', 'X']);
|
||||
next.observations = [];
|
||||
const nextPlan = f.plan(next);
|
||||
expect(nextPlan.every(input => !input.decision)).toBe(true);
|
||||
for (const input of nextPlan) {
|
||||
f.apply(input.command);
|
||||
}
|
||||
expect(f.current().view.portfolio.positions.map(position => position.quantity)).toEqual([
|
||||
parseFinancialDecimal('2'),
|
||||
parseFinancialDecimal('2'),
|
||||
]);
|
||||
expect<string>(f.current().view.portfolio.cash).toBe('959.60000000');
|
||||
expect(f.current().view.portfolio.fees).toEqual([
|
||||
{ ownerId: 'owner-X', amount: parseFinancialDecimal('0.2') },
|
||||
{ ownerId: 'owner-Y', amount: parseFinancialDecimal('0.2') },
|
||||
]);
|
||||
});
|
||||
|
||||
test('quote identities survive frame/connection renaming and reject retimed reuse or backwards physical time', () => {
|
||||
const f = fixture();
|
||||
const first = f.plan();
|
||||
const renamed = paperFeedFrame();
|
||||
renamed.id = 'renamed';
|
||||
renamed.connectionId = 'reconnected';
|
||||
renamed.sequence = 9;
|
||||
expect(f.plan(renamed).at(-1)!.command.commandId).toBe(first.at(-1)!.command.commandId);
|
||||
for (const input of first) {
|
||||
f.apply(input.command);
|
||||
}
|
||||
const reused = paperFeedFrame(1001);
|
||||
reused.observations = [];
|
||||
reused.quotes[0]!.observedAt = 1000;
|
||||
reused.quotes[0]!.sourceSequence = 1000;
|
||||
expect(() => f.plan(reused)).toThrow('physical quote liquidity');
|
||||
reused.quotes[0]!.sourceSequence = 1001;
|
||||
reused.quotes[0]!.observedAt = 999;
|
||||
expect(() => f.plan(reused)).toThrow('regresses');
|
||||
reused.quotes[0]!.sourceSequence = 0;
|
||||
reused.quotes[0]!.observedAt = 1001;
|
||||
expect(f.plan(reused).at(-1)!.command.key.sourceSequence).toBe(0);
|
||||
});
|
||||
|
||||
test('a newly published auxiliary series neither creates liquidity nor wakes unrelated cadence owners', () => {
|
||||
const raw = paperFeedConfiguration(['X', 'Y']);
|
||||
raw.policy.observations.push({
|
||||
seriesId: 'X:aux',
|
||||
instrumentId: 'X',
|
||||
intervalMs: 1000,
|
||||
staleAfterMs: 50,
|
||||
});
|
||||
const f = fixture(raw);
|
||||
const frame = paperFeedFrame(1000, ['X', 'Y']);
|
||||
frame.observations = [{ ...frame.observations[0]!, series_id: 'X:aux' }];
|
||||
const auxiliary = f.plan(frame);
|
||||
expect(auxiliary.filter(input => input.command.body.kind === 'execute')).toHaveLength(2);
|
||||
expect(auxiliary.filter(input => input.decision)).toHaveLength(0);
|
||||
frame.observations.push(paperFeedFrame().observations[0]!);
|
||||
const due = f.plan(frame).at(-1)!;
|
||||
expect(due.decision!.ownerIds).toEqual(['owner-X']);
|
||||
expect(due.decision!.inputs.find(input => input.series_id === 'Y:bar')!.availability).toBe(
|
||||
'Missing'
|
||||
);
|
||||
expect(due.decision!.inputs.find(input => input.series_id === 'X:aux')!.availability).toEqual({
|
||||
Fresh: { event_time: 1000, available_at: 1000 },
|
||||
});
|
||||
});
|
||||
|
||||
test('accepts session-clipped complete bars and emits declared close/risk/open boundaries in native order', () => {
|
||||
const raw = paperFeedConfiguration();
|
||||
raw.policy.calendars[0]!.sessions = [
|
||||
{ sessionId: 'half-day', opensAt: 0, closesAt: 1500 },
|
||||
{ sessionId: 'next-day', opensAt: 2000, closesAt: 3500 },
|
||||
];
|
||||
raw.policy.riskBoundaries = [
|
||||
{ ...raw.matching.risk.ledger.riskSession, sessionId: 'risk-2', startsAt: 2000 },
|
||||
];
|
||||
raw.policy.observations[0]!.staleAfterMs = 500;
|
||||
const f = fixture(raw);
|
||||
for (const input of f.plan()) {
|
||||
f.apply(input.command);
|
||||
}
|
||||
const frame = paperFeedFrame(2100);
|
||||
frame.observations[0] = {
|
||||
...frame.observations[0]!,
|
||||
interval_start: 1000,
|
||||
interval_end: 1500,
|
||||
event_time: 1500,
|
||||
available_at: 2100,
|
||||
};
|
||||
const plan = f.plan(frame);
|
||||
expect(
|
||||
plan.map(input => [
|
||||
input.command.body.kind,
|
||||
input.command.key.at,
|
||||
input.command.key.sourceSequence,
|
||||
])
|
||||
).toEqual([
|
||||
['closeSession', 1500, 0],
|
||||
['riskSessionBoundary', 2000, 1],
|
||||
['openSession', 2000, 2],
|
||||
['execute', 2100, 2100],
|
||||
]);
|
||||
expect(plan.at(-1)!.decision!.inputs[0]!.availability).toEqual({
|
||||
Stale: { event_time: 1500, available_at: 2100 },
|
||||
});
|
||||
for (const input of plan) {
|
||||
f.apply(input.command);
|
||||
}
|
||||
expect(f.current().checkpoint.sessions).toEqual([
|
||||
['X', { sessionId: 'next-day', opensAt: 2000, closesAt: 3500 }],
|
||||
]);
|
||||
const daily = structuredClone(raw);
|
||||
daily.policy.observations[0]!.intervalMs = 86400000;
|
||||
frame.observations[0]!.interval_start = 0;
|
||||
expect(
|
||||
validatePaperFrame(validatePaperConfiguration(daily), frame, 2100).observations[0]!
|
||||
.interval_end
|
||||
).toBe(1500);
|
||||
frame.quotes[0]!.observedAt = 1499;
|
||||
expect(() => validatePaperFrame(f.config, frame, 2100)).toThrow('identity, time');
|
||||
});
|
||||
|
||||
test('keeps newly available older observations, while unchanged latest does not create decisions', () => {
|
||||
const f = fixture();
|
||||
const newest = validatePaperFrame(f.config, paperFeedFrame(2000), 2000).observations[0]!;
|
||||
const account = { ...f.account(), latestObservations: [newest], observed: 1 };
|
||||
const delayed = paperFeedFrame(3000);
|
||||
delayed.observations = [{ ...paperFeedFrame().observations[0]!, available_at: 3000 }];
|
||||
const before = JSON.stringify(account);
|
||||
const plan = planPaperFrame(f.config, validatePaperFrame(f.config, delayed, 3000), account);
|
||||
expect(plan.at(-1)!.observations[0]!.event_time).toBe(1000);
|
||||
expect(plan.at(-1)!.decision!.inputs[0]!.availability).toEqual({
|
||||
Fresh: { event_time: 2000, available_at: 2000 },
|
||||
});
|
||||
expect(JSON.stringify(account)).toBe(before);
|
||||
delayed.observations = [newest];
|
||||
expect(
|
||||
planPaperFrame(f.config, validatePaperFrame(f.config, delayed, 3000), account).at(-1)!
|
||||
.decision
|
||||
).toBeUndefined();
|
||||
delayed.observations = [{ ...newest, volume: parseFinancialDecimal('101') }];
|
||||
expect(() =>
|
||||
planPaperFrame(f.config, validatePaperFrame(f.config, delayed, 3000), account)
|
||||
).toThrow('retained identity');
|
||||
});
|
||||
|
||||
test('atomic plan keys and physical sequence order are deterministic and fail closed behind the cursor', () => {
|
||||
const f = fixture();
|
||||
const frame = paperFeedFrame();
|
||||
frame.quotes.push({ ...frame.quotes[0]!, observedAt: 999, sourceSequence: 999 });
|
||||
expect(
|
||||
f
|
||||
.plan(frame)
|
||||
.filter(input => input.command.body.kind === 'execute')
|
||||
.map(input => input.command.key.sourceSequence)
|
||||
).toEqual([999, 1000]);
|
||||
frame.quotes[1]!.observedAt = 1000;
|
||||
frame.quotes[0]!.observedAt = 999;
|
||||
expect(() => f.plan(frame)).toThrow('reverses');
|
||||
for (const input of f.plan()) {
|
||||
f.apply(input.command);
|
||||
}
|
||||
const behind = paperFeedFrame(999);
|
||||
behind.observations = [];
|
||||
behind.quotes[0]!.observedAt = 999;
|
||||
expect(() => f.plan(behind)).toThrow();
|
||||
const snapshot = f.account();
|
||||
snapshot.checkpoint.status = 'Complete';
|
||||
expect(() =>
|
||||
planPaperFrame(f.config, validatePaperFrame(f.config, paperFeedFrame(2000), 2000), snapshot)
|
||||
).toThrow(PaperRuntimeError);
|
||||
});
|
||||
});
|
||||
377
test/integration/paper-routes.test.ts
Normal file
377
test/integration/paper-routes.test.ts
Normal file
|
|
@ -0,0 +1,377 @@
|
|||
import { describe, expect, mock, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import type { Server as SocketIOServer } from 'socket.io';
|
||||
import { createHttpSecurity } from '@stock-bot/di';
|
||||
import { createPaperRoutes } from '../../apps/stock/orchestrator/src/api/rest/paper';
|
||||
import {
|
||||
PaperRuntimeError,
|
||||
type PaperConfigurationInput,
|
||||
type PaperConnection,
|
||||
type PaperFrameInput,
|
||||
type PaperReadiness,
|
||||
type PaperRuntime,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/paper-runtime';
|
||||
import { ExecutionConflictError } from '../../apps/stock/orchestrator/src/execution/repository';
|
||||
import { createRoutes } from '../../apps/stock/orchestrator/src/routes/create-routes';
|
||||
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
|
||||
import { paperFeedFrame } from '../fixtures/paper-feed';
|
||||
|
||||
const tokens = {
|
||||
operator: 'paper-routes-admin-fixture-not-a-real-secret-1234',
|
||||
service: 'paper-routes-service-fixture-not-a-real-secret-1234',
|
||||
read: 'paper-routes-read-fixture-not-a-real-secret-1234',
|
||||
};
|
||||
type Role = keyof typeof tokens;
|
||||
const connection = { sourceId: 'trusted-fixture', connectionId: 'connection-1' };
|
||||
const readiness = (): PaperReadiness => ({
|
||||
configured: true,
|
||||
accountId: 'paper-account',
|
||||
sourceId: 'trusted-fixture',
|
||||
active: false,
|
||||
ready: true,
|
||||
operatorHalted: true,
|
||||
connected: true,
|
||||
reasons: [],
|
||||
lastReceivedAt: 1000,
|
||||
lastAvailableAt: 1000,
|
||||
requiresHistoricalRecovery: false,
|
||||
pendingInput: null,
|
||||
pendingBatch: null,
|
||||
pendingDecisionSequence: null,
|
||||
nativeStatus: 'Running',
|
||||
risk: { dailyHalted: false, drawdownHalted: false },
|
||||
});
|
||||
|
||||
function runtimeFixture() {
|
||||
return {
|
||||
initialize: mock(async (_input: PaperConfigurationInput) => {}),
|
||||
status: mock(async () => readiness()),
|
||||
connect: mock(async (_input: PaperConnection) => readiness()),
|
||||
disconnect: mock(async (_input: PaperConnection) => readiness()),
|
||||
ingest: mock(async (_input: PaperFrameInput) => ({
|
||||
duplicate: false,
|
||||
disposition: 'admitted' as const,
|
||||
readiness: readiness(),
|
||||
})),
|
||||
activate: mock(async (_input: { recoverPending: boolean }) => readiness()),
|
||||
halt: mock(async (_reason: string) => readiness()),
|
||||
shutdown: mock(async () => {}),
|
||||
} satisfies PaperRuntime;
|
||||
}
|
||||
|
||||
function fixture(runtime: PaperRuntime | null = runtimeFixture(), allRoutes = false) {
|
||||
const logger = {
|
||||
info: mock(() => {}),
|
||||
warn: mock(() => {}),
|
||||
debug: mock(() => {}),
|
||||
error: mock(() => {}),
|
||||
};
|
||||
const legacy = {
|
||||
submitOrder: mock(async () => {
|
||||
throw new Error('Legacy submit must be unreachable');
|
||||
}),
|
||||
cancelOrder: mock(async () => {
|
||||
throw new Error('Legacy cancel must be unreachable');
|
||||
}),
|
||||
getPositions: mock(async () => {
|
||||
throw new Error('Legacy positions must be unreachable');
|
||||
}),
|
||||
getRecoveryStatus: mock(async () => {
|
||||
throw new Error('Legacy recovery must be unreachable');
|
||||
}),
|
||||
on: mock(() => {}),
|
||||
};
|
||||
const services = {
|
||||
logger,
|
||||
custom: {
|
||||
...(runtime ? { CanonicalPaperRuntime: runtime } : {}),
|
||||
ExecutionService: legacy,
|
||||
BacktestRunner: {},
|
||||
ModeManager: { getCurrentMode: mock(() => 'live') },
|
||||
},
|
||||
} as unknown as OrchestratorServices;
|
||||
const io = { on: mock(() => {}) };
|
||||
const app = new Hono();
|
||||
createHttpSecurity({
|
||||
adminToken: tokens.operator,
|
||||
serviceToken: tokens.service,
|
||||
readToken: tokens.read,
|
||||
environment: 'test',
|
||||
}).mount(app);
|
||||
if (allRoutes) {
|
||||
app.route('/', createRoutes(services, io as unknown as SocketIOServer));
|
||||
} else {
|
||||
app.route('/api/paper', createPaperRoutes(services));
|
||||
}
|
||||
return {
|
||||
app,
|
||||
logger,
|
||||
legacy,
|
||||
io,
|
||||
request(path: string, role?: Role, body?: unknown, headers?: Record<string, string>) {
|
||||
return app.request(`/api/paper${path}`, {
|
||||
method: body === undefined ? 'GET' : 'POST',
|
||||
headers: {
|
||||
...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}),
|
||||
'Content-Type': 'application/json',
|
||||
...headers,
|
||||
},
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const mutations = [
|
||||
{ path: '/activate', method: 'activate', body: {}, feed: false },
|
||||
{ path: '/halt', method: 'halt', body: { reason: 'operator-request' }, feed: false },
|
||||
{ path: '/feed/connect', method: 'connect', body: connection, feed: true },
|
||||
{ path: '/feed/disconnect', method: 'disconnect', body: connection, feed: true },
|
||||
{ path: '/feed/frames', method: 'ingest', body: paperFeedFrame(), feed: true },
|
||||
] as const;
|
||||
|
||||
describe('canonical paper HTTP authorization', () => {
|
||||
test('real security distinguishes operator, service producer, reader and anonymous callers', async () => {
|
||||
for (const role of ['operator', 'service', 'read', undefined] as const) {
|
||||
const runtime = runtimeFixture();
|
||||
const f = fixture(runtime);
|
||||
const response = await f.request('/readiness', role);
|
||||
expect(response.status).toBe(role ? 200 : 401);
|
||||
expect(runtime.status.mock.calls).toHaveLength(role ? 1 : 0);
|
||||
for (const endpoint of mutations) {
|
||||
const allowed = role === 'operator' || (role === 'service' && endpoint.feed);
|
||||
const mutation = await f.request(endpoint.path, role, endpoint.body);
|
||||
expect(mutation.status).toBe(allowed ? 200 : role ? 403 : 401);
|
||||
expect(runtime[endpoint.method].mock.calls).toHaveLength(allowed ? 1 : 0);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('caller actor headers, query strings and body fields cannot manufacture operator authority', async () => {
|
||||
const runtime = runtimeFixture();
|
||||
const f = fixture(runtime);
|
||||
const forged = { 'X-Actor': 'operator', 'X-Principal': 'operator', 'X-Role': 'admin' };
|
||||
for (const role of ['service', 'read', undefined] as const) {
|
||||
const response = await f.request(
|
||||
'/activate?principal=operator&actor=admin',
|
||||
role,
|
||||
{},
|
||||
forged
|
||||
);
|
||||
expect(response.status).toBe(role ? 403 : 401);
|
||||
}
|
||||
expect((await f.request('/activate', 'operator', { actor: 'operator' }, forged)).status).toBe(
|
||||
400
|
||||
);
|
||||
expect(runtime.activate.mock.calls).toHaveLength(0);
|
||||
expect((await f.request('/feed/connect', undefined, connection, forged)).status).toBe(401);
|
||||
expect(runtime.connect.mock.calls).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('canonical paper HTTP input and readiness contracts', () => {
|
||||
test('activation defaults to no historical recovery and accepts only the explicit strict option', async () => {
|
||||
const runtime = runtimeFixture();
|
||||
const f = fixture(runtime);
|
||||
expect((await f.request('/activate', 'operator', {})).status).toBe(200);
|
||||
expect((await f.request('/activate', 'operator', { recoverPending: true })).status).toBe(200);
|
||||
expect(runtime.activate.mock.calls).toEqual([
|
||||
[{ recoverPending: false }],
|
||||
[{ recoverPending: true }],
|
||||
]);
|
||||
for (const body of [
|
||||
{ recoverPending: 'true' },
|
||||
{ recoverPending: true, resetCapital: true },
|
||||
null,
|
||||
[],
|
||||
]) {
|
||||
expect((await f.request('/activate', 'operator', body)).status).toBe(400);
|
||||
}
|
||||
const malformed = await f.app.request('/api/paper/activate', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${tokens.operator}` },
|
||||
body: '{',
|
||||
});
|
||||
expect(malformed.status).toBe(400);
|
||||
expect(runtime.activate.mock.calls).toHaveLength(2);
|
||||
});
|
||||
|
||||
test('halt and feed endpoints pass only validated normalized arguments to the runtime', async () => {
|
||||
const runtime = runtimeFixture();
|
||||
const f = fixture(runtime);
|
||||
expect((await f.request('/halt', 'operator', { reason: ' stop requested ' })).status).toBe(
|
||||
200
|
||||
);
|
||||
expect(runtime.halt.mock.calls).toEqual([['stop requested']]);
|
||||
for (const body of [{ reason: '' }, { reason: ' ' }, { reason: 'stop', resetRisk: true }]) {
|
||||
expect((await f.request('/halt', 'operator', body)).status).toBe(400);
|
||||
}
|
||||
for (const path of ['/feed/connect', '/feed/disconnect']) {
|
||||
expect((await f.request(path, 'service', connection)).status).toBe(200);
|
||||
expect((await f.request(path, 'service', { sourceId: connection.sourceId })).status).toBe(
|
||||
400
|
||||
);
|
||||
expect((await f.request(path, 'service', { ...connection, actor: 'operator' })).status).toBe(
|
||||
400
|
||||
);
|
||||
}
|
||||
expect(runtime.connect.mock.calls).toEqual([[connection]]);
|
||||
expect(runtime.disconnect.mock.calls).toEqual([[connection]]);
|
||||
const frame = paperFeedFrame();
|
||||
const admitted = await f.request('/feed/frames', 'service', frame);
|
||||
expect(admitted.status).toBe(200);
|
||||
expect(await admitted.json()).toEqual({
|
||||
duplicate: false,
|
||||
disposition: 'admitted',
|
||||
readiness: readiness(),
|
||||
});
|
||||
expect(runtime.ingest.mock.calls[0]![0].quotes[0]!.bid).toBe('10.00000000');
|
||||
for (const body of [
|
||||
{ ...frame, unexpected: true },
|
||||
{ ...frame, quotes: [] },
|
||||
{ ...frame, quotes: [{ ...frame.quotes[0], brokerOrderId: 'forbidden' }] },
|
||||
{ ...frame, observations: [{ ...frame.observations[0], futureFeature: 'forbidden' }] },
|
||||
]) {
|
||||
expect((await f.request('/feed/frames', 'service', body)).status).toBe(400);
|
||||
}
|
||||
expect(runtime.ingest.mock.calls).toHaveLength(1);
|
||||
expect(runtime.initialize.mock.calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('malformed quote and observation decimals return400 before runtime admission', async () => {
|
||||
const runtime = runtimeFixture();
|
||||
const f = fixture(runtime);
|
||||
for (const malformed of ['bad', 'NaN', '1e5', '1.000000001']) {
|
||||
const quote = paperFeedFrame();
|
||||
quote.quotes[0]!.bid = malformed;
|
||||
expect((await f.request('/feed/frames', 'service', quote)).status).toBe(400);
|
||||
const observation = paperFeedFrame();
|
||||
const body = {
|
||||
...observation,
|
||||
observations: [{ ...observation.observations[0], close: malformed }],
|
||||
};
|
||||
expect((await f.request('/feed/frames', 'service', body)).status).toBe(400);
|
||||
}
|
||||
expect(runtime.ingest.mock.calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('unconfigured readiness reports explicit unavailable state and never invents an account', async () => {
|
||||
const f = fixture(null);
|
||||
const response = await f.request('/readiness', 'read');
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
||||
expect(await response.json()).toEqual({
|
||||
configured: false,
|
||||
accountId: null,
|
||||
sourceId: null,
|
||||
active: false,
|
||||
ready: false,
|
||||
operatorHalted: true,
|
||||
connected: false,
|
||||
reasons: ['not-configured'],
|
||||
lastReceivedAt: null,
|
||||
lastAvailableAt: null,
|
||||
requiresHistoricalRecovery: false,
|
||||
pendingInput: null,
|
||||
pendingBatch: null,
|
||||
pendingDecisionSequence: null,
|
||||
nativeStatus: null,
|
||||
risk: null,
|
||||
});
|
||||
const activate = await f.request('/activate', 'operator', {});
|
||||
expect(activate.status).toBe(409);
|
||||
expect(await activate.json()).toMatchObject({ code: 'not-ready' });
|
||||
});
|
||||
|
||||
test('configured readiness preserves recovery and risk diagnostics without claiming activation', async () => {
|
||||
const runtime = runtimeFixture();
|
||||
const blocked: PaperReadiness = {
|
||||
...readiness(),
|
||||
ready: false,
|
||||
active: false,
|
||||
connected: false,
|
||||
reasons: ['disconnected', 'pending-financial-work'],
|
||||
requiresHistoricalRecovery: true,
|
||||
pendingInput: 'input-7',
|
||||
pendingBatch: 'batch-3',
|
||||
pendingDecisionSequence: 8,
|
||||
risk: { dailyHalted: true, drawdownHalted: false },
|
||||
};
|
||||
runtime.status.mockImplementation(async () => blocked);
|
||||
const response = await fixture(runtime).request('/readiness', 'read');
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toEqual(blocked);
|
||||
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
||||
});
|
||||
});
|
||||
|
||||
describe('canonical paper HTTP failure and legacy gateway isolation', () => {
|
||||
test('typed validation/readiness/conflict failures keep their public status classification', async () => {
|
||||
const runtime = runtimeFixture();
|
||||
const f = fixture(runtime);
|
||||
for (const [error, expectedStatus, code] of [
|
||||
[new PaperRuntimeError('invalid-input', 'Invalid physical quote'), 400, 'invalid-input'],
|
||||
[new PaperRuntimeError('not-ready', 'Feed disconnected'), 409, 'not-ready'],
|
||||
[new PaperRuntimeError('conflict', 'Frame conflicts'), 409, 'conflict'],
|
||||
[new ExecutionConflictError('Account conflicts'), 409, 'conflict'],
|
||||
] as const) {
|
||||
runtime.activate.mockImplementation(async () => {
|
||||
throw error;
|
||||
});
|
||||
const response = await f.request('/activate', 'operator', {});
|
||||
expect(response.status).toBe(expectedStatus);
|
||||
expect(await response.json()).toEqual({ error: error.message, code });
|
||||
}
|
||||
expect(f.logger.error.mock.calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('runtime failures return503 and never leak internal database or transport details', async () => {
|
||||
const runtime = runtimeFixture();
|
||||
const f = fixture(runtime);
|
||||
const failure = new Error('sensitive database driver details');
|
||||
runtime.status.mockImplementation(async () => {
|
||||
throw failure;
|
||||
});
|
||||
const failedStatus = await f.request('/readiness', 'read');
|
||||
expect(failedStatus.status).toBe(503);
|
||||
expect(await failedStatus.json()).toEqual({ error: 'Canonical paper runtime unavailable' });
|
||||
for (const endpoint of mutations) {
|
||||
runtime[endpoint.method].mockImplementation(async () => {
|
||||
throw failure;
|
||||
});
|
||||
const response = await f.request(endpoint.path, 'operator', endpoint.body);
|
||||
expect(response.status).toBe(503);
|
||||
expect(await response.json()).toEqual({ error: 'Canonical paper runtime unavailable' });
|
||||
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
||||
}
|
||||
expect(f.logger.error.mock.calls).toHaveLength(6);
|
||||
});
|
||||
|
||||
test('canonical createRoutes blocks legacy account REST paths and does not register legacy WebSocket handlers', async () => {
|
||||
const runtime = runtimeFixture();
|
||||
const f = fixture(runtime, true);
|
||||
const headers = { Authorization: `Bearer ${tokens.operator}` };
|
||||
for (const path of [
|
||||
'/api/orders',
|
||||
'/api/orders/order-1',
|
||||
'/api/positions',
|
||||
'/api/positions/X',
|
||||
]) {
|
||||
for (const method of ['GET', 'POST', 'DELETE']) {
|
||||
const response = await f.app.request(path, { method, headers });
|
||||
expect(response.status).toBe(409);
|
||||
expect(await response.json()).toEqual({
|
||||
error: 'Legacy account gateway unavailable in canonical paper mode',
|
||||
});
|
||||
}
|
||||
}
|
||||
const recovery = await f.app.request('/api/recovery', { headers });
|
||||
expect(await recovery.json()).toEqual({ engine: 'canonical-paper', ...readiness() });
|
||||
const health = await f.app.request('/health');
|
||||
expect(await health.json()).toMatchObject({ mode: 'paper', execution: 'canonical-paper' });
|
||||
expect(f.io.on.mock.calls).toHaveLength(0);
|
||||
for (const call of Object.values(f.legacy)) {
|
||||
expect(call.mock.calls).toHaveLength(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
192
test/postgres/paper-http.test.ts
Normal file
192
test/postgres/paper-http.test.ts
Normal file
|
|
@ -0,0 +1,192 @@
|
|||
import { asValue } from 'awilix';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { createHttpSecurity, ServiceContainerBuilder } from '@stock-bot/di';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import { createPaperRoutes } from '../../apps/stock/orchestrator/src/api/rest/paper';
|
||||
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
|
||||
import { builtinStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
|
||||
import type { PaperRuntime } from '../../apps/stock/orchestrator/src/contracts/paper-runtime';
|
||||
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-sma';
|
||||
import {
|
||||
BacktestConfigSchema,
|
||||
type OrchestratorServices,
|
||||
} from '../../apps/stock/orchestrator/src/types';
|
||||
import { logger } from '../fixtures/execution';
|
||||
import { paperConfig, paperFixture, paperFrame } from '../fixtures/paper-runtime';
|
||||
|
||||
const adminToken = 'paper-http-test-admin-token-not-real-123456';
|
||||
const serviceToken = 'paper-http-test-service-token-not-real-123456';
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
function api(runtime: PaperRuntime) {
|
||||
const app = new Hono();
|
||||
createHttpSecurity({ adminToken, serviceToken }).mount(app);
|
||||
app.route(
|
||||
'/api/paper',
|
||||
createPaperRoutes({ logger, custom: { CanonicalPaperRuntime: runtime } })
|
||||
);
|
||||
return async (path: string, body: unknown, producer = false) => {
|
||||
const response = await app.request(`/api/paper/${path}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${producer ? serviceToken : adminToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const result = await response.json();
|
||||
expect(response.status, JSON.stringify(result)).toBe(200);
|
||||
return result;
|
||||
};
|
||||
}
|
||||
|
||||
describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)(
|
||||
'canonical paper HTTP and composition',
|
||||
() => {
|
||||
test('authenticated feed -> actual SMA -> next quote Rust fill -> durable restart without capital reset', async () => {
|
||||
const config = paperConfig();
|
||||
config.matching.risk.ledger.initialCapital = '1234';
|
||||
config.strategies[0]!.ownerBudget = '20';
|
||||
const program = createBuiltinStrategy(
|
||||
builtinStrategySelectionSchema.parse(config.strategies[0])
|
||||
);
|
||||
const f = await paperFixture(config, program);
|
||||
cleanup.push(f.close);
|
||||
let post = api(f.runtime);
|
||||
const connection = { sourceId: 'fixture', connectionId: 'one' };
|
||||
await post('feed/connect', connection, true);
|
||||
await post('feed/frames', paperFrame(1), true);
|
||||
await post('activate', {});
|
||||
const send = async (sequence: number, price: string, bars = true) => {
|
||||
f.clock(sequence * 10);
|
||||
const frame = paperFrame(sequence);
|
||||
frame.quotes[0]!.bid = frame.quotes[0]!.ask = parseFinancialDecimal(price);
|
||||
frame.observations = bars
|
||||
? frame.observations.map(row => ({
|
||||
...row,
|
||||
open: parseFinancialDecimal(price),
|
||||
high: parseFinancialDecimal(price),
|
||||
low: parseFinancialDecimal(price),
|
||||
close: parseFinancialDecimal(price),
|
||||
}))
|
||||
: [];
|
||||
await post('feed/frames', frame, true);
|
||||
};
|
||||
await send(2, '11');
|
||||
await send(3, '9');
|
||||
await send(4, '10');
|
||||
const decision = await f.snapshot();
|
||||
expect(decision.account.view.portfolio.positions).toHaveLength(0);
|
||||
expect(decision.owners[0]!.diagnostic.nextDecisionSequence).toBe(3);
|
||||
await send(5, '10', false);
|
||||
const filled = await f.snapshot();
|
||||
expect(filled.account.view.portfolio.positions[0]!.quantity).toBe(parseFinancialDecimal('2'));
|
||||
expect(filled.account.view.portfolio.cash).toBe(parseFinancialDecimal('1213.8'));
|
||||
expect(filled.account.view.equity).toBe(parseFinancialDecimal('1233.8'));
|
||||
expect(filled.journal.filter(row => row.payload.kind === 'effect')).not.toHaveLength(0);
|
||||
await post('halt', { reason: 'restart fixture' });
|
||||
const restored = await f.make();
|
||||
post = api(restored);
|
||||
expect(await restored.status()).toMatchObject({
|
||||
operatorHalted: true,
|
||||
active: false,
|
||||
connected: false,
|
||||
});
|
||||
expect((await f.snapshot()).account.view).toEqual(filled.account.view);
|
||||
expect((await f.snapshot()).account.checkpoint).toEqual(filled.account.checkpoint);
|
||||
expect((await f.snapshot()).journal).toEqual(filled.journal);
|
||||
expect((await f.snapshot()).owners).toEqual(filled.owners);
|
||||
await post('feed/connect', { ...connection, connectionId: 'two' }, true);
|
||||
f.clock(60);
|
||||
await post('feed/frames', paperFrame(6, 60, 'two'), true);
|
||||
await post('activate', {});
|
||||
expect((await f.snapshot()).account.view).toEqual(filled.account.view);
|
||||
expect((await f.snapshot()).account.checkpoint).toEqual(filled.account.checkpoint);
|
||||
expect((await f.snapshot()).journal).toEqual(filled.journal);
|
||||
});
|
||||
|
||||
test('opt-in composition exposes canonical custody only and research cannot change its state', async () => {
|
||||
const config = paperConfig();
|
||||
const f = await paperFixture(
|
||||
config,
|
||||
createBuiltinStrategy(builtinStrategySelectionSchema.parse(config.strategies[0]))
|
||||
);
|
||||
cleanup.push(f.close);
|
||||
const container = await new ServiceContainerBuilder()
|
||||
.withOptions({
|
||||
enableCache: false,
|
||||
enableQueue: false,
|
||||
enableMongoDB: false,
|
||||
enablePostgres: false,
|
||||
enableQuestDB: false,
|
||||
enableBrowser: false,
|
||||
enableProxy: false,
|
||||
})
|
||||
.build();
|
||||
const services: OrchestratorServices = { logger, postgres: f.postgres };
|
||||
container.register({ serviceContainer: asValue(services) });
|
||||
await registerOrchestratorServices(container, {
|
||||
canonicalPaper: config,
|
||||
nativeExecutionTimeoutMs: 10000,
|
||||
});
|
||||
const custom = services.custom!;
|
||||
cleanup.push(async () => {
|
||||
await custom.CanonicalPaperRuntime!.shutdown();
|
||||
await custom.BacktestRunner!.shutdown();
|
||||
await container.dispose();
|
||||
});
|
||||
expect(custom.CanonicalPaperRuntime).toBeDefined();
|
||||
for (const key of [
|
||||
'ExecutionService',
|
||||
'ModeManager',
|
||||
'StrategyManager',
|
||||
'MarketDataService',
|
||||
'PaperTradingManager',
|
||||
] as const) {
|
||||
expect(custom[key]).toBeUndefined();
|
||||
expect(container.hasRegistration(key)).toBe(false);
|
||||
}
|
||||
expect((await custom.CanonicalPaperRuntime!.status()).active).toBe(false);
|
||||
const before = await f.snapshot();
|
||||
const research = BacktestConfigSchema.parse({
|
||||
mode: 'backtest',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['RESEARCH.TEST'],
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-01-21T00:00:00.000Z',
|
||||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
config: { fastPeriod: 2, slowPeriod: 3 },
|
||||
});
|
||||
custom.StorageService!.getHistoricalBars = async () =>
|
||||
Array.from({ length: 20 }, (_, i) => {
|
||||
const close = 100 + Math.sin(i) * 5;
|
||||
return {
|
||||
symbol: 'RESEARCH.TEST',
|
||||
source: 'eod' as const,
|
||||
timestamp: new Date(Date.parse(research.startDate) + i * 86400000),
|
||||
open: close,
|
||||
high: close + 1,
|
||||
low: close - 1,
|
||||
close,
|
||||
volume: 1000000,
|
||||
};
|
||||
});
|
||||
expect((await custom.BacktestEngine!.runBacktest(research)).status).toBe('completed');
|
||||
expect(await f.snapshot()).toEqual(before);
|
||||
await expect(
|
||||
registerOrchestratorServices(container, { canonicalPaper: config })
|
||||
).rejects.toThrow('fresh runtime composition');
|
||||
await expect(registerOrchestratorServices(container)).rejects.toThrow(
|
||||
'fresh runtime composition'
|
||||
);
|
||||
});
|
||||
}
|
||||
);
|
||||
543
test/postgres/paper-runtime.test.ts
Normal file
543
test/postgres/paper-runtime.test.ts
Normal file
|
|
@ -0,0 +1,543 @@
|
|||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import { compareEventKeys } from '../../apps/stock/orchestrator/src/execution/canonical-paper';
|
||||
import { CanonicalPaperExecution } from '../../apps/stock/orchestrator/src/execution/CanonicalPaperExecution';
|
||||
import { counterProgram, quoteInput } from '../fixtures/canonical-paper';
|
||||
import { paperConfig, paperFixture, paperFrame } from '../fixtures/paper-runtime';
|
||||
|
||||
const connection = { sourceId: 'fixture', connectionId: 'one' };
|
||||
test('host event keys preserve Rust UTF-8 instrument ordering for supplementary Unicode', () => {
|
||||
const key = { at: 1, phase: 'Execution' as const, sourceSequence: 1 };
|
||||
expect(
|
||||
compareEventKeys({ ...key, instrumentId: '\u{10000}' }, { ...key, instrumentId: '\ue000' })
|
||||
).toBeGreaterThan(0);
|
||||
});
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
async function fixture(config = paperConfig(), program = counterProgram()) {
|
||||
const f = await paperFixture(config, program);
|
||||
cleanup.push(f.close);
|
||||
return f;
|
||||
}
|
||||
async function start(f: Awaited<ReturnType<typeof fixture>>) {
|
||||
await f.runtime.connect(connection);
|
||||
expect((await f.runtime.ingest(paperFrame(1))).disposition).toBe('health-only');
|
||||
await f.runtime.activate({ recoverPending: false });
|
||||
}
|
||||
function deferred() {
|
||||
let resolve!: () => void;
|
||||
const promise = new Promise<void>(done => {
|
||||
resolve = done;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)(
|
||||
'controlled canonical paper on real PostgreSQL',
|
||||
() => {
|
||||
test('requires initial activation, retains inactive retry disposition, and freezes active retries after halt', async () => {
|
||||
const f = await fixture();
|
||||
const initial = await f.runtime.status();
|
||||
expect(initial).toMatchObject({
|
||||
active: false,
|
||||
ready: false,
|
||||
connected: false,
|
||||
operatorHalted: true,
|
||||
});
|
||||
await start(f);
|
||||
expect(await f.runtime.ingest(paperFrame(1))).toMatchObject({
|
||||
duplicate: true,
|
||||
disposition: 'health-only',
|
||||
});
|
||||
expect((await f.snapshot()).account.inputSequence).toBe(0);
|
||||
f.clock(20);
|
||||
const frame = paperFrame(2);
|
||||
expect((await f.runtime.ingest(frame)).disposition).toBe('admitted');
|
||||
const before = await f.snapshot();
|
||||
expect(before.owners[0]!.diagnostic.nextDecisionSequence).toBe(1);
|
||||
await f.runtime.halt('human stop');
|
||||
expect(await f.runtime.ingest(frame)).toMatchObject({
|
||||
duplicate: true,
|
||||
disposition: 'admitted',
|
||||
readiness: { active: false, operatorHalted: true },
|
||||
});
|
||||
expect((await f.snapshot()).account.checkpoint).toEqual(before.account.checkpoint);
|
||||
f.clock(30);
|
||||
expect((await f.runtime.ingest(paperFrame(3))).disposition).toBe('health-only');
|
||||
expect((await f.snapshot()).owners).toEqual(before.owners);
|
||||
});
|
||||
|
||||
test('persists halt and fences all stale-generation controls, ingestion and shutdown after replacement', async () => {
|
||||
const f = await fixture();
|
||||
await start(f);
|
||||
await f.runtime.halt('persist me');
|
||||
const replacement = await f.make();
|
||||
expect(await replacement.status()).toMatchObject({
|
||||
active: false,
|
||||
connected: false,
|
||||
operatorHalted: true,
|
||||
});
|
||||
f.clock(20);
|
||||
await expect(f.runtime.ingest(paperFrame(2))).rejects.toThrow('generation');
|
||||
await expect(f.runtime.activate({ recoverPending: true })).rejects.toThrow('generation');
|
||||
await expect(f.runtime.shutdown()).rejects.toThrow('generation');
|
||||
await expect(
|
||||
(f.runtime as unknown as { execution: CanonicalPaperExecution }).execution.drain()
|
||||
).rejects.toThrow('generation');
|
||||
await replacement.connect({ ...connection, connectionId: 'two' });
|
||||
f.clock(20);
|
||||
await replacement.ingest(paperFrame(2, 20, 'two'));
|
||||
await replacement.activate({ recoverPending: false });
|
||||
expect(await replacement.status()).toMatchObject({
|
||||
active: true,
|
||||
connected: true,
|
||||
operatorHalted: false,
|
||||
});
|
||||
await replacement.disconnect(connection);
|
||||
expect((await replacement.status()).active).toBe(true);
|
||||
await replacement.connect({ ...connection, connectionId: 'two' });
|
||||
expect((await replacement.status()).active).toBe(true);
|
||||
await replacement.connect({ ...connection, connectionId: 'three' });
|
||||
expect(await replacement.status()).toMatchObject({
|
||||
active: false,
|
||||
connected: true,
|
||||
ready: false,
|
||||
});
|
||||
});
|
||||
|
||||
test('long idle then a fresh frame revokes activation without a preceding status poll', async () => {
|
||||
const f = await fixture();
|
||||
await start(f);
|
||||
f.clock(200);
|
||||
const result = await f.runtime.ingest(paperFrame(2, 200));
|
||||
expect(result).toMatchObject({ disposition: 'health-only', readiness: { active: false } });
|
||||
expect((await f.snapshot()).account.inputSequence).toBe(0);
|
||||
await f.runtime.activate({ recoverPending: false });
|
||||
expect((await f.runtime.status()).active).toBe(true);
|
||||
});
|
||||
|
||||
test('frame inputs, health and receipts commit atomically and conflicting retries cannot alter them', async () => {
|
||||
const f = await fixture();
|
||||
await start(f);
|
||||
const before = await f.snapshot();
|
||||
let writes = 0;
|
||||
f.wrap(tx => ({
|
||||
...tx,
|
||||
async putInput(input) {
|
||||
if (++writes === 2) {
|
||||
throw new Error('atomic enqueue failure');
|
||||
}
|
||||
await tx.putInput(input);
|
||||
},
|
||||
}));
|
||||
f.clock(20);
|
||||
await expect(f.runtime.ingest(paperFrame(2))).rejects.toThrow('atomic enqueue failure');
|
||||
expect((await f.snapshot()).account).toEqual(before.account);
|
||||
f.wrap(tx => tx);
|
||||
expect(await f.runtime.ingest(paperFrame(2))).toMatchObject({
|
||||
duplicate: false,
|
||||
disposition: 'admitted',
|
||||
});
|
||||
const saved = await f.snapshot();
|
||||
const conflict = paperFrame(2);
|
||||
conflict.quotes[0]!.ask = parseFinancialDecimal('11');
|
||||
await expect(f.runtime.ingest(conflict)).rejects.toThrow('conflicting content');
|
||||
expect((await f.snapshot()).account).toEqual(saved.account);
|
||||
});
|
||||
|
||||
test('new frame IDs cannot turn inactive probe quotes into later tradable liquidity', async () => {
|
||||
const f = await fixture();
|
||||
await start(f);
|
||||
f.clock(20);
|
||||
const recycled = paperFrame(2);
|
||||
recycled.quotes = paperFrame(1).quotes;
|
||||
await expect(f.runtime.ingest(recycled)).rejects.toThrow('known physical quote');
|
||||
recycled.quotes[0]!.bidSize = parseFinancialDecimal('11');
|
||||
await expect(f.runtime.ingest(recycled)).rejects.toThrow('conflicting content');
|
||||
expect((await f.snapshot()).account.inputSequence).toBe(0);
|
||||
});
|
||||
|
||||
test('new quote identities cannot regress a fresh inactive probe or hide stale executable quotes', async () => {
|
||||
const f = await fixture();
|
||||
await start(f);
|
||||
f.clock(20);
|
||||
const old = paperFrame(2);
|
||||
old.quotes[0]!.observedAt = 5;
|
||||
await expect(f.runtime.ingest(old)).rejects.toThrow('regresses');
|
||||
expect((await f.snapshot()).account.inputSequence).toBe(0);
|
||||
await f.runtime.halt('probe');
|
||||
f.clock(200);
|
||||
await f.runtime.ingest(paperFrame(3, 200));
|
||||
await f.runtime.activate({ recoverPending: false });
|
||||
f.clock(210);
|
||||
const stale = paperFrame(4, 210);
|
||||
stale.quotes[0]!.observedAt = 100;
|
||||
await expect(f.runtime.ingest(stale)).rejects.toThrow('regresses');
|
||||
expect((await f.snapshot()).account.inputSequence).toBe(0);
|
||||
});
|
||||
|
||||
test('equal-time quotes require nonregressing physical sequence; a newer sequence remains admissible', async () => {
|
||||
const f = await fixture();
|
||||
await start(f);
|
||||
f.clock(20);
|
||||
const newer = paperFrame(2);
|
||||
newer.quotes[0]!.observedAt = 10;
|
||||
expect((await f.runtime.ingest(newer)).disposition).toBe('admitted');
|
||||
const saved = await f.snapshot();
|
||||
f.clock(30);
|
||||
const older = paperFrame(3);
|
||||
older.quotes[0]!.observedAt = 10;
|
||||
older.quotes[0]!.sourceSequence = 0;
|
||||
await expect(f.runtime.ingest(older)).rejects.toThrow('regresses');
|
||||
expect((await f.snapshot()).account.checkpoint).toEqual(saved.account.checkpoint);
|
||||
});
|
||||
|
||||
test.each(['reconnect', 'restart'] as const)(
|
||||
'%s preserves quote highwater while requiring new connection health',
|
||||
async kind => {
|
||||
const f = await fixture();
|
||||
await f.runtime.connect(connection);
|
||||
f.clock(30);
|
||||
await f.runtime.ingest(paperFrame(3));
|
||||
const runtime = kind === 'restart' ? await f.make() : f.runtime;
|
||||
await runtime.connect({ ...connection, connectionId: 'two' });
|
||||
expect((await runtime.status()).reasons).toContain('quote-stale:X');
|
||||
f.clock(40);
|
||||
const old = paperFrame(4, 40, 'two');
|
||||
old.quotes[0]!.observedAt = 20;
|
||||
old.quotes[0]!.sourceSequence = 2;
|
||||
await expect(runtime.ingest(old)).rejects.toThrow('regresses');
|
||||
expect((await f.snapshot()).account.inputSequence).toBe(0);
|
||||
await runtime.ingest(paperFrame(4, 40, 'two'));
|
||||
expect((await runtime.activate({ recoverPending: false })).active).toBe(true);
|
||||
}
|
||||
);
|
||||
|
||||
test.each(['malformed', 'conflict', 'activation'] as const)(
|
||||
'a rejected %s request durably latches stale inactivity without polling or admitting its input',
|
||||
async kind => {
|
||||
const f = await fixture();
|
||||
await start(f);
|
||||
const before = await f.snapshot();
|
||||
f.clock(200);
|
||||
if (kind === 'activation') {
|
||||
await expect(f.runtime.activate({ recoverPending: false })).rejects.toThrow(
|
||||
'unavailable'
|
||||
);
|
||||
} else {
|
||||
const rejected = kind === 'conflict' ? paperFrame(1) : paperFrame(2, 200);
|
||||
if (kind === 'conflict') {
|
||||
rejected.quotes[0]!.ask = parseFinancialDecimal('11');
|
||||
} else {
|
||||
rejected.quotes[0]!.ask = parseFinancialDecimal('0');
|
||||
}
|
||||
await expect(f.runtime.ingest(rejected)).rejects.toThrow();
|
||||
}
|
||||
// Read persisted custody directly: status() must not be what latches the halt.
|
||||
const stopped = await f.snapshot();
|
||||
expect(stopped.account.host?.active).toBe(false);
|
||||
expect(stopped.account.checkpoint).toEqual(before.account.checkpoint);
|
||||
expect(stopped.account.inputSequence).toBe(0);
|
||||
expect(stopped.account.host!.frames).toEqual(before.account.host!.frames);
|
||||
expect(stopped.account.host!.lastAvailableAt).toBe(before.account.host!.lastAvailableAt);
|
||||
}
|
||||
);
|
||||
|
||||
test('fresh transport and asset A cannot certify a stale required asset B or exhausted calendars', async () => {
|
||||
const config = paperConfig();
|
||||
config.matching.series.push({ instrumentId: 'Y', seriesId: 'Y:quote', mode: 'Quote' });
|
||||
config.policy.calendars.push({ ...config.policy.calendars[0]!, instrumentId: 'Y' });
|
||||
const f = await fixture(config);
|
||||
await f.runtime.connect(connection);
|
||||
await f.runtime.ingest(paperFrame(1));
|
||||
await expect(f.runtime.activate({ recoverPending: false })).rejects.toThrow('quote-stale:Y');
|
||||
f.clock(20);
|
||||
const frame = paperFrame(2);
|
||||
frame.quotes.push({ ...frame.quotes[0]!, instrumentId: 'Y', seriesId: 'Y:quote' });
|
||||
await f.runtime.ingest(frame);
|
||||
await f.runtime.activate({ recoverPending: false });
|
||||
f.clock(110);
|
||||
await f.runtime.ingest(paperFrame(3, 110));
|
||||
f.clock(121);
|
||||
expect(await f.runtime.status()).toMatchObject({ active: false, ready: false });
|
||||
expect((await f.runtime.status()).reasons).toContain('quote-stale:Y');
|
||||
f.clock(10000);
|
||||
expect((await f.runtime.status()).reasons).toContain('calendar-uncovered:X');
|
||||
});
|
||||
|
||||
test('binds configured capital and policy and refuses uncontrolled reopening or direct enqueue', async () => {
|
||||
const f = await fixture();
|
||||
expect((await f.snapshot()).account.view.portfolio.cash).toBe(parseFinancialDecimal('1000'));
|
||||
const changed = paperConfig();
|
||||
changed.matching.risk.ledger.initialCapital = '2000';
|
||||
await expect(f.make(changed)).rejects.toThrow('configuration');
|
||||
const plain = new CanonicalPaperExecution({
|
||||
repository: f.repository,
|
||||
programs: [
|
||||
{
|
||||
...counterProgram(),
|
||||
strategyId: 'sma_crossover',
|
||||
strategyVersion: 'sma-crossover-long-only/v1',
|
||||
},
|
||||
],
|
||||
});
|
||||
await expect(plain.initialize(f.configuration.matching)).rejects.toThrow('configuration');
|
||||
const privileged = (f.runtime as unknown as { execution: CanonicalPaperExecution }).execution;
|
||||
await expect(privileged.enqueue(quoteInput(1))).rejects.toThrow('atomic producer frames');
|
||||
expect((await f.snapshot()).account.inputSequence).toBe(0);
|
||||
});
|
||||
|
||||
test('requires explicit historical recovery, preserves original times, and retains poisoned decisions', async () => {
|
||||
let fail = true;
|
||||
const base = counterProgram();
|
||||
const f = await fixture(paperConfig(), {
|
||||
...base,
|
||||
decide: context => {
|
||||
if (fail) {
|
||||
throw new Error('poisoned strategy');
|
||||
}
|
||||
return base.decide(context);
|
||||
},
|
||||
});
|
||||
await start(f);
|
||||
f.clock(20);
|
||||
await expect(f.runtime.ingest(paperFrame(2))).rejects.toThrow('poisoned strategy');
|
||||
const pending = await f.runtime.status();
|
||||
expect(pending).toMatchObject({ active: false, requiresHistoricalRecovery: true });
|
||||
f.clock(200);
|
||||
await f.runtime.ingest(paperFrame(3, 200));
|
||||
await f.repository.transact(f.configuration.matching.risk.ledger.accountId, async tx => {
|
||||
if (tx.account.host) {
|
||||
tx.account.host.diagnostic = null;
|
||||
}
|
||||
});
|
||||
expect(await f.runtime.status()).toMatchObject({
|
||||
ready: false,
|
||||
reasons: ['historical-recovery-required'],
|
||||
});
|
||||
await expect(f.runtime.activate({ recoverPending: false })).rejects.toThrow('recoverPending');
|
||||
await expect(f.runtime.activate({ recoverPending: true })).rejects.toThrow(
|
||||
'poisoned strategy'
|
||||
);
|
||||
expect(await f.runtime.status()).toMatchObject({
|
||||
active: false,
|
||||
requiresHistoricalRecovery: true,
|
||||
});
|
||||
fail = false;
|
||||
expect(await f.runtime.activate({ recoverPending: true })).toMatchObject({
|
||||
active: true,
|
||||
ready: true,
|
||||
requiresHistoricalRecovery: false,
|
||||
});
|
||||
const snapshot = await f.snapshot();
|
||||
const decisions = snapshot.journal.filter(row => row.payload.kind === 'decision');
|
||||
expect(decisions).toHaveLength(1);
|
||||
expect(decisions[0]!.payload.kind === 'decision' && decisions[0]!.payload.key.at).toBe(20);
|
||||
expect(snapshot.owners[0]!.diagnostic.observationCount).toBe(1);
|
||||
});
|
||||
|
||||
test('explicit recovery after an hour fills an already admitted quote at its original price/time exactly once', async () => {
|
||||
const config = paperConfig();
|
||||
config.policy.calendars[0]!.sessions[0]!.closesAt = 7_200_000;
|
||||
const f = await fixture(config);
|
||||
await start(f);
|
||||
f.clock(20);
|
||||
await f.runtime.ingest(paperFrame(2));
|
||||
let armed = true;
|
||||
f.wrap(tx => ({
|
||||
...tx,
|
||||
async appendJournal(payload) {
|
||||
if (armed) {
|
||||
armed = false;
|
||||
throw new Error('crash before quote commit');
|
||||
}
|
||||
return tx.appendJournal(payload);
|
||||
},
|
||||
}));
|
||||
f.clock(30);
|
||||
const admitted = paperFrame(3);
|
||||
await expect(f.runtime.ingest(admitted)).rejects.toThrow('crash before quote commit');
|
||||
expect((await f.snapshot()).account.view.portfolio.positions).toHaveLength(0);
|
||||
const restored = await f.make();
|
||||
await restored.connect({ ...connection, connectionId: 'two' });
|
||||
f.clock(3_600_030);
|
||||
const probe = paperFrame(4, 3_600_030, 'two');
|
||||
probe.quotes[0]!.bid = parseFinancialDecimal('99');
|
||||
probe.quotes[0]!.ask = parseFinancialDecimal('99');
|
||||
expect((await restored.ingest(probe)).disposition).toBe('health-only');
|
||||
await expect(restored.activate({ recoverPending: false })).rejects.toThrow('recoverPending');
|
||||
expect(await restored.activate({ recoverPending: true })).toMatchObject({
|
||||
active: true,
|
||||
ready: true,
|
||||
requiresHistoricalRecovery: false,
|
||||
});
|
||||
const recovered = await f.snapshot();
|
||||
expect(recovered.account.view.portfolio.cash).toBe(parseFinancialDecimal('979.8'));
|
||||
expect(recovered.account.view.portfolio.positions[0]!.quantity).toBe(
|
||||
parseFinancialDecimal('2')
|
||||
);
|
||||
expect(recovered.account.view.portfolio.fees[0]!.amount).toBe(parseFinancialDecimal('0.2'));
|
||||
const quotes = recovered.journal.filter(
|
||||
row =>
|
||||
row.payload.kind === 'command' &&
|
||||
row.payload.command.key.at === 30 &&
|
||||
row.payload.command.body.kind === 'execute'
|
||||
);
|
||||
expect(quotes).toHaveLength(1);
|
||||
const payload = quotes[0]!.payload;
|
||||
if (payload.kind !== 'command' || payload.command.body.kind !== 'execute') {
|
||||
throw new Error('Missing quote command');
|
||||
}
|
||||
expect(payload.command.body.observation).toMatchObject({
|
||||
kind: 'quote',
|
||||
observedAt: 30,
|
||||
ask: parseFinancialDecimal('10'),
|
||||
});
|
||||
expect(await restored.ingest(admitted)).toMatchObject({
|
||||
duplicate: true,
|
||||
disposition: 'admitted',
|
||||
});
|
||||
expect((await f.snapshot()).account.checkpoint).toEqual(recovered.account.checkpoint);
|
||||
});
|
||||
|
||||
test('a halt waiting on the real account lock stops the next financial step without discarding work', async () => {
|
||||
const f = await fixture();
|
||||
await start(f);
|
||||
const reached = deferred();
|
||||
const release = deferred();
|
||||
let armed = true;
|
||||
f.wrap(tx => ({
|
||||
...tx,
|
||||
async appendJournal(payload) {
|
||||
if (armed && payload.kind === 'decision') {
|
||||
armed = false;
|
||||
reached.resolve();
|
||||
await release.promise;
|
||||
}
|
||||
return tx.appendJournal(payload);
|
||||
},
|
||||
}));
|
||||
f.clock(20);
|
||||
const ingest = f.runtime.ingest(paperFrame(2));
|
||||
await reached.promise;
|
||||
const halt = f.runtime.halt('race stop');
|
||||
// Verify PostgreSQL sees a lock waiter before allowing the financial step to commit.
|
||||
let waiting = false;
|
||||
for (let attempt = 0; attempt < 100; attempt++) {
|
||||
const rows = await f.pool.query(
|
||||
"SELECT 1 FROM pg_stat_activity WHERE datname=current_database() AND wait_event_type='Lock' AND query LIKE 'SELECT state FROM simulation_accounts%' "
|
||||
);
|
||||
if (rows.rowCount) {
|
||||
waiting = true;
|
||||
break;
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 5));
|
||||
}
|
||||
release.resolve();
|
||||
expect(waiting).toBe(true);
|
||||
expect(await halt).toMatchObject({ active: false, operatorHalted: true });
|
||||
await ingest;
|
||||
const snapshot = await f.snapshot();
|
||||
expect(snapshot.account.pendingDecisionSequence).not.toBeNull();
|
||||
expect(snapshot.owners[0]!.diagnostic.nextDecisionSequence).toBe(0);
|
||||
expect(snapshot.account.view.orders).toHaveLength(0);
|
||||
});
|
||||
|
||||
test.each(['input', 'batch'] as const)(
|
||||
'explicit recovery retains %s work across transient SQL or acknowledgement failures',
|
||||
async stage => {
|
||||
const f = await fixture();
|
||||
await start(f);
|
||||
let armed = true;
|
||||
let lostAcknowledgement = false;
|
||||
f.wrap(tx => ({
|
||||
...tx,
|
||||
async appendJournal(payload) {
|
||||
if (stage === 'input' && armed) {
|
||||
armed = false;
|
||||
throw new Error('transient SQL failure');
|
||||
}
|
||||
return tx.appendJournal(payload);
|
||||
},
|
||||
async putBatch(batch) {
|
||||
await tx.putBatch(batch);
|
||||
if (stage === 'batch' && armed) {
|
||||
armed = false;
|
||||
lostAcknowledgement = true;
|
||||
}
|
||||
},
|
||||
}));
|
||||
f.afterCommit(() => {
|
||||
if (lostAcknowledgement) {
|
||||
lostAcknowledgement = false;
|
||||
throw new Error('lost batch acknowledgement');
|
||||
}
|
||||
});
|
||||
f.clock(20);
|
||||
await expect(f.runtime.ingest(paperFrame(2))).rejects.toThrow();
|
||||
const stopped = await f.runtime.status();
|
||||
expect(stopped.active).toBe(false);
|
||||
expect(stage === 'input' ? stopped.pendingInput : stopped.pendingBatch).not.toBeNull();
|
||||
f.clock(200);
|
||||
await f.runtime.ingest(paperFrame(3, 200));
|
||||
await expect(f.runtime.activate({ recoverPending: false })).rejects.toThrow(
|
||||
'recoverPending'
|
||||
);
|
||||
expect(await f.runtime.activate({ recoverPending: true })).toMatchObject({
|
||||
active: true,
|
||||
requiresHistoricalRecovery: false,
|
||||
});
|
||||
expect((await f.snapshot()).owners[0]!.diagnostic.nextDecisionSequence).toBe(1);
|
||||
}
|
||||
);
|
||||
|
||||
test('auxiliary cadence survives restart; known old physical bars dedup while new delayed bars remain visible', async () => {
|
||||
const config = paperConfig();
|
||||
config.policy.observations.push({
|
||||
seriesId: 'X:slow',
|
||||
instrumentId: 'X',
|
||||
intervalMs: 10,
|
||||
staleAfterMs: 100,
|
||||
});
|
||||
config.policy.cadence[0]!.seriesIds = ['X:slow'];
|
||||
config.strategies[0]!.seriesId = 'X:slow';
|
||||
const f = await fixture(config);
|
||||
await start(f);
|
||||
f.clock(20);
|
||||
const fast = paperFrame(2);
|
||||
await f.runtime.ingest(fast);
|
||||
expect((await f.snapshot()).owners[0]!.pendingObservations).toHaveLength(1);
|
||||
const restored = await f.make();
|
||||
await restored.connect({ ...connection, connectionId: 'two' });
|
||||
f.clock(30);
|
||||
await restored.ingest(paperFrame(3, 30, 'two'));
|
||||
await restored.activate({ recoverPending: false });
|
||||
f.clock(40);
|
||||
const slow = paperFrame(4, 40, 'two');
|
||||
slow.observations = [
|
||||
fast.observations[0]!,
|
||||
{
|
||||
...fast.observations[0]!,
|
||||
series_id: 'X:slow',
|
||||
event_time: 20,
|
||||
available_at: 40,
|
||||
source_sequence: 99,
|
||||
},
|
||||
];
|
||||
await restored.ingest(slow);
|
||||
const snapshot = await f.snapshot();
|
||||
expect(snapshot.owners[0]!.diagnostic.observationCount).toBe(2);
|
||||
expect(snapshot.owners[0]!.diagnostic.nextDecisionSequence).toBe(1);
|
||||
expect(snapshot.owners[0]!.diagnostic.state).toMatchObject({ seen: [2, 99] });
|
||||
f.clock(50);
|
||||
const conflict = paperFrame(5, 50, 'two');
|
||||
conflict.observations = [{ ...fast.observations[0]!, volume: parseFinancialDecimal('11') }];
|
||||
await expect(restored.ingest(conflict)).rejects.toThrow('conflicting content');
|
||||
expect((await f.snapshot()).account.checkpoint).toEqual(snapshot.account.checkpoint);
|
||||
});
|
||||
}
|
||||
);
|
||||
Loading…
Add table
Add a link
Reference in a new issue