feat(execution): preserve durable recovery on canonical Rust core

This commit is contained in:
Boki 2026-10-23 15:58:44 -04:00
parent 5e9655de0b
commit c01e96e4dd
27 changed files with 3644 additions and 182 deletions

View file

@ -0,0 +1,518 @@
import { AsyncLocalStorage } from 'node:async_hooks';
import { createHash } from 'node:crypto';
import { stageFinancialTransaction } from '@stock-bot/engine';
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,
metadataSchema,
stageStrategyDecision,
stateCopy,
type Metadata,
} from '../strategies/strategy-decision';
import {
canonicalPaperInputSchema,
compareEventKeys,
type CanonicalAccount,
type CanonicalExecutionRepository,
type CanonicalJournalEntry,
type CanonicalOwner,
type CanonicalPaperInput,
type CanonicalTransaction,
} from './canonical-paper';
import { ExecutionConflictError } from './repository';
import { canonicalJson } from './strategy-recovery';
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>;
}
) {
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: {
ownerId,
strategyId,
strategyVersion,
nextDecisionSequence: 0,
state: stateCopy(initialState),
rng: { algorithm: 'lcg32-v1', seed, state: seed, draws: 0 },
observationCount: 0,
previousAdmission: null,
},
pendingObservations: [],
};
})
.sort((a, b) => (a.definition.ownerId < b.definition.ownerId ? -1 : 1));
// Program closures are trusted code. Metadata and state are detached now, before any await.
freeze(this.initialOwners);
}
initialize(configuration: CanonicalMatchingConfig): 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: [],
};
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();
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');
return this.options.repository.transact(id, async tx => {
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 = {
decision: decision.decision,
revision: result.outcome.revision,
orders: orders
.filter(order => order.order.decision.ownerId === owner.definition.ownerId)
.map(order => ({
orderId: order.order.orderId,
instrumentId: order.order.instrumentId,
decision: order.order.decision,
status: order.status,
})),
};
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.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.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(),
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.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 => {
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,
}));
}
}

View file

