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

@ -13,6 +13,7 @@ export const {
TradingEngine,
BacktestEngine,
FinancialReplaySession,
stageFinancialTransaction,
TechnicalIndicators,
IncrementalSma,
IncrementalEma,

View file

@ -1,12 +1,14 @@
mod backtest;
mod indicators;
mod replay;
mod paper;
mod risk;
mod strategy_parameters;
pub use backtest::BacktestEngine;
pub use indicators::{IncrementalEMA, IncrementalRSI, IncrementalSMA, TechnicalIndicators};
pub use replay::FinancialReplaySession;
pub use paper::stage_financial_transaction;
pub use risk::{OrderbookAnalyzer, RiskAnalyzer};
use crate::risk::RiskLimits;

View file

@ -0,0 +1,184 @@
//! Stateless trusted durable-host seam. SQL owns custody and commit/publication;
//! MatchingAccount owns all financial transitions. No process-resident mutation.
use crate::financial::{contract::*, matching::*, risk::RiskAccount};
use napi::{Error, Result};
#[cfg(not(test))]
use napi_derive::napi;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::BTreeMap;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct Identity {
session_id: Id,
account_id: Id,
}
#[derive(Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
enum Request {
Initialize {
version: Version,
identity: Identity,
config: MatchingConfig,
},
Apply {
version: Version,
identity: Identity,
checkpoint: MatchingCheckpoint,
command: MatchingCommand,
},
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct JournalEntry {
index: Counter,
effect: MatchingEffect,
view_after: Value,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct Response {
version: Version,
identity: Identity,
checkpoint: MatchingCheckpoint,
view: Value,
outcome: Option<MatchingOutcome>,
journal: Vec<JournalEntry>,
}
fn error(error: impl std::fmt::Display) -> Error {
Error::from_reason(error.to_string())
}
// Option fields in checkpoints are required wire fields, including explicit nulls.
fn keys_match(input: &Value, typed: &Value) -> bool {
match (input, typed) {
(Value::Object(a), Value::Object(b)) => {
a.len() == b.len()
&& a.iter()
.all(|(k, v)| b.get(k).is_some_and(|other| keys_match(v, other)))
}
(Value::Array(a), Value::Array(b)) => {
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| keys_match(a, b))
}
_ => true,
}
}
fn view(
risk: &RiskAccount,
orders: &BTreeMap<Id, ManagedOrder>,
revision: Counter,
) -> Result<Value> {
Ok(json!({
"admissionRevision": revision,
"portfolio": risk.ledger().economic_snapshot(),
"equity": risk.ledger().equity().map_err(error)?,
"availableCash": risk.available_cash(),
"orders": risk.reservations().filter_map(|r|orders.get(&r.order.order_id)).filter(|o|o.status == OrderStatus::Open).collect::<Vec<_>>(),
"reservations": risk.reservations().collect::<Vec<_>>(),
"risk": risk.state(),
}))
}
fn order_map(orders: impl IntoIterator<Item = ManagedOrder>) -> BTreeMap<Id, ManagedOrder> {
orders
.into_iter()
.map(|order| (order.order.order_id.clone(), order))
.collect()
}
fn stage(request: Request) -> Result<Response> {
let (identity, mut account, command) = match request {
Request::Initialize {
identity, config, ..
} => (
identity,
MatchingAccount::new(config).map_err(error)?.0,
None,
),
Request::Apply {
identity,
checkpoint,
command,
..
} => (
identity,
MatchingAccount::restore(checkpoint).map_err(error)?.0,
Some(command),
),
};
let before = account.checkpoint();
if before.config.risk.ledger.session_id != identity.session_id
|| before.config.risk.ledger.account_id != identity.account_id
{
return Err(error("financial transaction identity mismatch"));
}
let outcome = command
.as_ref()
.map(|command| account.apply(command).map_err(error))
.transpose()?;
let checkpoint = account.checkpoint();
let mut journal = Vec::new();
if let Some(outcome) = &outcome {
if !outcome.replayed {
// Recovery-only projections: reapply exact retained commands through
// the same risk kernel. Never approximate intermediate state in TS.
let (mut risk, authority) = RiskAccount::restore(before.risk).map_err(error)?;
let mut orders = order_map(before.orders);
for (index, effect) in outcome.effects.iter().enumerate() {
let reproduced = match effect {
MatchingEffect::Risk { command, outcome } => {
Some((risk.apply(command).map_err(error)?, outcome))
}
MatchingEffect::Operator { command, outcome } => {
Some((risk.reset(&authority, command).map_err(error)?, outcome))
}
MatchingEffect::Order(order) => {
orders.insert(order.order.order_id.clone(), order.clone());
None
}
};
if reproduced.is_some_and(|(actual, expected)| actual != *expected) {
return Err(error("financial effect reconstruction mismatch"));
}
journal.push(JournalEntry {
index: (index as u64).try_into().map_err(error)?,
effect: effect.clone(),
view_after: view(&risk, &orders, before.revision)?,
});
}
if risk.checkpoint() != checkpoint.risk
|| orders.into_values().collect::<Vec<_>>() != checkpoint.orders
{
return Err(error("financial checkpoint reconstruction mismatch"));
}
}
}
let final_view = view(
account.risk(),
&order_map(checkpoint.orders.clone()),
checkpoint.revision,
)?;
Ok(Response {
version: Version,
identity,
checkpoint,
view: final_view,
outcome,
journal,
})
}
/// The caller persists the returned checkpoint/journal atomically before publish.
/// Failed outcomes carry a valid terminal prefix to persist; Err returns no state.
/// Replayed outcomes retain the original receipt but always emit an empty journal.
#[cfg_attr(not(test), napi)]
pub fn stage_financial_transaction(input: String) -> Result<String> {
let raw: Value = serde_json::from_str(&input).map_err(error)?;
let request: Request = serde_json::from_str(&input).map_err(error)?;
if !keys_match(&raw, &serde_json::to_value(&request).map_err(error)?) {
return Err(error("unexpected or missing financial transaction fields"));
}
serde_json::to_string(&stage(request)?).map_err(error)
}
#[cfg(test)]
#[path = "paper/tests.rs"]
mod tests;

View file

@ -0,0 +1,348 @@
use super::*;
use crate::financial::scalar::MAX_POSTING;
fn config() -> Value {
json!({
"risk":{"ledger":{"version":1,"sessionId":"run","accountId":"account","baseCurrency":"USD","reserveOwnerId":"reserve","ownerIds":["A","B"],"initialCapital":"1000","riskSession":{"calendarId":"account","calendarRevision":"1","sessionId":"day1","startsAt":0}},
"feeRate":"0.01","maxOrderQuantity":"1000000","maxPositionQuantity":"1000000","maxSymbolExposure":"1000000","maxGrossExposure":"1000000","maxDailyLoss":"1000000","maxDrawdownAmount":"1000000","maxMarkAgeMs":1000000},
"owners":[{"ownerId":"A","mode":"Orders"},{"ownerId":"B","mode":"Orders"}],
"series":[{"instrumentId":"X","seriesId":"X-quotes","mode":"Quote"}],
"halfSpreadRate":"0","slippageRate":"0","latencyMs":0
})
}
fn identity() -> Value {
json!({"sessionId":"run","accountId":"account"})
}
fn wire(value: Value) -> Result<Response> {
serde_json::from_str(&stage_financial_transaction(value.to_string())?).map_err(error)
}
fn command(name: &str, at: i64, phase: &str, sequence: u64, body: Value) -> Value {
json!({"commandId":name,"key":{"at":at,"phase":phase,"instrumentId":"X","sourceSequence":sequence},"body":body})
}
fn quote(name: &str, at: i64, sequence: u64, price: &str, capacity: &str) -> Value {
command(
name,
at,
"Execution",
sequence,
json!({"kind":"execute","seriesId":"X-quotes","observation":{"kind":"quote","observedAt":at,"bid":price,"ask":price,"bidSize":capacity,"askSize":capacity}}),
)
}
fn order(name: &str, side: &str, quantity: &str, tif: &str) -> Value {
json!({"kind":"market","orderId":name,"instrumentId":"X","side":side,"quantity":quantity,"timeInForce":tif})
}
struct Harness {
checkpoint: MatchingCheckpoint,
direct: MatchingAccount,
}
impl Harness {
fn new(config: Value) -> Self {
let direct = MatchingAccount::new(serde_json::from_value(config.clone()).unwrap())
.unwrap()
.0;
let initialized =
wire(json!({"version":1,"kind":"initialize","identity":identity(),"config":config}))
.unwrap();
assert!(initialized.outcome.is_none());
assert!(initialized.journal.is_empty());
assert_eq!(initialized.view["admissionRevision"], json!(0));
assert_eq!(initialized.checkpoint, direct.checkpoint());
Self {
checkpoint: initialized.checkpoint,
direct,
}
}
fn apply(&mut self, command: Value) -> Response {
let direct = self
.direct
.apply(&serde_json::from_value(command.clone()).unwrap())
.unwrap();
let result = wire(json!({"version":1,"kind":"apply","identity":identity(),"checkpoint":self.checkpoint,"command":command})).unwrap();
assert_eq!(result.outcome.as_ref().unwrap(), &direct);
assert_eq!(result.checkpoint, self.direct.checkpoint());
assert_eq!(
result.view,
view(
self.direct.risk(),
&order_map(self.direct.orders().cloned()),
self.direct.admission_revision()
)
.unwrap()
);
if direct.replayed {
assert!(result.journal.is_empty());
} else {
assert_eq!(result.journal.len(), direct.effects.len());
for (index, row) in result.journal.iter().enumerate() {
assert_eq!(row.index.get(), index as u64);
assert_eq!(row.effect, direct.effects[index]);
assert_eq!(
row.view_after["admissionRevision"],
json!(self.checkpoint.revision)
);
}
}
self.checkpoint = result.checkpoint.clone();
result
}
fn setup(config: Value, price: &str) -> Self {
let mut h = Self::new(config);
h.apply(command("session",0,"Observation",0,json!({"kind":"openSession","session":{"sessionId":"venue","opensAt":0,"closesAt":100}})));
h.apply(command(
"mark",
0,
"Observation",
1,
json!({"kind":"mark","seriesId":"X-quotes","price":price,"observedAt":0}),
));
h
}
fn decision(&self, owner: &str, sequence: u64, orders: Vec<Value>) -> Value {
json!({"version":1,"sessionId":"run","barrierId":format!("barrier-{}",self.checkpoint.revision.get()),"revision":self.checkpoint.revision,"decision":{"ownerId":owner,"decisionId":format!("decision-{owner}-{sequence}"),"sequence":sequence},"intent":{"mode":"orders","orders":orders}})
}
fn submit(&mut self, name: &str, at: i64, decisions: Vec<Value>) -> Response {
self.apply(command(
name,
at,
"Decision",
0,
json!({"kind":"submit","decisions":decisions}),
))
}
}
#[test]
fn staged_multi_owner_fills_match_kernel_and_record_each_effect_view() {
let mut h = Harness::setup(config(), "10");
h.submit(
"orders",
1,
vec![
h.decision("A", 0, vec![order("a", "buy", "2", "GTC")]),
h.decision("B", 0, vec![order("b", "buy", "3", "GTC")]),
],
);
let result = h.apply(quote("fill", 2, 0, "10", "5"));
let fills: Vec<_> = result.journal.iter().filter(|row| matches!(&row.effect,MatchingEffect::Risk{outcome,..} if outcome.financial.as_ref().is_some_and(|financial| financial.effects.effects.iter().any(|effect|matches!(effect,FinancialEffect::FillApplied{..}))))).collect();
assert_eq!(fills.len(), 2);
assert_eq!(
fills[0].view_after["portfolio"]["cash"],
json!("979.80000000")
);
assert_eq!(
fills[1].view_after["portfolio"]["cash"],
json!("949.50000000")
);
assert_ne!(fills[0].view_after, result.view);
assert_eq!(result.view["equity"], json!("999.50000000"));
assert_eq!(result.view["availableCash"], json!("949.50000000"));
assert_eq!(
result.view["portfolio"]["positions"]
.as_array()
.unwrap()
.len(),
2
);
// Failure or a lost SQL commit discards the private returned state; retrying
// the prior checkpoint deterministically reconstructs exactly this result.
let restored = MatchingAccount::restore(result.checkpoint.clone())
.unwrap()
.0;
assert_eq!(restored.checkpoint(), result.checkpoint);
}
#[test]
fn replay_of_old_command_and_alias_preserves_current_state_without_publication() {
let mut h = Harness::setup(config(), "10");
let first = quote("quote", 1, 0, "10", "5");
let original = h.apply(first.clone());
h.apply(quote("later", 2, 0, "11", "5"));
let current = h.checkpoint.clone();
let replay = h.apply(first.clone());
assert!(replay.outcome.unwrap().replayed);
assert_eq!(replay.checkpoint, current);
let mut alias = first;
alias["commandId"] = json!("alias");
let aliased = h.apply(alias.clone());
assert_eq!(aliased.checkpoint.revision, current.revision);
assert_eq!(
aliased.checkpoint.receipts.len(),
current.receipts.len() + 1
);
assert_eq!(aliased.view, replay.view);
assert_eq!(
aliased.outcome.unwrap().effects,
original.outcome.unwrap().effects
);
h.apply(alias);
}
#[test]
fn failed_committed_prefix_is_returned_and_restorable_without_reapplying_fees() {
let mut c = config();
c["risk"]["ledger"]["initialCapital"] = json!("100000000000000000000");
for key in [
"maxOrderQuantity",
"maxPositionQuantity",
"maxSymbolExposure",
"maxGrossExposure",
] {
c["risk"][key] = json!(MAX_POSTING);
}
let mut h = Harness::setup(c, "0.00000001");
h.submit(
"seed",
1,
vec![h.decision("A", 0, vec![order("seed", "buy", "1", "GTC")])],
);
h.apply(quote("seed-fill", 1, 0, "0.00000001", "1"));
h.submit(
"orders",
2,
vec![
h.decision("A", 1, vec![order("sell", "sell", "1", "GTC")]),
h.decision(
"B",
1,
vec![order("overflow", "buy", "396140812571321687967", "GTC")],
),
],
);
let failure = quote("failure", 2, 0, "3", MAX_POSTING);
let result = h.apply(failure.clone());
assert!(matches!(
result.outcome.as_ref().unwrap().status,
AttemptStatus::Failed { .. }
));
assert!(!result.journal.is_empty());
assert_eq!(
h.direct.ledger().valuation().unwrap().fees.to_string(),
"0.03000000"
);
assert_eq!(
h.direct
.order(&serde_json::from_value(json!("sell")).unwrap())
.unwrap()
.status,
OrderStatus::Filled
);
assert_eq!(
MatchingAccount::restore(result.checkpoint.clone())
.unwrap()
.0
.checkpoint(),
result.checkpoint
);
h.apply(failure);
let next = json!({"version":1,"kind":"apply","identity":identity(),"checkpoint":h.checkpoint,"command":quote("next",3,0,"3","1")});
assert!(wire(next).unwrap_err().reason.contains("terminal"));
}
#[test]
fn partial_and_time_in_force_states_survive_each_staged_checkpoint() {
for (tif, expected) in [
("GTC", OrderStatus::Open),
("DAY", OrderStatus::Open),
("IOC", OrderStatus::Cancelled),
("FOK", OrderStatus::Cancelled),
] {
let mut h = Harness::setup(config(), "10");
h.submit(
"orders",
1,
vec![h.decision("A", 0, vec![order("o", "buy", "2", tif)])],
);
h.apply(quote("fill", 2, 0, "10", "1"));
let stored = h.checkpoint.orders.first().unwrap();
assert_eq!(stored.status, expected);
assert_eq!(
serde_json::to_value(stored.filled).unwrap(),
json!(if tif == "FOK" {
"0.00000000"
} else {
"1.00000000"
})
);
h.apply(command(
"close",
100,
"SessionClose",
0,
json!({"kind":"closeSession","sessionId":"venue"}),
));
if tif == "DAY" {
assert_eq!(h.checkpoint.orders[0].status, OrderStatus::Expired);
}
if tif == "GTC" {
assert_eq!(h.checkpoint.orders[0].status, OrderStatus::Open);
}
}
}
#[test]
fn wrong_identity_conflicts_corruption_and_operator_inputs_return_no_state() {
let mut h = Harness::setup(config(), "10");
h.submit(
"orders",
1,
vec![h.decision("A", 0, vec![order("o", "buy", "2", "GTC")])],
);
let checkpoint = h.checkpoint.clone();
let request = json!({"version":1,"kind":"apply","identity":identity(),"checkpoint":checkpoint,"command":quote("next",2,0,"10","1")});
for field in [
"identity", "version", "revision", "order", "receipt", "risk", "missing",
] {
let mut bad = request.clone();
match field {
"identity" => bad["identity"]["accountId"] = json!("other"),
"version" => bad["checkpoint"]["version"] = json!(2),
"revision" => bad["checkpoint"]["revision"] = json!(99),
"order" => bad["checkpoint"]["orders"][0]["remaining"] = json!("1"),
"receipt" => bad["checkpoint"]["receipts"][1]["outcome"]["effects"] = json!([]),
"risk" => bad["checkpoint"]["risk"]["revision"] = json!(99),
_ => {
bad["checkpoint"].as_object_mut().unwrap().remove("cursor");
}
}
assert!(wire(bad).is_err(), "{field}");
}
let mut conflict = request.clone();
conflict["command"]["commandId"] = json!("mark");
assert!(wire(conflict).unwrap_err().reason.contains("conflicts"));
let mut operator = request.clone();
operator["command"]["body"] = json!({"kind":"reset","actorId":"operator","reason":"reason"});
assert!(wire(operator).is_err());
assert_eq!(h.checkpoint, checkpoint);
h.apply(quote("next", 2, 0, "10", "1"));
}
#[test]
fn quote_cannot_be_reused_for_a_new_decision_and_capital_is_enforced() {
let mut h = Harness::setup(config(), "10");
let q = quote("quote", 1, 0, "10", "100");
h.apply(q.clone());
// Quote-driven decisions use the exact consumed event cursor, not a false
// earlier Decision phase. The next physical event is required to fill.
let decision = h.decision(
"A",
0,
vec![
order("o", "buy", "2", "GTC"),
order("unfunded", "buy", "1000", "GTC"),
],
);
h.apply(command(
"orders",
1,
"Execution",
0,
json!({"kind":"submit","decisions":[decision]}),
));
assert!(matches!(
h.checkpoint
.orders
.iter()
.find(|o| o.order.order_id == serde_json::from_value(json!("unfunded")).unwrap())
.unwrap()
.status,
OrderStatus::Rejected(_)
));
h.apply(q);
assert!(h.direct.ledger().economic_snapshot().positions.is_empty());
h.apply(quote("next", 2, 0, "10", "100"));
assert_eq!(h.direct.ledger().economic_snapshot().positions.len(), 1);
}

View file

@ -36,3 +36,7 @@ mod reporting_tests;
#[cfg(test)]
#[path = "../api/replay.rs"]
mod native_replay_tests;
#[cfg(test)]
#[path = "../api/paper.rs"]
mod native_paper_tests;

View file

@ -1,8 +1,6 @@
/** Trusted synchronous programs on the canonical financial engine. Fresh
* attempts recompute from original inputs; diagnostics are not resume tokens. */
import { types } from 'node:util';
import { z } from 'zod';
import { parseFinancialStrategyDecision, type FinancialStrategyDecision } from '@stock-bot/types';
import type { FinancialStrategyDecision } from '@stock-bot/types';
import type {
DeepReadonly,
StrategyAdmissionFeedback,
@ -23,6 +21,14 @@ import {
type ReplayResult,
type ReplaySubmissionOutcome,
} from '../contracts/native-replay';
import {
freeze,
increment,
metadataSchema,
stageStrategyDecision,
stateCopy,
type Metadata,
} from '../strategies/strategy-decision';
import {
NativeReplaySession,
runReplaySession,
@ -51,92 +57,11 @@ export class StrategyReplayError extends Error {
}
}
function freeze<T>(value: T): DeepReadonly<T> {
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
for (const child of Object.values(value)) {
freeze(child);
}
Object.freeze(value);
}
return value as DeepReadonly<T>;
}
/** Check descriptors before reading values: JSON.stringify would silently lose
* symbols/custom array keys, invoke accessors, or rewrite non-JSON objects. */
function stateCopy(input: unknown, ancestors = new Set<object>()): unknown {
if (input === null || typeof input === 'string' || typeof input === 'boolean') {
return input;
}
if (typeof input === 'number' && Number.isFinite(input)) {
if (Object.is(input, -0)) {
throw new Error('Strategy state cannot contain negative zero');
}
return input;
}
const invalid = () => new Error('Strategy state requires finite plain JSON data properties');
if (!input || typeof input !== 'object' || ancestors.has(input)) {
throw invalid();
}
const array = Array.isArray(input);
if (Object.getPrototypeOf(input) !== (array ? Array.prototype : Object.prototype)) {
throw invalid();
}
const descriptors = Object.getOwnPropertyDescriptors(input);
const keys = Reflect.ownKeys(input);
if (keys.some(key => typeof key !== 'string')) {
throw invalid();
}
ancestors.add(input);
try {
const data = (key: string): unknown => {
const descriptor = descriptors[key];
if (!descriptor?.enumerable || !('value' in descriptor)) {
throw invalid();
}
return stateCopy(descriptor.value, ancestors);
};
if (array) {
if (keys.length !== input.length + 1) {
throw invalid();
}
return Array.from({ length: input.length }, (_, index) => data(String(index)));
}
// fromEntries preserves an own '__proto__' key without changing prototype.
return Object.fromEntries((keys as string[]).sort().map(key => [key, data(key)]));
} finally {
ancestors.delete(input);
}
}
const id = z
.string()
.min(1)
.refine(value =>
[...value].every(char => char.charCodeAt(0) >= 32 && char.charCodeAt(0) !== 127)
);
const metadataSchema = z
.object({
ownerId: id,
strategyId: id,
strategyVersion: id,
mode: z.enum(['target', 'orders']),
seed: z.number().int().min(0).max(0xffff_ffff),
})
.strict();
type Metadata = z.infer<typeof metadataSchema>;
interface Slot {
program: Metadata & { decide: StrategyProgram['decide'] };
diagnostic: DeepReadonly<StrategyDiagnostic>;
pendingObservations: PublishedObservation[];
}
function increment(value: number, amount = 1): number {
const next = value + amount;
if (!Number.isSafeInteger(next) || next < 0) {
throw new Error('Strategy counter exhausted');
}
return next;
}
class StrategyController implements ReplayController {
private slots: Map<string, Slot>;
private committedBarriers = 0;
@ -229,90 +154,15 @@ class StrategyController implements ReplayController {
if (!due.has(slot.program.ownerId)) {
continue;
}
const { program, diagnostic } = slot;
let active = true,
rngState = diagnostic.rng.state,
draws = diagnostic.rng.draws;
const random = () => {
if (!active) {
throw new Error('Strategy random is only valid during its decision');
}
draws = increment(draws);
rngState = (Math.imul(rngState, 1664525) + 1013904223) >>> 0;
return rngState / 4294967296;
};
let output: ReturnType<StrategyProgram['decide']>;
try {
const decide = program.decide;
output = decide(
Object.freeze({
ownerId: program.ownerId,
strategyId: program.strategyId,
strategyVersion: program.strategyVersion,
decisionSequence: diagnostic.nextDecisionSequence,
now: context.barrier.at,
barrier: context.barrier,
portfolio: context.view,
positions: Object.freeze(
context.view.portfolio.positions.filter(
position => position.ownerId === program.ownerId
)
),
observations: Object.freeze([...slot.pendingObservations]),
previousAdmission: diagnostic.previousAdmission,
state: diagnostic.state,
random,
})
);
} finally {
active = false;
}
if (types.isPromise(output)) {
// Reject async strategies synchronously, but observe their actual
// Promise rejection so failed attempts cannot leak unhandled errors.
// Do not await it or call arbitrary thenable methods.
Promise.prototype.then.call(output, undefined, () => {});
throw new Error('Strategy decide must synchronously return nextState and intent');
}
if (!output || typeof output !== 'object' || 'then' in output) {
throw new Error('Strategy decide must synchronously return nextState and intent');
}
const state = freeze(stateCopy(output.nextState));
const decision = parseFinancialStrategyDecision({
version: 1,
sessionId: this.identity.sessionId,
barrierId: context.barrier.barrier_id,
revision: context.barrier.revision,
decision: {
ownerId: program.ownerId,
decisionId: JSON.stringify([
'strategy',
program.ownerId,
program.strategyId,
program.strategyVersion,
diagnostic.nextDecisionSequence,
]),
sequence: diagnostic.nextDecisionSequence,
},
intent: output.intent,
});
if (decision.intent.mode !== program.mode) {
throw new Error('Strategy intent mode differs from its configured mode');
}
staged.owners.push({
ownerId: program.ownerId,
decision,
diagnostic: {
ownerId: program.ownerId,
strategyId: program.strategyId,
strategyVersion: program.strategyVersion,
state,
nextDecisionSequence: increment(diagnostic.nextDecisionSequence),
rng: { algorithm: 'lcg32-v1', seed: program.seed, state: rngState, draws },
observationCount: increment(diagnostic.observationCount, slot.pendingObservations.length),
previousAdmission: null,
},
});
staged.owners.push(
stageStrategyDecision(
this.identity.sessionId,
slot.program,
slot.diagnostic,
slot.pendingObservations,
context
)
);
}
this.staged = staged;
return staged.owners.map(owner => owner.decision);

View file

@ -0,0 +1,273 @@
/** Trusted durable-host wire boundary. Native checkpoints are opaque custody,
* not a TypeScript accounting implementation or a strategy mutation API. */
import { z } from 'zod';
import {
parseFinancialDecimal,
parseFinancialEffects,
parseFinancialStrategyDecision,
} from '@stock-bot/types';
import {
nativeFinancialViewSchema,
nativeManagedOrderSchema,
nativeMatchingOutcomeSchema,
replayConfigSchema,
} from './native-replay';
const id = z
.string()
.min(1)
.refine(value =>
[...value].every(char => char.charCodeAt(0) >= 32 && char.charCodeAt(0) !== 127)
);
const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
const time = z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER);
const decimal = z.string().transform(value => parseFinancialDecimal(value));
const nonnegative = decimal.refine(value => !value.startsWith('-'));
const positive = nonnegative.refine(value => value !== '0.00000000');
const identitySchema = z.object({ sessionId: id, accountId: id }).strict();
export type CanonicalExecutionIdentity = z.infer<typeof identitySchema>;
export const canonicalMatchingConfigSchema = replayConfigSchema.shape.matching.extend({
series: z.array(
replayConfigSchema.shape.matching.shape.series.element.extend({
mode: z.enum(['Open', 'Quote']),
})
),
});
export type CanonicalMatchingConfig = z.input<typeof canonicalMatchingConfigSchema>;
const eventKeySchema = z
.object({
at: time,
phase: z.enum(['Observation', 'Decision', 'Execution', 'SessionClose']),
instrumentId: id,
sourceSequence: counter,
})
.strict();
const venueSessionSchema = z.object({ sessionId: id, opensAt: time, closesAt: time }).strict();
const riskSessionSchema =
replayConfigSchema.shape.matching.shape.risk.shape.ledger.shape.riskSession;
export const matchingCommandSchema = z
.object({
commandId: id,
key: eventKeySchema,
body: z.discriminatedUnion('kind', [
z
.object({
kind: z.literal('submit'),
decisions: z.array(z.unknown().transform(value => parseFinancialStrategyDecision(value))),
})
.strict(),
z
.object({
kind: z.literal('execute'),
seriesId: id,
observation: z.discriminatedUnion('kind', [
z
.object({
kind: z.literal('open'),
opensAt: time,
price: positive,
capacity: nonnegative,
})
.strict(),
z
.object({
kind: z.literal('quote'),
observedAt: time,
bid: positive,
ask: positive,
bidSize: nonnegative,
askSize: nonnegative,
})
.strict(),
]),
})
.strict(),
z
.object({ kind: z.literal('mark'), seriesId: id, price: positive, observedAt: time })
.strict(),
z.object({ kind: z.literal('openSession'), session: venueSessionSchema }).strict(),
z.object({ kind: z.literal('closeSession'), sessionId: id }).strict(),
z.object({ kind: z.literal('riskSessionBoundary'), riskSession: riskSessionSchema }).strict(),
z.object({ kind: z.literal('finish') }).strict(),
]),
})
.strict();
export type CanonicalMatchingCommand = z.input<typeof matchingCommandSchema>;
/** Metadata and shapes only. Rust restores and validates all nested receipts,
* reservations, accounting and indexes before any transition. */
export const canonicalExecutionCheckpointSchema = z
.object({
version: z.literal(1),
config: canonicalMatchingConfigSchema,
risk: z.record(z.unknown()),
revision: counter,
status: nativeMatchingOutcomeSchema.shape.status,
cursor: eventKeySchema.nullable(),
orders: z.array(nativeManagedOrderSchema),
sessions: z.array(z.tuple([id, venueSessionSchema])),
receipts: z.array(z.record(z.unknown())),
})
.strict();
export type CanonicalExecutionCheckpoint = z.infer<typeof canonicalExecutionCheckpointSchema>;
export const financialTransactionRequestSchema = z.discriminatedUnion('kind', [
z
.object({
version: z.literal(1),
kind: z.literal('initialize'),
identity: identitySchema,
config: canonicalMatchingConfigSchema,
})
.strict(),
z
.object({
version: z.literal(1),
kind: z.literal('apply'),
identity: identitySchema,
checkpoint: canonicalExecutionCheckpointSchema,
command: matchingCommandSchema,
})
.strict(),
]);
export type FinancialTransactionRequest = z.input<typeof financialTransactionRequestSchema>;
const riskOutcomeSchema = z
.object({
replayed: z.boolean(),
revision: counter,
disposition: z.union([z.literal('Accepted'), nativeManagedOrderSchema.shape.status.options[1]]),
financial: z
.object({
replayed: z.boolean(),
effects: z.unknown().transform(value => parseFinancialEffects(value)),
})
.strict()
.nullable(),
remaining: z.record(z.unknown()).nullable(),
releasedOrder: id.nullable(),
resetBaseline: nonnegative.nullable(),
})
.strict();
const matchingEffectSchema = z.union([
z.object({ Order: nativeManagedOrderSchema }).strict(),
z
.object({
Risk: z.object({ command: z.record(z.unknown()), outcome: riskOutcomeSchema }).strict(),
})
.strict(),
z
.object({
Operator: z.object({ command: z.record(z.unknown()), outcome: riskOutcomeSchema }).strict(),
})
.strict(),
]);
export const financialTransactionResultSchema = z
.object({
version: z.literal(1),
identity: identitySchema,
checkpoint: canonicalExecutionCheckpointSchema,
view: nativeFinancialViewSchema,
outcome: nativeMatchingOutcomeSchema.nullable(),
journal: z.array(
z
.object({
index: counter,
effect: matchingEffectSchema,
viewAfter: nativeFinancialViewSchema,
})
.strict()
),
})
.strict();
export type FinancialTransactionResult = z.infer<typeof financialTransactionResultSchema>;
export type CanonicalFinancialView = z.infer<typeof nativeFinancialViewSchema>;
// JSON object key order is not semantically significant (including opaque commands).
function equalJson(left: unknown, right: unknown): boolean {
if (left === right) {
return true;
}
if (left === null || right === null || typeof left !== 'object' || typeof right !== 'object') {
return false;
}
if (Array.isArray(left) || Array.isArray(right)) {
return (
Array.isArray(left) &&
Array.isArray(right) &&
left.length === right.length &&
left.every((value, index) => equalJson(value, right[index]))
);
}
const a = left as Record<string, unknown>,
b = right as Record<string, unknown>;
return (
Object.keys(a).length === Object.keys(b).length &&
Object.keys(a).every(key => Object.hasOwn(b, key) && equalJson(a[key], b[key]))
);
}
export function parseFinancialTransactionResult(
input: string,
expectedIdentity: CanonicalExecutionIdentity
): FinancialTransactionResult {
const result = financialTransactionResultSchema.parse(JSON.parse(input));
const expected = identitySchema.parse(expectedIdentity),
ledger = result.checkpoint.config.risk.ledger;
if (
!equalJson(result.identity, expected) ||
ledger.sessionId !== expected.sessionId ||
ledger.accountId !== expected.accountId ||
result.view.admissionRevision !== result.checkpoint.revision
) {
throw new Error('Native financial transaction identity or revision mismatch');
}
const checkView = (view: CanonicalFinancialView) => {
if (
view.portfolio.sessionId !== expected.sessionId ||
view.portfolio.accountId !== expected.accountId ||
view.portfolio.baseCurrency !== ledger.baseCurrency ||
view.portfolio.reserveOwnerId !== ledger.reserveOwnerId
) {
throw new Error('Native financial transaction view identity mismatch');
}
};
checkView(result.view);
if (result.outcome === null) {
if (
result.checkpoint.revision !== 0 ||
result.checkpoint.status !== 'Running' ||
result.checkpoint.cursor !== null ||
result.checkpoint.orders.length !== 0 ||
result.checkpoint.sessions.length !== 0 ||
result.view.orders.length !== 0 ||
result.view.reservations.length !== 0 ||
result.journal.length !== 0 ||
result.checkpoint.receipts.length !== 0
) {
throw new Error('Invalid initialized financial transaction');
}
} else if (result.outcome.replayed) {
if (result.journal.length !== 0 || result.outcome.revision > result.checkpoint.revision) {
throw new Error('Replayed financial transaction cannot publish effects');
}
} else {
if (
result.outcome.revision !== result.checkpoint.revision ||
!equalJson(result.outcome.status, result.checkpoint.status) ||
result.journal.length !== result.outcome.effects.length
) {
throw new Error('Native financial transaction outcome mismatch');
}
for (const [index, row] of result.journal.entries()) {
checkView(row.viewAfter);
if (
row.index !== index ||
row.viewAfter.admissionRevision !== result.checkpoint.revision - 1 ||
!equalJson(row.effect, matchingEffectSchema.parse(result.outcome.effects[index]))
) {
throw new Error('Native financial transaction journal mismatch');
}
}
}
return result;
}

View file

@ -230,6 +230,12 @@ const managedOrderSchema = z
admissionSequence: counter,
})
.strict();
// Shared wire projections; the native reducers remain their only financial authority.
export {
viewSchema as nativeFinancialViewSchema,
outcomeSchema as nativeMatchingOutcomeSchema,
managedOrderSchema as nativeManagedOrderSchema,
};
const admissionEffectSchema = z.union([
z.object({ Order: managedOrderSchema }).strict(),
z.object({ Risk: z.record(z.unknown()) }).strict(),

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'
);
}
}

