- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched) - Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations() - Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation - Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims - Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution - Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
522 lines
18 KiB
TypeScript
522 lines
18 KiB
TypeScript
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 '@stock-bot/research/strategy-api';
|
|
import {
|
|
paperActivationSchema,
|
|
paperConnectionSchema,
|
|
paperHaltSchema,
|
|
PaperRuntimeError,
|
|
type PaperConfiguration,
|
|
type PaperConfigurationInput,
|
|
type PaperConnection,
|
|
type PaperFrameInput,
|
|
type PaperReadiness,
|
|
type PaperRuntime,
|
|
} from '@stock-bot/stock-config/paper-runtime';
|
|
import type {
|
|
CanonicalAccount,
|
|
CanonicalExecutionRepository,
|
|
CanonicalJournalEntry,
|
|
CanonicalPaperHost,
|
|
CanonicalTransaction,
|
|
} from '../execution/canonical-paper';
|
|
import { CanonicalPaperExecution } from '../execution/CanonicalPaperExecution';
|
|
import { planPaperFrame, validatePaperConfiguration, validatePaperFrame } from './feed';
|
|
|
|
const fingerprint = (value: unknown) =>
|
|
createHash('sha256').update(canonicalJson(value)).digest('hex');
|
|
function hostState(account: CanonicalAccount): CanonicalPaperHost {
|
|
if (!account.host) {
|
|
throw new PaperRuntimeError('conflict', 'Paper account has no host policy');
|
|
}
|
|
return account.host;
|
|
}
|
|
|
|
function paperHealthReasons(account: CanonicalAccount, now: number): string[] {
|
|
const host = hostState(account);
|
|
const { policy, matching } = host.configuration;
|
|
const reasons: string[] = [];
|
|
if (!host.connection) {
|
|
reasons.push('feed-disconnected');
|
|
}
|
|
if (
|
|
host.lastReceivedAt === null ||
|
|
host.lastAvailableAt === null ||
|
|
now < host.lastReceivedAt ||
|
|
now < host.lastAvailableAt ||
|
|
now - host.lastReceivedAt > policy.maxFeedAgeMs ||
|
|
now - host.lastAvailableAt > policy.maxFeedAgeMs
|
|
) {
|
|
reasons.push('feed-stale');
|
|
}
|
|
for (const series of matching.series) {
|
|
const quote = host.quotes.find(item => item.instrumentId === series.instrumentId);
|
|
if (!quote || now < quote.observedAt || now - quote.observedAt > matching.risk.maxMarkAgeMs) {
|
|
reasons.push(`quote-stale:${series.instrumentId}`);
|
|
}
|
|
const calendar = policy.calendars.find(item => item.instrumentId === series.instrumentId);
|
|
if (!calendar?.sessions.some(session => session.opensAt <= now && now < session.closesAt)) {
|
|
reasons.push(`calendar-uncovered:${series.instrumentId}`);
|
|
}
|
|
}
|
|
if (account.checkpoint.status !== 'Running') {
|
|
reasons.push('native-not-running');
|
|
}
|
|
return reasons;
|
|
}
|
|
|
|
/** Pure diagnostic projection. It never changes activation or persists safety latches. */
|
|
export function projectPaperReadiness(
|
|
account: CanonicalAccount,
|
|
pending: Pick<PaperReadiness, 'pendingInput' | 'pendingBatch'>,
|
|
now: number
|
|
): PaperReadiness {
|
|
const { pendingInput, pendingBatch } = pending;
|
|
const host = hostState(account);
|
|
const reasons = paperHealthReasons(account, now);
|
|
if (host.operatorHalted) {
|
|
reasons.push('operator-halted');
|
|
}
|
|
if (host.diagnostic) {
|
|
reasons.push(host.diagnostic);
|
|
}
|
|
const pendingDecisionSequence = account.pendingDecisionSequence;
|
|
const requiresHistoricalRecovery =
|
|
pendingInput !== null || pendingBatch !== null || pendingDecisionSequence !== null;
|
|
if (requiresHistoricalRecovery) {
|
|
reasons.push('historical-recovery-required');
|
|
}
|
|
return {
|
|
configured: true,
|
|
accountId: account.identity.accountId,
|
|
sourceId: host.configuration.policy.sourceId,
|
|
active: host.active,
|
|
ready: reasons.length === 0,
|
|
operatorHalted: host.operatorHalted,
|
|
connected: host.connection !== null,
|
|
reasons,
|
|
lastReceivedAt: host.lastReceivedAt,
|
|
lastAvailableAt: host.lastAvailableAt,
|
|
requiresHistoricalRecovery,
|
|
pendingInput,
|
|
pendingBatch,
|
|
pendingDecisionSequence,
|
|
nativeStatus: account.checkpoint.status,
|
|
risk: {
|
|
dailyHalted: account.view.risk.dailyHalted,
|
|
drawdownHalted: account.view.risk.drawdownHalted,
|
|
},
|
|
};
|
|
}
|
|
|
|
/** An operational gate around durable custody, never a second financial simulator.
|
|
* Each transaction releases the account lock so a halt can stop the next step. */
|
|
export class CanonicalPaperRuntime implements PaperRuntime {
|
|
private readonly generation = randomUUID();
|
|
private readonly execution: CanonicalPaperExecution;
|
|
private configuration?: PaperConfiguration;
|
|
private readonly now: () => number;
|
|
|
|
constructor(
|
|
private readonly options: {
|
|
repository: CanonicalExecutionRepository;
|
|
deployment?: PaperDeploymentBinding;
|
|
programs: readonly StrategyProgram[];
|
|
now?: () => number;
|
|
publish?: (entries: readonly CanonicalJournalEntry[]) => void | Promise<void>;
|
|
}
|
|
) {
|
|
this.now = options.now ?? Date.now;
|
|
this.execution = new CanonicalPaperExecution({
|
|
repository: options.repository,
|
|
programs: options.programs,
|
|
publish: options.publish,
|
|
control: {
|
|
generation: this.generation,
|
|
guard: account => this.enforceReadinessExpiry(account),
|
|
},
|
|
});
|
|
}
|
|
|
|
async initialize(input: PaperConfigurationInput): Promise<void> {
|
|
if (this.configuration) {
|
|
throw new PaperRuntimeError('conflict', 'Paper runtime is already initialized');
|
|
}
|
|
const configuration = validatePaperConfiguration(input);
|
|
if (
|
|
configuration.strategies.length !== this.options.programs.length ||
|
|
configuration.strategies.some(
|
|
selection =>
|
|
!this.options.programs.some(
|
|
program =>
|
|
program.ownerId === selection.ownerId &&
|
|
program.strategyId === selection.strategyId &&
|
|
program.strategyVersion === selection.strategyVersion &&
|
|
program.seed === selection.seed &&
|
|
program.mode === 'target'
|
|
)
|
|
)
|
|
) {
|
|
throw new PaperRuntimeError(
|
|
'conflict',
|
|
'Paper programs must match immutable configured strategy selections'
|
|
);
|
|
}
|
|
const host: CanonicalPaperHost = {
|
|
version: 1,
|
|
configuration,
|
|
...(this.options.deployment ? { deployment: structuredClone(this.options.deployment) } : {}),
|
|
generation: this.generation,
|
|
active: false,
|
|
operatorHalted: true,
|
|
haltReason: 'Initial operator activation required',
|
|
diagnostic: null,
|
|
connection: null,
|
|
lastReceivedAt: null,
|
|
lastAvailableAt: null,
|
|
lastSequence: null,
|
|
quotes: [],
|
|
quoteHighWater: [],
|
|
frames: {},
|
|
observations: {},
|
|
physicalQuotes: {},
|
|
};
|
|
await this.execution.initialize(configuration.matching, host);
|
|
await this.options.repository.transact(
|
|
configuration.matching.risk.ledger.accountId,
|
|
async tx => {
|
|
if (!tx.account.host) {
|
|
throw new PaperRuntimeError('conflict', 'Paper account has no host policy');
|
|
}
|
|
tx.account.host.generation = this.generation;
|
|
tx.account.host.active = false;
|
|
tx.account.host.connection = null;
|
|
tx.account.host.lastReceivedAt = null;
|
|
tx.account.host.lastSequence = null;
|
|
tx.account.host.quotes = [];
|
|
}
|
|
);
|
|
this.configuration = configuration;
|
|
}
|
|
|
|
private transaction<T>(
|
|
work: (tx: CanonicalTransaction, host: CanonicalPaperHost) => Promise<T>
|
|
): Promise<T> {
|
|
if (!this.configuration) {
|
|
throw new PaperRuntimeError('not-ready', 'Paper runtime is not initialized');
|
|
}
|
|
return this.options.repository.transact(
|
|
this.configuration.matching.risk.ledger.accountId,
|
|
async tx => {
|
|
const host = tx.account.host;
|
|
if (!host || host.generation !== this.generation) {
|
|
throw new PaperRuntimeError('conflict', 'Paper runtime generation is obsolete');
|
|
}
|
|
return work(tx, host);
|
|
}
|
|
);
|
|
}
|
|
|
|
/** Mutates the transaction-owned safety latch; fresh data never reactivates it. */
|
|
private enforceReadinessExpiry(account: CanonicalAccount): boolean {
|
|
const host = hostState(account);
|
|
if (paperHealthReasons(account, this.now()).length && host.active) {
|
|
host.active = false;
|
|
host.diagnostic =
|
|
'Operational readiness expired; fresh feed and operator activation required';
|
|
}
|
|
return host.active && !host.operatorHalted;
|
|
}
|
|
|
|
private async readReadiness(tx: CanonicalTransaction): Promise<PaperReadiness> {
|
|
const now = this.now();
|
|
const pendingInput = (await tx.nextInput())?.id ?? null;
|
|
const pendingBatch = (await tx.nextBatch())?.id ?? null;
|
|
return projectPaperReadiness(tx.account, { pendingInput, pendingBatch }, now);
|
|
}
|
|
|
|
/** A rejected request rolls back its admission transaction. Persist ONLY the
|
|
* freshness latch separately, preserving the original failure if storage is down. */
|
|
private async withFreshnessLatch<T>(work: () => Promise<T>): Promise<T> {
|
|
try {
|
|
return await work();
|
|
} catch (error) {
|
|
try {
|
|
await this.transaction(async tx => {
|
|
this.enforceReadinessExpiry(tx.account);
|
|
});
|
|
} catch {
|
|
// A replacement generation or unavailable repository must not mask the original error.
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
connect(input: PaperConnection): Promise<PaperReadiness> {
|
|
const connection = paperConnectionSchema.parse(input);
|
|
return this.transaction(async (tx, host) => {
|
|
if (connection.sourceId !== host.configuration.policy.sourceId) {
|
|
throw new PaperRuntimeError(
|
|
'invalid-input',
|
|
'Paper source does not match its configured provider'
|
|
);
|
|
}
|
|
this.enforceReadinessExpiry(tx.account);
|
|
if (canonicalJson(connection) !== canonicalJson(host.connection)) {
|
|
host.connection = connection;
|
|
host.active = false;
|
|
host.lastReceivedAt = null;
|
|
host.lastSequence = null;
|
|
host.quotes = [];
|
|
}
|
|
this.enforceReadinessExpiry(tx.account);
|
|
return this.readReadiness(tx);
|
|
});
|
|
}
|
|
|
|
disconnect(input: PaperConnection): Promise<PaperReadiness> {
|
|
const connection = paperConnectionSchema.parse(input);
|
|
return this.transaction(async (tx, host) => {
|
|
if (canonicalJson(connection) === canonicalJson(host.connection)) {
|
|
host.active = false;
|
|
host.connection = null;
|
|
}
|
|
this.enforceReadinessExpiry(tx.account);
|
|
return this.readReadiness(tx);
|
|
});
|
|
}
|
|
|
|
async ingest(input: PaperFrameInput): ReturnType<PaperRuntime['ingest']> {
|
|
return this.withFreshnessLatch(async () => {
|
|
if (!this.configuration) {
|
|
throw new PaperRuntimeError('not-ready', 'Paper runtime is not initialized');
|
|
}
|
|
const frame = validatePaperFrame(this.configuration, input, this.now());
|
|
const digest = fingerprint(frame);
|
|
const frameIdentity = fingerprint(frame.id);
|
|
const receipt = await this.transaction(async (tx, host) => {
|
|
const old = host.frames[frameIdentity];
|
|
if (old) {
|
|
if (old.fingerprint !== digest) {
|
|
throw new PaperRuntimeError('conflict', 'Paper frame ID has conflicting content');
|
|
}
|
|
this.enforceReadinessExpiry(tx.account);
|
|
return { duplicate: true, disposition: old.disposition };
|
|
}
|
|
if (
|
|
!host.connection ||
|
|
host.connection.sourceId !== frame.sourceId ||
|
|
host.connection.connectionId !== frame.connectionId
|
|
) {
|
|
throw new PaperRuntimeError('conflict', 'Paper frame belongs to an inactive connection');
|
|
}
|
|
if (
|
|
(host.lastSequence !== null && frame.sequence <= host.lastSequence) ||
|
|
(host.lastAvailableAt !== null && frame.availableAt <= host.lastAvailableAt)
|
|
) {
|
|
throw new PaperRuntimeError(
|
|
'conflict',
|
|
'Distinct paper frames require increasing sequence and availability time'
|
|
);
|
|
}
|
|
// Compare the OLD health deadline before this fresh frame can change it.
|
|
this.enforceReadinessExpiry(tx.account);
|
|
if (
|
|
host.active &&
|
|
((await tx.nextInput()) ||
|
|
(await tx.nextBatch()) ||
|
|
tx.account.pendingDecisionSequence !== null)
|
|
) {
|
|
throw new PaperRuntimeError(
|
|
'not-ready',
|
|
'Previously admitted paper work requires completion before another frame'
|
|
);
|
|
}
|
|
const observations = frame.observations.filter(observation => {
|
|
const identity = fingerprint([
|
|
observation.series_id,
|
|
observation.event_time,
|
|
observation.source_sequence,
|
|
]);
|
|
const value = fingerprint(observation);
|
|
const known = host.observations[identity];
|
|
if (known && known !== value) {
|
|
throw new PaperRuntimeError(
|
|
'conflict',
|
|
'Physical observation identity has conflicting content'
|
|
);
|
|
}
|
|
return !known;
|
|
});
|
|
for (const quote of frame.quotes) {
|
|
const latest = host.quoteHighWater.find(item => item.instrumentId === quote.instrumentId);
|
|
if (
|
|
latest &&
|
|
(quote.observedAt < latest.observedAt ||
|
|
(quote.observedAt === latest.observedAt &&
|
|
quote.sourceSequence < latest.sourceSequence))
|
|
) {
|
|
throw new PaperRuntimeError(
|
|
'invalid-input',
|
|
'Paper quote regresses the retained physical event time'
|
|
);
|
|
}
|
|
if (
|
|
host.active &&
|
|
this.now() - quote.observedAt > host.configuration.matching.risk.maxMarkAgeMs
|
|
) {
|
|
throw new PaperRuntimeError('invalid-input', 'Admitted paper quote is stale');
|
|
}
|
|
const known =
|
|
host.physicalQuotes[
|
|
fingerprint([quote.instrumentId, quote.observedAt, quote.sourceSequence])
|
|
];
|
|
if (known) {
|
|
throw new PaperRuntimeError(
|
|
'conflict',
|
|
known === fingerprint(quote)
|
|
? 'New paper frame reuses known physical quote liquidity'
|
|
: 'Physical quote identity has conflicting content'
|
|
);
|
|
}
|
|
}
|
|
const disposition = host.active ? ('admitted' as const) : ('health-only' as const);
|
|
host.lastReceivedAt = this.now();
|
|
host.lastAvailableAt = frame.availableAt;
|
|
host.lastSequence = frame.sequence;
|
|
for (const quote of frame.quotes) {
|
|
for (const clocks of [host.quotes, host.quoteHighWater]) {
|
|
const oldQuote = clocks.find(item => item.instrumentId === quote.instrumentId);
|
|
if (!oldQuote) {
|
|
clocks.push({
|
|
instrumentId: quote.instrumentId,
|
|
observedAt: quote.observedAt,
|
|
sourceSequence: quote.sourceSequence,
|
|
});
|
|
} else if (
|
|
quote.observedAt > oldQuote.observedAt ||
|
|
(quote.observedAt === oldQuote.observedAt &&
|
|
quote.sourceSequence > oldQuote.sourceSequence)
|
|
) {
|
|
Object.assign(oldQuote, {
|
|
observedAt: quote.observedAt,
|
|
sourceSequence: quote.sourceSequence,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
if (disposition === 'admitted') {
|
|
await this.execution.enqueueFrame(
|
|
tx,
|
|
planPaperFrame(host.configuration, { ...frame, observations }, tx.account)
|
|
);
|
|
}
|
|
for (const observation of frame.observations) {
|
|
host.observations[
|
|
fingerprint([
|
|
observation.series_id,
|
|
observation.event_time,
|
|
observation.source_sequence,
|
|
])
|
|
] = fingerprint(observation);
|
|
}
|
|
for (const quote of frame.quotes) {
|
|
host.physicalQuotes[
|
|
fingerprint([quote.instrumentId, quote.observedAt, quote.sourceSequence])
|
|
] = fingerprint(quote);
|
|
}
|
|
host.frames[frameIdentity] = { fingerprint: digest, disposition };
|
|
return { duplicate: false, disposition };
|
|
});
|
|
// A retry retains its first disposition and never replays an inactive probe.
|
|
if (!receipt.duplicate && receipt.disposition === 'admitted') {
|
|
await this.drain();
|
|
}
|
|
return { ...receipt, readiness: await this.status() };
|
|
});
|
|
}
|
|
|
|
private async drain(): Promise<void> {
|
|
try {
|
|
await this.execution.drain();
|
|
} catch (error) {
|
|
await this.transaction(async (_tx, host) => {
|
|
host.active = false;
|
|
host.diagnostic = error instanceof Error ? error.message : String(error);
|
|
}).catch(() => {
|
|
/* A replacement generation alone controls its account. */
|
|
});
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async activate(input: { recoverPending: boolean }): Promise<PaperReadiness> {
|
|
return this.withFreshnessLatch(async () => {
|
|
const { recoverPending } = paperActivationSchema.parse(input);
|
|
await this.transaction(async (tx, host) => {
|
|
this.enforceReadinessExpiry(tx.account);
|
|
const reasons = paperHealthReasons(tx.account, this.now());
|
|
if (reasons.length) {
|
|
throw new PaperRuntimeError(
|
|
'not-ready',
|
|
`Paper activation unavailable: ${reasons.join(', ')}`
|
|
);
|
|
}
|
|
if (
|
|
!recoverPending &&
|
|
((await tx.nextInput()) ||
|
|
(await tx.nextBatch()) ||
|
|
tx.account.pendingDecisionSequence !== null)
|
|
) {
|
|
throw new PaperRuntimeError(
|
|
'not-ready',
|
|
'Historical admitted work requires explicit recoverPending: true'
|
|
);
|
|
}
|
|
host.active = true;
|
|
host.operatorHalted = false;
|
|
host.haltReason = null;
|
|
host.diagnostic = null;
|
|
});
|
|
await this.drain();
|
|
const result = await this.status();
|
|
if (!result.active || !result.ready || result.requiresHistoricalRecovery) {
|
|
await this.transaction(async (_tx, host) => {
|
|
host.active = false;
|
|
});
|
|
throw new PaperRuntimeError(
|
|
'not-ready',
|
|
'Paper activation stopped before recovery and fresh readiness completed'
|
|
);
|
|
}
|
|
return result;
|
|
});
|
|
}
|
|
|
|
halt(reason: string): Promise<PaperReadiness> {
|
|
const parsed = paperHaltSchema.parse({ reason });
|
|
return this.transaction(async (tx, host) => {
|
|
host.active = false;
|
|
host.operatorHalted = true;
|
|
host.haltReason = parsed.reason;
|
|
this.enforceReadinessExpiry(tx.account);
|
|
return this.readReadiness(tx);
|
|
});
|
|
}
|
|
|
|
/** A status poll commits expired activation before returning its diagnostic projection. */
|
|
status(): Promise<PaperReadiness> {
|
|
return this.transaction(async tx => {
|
|
this.enforceReadinessExpiry(tx.account);
|
|
return this.readReadiness(tx);
|
|
});
|
|
}
|
|
|
|
async shutdown(): Promise<void> {
|
|
await this.transaction(async (_tx, host) => {
|
|
host.active = false;
|
|
host.connection = null;
|
|
});
|
|
}
|
|
}
|