@ -0,0 +1,260 @@
import { increment } from '../strategies/strategy-decision';
import {
canonicalAccountSchema,
canonicalBatchSchema,
canonicalJournalSchema,
canonicalOwnerSchema,
canonicalStoredInputSchema,
type CanonicalAccount,
type CanonicalExecutionRepository,
type CanonicalOwner,
type CanonicalPostgres,
type CanonicalTransaction,
} from './canonical-paper';
import { ExecutionConflictError } from './repository';
import { canonicalJson } from './strategy-recovery';
function accountState(raw: unknown): CanonicalAccount {
const result = canonicalAccountSchema.safeParse(raw);
if (!result.success) {
throw new ExecutionConflictError(
'Incompatible execution snapshot; use an explicit migration or a new canonical account ID'
);
}
const account = result.data;
const ledger = account.checkpoint.config.risk.ledger;
const portfolio = account.view.portfolio;
if (
account.identity.sessionId !== ledger.sessionId ||
account.identity.accountId !== ledger.accountId ||
portfolio.sessionId !== ledger.sessionId ||
portfolio.accountId !== ledger.accountId ||
portfolio.baseCurrency !== ledger.baseCurrency ||
portfolio.reserveOwnerId !== ledger.reserveOwnerId ||
account.view.admissionRevision !== account.checkpoint.revision
) {
throw new ExecutionConflictError('Canonical envelope identity or revision mismatch');
}
return account;
}
/** Same account row lock as legacy custody; no transaction-local native state escapes. */
export class PostgresCanonicalExecutionRepository implements CanonicalExecutionRepository {
constructor(private readonly postgres: CanonicalPostgres) {}
async initialize(initial: CanonicalAccount, owners: CanonicalOwner[]) {
const expected = canonicalAccountSchema.parse(initial);
await this.postgres.transaction(async client => {
const inserted = await client.query(
'INSERT INTO simulation_accounts (id,state) VALUES ($1,$2::jsonb) ON CONFLICT (id) DO NOTHING RETURNING id',
[expected.identity.accountId, JSON.stringify(expected)]
);
const row = await client.query(
'SELECT state FROM simulation_accounts WHERE id = $1 FOR UPDATE',
[expected.identity.accountId]
);
const account = accountState(row.rows[0].state);
if (
canonicalJson({
identity: account.identity,
config: account.checkpoint.config,
definitions: account.definitions,
}) !==
canonicalJson({
identity: expected.identity,
config: expected.checkpoint.config,
definitions: expected.definitions,
})
) {
throw new ExecutionConflictError(
'Canonical account configuration or strategy definition changed; use an explicit migration or a new account ID'
);
}
if (inserted.rows.length) {
for (const owner of owners) {
const parsed = canonicalOwnerSchema.parse(owner);
await client.query(
'INSERT INTO simulation_strategy_checkpoints (account_id,strategy_id,payload) VALUES ($1,$2,$3::jsonb)',
[account.identity.accountId, parsed.definition.ownerId, JSON.stringify(parsed)]
);
}
}
const saved = await client.query(
'SELECT payload FROM simulation_strategy_checkpoints WHERE account_id = $1',
[account.identity.accountId]
);
this.validateOwners(
account,
saved.rows.map(row => canonicalOwnerSchema.parse(row.payload))
);
});
}
private validateOwners(account: CanonicalAccount, owners: CanonicalOwner[]) {
if (
owners.length !== account.definitions.length ||
new Set(owners.map(owner => owner.definition.ownerId)).size !== owners.length
) {
throw new ExecutionConflictError('Missing or duplicate canonical strategy checkpoints');
}
for (const owner of owners) {
const definition = account.definitions.find(
item => item.ownerId === owner.definition.ownerId
);
const diagnostic = owner.diagnostic;
if (
canonicalJson(definition) !== canonicalJson(owner.definition) ||
diagnostic.ownerId !== owner.definition.ownerId ||
diagnostic.strategyId !== owner.definition.strategyId ||
diagnostic.strategyVersion !== owner.definition.strategyVersion ||
diagnostic.rng.seed !== owner.definition.seed ||
diagnostic.observationCount + owner.pendingObservations.length !== account.observed ||
owner.cursor > account.journalSequence
) {
throw new ExecutionConflictError(
'Canonical strategy checkpoint definition or observation cursor mismatch'
);
}
}
}
transact<T>(accountId: string, work: (tx: CanonicalTransaction) => Promise<T>): Promise<T> {
return this.postgres.transaction(async client => {
const locked = await client.query(
'SELECT state FROM simulation_accounts WHERE id = $1 FOR UPDATE',
[accountId]
);
if (!locked.rows[0]) {
throw new Error('Canonical execution account is not initialized');
}
const account = accountState(locked.rows[0].state);
if (account.identity.accountId !== accountId) {
throw new ExecutionConflictError('Canonical account identity mismatch');
}
const owners = async () => {
const result = await client.query(
'SELECT payload FROM simulation_strategy_checkpoints WHERE account_id = $1 ORDER BY strategy_id COLLATE "C"',
[accountId]
);
return result.rows.map(row => canonicalOwnerSchema.parse(row.payload));
};
this.validateOwners(account, await owners());
const readInput = async (id: string) => {
const result = await client.query(
'SELECT payload FROM simulation_market_inputs WHERE account_id = $1 AND id = $2',
[accountId, id]
);
return result.rows[0]
? canonicalStoredInputSchema.parse(result.rows[0].payload)
: undefined;
};
const result = await work({
account,
owners,
async putOwner(value) {
const owner = canonicalOwnerSchema.parse(value);
await client.query(
`INSERT INTO simulation_strategy_checkpoints (account_id,strategy_id,payload) VALUES ($1,$2,$3::jsonb)
ON CONFLICT (account_id,strategy_id) DO UPDATE SET payload = EXCLUDED.payload`,
[accountId, owner.definition.ownerId, JSON.stringify(owner)]
);
},
getInput: readInput,
async nextInput() {
const result = await client.query(
"SELECT payload FROM simulation_market_inputs WHERE account_id = $1 AND status = 'pending' ORDER BY sequence LIMIT 1",
[accountId]
);
return result.rows[0]
? canonicalStoredInputSchema.parse(result.rows[0].payload)
: undefined;
},
async putInput(value) {
const input = canonicalStoredInputSchema.parse(value);
const old = await readInput(input.id);
if (
old &&
(old.fingerprint !== input.fingerprint ||
old.sequence !== input.sequence ||
canonicalJson(old.input) !== canonicalJson(input.input) ||
(old.status === 'applied' && input.status !== 'applied'))
) {
throw new ExecutionConflictError('Conflicting canonical market input');
}
await client.query(
`INSERT INTO simulation_market_inputs (account_id,id,sequence,status,payload) VALUES ($1,$2,$3,$4,$5::jsonb)
ON CONFLICT (account_id,id) DO UPDATE SET status = EXCLUDED.status,payload = EXCLUDED.payload`,
[accountId, input.id, input.sequence, input.status, JSON.stringify(input)]
);
},
async nextBatch() {
const result = await client.query(
"SELECT payload FROM simulation_canonical_intents WHERE account_id = $1 AND status = 'pending' ORDER BY sequence LIMIT 1",
[accountId]
);
return result.rows[0] ? canonicalBatchSchema.parse(result.rows[0].payload) : undefined;
},
async putBatch(value) {
const batch = canonicalBatchSchema.parse(value);
if (batch.command.body.kind !== 'submit' || batch.id !== batch.command.commandId) {
throw new ExecutionConflictError(
'Canonical intent must contain one complete submission batch'
);
}
const result = await client.query(
'SELECT payload FROM simulation_canonical_intents WHERE account_id = $1 AND id = $2',
[accountId, batch.id]
);
const old = result.rows[0]
? canonicalBatchSchema.parse(result.rows[0].payload)
: undefined;
if (
old &&
(old.sequence !== batch.sequence ||
canonicalJson(old.command) !== canonicalJson(batch.command) ||
(old.status !== 'pending' && old.status !== batch.status))
) {
throw new ExecutionConflictError('Conflicting canonical decision batch');
}
await client.query(
`INSERT INTO simulation_canonical_intents (account_id,id,sequence,status,payload) VALUES ($1,$2,$3,$4,$5::jsonb)
ON CONFLICT (account_id,id) DO UPDATE SET status = EXCLUDED.status,payload = EXCLUDED.payload`,
[accountId, batch.id, batch.sequence, batch.status, JSON.stringify(batch)]
);
},
async appendJournal(value) {
const payload = canonicalJournalSchema.parse(value);
account.journalSequence = increment(account.journalSequence);
const entry = { sequence: account.journalSequence, payload };
await client.query(
'INSERT INTO simulation_strategy_journal (account_id,sequence,payload) VALUES ($1,$2,$3::jsonb)',
[accountId, entry.sequence, JSON.stringify(payload)]
);
return entry;
},
async journal(after) {
if (!Number.isSafeInteger(after) || after < 0) {
throw new Error('Invalid canonical journal cursor');
}
const result = await client.query(
'SELECT sequence,payload FROM simulation_strategy_journal WHERE account_id = $1 AND sequence > $2 ORDER BY sequence',
[accountId, after]
);
return result.rows.map(row => {
const sequence = Number(row.sequence);
if (!Number.isSafeInteger(sequence) || sequence <= 0) {
throw new Error('Invalid canonical journal sequence');
}
return { sequence, payload: canonicalJournalSchema.parse(row.payload) };
});
},
});
this.validateOwners(account, await owners());
await client.query(
'UPDATE simulation_accounts SET state = $2::jsonb,updated_at = NOW() WHERE id = $1',
[accountId, JSON.stringify(canonicalAccountSchema.parse(account))]
);
return result;
});
}
}