View file

@ -0,0 +1,182 @@
/** Shared trusted strategy decision staging. Callers own the durable/native commit boundary. */
import { types } from 'node:util';
import { z } from 'zod';
import { parseFinancialStrategyDecision, type FinancialStrategyDecision } from '@stock-bot/types';
import type {
DeepReadonly,
StrategyDiagnostic,
StrategyProgram,
} from '../contracts/canonical-strategy';
import type { DecisionContext, PublishedObservation } from '../contracts/native-replay';
export function freeze<T>(value: T): DeepReadonly<T> {
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
for (const child of Object.values(value)) {
freeze(child);
}
Object.freeze(value);
}
return value as DeepReadonly<T>;
}
/** Check descriptors before reading values: JSON.stringify would silently lose
* symbols/custom array keys, invoke accessors, or rewrite non-JSON objects. */
export function stateCopy(input: unknown, ancestors = new Set<object>()): unknown {
if (input === null || typeof input === 'string' || typeof input === 'boolean') {
return input;
}
if (typeof input === 'number' && Number.isFinite(input)) {
if (Object.is(input, -0)) {
throw new Error('Strategy state cannot contain negative zero');
}
return input;
}
const invalid = () => new Error('Strategy state requires finite plain JSON data properties');
if (!input || typeof input !== 'object' || ancestors.has(input)) {
throw invalid();
}
const array = Array.isArray(input);
if (Object.getPrototypeOf(input) !== (array ? Array.prototype : Object.prototype)) {
throw invalid();
}
const descriptors = Object.getOwnPropertyDescriptors(input);
const keys = Reflect.ownKeys(input);
if (keys.some(key => typeof key !== 'string')) {
throw invalid();
}
ancestors.add(input);
try {
const data = (key: string): unknown => {
const descriptor = descriptors[key];
if (!descriptor?.enumerable || !('value' in descriptor)) {
throw invalid();
}
return stateCopy(descriptor.value, ancestors);
};
if (array) {
if (keys.length !== input.length + 1) {
throw invalid();
}
return Array.from({ length: input.length }, (_, index) => data(String(index)));
}
// fromEntries preserves an own '__proto__' key without changing prototype.
return Object.fromEntries((keys as string[]).sort().map(key => [key, data(key)]));
} finally {
ancestors.delete(input);
}
}
const id = z
.string()
.min(1)
.refine(value =>
[...value].every(char => char.charCodeAt(0) >= 32 && char.charCodeAt(0) !== 127)
);
export const metadataSchema = z
.object({
ownerId: id,
strategyId: id,
strategyVersion: id,
mode: z.enum(['target', 'orders']),
seed: z.number().int().min(0).max(0xffff_ffff),
})
.strict();
export type Metadata = z.infer<typeof metadataSchema>;
export function increment(value: number, amount = 1): number {
const next = value + amount;
if (!Number.isSafeInteger(next) || next < 0) {
throw new Error('Strategy counter exhausted');
}
return next;
}
export function stageStrategyDecision(
sessionId: string,
program: Metadata & { decide: StrategyProgram['decide'] },
diagnostic: DeepReadonly<StrategyDiagnostic>,
observations: readonly PublishedObservation[],
context: DecisionContext
): { ownerId: string; decision: FinancialStrategyDecision; diagnostic: StrategyDiagnostic } {
let active = true,
rngState = diagnostic.rng.state,
draws = diagnostic.rng.draws;
const random = () => {
if (!active) {
throw new Error('Strategy random is only valid during its decision');
}
draws = increment(draws);
rngState = (Math.imul(rngState, 1664525) + 1013904223) >>> 0;
return rngState / 4294967296;
};
let output: ReturnType<StrategyProgram['decide']>;
try {
const decide = program.decide;
output = decide(
Object.freeze({
ownerId: program.ownerId,
strategyId: program.strategyId,
strategyVersion: program.strategyVersion,
decisionSequence: diagnostic.nextDecisionSequence,
now: context.barrier.at,
barrier: context.barrier,
portfolio: context.view,
positions: Object.freeze(
context.view.portfolio.positions.filter(position => position.ownerId === program.ownerId)
),
observations: Object.freeze([...observations]),
previousAdmission: diagnostic.previousAdmission,
state: diagnostic.state,
random,
})
);
} finally {
active = false;
}
if (types.isPromise(output)) {
// Reject async strategies synchronously, but observe their actual
// Promise rejection so failed attempts cannot leak unhandled errors.
// Do not await it or call arbitrary thenable methods.
Promise.prototype.then.call(output, undefined, () => {});
throw new Error('Strategy decide must synchronously return nextState and intent');
}
if (!output || typeof output !== 'object' || 'then' in output) {
throw new Error('Strategy decide must synchronously return nextState and intent');
}
const state = freeze(stateCopy(output.nextState));
const decision = parseFinancialStrategyDecision({
version: 1,
sessionId: sessionId,
barrierId: context.barrier.barrier_id,
revision: context.barrier.revision,
decision: {
ownerId: program.ownerId,
decisionId: JSON.stringify([
'strategy',
program.ownerId,
program.strategyId,
program.strategyVersion,
diagnostic.nextDecisionSequence,
]),
sequence: diagnostic.nextDecisionSequence,
},
intent: output.intent,
});
if (decision.intent.mode !== program.mode) {
throw new Error('Strategy intent mode differs from its configured mode');
}
return {
ownerId: program.ownerId,
decision,
diagnostic: {
ownerId: program.ownerId,
strategyId: program.strategyId,
strategyVersion: program.strategyVersion,
state,
nextDecisionSequence: increment(diagnostic.nextDecisionSequence),
rng: { algorithm: 'lcg32-v1', seed: program.seed, state: rngState, draws },
observationCount: increment(diagnostic.observationCount, observations.length),
previousAdmission: null,
},
};
}

View file

@ -54,7 +54,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
f === '11-simulation-execution-ledger.sql' ||
f === '12-historical-datasets.sql' ||
f === '13-strategy-recovery.sql' ||
f === '14-backtest-submission.sql')
f === '14-backtest-submission.sql' ||
f === '15-canonical-paper-intents.sql')
) // Explicit additive migration allowlist; never replay destructive init migrations
.sort();