563 lines
20 KiB
TypeScript
563 lines
20 KiB
TypeScript
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
import { createHash } from 'node:crypto';
|
|
import { stageFinancialTransaction } from '@stock-bot/engine';
|
|
import { canonicalJson } from '../canonical-json';
|
|
import {
|
|
canonicalMatchingConfigSchema,
|
|
financialTransactionRequestSchema,
|
|
matchingCommandSchema,
|
|
parseFinancialTransactionResult,
|
|
type CanonicalExecutionIdentity,
|
|
type CanonicalMatchingConfig,
|
|
type FinancialTransactionRequest,
|
|
} from '../contracts/canonical-execution';
|
|
import type { StrategyProgram } from '../contracts/canonical-strategy';
|
|
import { nativeAdmissionOrders, type DecisionContext } from '../contracts/native-replay';
|
|
import {
|
|
freeze,
|
|
increment,
|
|
initialStrategyDiagnostic,
|
|
metadataSchema,
|
|
ownerAdmissionFeedback,
|
|
stageStrategyDecision,
|
|
stateCopy,
|
|
type Metadata,
|
|
} from '../strategies/strategy-decision';
|
|
import {
|
|
canonicalPaperInputSchema,
|
|
compareEventKeys,
|
|
type CanonicalAccount,
|
|
type CanonicalExecutionRepository,
|
|
type CanonicalJournalEntry,
|
|
type CanonicalOwner,
|
|
type CanonicalPaperHost,
|
|
type CanonicalPaperInput,
|
|
type CanonicalTransaction,
|
|
} from './canonical-paper';
|
|
import { ExecutionConflictError } from './repository';
|
|
|
|
const callback = new AsyncLocalStorage<boolean>();
|
|
function outsideCallback() {
|
|
if (callback.getStore()) {
|
|
throw new Error('Canonical execution I/O is forbidden during a strategy callback');
|
|
}
|
|
}
|
|
function stage(request: FinancialTransactionRequest) {
|
|
const input = financialTransactionRequestSchema.parse(request);
|
|
return parseFinancialTransactionResult(
|
|
stageFinancialTransaction(JSON.stringify(input)),
|
|
input.identity
|
|
);
|
|
}
|
|
function diagnosticFailure(account: CanonicalAccount): string | undefined {
|
|
return typeof account.checkpoint.status === 'object'
|
|
? account.checkpoint.status.Failed.diagnostic
|
|
: undefined;
|
|
}
|
|
|
|
/** Trusted host only. S04 supplies normalized feeds/session scheduling; this class
|
|
* never connects brokers or activates paper execution. Rust owns every economic transition. */
|
|
export class CanonicalPaperExecution {
|
|
private identity?: CanonicalExecutionIdentity;
|
|
private readonly programs: Map<string, Metadata & { decide: StrategyProgram['decide'] }>;
|
|
private readonly initialOwners: CanonicalOwner[];
|
|
|
|
constructor(
|
|
private readonly options: {
|
|
repository: CanonicalExecutionRepository;
|
|
programs: readonly StrategyProgram[];
|
|
/** Best effort after SQL commit. Recover missed notifications using journal(sequence). */
|
|
publish?: (entries: readonly CanonicalJournalEntry[]) => void | Promise<void>;
|
|
/** Only the trusted paper runtime owns this generation and operational gate. */
|
|
control?: { generation: string; guard(account: CanonicalAccount): boolean };
|
|
}
|
|
) {
|
|
this.programs = new Map();
|
|
this.initialOwners = options.programs
|
|
.map((program): CanonicalOwner => {
|
|
const { ownerId, strategyId, strategyVersion, mode, seed } = program;
|
|
const metadata = metadataSchema.parse({ ownerId, strategyId, strategyVersion, mode, seed });
|
|
const decide = program.decide;
|
|
if (this.programs.has(ownerId) || typeof decide !== 'function') {
|
|
throw new Error('Canonical programs require unique owners and synchronous callable code');
|
|
}
|
|
this.programs.set(ownerId, { ...metadata, decide });
|
|
const initialState = stateCopy(program.initialState);
|
|
return {
|
|
version: 1,
|
|
definition: { ...metadata, initialState },
|
|
cursor: 0,
|
|
diagnostic: initialStrategyDiagnostic(metadata, initialState),
|
|
pendingObservations: [],
|
|
};
|
|
})
|
|
.sort((a, b) =>
|
|
Buffer.compare(Buffer.from(a.definition.ownerId), Buffer.from(b.definition.ownerId))
|
|
);
|
|
// Program closures are trusted code. Metadata and state are detached now, before any await.
|
|
freeze(this.initialOwners);
|
|
}
|
|
|
|
initialize(configuration: CanonicalMatchingConfig, host?: CanonicalPaperHost): Promise<void> {
|
|
outsideCallback();
|
|
const config = canonicalMatchingConfigSchema.parse(configuration);
|
|
const identity = {
|
|
sessionId: config.risk.ledger.sessionId,
|
|
accountId: config.risk.ledger.accountId,
|
|
};
|
|
if (this.identity && canonicalJson(this.identity) !== canonicalJson(identity)) {
|
|
throw new Error('A canonical host cannot change account identity');
|
|
}
|
|
if (
|
|
config.owners.length !== this.programs.size ||
|
|
config.owners.some(
|
|
owner => this.programs.get(owner.ownerId)?.mode !== owner.mode.toLowerCase()
|
|
)
|
|
) {
|
|
throw new Error('Programs must exactly match configured owners and modes');
|
|
}
|
|
const result = stage({ version: 1, kind: 'initialize', identity, config });
|
|
const initial: CanonicalAccount = {
|
|
kind: 'canonical-paper',
|
|
version: 1,
|
|
identity,
|
|
definitions: this.initialOwners.map(owner => owner.definition),
|
|
checkpoint: result.checkpoint,
|
|
view: result.view,
|
|
inputSequence: 0,
|
|
journalSequence: 0,
|
|
observed: 0,
|
|
pendingDecisionSequence: null,
|
|
latestObservations: [],
|
|
...(host ? { host } : {}),
|
|
};
|
|
return this.options.repository.initialize(initial, this.initialOwners).then(() => {
|
|
this.identity = identity;
|
|
});
|
|
}
|
|
|
|
private accountId() {
|
|
if (!this.identity) {
|
|
throw new Error('Canonical host must be initialized before use');
|
|
}
|
|
return this.identity.accountId;
|
|
}
|
|
|
|
/** Invalid trusted queued commands stay pending with a drain diagnostic. No skip,
|
|
* restamping or automatic repair can silently alter the retained tape. */
|
|
enqueue(value: CanonicalPaperInput): Promise<boolean> {
|
|
outsideCallback();
|
|
const id = this.accountId();
|
|
return this.options.repository.transact(id, async tx => {
|
|
if (tx.account.host) {
|
|
throw new ExecutionConflictError(
|
|
'Controlled paper accounts accept only atomic producer frames'
|
|
);
|
|
}
|
|
return this.enqueueInput(tx, value);
|
|
});
|
|
}
|
|
|
|
/** The runtime calls this while holding the account lock for the whole frame. */
|
|
async enqueueFrame(
|
|
tx: CanonicalTransaction,
|
|
inputs: readonly CanonicalPaperInput[]
|
|
): Promise<void> {
|
|
outsideCallback();
|
|
if (
|
|
tx.account.identity.accountId !== this.accountId() ||
|
|
!tx.account.host ||
|
|
!this.allowed(tx.account)
|
|
) {
|
|
throw new ExecutionConflictError('Paper frame admission requires an active owned runtime');
|
|
}
|
|
for (const input of inputs) {
|
|
await this.enqueueInput(tx, input);
|
|
}
|
|
}
|
|
|
|
private allowed(account: CanonicalAccount): boolean {
|
|
if (!account.host) {
|
|
return true;
|
|
}
|
|
const control = this.options.control;
|
|
if (!control || account.host.generation !== control.generation) {
|
|
throw new ExecutionConflictError('Canonical paper runtime generation is obsolete');
|
|
}
|
|
return control.guard(account) && account.host.active && !account.host.operatorHalted;
|
|
}
|
|
|
|
private async enqueueInput(
|
|
tx: CanonicalTransaction,
|
|
value: CanonicalPaperInput
|
|
): Promise<boolean> {
|
|
const input = canonicalPaperInputSchema.parse(value);
|
|
if (input.command.body.kind === 'submit') {
|
|
throw new Error('Strategy submissions require a durable all-owner decision batch');
|
|
}
|
|
const decision = input.decision;
|
|
if (
|
|
decision &&
|
|
((decision.key.phase !== 'Decision' &&
|
|
!(
|
|
input.command.body.kind === 'execute' &&
|
|
input.command.body.observation.kind === 'quote' &&
|
|
compareEventKeys(decision.key, input.command.key) === 0
|
|
)) ||
|
|
compareEventKeys(decision.key, input.command.key) < 0 ||
|
|
decision.commandId === input.command.commandId ||
|
|
input.command.body.kind === 'finish' ||
|
|
new Set(decision.ownerIds).size !== decision.ownerIds.length ||
|
|
decision.ownerIds.some(owner => !this.programs.has(owner)))
|
|
) {
|
|
throw new Error('Invalid canonical decision schedule or owner set');
|
|
}
|
|
if (
|
|
input.observations.some(
|
|
observation =>
|
|
observation.available_at > input.command.key.at ||
|
|
observation.event_time > observation.available_at ||
|
|
observation.interval_end > observation.available_at ||
|
|
observation.interval_start > observation.interval_end
|
|
)
|
|
) {
|
|
throw new Error('Observation is unavailable at its admitted input time');
|
|
}
|
|
const fingerprint = createHash('sha256').update(canonicalJson(input)).digest('hex');
|
|
const old = await tx.getInput(input.command.commandId);
|
|
if (old) {
|
|
if (old.fingerprint !== fingerprint) {
|
|
throw new ExecutionConflictError('Conflicting canonical market input identity');
|
|
}
|
|
return false;
|
|
}
|
|
if (tx.account.checkpoint.status !== 'Running') {
|
|
throw new Error(
|
|
`Canonical account is terminal: ${diagnosticFailure(tx.account) ?? tx.account.checkpoint.status}`
|
|
);
|
|
}
|
|
tx.account.inputSequence = increment(tx.account.inputSequence);
|
|
await tx.putInput({
|
|
version: 1,
|
|
id: input.command.commandId,
|
|
sequence: tx.account.inputSequence,
|
|
fingerprint,
|
|
status: 'pending',
|
|
input,
|
|
});
|
|
return true;
|
|
}
|
|
|
|
private async persist(
|
|
tx: CanonicalTransaction,
|
|
command: FinancialTransactionRequest & { kind: 'apply' }
|
|
) {
|
|
const result = stage(command);
|
|
tx.account.checkpoint = result.checkpoint;
|
|
tx.account.view = result.view;
|
|
const entries: CanonicalJournalEntry[] = [];
|
|
if (!result.outcome?.replayed) {
|
|
for (const fact of result.journal) {
|
|
entries.push(
|
|
await tx.appendJournal({ kind: 'effect', commandId: command.command.commandId, fact })
|
|
);
|
|
}
|
|
entries.push(
|
|
await tx.appendJournal({
|
|
kind: 'command',
|
|
command: matchingCommandSchema.parse(command.command),
|
|
outcome: result.outcome,
|
|
view: result.view,
|
|
})
|
|
);
|
|
}
|
|
return { result, entries };
|
|
}
|
|
|
|
private applyRequest(
|
|
account: CanonicalAccount,
|
|
command: CanonicalPaperInput['command']
|
|
): FinancialTransactionRequest & { kind: 'apply' } {
|
|
return {
|
|
version: 1,
|
|
kind: 'apply',
|
|
identity: account.identity,
|
|
checkpoint: account.checkpoint,
|
|
command,
|
|
};
|
|
}
|
|
|
|
private async dispatch(
|
|
tx: CanonicalTransaction,
|
|
batch: NonNullable<Awaited<ReturnType<CanonicalTransaction['nextBatch']>>>
|
|
) {
|
|
const { result, entries } = await this.persist(
|
|
tx,
|
|
this.applyRequest(tx.account, batch.command)
|
|
);
|
|
const failure = diagnosticFailure(tx.account);
|
|
await tx.putBatch({ ...batch, status: failure ? 'failed' : 'dispatched' });
|
|
if (!failure) {
|
|
if (
|
|
!result.outcome ||
|
|
result.outcome.status !== 'Running' ||
|
|
batch.command.body.kind !== 'submit'
|
|
) {
|
|
throw new Error('Unexpected canonical decision acknowledgement');
|
|
}
|
|
const orders = nativeAdmissionOrders(result.outcome.effects);
|
|
const decisions = batch.command.body.decisions;
|
|
if (
|
|
orders.some(
|
|
order =>
|
|
!decisions.some(decision => decision.decision.ownerId === order.order.decision.ownerId)
|
|
)
|
|
) {
|
|
throw new Error('Native admission feedback belongs to an owner outside the batch');
|
|
}
|
|
for (const owner of await tx.owners()) {
|
|
const decision = decisions.find(item => item.decision.ownerId === owner.definition.ownerId);
|
|
if (!decision) {
|
|
continue;
|
|
}
|
|
owner.diagnostic.previousAdmission = ownerAdmissionFeedback(
|
|
decision.decision,
|
|
result.outcome.revision,
|
|
orders
|
|
);
|
|
await tx.putOwner(owner);
|
|
}
|
|
}
|
|
return { worked: true, entries, failure };
|
|
}
|
|
|
|
private async decide(tx: CanonicalTransaction, sequence: number) {
|
|
const row = (await tx.journal(sequence - 1))[0];
|
|
if (row?.sequence !== sequence || row.payload.kind !== 'decision') {
|
|
throw new Error('Missing durable canonical decision context');
|
|
}
|
|
const payload = row.payload;
|
|
const context = freeze(payload.context);
|
|
if (
|
|
context.view.admissionRevision !== tx.account.checkpoint.revision ||
|
|
context.barrier.revision !== tx.account.checkpoint.revision ||
|
|
canonicalJson(context.view) !== canonicalJson(tx.account.view) ||
|
|
context.barrier.observation_count !== tx.account.observed
|
|
) {
|
|
throw new Error('Durable decision context no longer matches the financial snapshot');
|
|
}
|
|
const owners = await tx.owners();
|
|
const decisions = [];
|
|
for (const ownerId of context.barrier.owner_ids) {
|
|
const owner = owners.find(item => item.definition.ownerId === ownerId);
|
|
const program = this.programs.get(ownerId);
|
|
if (!owner || !program) {
|
|
throw new Error('Missing durable strategy owner');
|
|
}
|
|
const staged = callback.run(true, () =>
|
|
stageStrategyDecision(
|
|
tx.account.identity.sessionId,
|
|
program,
|
|
freeze(owner.diagnostic),
|
|
freeze(owner.pendingObservations),
|
|
context as DecisionContext
|
|
)
|
|
);
|
|
await tx.putOwner({
|
|
...owner,
|
|
diagnostic: staged.diagnostic,
|
|
pendingObservations: [],
|
|
cursor: sequence,
|
|
});
|
|
decisions.push(staged.decision);
|
|
}
|
|
await tx.putBatch({
|
|
version: 1,
|
|
id: payload.commandId,
|
|
sequence,
|
|
status: 'pending',
|
|
command: {
|
|
commandId: payload.commandId,
|
|
key: payload.key,
|
|
body: { kind: 'submit', decisions },
|
|
},
|
|
});
|
|
tx.account.pendingDecisionSequence = null;
|
|
return { worked: true, entries: [] as CanonicalJournalEntry[], failure: undefined };
|
|
}
|
|
|
|
private context(
|
|
tx: CanonicalTransaction,
|
|
input: NonNullable<CanonicalPaperInput['decision']>
|
|
): DecisionContext {
|
|
const series =
|
|
tx.account.host?.configuration.policy.observations ?? tx.account.checkpoint.config.series;
|
|
if (
|
|
input.inputs.length !== series.length ||
|
|
new Set(input.inputs.map(item => item.series_id)).size !== series.length ||
|
|
input.inputs.some(item => !series.some(configured => configured.seriesId === item.series_id))
|
|
) {
|
|
throw new Error('Decision availability must describe every configured series exactly once');
|
|
}
|
|
for (const item of input.inputs) {
|
|
const latest = tx.account.latestObservations.find(
|
|
observation => observation.series_id === item.series_id
|
|
);
|
|
const expected = !latest
|
|
? 'Missing'
|
|
: {
|
|
[input.key.at - latest.event_time >
|
|
(tx.account.host?.configuration.policy.observations.find(
|
|
series => series.seriesId === item.series_id
|
|
)?.staleAfterMs ?? tx.account.checkpoint.config.risk.maxMarkAgeMs)
|
|
? 'Stale'
|
|
: 'Fresh']: { event_time: latest.event_time, available_at: latest.available_at },
|
|
};
|
|
if (
|
|
canonicalJson(item.availability) !== canonicalJson(expected) ||
|
|
(latest && latest.available_at > input.key.at)
|
|
) {
|
|
throw new Error('Decision availability does not match the committed observation prefix');
|
|
}
|
|
}
|
|
return {
|
|
type: 'decisionBatch',
|
|
barrier: {
|
|
barrier_id: input.barrierId,
|
|
at: input.key.at,
|
|
revision: tx.account.view.admissionRevision,
|
|
owner_ids: [...input.ownerIds].sort((a, b) =>
|
|
Buffer.compare(Buffer.from(a), Buffer.from(b))
|
|
),
|
|
observation_count: tx.account.observed,
|
|
inputs: input.inputs,
|
|
},
|
|
view: tx.account.view,
|
|
};
|
|
}
|
|
|
|
private async consume(
|
|
tx: CanonicalTransaction,
|
|
input: NonNullable<Awaited<ReturnType<CanonicalTransaction['nextInput']>>>
|
|
) {
|
|
const { result, entries } = await this.persist(
|
|
tx,
|
|
this.applyRequest(tx.account, input.input.command)
|
|
);
|
|
const failure = diagnosticFailure(tx.account);
|
|
if (!result.outcome?.replayed && !failure) {
|
|
const observations = input.input.observations;
|
|
for (const observation of observations) {
|
|
if (
|
|
!(
|
|
tx.account.host?.configuration.policy.observations ??
|
|
tx.account.checkpoint.config.series
|
|
).some(
|
|
series =>
|
|
series.seriesId === observation.series_id &&
|
|
series.instrumentId === observation.instrument_id
|
|
)
|
|
) {
|
|
throw new Error('Published observation is outside configured series');
|
|
}
|
|
const index = tx.account.latestObservations.findIndex(
|
|
item => item.series_id === observation.series_id
|
|
);
|
|
const old = tx.account.latestObservations[index];
|
|
if (!old) {
|
|
tx.account.latestObservations.push(observation);
|
|
} else if (
|
|
observation.event_time > old.event_time ||
|
|
(observation.event_time === old.event_time &&
|
|
observation.source_sequence > old.source_sequence)
|
|
) {
|
|
tx.account.latestObservations[index] = observation;
|
|
}
|
|
}
|
|
tx.account.observed = increment(tx.account.observed, observations.length);
|
|
for (const owner of await tx.owners()) {
|
|
await tx.putOwner({
|
|
...owner,
|
|
pendingObservations: [...owner.pendingObservations, ...observations],
|
|
});
|
|
}
|
|
if (input.input.decision) {
|
|
const context = this.context(tx, input.input.decision);
|
|
const row = await tx.appendJournal({
|
|
kind: 'decision',
|
|
commandId: input.input.decision.commandId,
|
|
key: input.input.decision.key,
|
|
context,
|
|
});
|
|
tx.account.pendingDecisionSequence = row.sequence;
|
|
entries.push(row);
|
|
}
|
|
}
|
|
await tx.putInput({ ...input, status: 'applied' });
|
|
return { worked: true, entries, failure };
|
|
}
|
|
|
|
drain(): Promise<void> {
|
|
outsideCallback();
|
|
const id = this.accountId();
|
|
return (async () => {
|
|
for (;;) {
|
|
const step = await this.options.repository.transact(id, async tx => {
|
|
if (!this.allowed(tx.account)) {
|
|
return { worked: false, entries: [], failure: undefined };
|
|
}
|
|
const failure = diagnosticFailure(tx.account);
|
|
if (failure) {
|
|
return { worked: false, entries: [], failure };
|
|
}
|
|
const batch = await tx.nextBatch();
|
|
if (batch) {
|
|
return this.dispatch(tx, batch);
|
|
}
|
|
if (tx.account.pendingDecisionSequence !== null) {
|
|
return this.decide(tx, tx.account.pendingDecisionSequence);
|
|
}
|
|
const input = await tx.nextInput();
|
|
return input
|
|
? this.consume(tx, input)
|
|
: { worked: false, entries: [], failure: undefined };
|
|
});
|
|
if (step.entries.length) {
|
|
try {
|
|
await this.options.publish?.(freeze(step.entries) as readonly CanonicalJournalEntry[]);
|
|
} catch {
|
|
// Finance already committed. Stable journal sequences recover notification gaps.
|
|
}
|
|
}
|
|
if (step.failure) {
|
|
throw new Error(`Canonical account failed: ${step.failure}`);
|
|
}
|
|
if (!step.worked) {
|
|
return;
|
|
}
|
|
}
|
|
})();
|
|
}
|
|
|
|
snapshot() {
|
|
outsideCallback();
|
|
return this.options.repository.transact(this.accountId(), async tx => ({
|
|
account: structuredClone(tx.account),
|
|
owners: await tx.owners(),
|
|
}));
|
|
}
|
|
journal(after = 0) {
|
|
outsideCallback();
|
|
return this.options.repository.transact(this.accountId(), tx => tx.journal(after));
|
|
}
|
|
getRecoveryStatus() {
|
|
outsideCallback();
|
|
return this.options.repository.transact(this.accountId(), async tx => ({
|
|
status: tx.account.checkpoint.status,
|
|
pendingDecisionSequence: tx.account.pendingDecisionSequence,
|
|
pendingBatch: (await tx.nextBatch())?.id ?? null,
|
|
pendingInput: (await tx.nextInput())?.id ?? null,
|
|
journalSequence: tx.account.journalSequence,
|
|
}));
|
|
}
|
|
}
|