View file

@ -1,4 +1,5 @@
import type { PostgresClient } from '@stock-bot/services';
import { refuseCanonicalAccount } from './canonical-paper';
import type { Account, Fill, StoredOrder } from './model';
import {
ExecutionConflictError,
@ -25,6 +26,7 @@ export class PostgresExecutionRepository implements ExecutionRepository {
'SELECT state FROM simulation_accounts WHERE id = $1 FOR UPDATE',
[id]
);
refuseCanonicalAccount(result.rows[0].state);
const account: Account = result.rows[0].state;
if (account.initialCapital !== initial.initialCapital) {
throw new ExecutionConflictError(
@ -52,6 +54,7 @@ export class PostgresExecutionRepository implements ExecutionRepository {
if (!state.rows[0]) {
throw new Error('Execution account is not initialized');
}
refuseCanonicalAccount(state.rows[0].state);
const readOrder = async (column: 'id' | 'client_order_id', key: string) => {
const result = await client.query(
`SELECT payload FROM simulation_orders WHERE account_id = $1 AND ${column} = $2`,

View file

@ -0,0 +1,184 @@
/** Durable custody contracts. Financial values and transitions belong to Rust. */
import { z } from 'zod';
import type { PostgresClient } from '@stock-bot/services';
import {
canonicalExecutionCheckpointSchema,
financialTransactionResultSchema,
matchingCommandSchema,
type CanonicalMatchingCommand,
} from '../contracts/canonical-execution';
import {
nativeFinancialViewSchema,
nativeManagedOrderSchema,
stepSchema,
} from '../contracts/native-replay';
import { metadataSchema, stateCopy } from '../strategies/strategy-decision';
const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
const json = z.unknown().transform(value => stateCopy(value));
const observation = stepSchema.shape.observations.element;
const barrier = stepSchema.shape.step.options[1].shape.barrier;
const definition = metadataSchema.extend({ initialState: json }).strict();
const feedback = z
.object({
decision: nativeManagedOrderSchema.shape.order.shape.decision,
revision: counter,
orders: z.array(
z
.object({
orderId: z.string(),
instrumentId: z.string(),
decision: nativeManagedOrderSchema.shape.order.shape.decision,
status: nativeManagedOrderSchema.shape.status,
})
.strict()
),
})
.strict();
export const canonicalOwnerSchema = z
.object({
version: z.literal(1),
definition,
cursor: counter,
diagnostic: z
.object({
ownerId: z.string(),
strategyId: z.string(),
strategyVersion: z.string(),
nextDecisionSequence: counter,
state: json,
rng: z
.object({
algorithm: z.literal('lcg32-v1'),
seed: metadataSchema.shape.seed,
state: metadataSchema.shape.seed,
draws: counter,
})
.strict(),
observationCount: counter,
previousAdmission: feedback.nullable(),
})
.strict()
.transform(value => ({ ...value, state: value.state })),
pendingObservations: z.array(observation),
})
.strict();
export const canonicalAccountSchema = z
.object({
kind: z.literal('canonical-paper'),
version: z.literal(1),
identity: financialTransactionResultSchema.shape.identity,
definitions: z.array(definition),
checkpoint: canonicalExecutionCheckpointSchema,
view: nativeFinancialViewSchema,
inputSequence: counter,
journalSequence: counter,
observed: counter,
pendingDecisionSequence: counter.nullable(),
latestObservations: z.array(observation),
})
.strict();
export const canonicalPaperInputSchema = z
.object({
command: matchingCommandSchema,
observations: z.array(observation),
decision: z
.object({
commandId: z.string().min(1),
key: matchingCommandSchema.shape.key,
barrierId: z.string().min(1),
ownerIds: z.array(z.string().min(1)).min(1),
inputs: barrier.shape.inputs,
})
.strict()
.optional(),
})
.strict();
export type CanonicalPaperInput = z.input<typeof canonicalPaperInputSchema>;
export const canonicalStoredInputSchema = z
.object({
version: z.literal(1),
id: z.string(),
sequence: counter,
fingerprint: z.string(),
status: z.enum(['pending', 'applied']),
input: canonicalPaperInputSchema,
})
.strict();
export const canonicalBatchSchema = z
.object({
version: z.literal(1),
id: z.string(),
sequence: counter,
status: z.enum(['pending', 'dispatched', 'failed']),
command: matchingCommandSchema,
})
.strict();
export const canonicalJournalSchema = z.discriminatedUnion('kind', [
z
.object({
kind: z.literal('effect'),
commandId: z.string(),
fact: financialTransactionResultSchema.shape.journal.element,
})
.strict(),
z
.object({
kind: z.literal('command'),
command: matchingCommandSchema,
outcome: financialTransactionResultSchema.shape.outcome,
view: nativeFinancialViewSchema,
})
.strict(),
z
.object({
kind: z.literal('decision'),
commandId: z.string(),
key: matchingCommandSchema.shape.key,
context: stepSchema.shape.step.options[1],
})
.strict(),
]);
export type CanonicalAccount = z.infer<typeof canonicalAccountSchema>;
export type CanonicalOwner = z.infer<typeof canonicalOwnerSchema>;
export type CanonicalStoredInput = z.infer<typeof canonicalStoredInputSchema>;
export type CanonicalBatch = z.infer<typeof canonicalBatchSchema>;
export type CanonicalJournalPayload = z.infer<typeof canonicalJournalSchema>;
export type CanonicalJournalEntry = { sequence: number; payload: CanonicalJournalPayload };
export interface CanonicalTransaction {
account: CanonicalAccount;
owners(): Promise<CanonicalOwner[]>;
putOwner(owner: CanonicalOwner): Promise<void>;
getInput(id: string): Promise<CanonicalStoredInput | undefined>;
nextInput(): Promise<CanonicalStoredInput | undefined>;
putInput(input: CanonicalStoredInput): Promise<void>;
nextBatch(): Promise<CanonicalBatch | undefined>;
putBatch(batch: CanonicalBatch): Promise<void>;
appendJournal(payload: CanonicalJournalPayload): Promise<CanonicalJournalEntry>;
journal(after: number): Promise<CanonicalJournalEntry[]>;
}
export interface CanonicalExecutionRepository {
initialize(initial: CanonicalAccount, owners: CanonicalOwner[]): Promise<void>;
transact<T>(accountId: string, work: (tx: CanonicalTransaction) => Promise<T>): Promise<T>;
}
export type CanonicalPostgres = Pick<PostgresClient, 'transaction'>;
export function compareEventKeys(
a: CanonicalMatchingCommand['key'],
b: CanonicalMatchingCommand['key']
): number {
const phases = { Observation: 0, Decision: 1, Execution: 2, SessionClose: 3 };
return (
a.at - b.at ||
phases[a.phase] - phases[b.phase] ||
(a.instrumentId < b.instrumentId ? -1 : a.instrumentId > b.instrumentId ? 1 : 0) ||
a.sourceSequence - b.sourceSequence
);
}
/** Legacy callers must never reinterpret any version of a canonical envelope. */
export function refuseCanonicalAccount(state: unknown): void {
if (state && typeof state === 'object' && 'kind' in state) {
throw new Error(
'Versioned execution account requires its canonical adapter; use an explicit migration or a new account ID'
);
}
}