diff --git a/apps/stock/engine/index.mjs b/apps/stock/engine/index.mjs index 7e463aa8..de6e3052 100644 --- a/apps/stock/engine/index.mjs +++ b/apps/stock/engine/index.mjs @@ -13,6 +13,7 @@ export const { TradingEngine, BacktestEngine, FinancialReplaySession, + stageFinancialTransaction, TechnicalIndicators, IncrementalSma, IncrementalEma, diff --git a/apps/stock/engine/src/api/mod.rs b/apps/stock/engine/src/api/mod.rs index ed7c93ad..b08fe90b 100644 --- a/apps/stock/engine/src/api/mod.rs +++ b/apps/stock/engine/src/api/mod.rs @@ -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; diff --git a/apps/stock/engine/src/api/paper.rs b/apps/stock/engine/src/api/paper.rs new file mode 100644 index 00000000..1bad2e13 --- /dev/null +++ b/apps/stock/engine/src/api/paper.rs @@ -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, + journal: Vec, +} +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, + revision: Counter, +) -> Result { + 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::>(), + "reservations": risk.reservations().collect::>(), + "risk": risk.state(), + })) +} +fn order_map(orders: impl IntoIterator) -> BTreeMap { + orders + .into_iter() + .map(|order| (order.order.order_id.clone(), order)) + .collect() +} +fn stage(request: Request) -> Result { + 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::>() != 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 { + 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; diff --git a/apps/stock/engine/src/api/paper/tests.rs b/apps/stock/engine/src/api/paper/tests.rs new file mode 100644 index 00000000..880ddc92 --- /dev/null +++ b/apps/stock/engine/src/api/paper/tests.rs @@ -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 { + 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 { + 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) -> 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); +} diff --git a/apps/stock/engine/src/financial/mod.rs b/apps/stock/engine/src/financial/mod.rs index 01020b77..446cd3b8 100644 --- a/apps/stock/engine/src/financial/mod.rs +++ b/apps/stock/engine/src/financial/mod.rs @@ -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; diff --git a/apps/stock/orchestrator/src/backtest/strategy-runtime.ts b/apps/stock/orchestrator/src/backtest/strategy-runtime.ts index 57aaf90d..8684cfbe 100644 --- a/apps/stock/orchestrator/src/backtest/strategy-runtime.ts +++ b/apps/stock/orchestrator/src/backtest/strategy-runtime.ts @@ -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(value: T): DeepReadonly { - if (value && typeof value === 'object' && !Object.isFrozen(value)) { - for (const child of Object.values(value)) { - freeze(child); - } - Object.freeze(value); - } - return value as DeepReadonly; -} - -/** 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()): 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; interface Slot { program: Metadata & { decide: StrategyProgram['decide'] }; diagnostic: DeepReadonly; 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; 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; - 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); diff --git a/apps/stock/orchestrator/src/contracts/canonical-execution.ts b/apps/stock/orchestrator/src/contracts/canonical-execution.ts new file mode 100644 index 00000000..719da74c --- /dev/null +++ b/apps/stock/orchestrator/src/contracts/canonical-execution.ts @@ -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; +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; +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; + +/** 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; + +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; +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; +export type CanonicalFinancialView = z.infer; + +// 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, + b = right as Record; + 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; +} diff --git a/apps/stock/orchestrator/src/contracts/native-replay.ts b/apps/stock/orchestrator/src/contracts/native-replay.ts index 421042e8..60457c21 100644 --- a/apps/stock/orchestrator/src/contracts/native-replay.ts +++ b/apps/stock/orchestrator/src/contracts/native-replay.ts @@ -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(), diff --git a/apps/stock/orchestrator/src/execution/CanonicalPaperExecution.ts b/apps/stock/orchestrator/src/execution/CanonicalPaperExecution.ts new file mode 100644 index 00000000..3fedce0b --- /dev/null +++ b/apps/stock/orchestrator/src/execution/CanonicalPaperExecution.ts @@ -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(); +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; + 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; + } + ) { + 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 { + 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 { + 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>> + ) { + 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 + ): 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>> + ) { + 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 { + 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, + })); + } +} diff --git a/apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository.ts b/apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository.ts new file mode 100644 index 00000000..c68b60dc --- /dev/null +++ b/apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository.ts @@ -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(accountId: string, work: (tx: CanonicalTransaction) => Promise): Promise { + 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; + }); + } +} diff --git a/apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts b/apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts index cb0b8014..7854a431 100644 --- a/apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts +++ b/apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts @@ -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`, diff --git a/apps/stock/orchestrator/src/execution/canonical-paper.ts b/apps/stock/orchestrator/src/execution/canonical-paper.ts new file mode 100644 index 00000000..99ae1152 --- /dev/null +++ b/apps/stock/orchestrator/src/execution/canonical-paper.ts @@ -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; +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; +export type CanonicalOwner = z.infer; +export type CanonicalStoredInput = z.infer; +export type CanonicalBatch = z.infer; +export type CanonicalJournalPayload = z.infer; +export type CanonicalJournalEntry = { sequence: number; payload: CanonicalJournalPayload }; +export interface CanonicalTransaction { + account: CanonicalAccount; + owners(): Promise; + putOwner(owner: CanonicalOwner): Promise; + getInput(id: string): Promise; + nextInput(): Promise; + putInput(input: CanonicalStoredInput): Promise; + nextBatch(): Promise; + putBatch(batch: CanonicalBatch): Promise; + appendJournal(payload: CanonicalJournalPayload): Promise; + journal(after: number): Promise; +} +export interface CanonicalExecutionRepository { + initialize(initial: CanonicalAccount, owners: CanonicalOwner[]): Promise; + transact(accountId: string, work: (tx: CanonicalTransaction) => Promise): Promise; +} +export type CanonicalPostgres = Pick; +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' + ); + } +} diff --git a/apps/stock/orchestrator/src/strategies/strategy-decision.ts b/apps/stock/orchestrator/src/strategies/strategy-decision.ts new file mode 100644 index 00000000..69cc3cf9 --- /dev/null +++ b/apps/stock/orchestrator/src/strategies/strategy-decision.ts @@ -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(value: T): DeepReadonly { + if (value && typeof value === 'object' && !Object.isFrozen(value)) { + for (const child of Object.values(value)) { + freeze(child); + } + Object.freeze(value); + } + return value as DeepReadonly; +} + +/** 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()): 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; + +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, + 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; + 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, + }, + }; +} diff --git a/apps/stock/web-api/src/migrations/migration-runner.ts b/apps/stock/web-api/src/migrations/migration-runner.ts index a9b75d73..9bdfbe57 100644 --- a/apps/stock/web-api/src/migrations/migration-runner.ts +++ b/apps/stock/web-api/src/migrations/migration-runner.ts @@ -54,7 +54,8 @@ export async function runMigrations(container: IServiceContainer): Promise 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(); diff --git a/database/postgres/init/15-canonical-paper-intents.sql b/database/postgres/init/15-canonical-paper-intents.sql new file mode 100644 index 00000000..f1855da6 --- /dev/null +++ b/database/postgres/init/15-canonical-paper-intents.sql @@ -0,0 +1,13 @@ +-- All owners at one financial revision commit one immutable native decision batch. +-- Native order IDs are retained verbatim in checkpoints/journals, not legacy UUID tables. +CREATE TABLE IF NOT EXISTS simulation_canonical_intents ( + account_id TEXT NOT NULL REFERENCES simulation_accounts(id), + id TEXT NOT NULL, + sequence BIGINT NOT NULL CHECK (sequence > 0), + status TEXT NOT NULL CHECK (status IN ('pending', 'dispatched', 'failed')), + payload JSONB NOT NULL, + PRIMARY KEY (account_id, id), + UNIQUE (account_id, sequence) +); +CREATE INDEX IF NOT EXISTS simulation_canonical_intents_pending + ON simulation_canonical_intents(account_id, sequence) WHERE status = 'pending'; diff --git a/docs/development/ROADMAP.md b/docs/development/ROADMAP.md index a64d94de..7c3c4bf5 100644 --- a/docs/development/ROADMAP.md +++ b/docs/development/ROADMAP.md @@ -410,6 +410,18 @@ S03 is the next highest-priority code/ADR-ready task. [Its pinned execution cont Preserve existing row locks, journal context, idempotency and rollback behavior. Canonical next-event timing and immutable policy differ explicitly from legacy execution; refuse implicit account conversion. Retain failed native prefixes atomically as terminal, and keep notification delivery separate from financial commit. No performance work, default switch, paper feed activation or other pending ADR approval is included. S04 owns feed readiness; R01/R11 still require ADR-006. +**Validated handoff:** S03 is `review` / `validated_uncommitted`. Twenty-two source/test files are integrated with recorded hashes and independent G1/G2 signoff. `stageFinancialTransaction` restores private state and applies the existing Rust matcher. Its ordered financial views are reconstructed through the same risk reducer and checked against the authoritative result. Replayed commands return their original outcome with the current checkpoint and no new effect journal. + +The canonical host uses the existing PostgreSQL account row lock. It commits all due owners' state/RNG/checkpoints and one complete batch intent together, then dispatches the batch in a separate transaction. Native snapshots, per-effect views, journals, input status and admission feedback commit atomically. Mixed-cadence owners retain their unconsumed observations. The shared decision helper preserves S01 research behavior. One additive migration stores complete canonical batches; legacy accounts explicitly refuse canonical envelopes and retain their existing execution path. + +Coverage includes competing hosts, SQL rollback, lost acknowledgements, frozen callback inputs, all four time-in-force policies, risk reservations, stale quotes, exact quote-cursor decisions, and terminal failures during both admission and execution. A real SMA program matches uninterrupted state and journals after repeated replacement. Four separate-process kill cases cover decision staging, checkpoint commit, admission commit and fill/fee commit; recovery matches uninterrupted execution exactly. + +`CARGO_BUILD_JOBS=2 bun run check` passed build/types/contracts/audit/lint plus **82 tooling, 43 utility, 44 calculation, 432 integration and 150 Rust tests**. Four existing manual Rust measurements remain ignored. The complete disposable PostgreSQL/Redis suite passed **81 tests / 545 assertions**. Extra strict TypeScript exposed only test fixture typing issues; these were corrected without changing application behavior, then strict test compilation, scoped format/lint and **38 targeted tests / 281 assertions** passed. Browser/Python boundaries were unchanged and their suites were not rerun. No profiling, optimization or benchmark run occurred. + +The native addon was built and verified against this checkout's debug library for the full gates, then rebuilt in release mode. Another **38 tests / 366 assertions** passed against the final release addon; no timing measurements were performed. Source archives, exact commands/hashes and logs are recorded in `manifest.json` → `sixteenth_wave_validation` and `/tmp/stock-bot-wave16.kgaZm4/`. Only the two exact disposable test containers were stopped; development services, worktrees and logs were retained. + +Limits remain explicit: trusted SQL custody, new canonical account IDs, execution-series observations only, immutable declared program metadata rather than retained code artifacts, and invalid queued inputs that fail closed until diagnosed. Rust validates opaque financial receipts before each financial transition; startup alone is not a full receipt audit. **Next after acceptance/commit: S04**, feed scheduling, auxiliary observation manifests and operator readiness. S05 is independently code/ADR-ready; R01/R11 still require ADR-006. S03 does not activate paper/live execution or switch existing web/research defaults. No S03 commit, push or PR was created. + ## Deferred and rejected Conditional: shared feature cache D04; cross-trial resident datasets P03; large-detail pagination/storage P05; tiny DSL P06; expanded cross-service monitoring O02. Each has a measured/real-need trigger and is not a prerequisite for scheduled work. diff --git a/docs/development/backlog/README.md b/docs/development/backlog/README.md index dc7e8bcc..faabfcac 100644 --- a/docs/development/backlog/README.md +++ b/docs/development/backlog/README.md @@ -1,6 +1,6 @@ # Canonical development backlog -**First fifteen waves committed; S03 is in progress.** S02 is accepted as `ca5abdd`. The owner deferred performance work; P08 is on hold. S03 preserves durable execution/recovery while adopting the canonical Rust kernel. Consult manifest execution_scope and [current wave](../ROADMAP.md#sixteenth-wave-execution--2026-10-23). ADR-002/003/004/005 are approved; other policies/default cutovers remain gated. +**First fifteen waves committed; S03 is validated for review.** S02 is accepted as `ca5abdd`. The owner deferred performance work; P08 is on hold. S03 preserves durable execution/recovery on the canonical Rust kernel, with full repository and disposable-database checks passing. Its changes remain uncommitted. Consult manifest execution_scope and [current wave](../ROADMAP.md#sixteenth-wave-execution--2026-10-23). ADR-002/003/004/005 are approved; other policies/default cutovers remain gated. ## One source of truth @@ -54,7 +54,7 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr | --- | --- | --- | --- | --- | | [S01 Run deterministic TypeScript decisions on Rust sessions](tasks/S01.md) | P0 / done | F07, ADR-004, ADR-005 | — | TypeScript trading infrastructure / M | | [S02 Adapt one SMA strategy for the first canonical path](tasks/S02.md) | P1 / done | S01 | — | TypeScript strategy/quant engineering / M | -| [S03 Adapt durable paper transactions to Rust financial reducers](tasks/S03.md) | P0 / in_progress | S01, C06, ADR-005 | — | Durable execution/Rust integration / L | +| [S03 Adapt durable paper transactions to Rust financial reducers](tasks/S03.md) | P0 / review | S01, C06, ADR-005 | — | Durable execution/Rust integration / L | | [S04 Establish a verified paper feed and operator safety gate](tasks/S04.md) | P1 / blocked | S02, S03 | — | TypeScript trading infrastructure / M | | [S05 Add a small composable multi-signal regime example](tasks/S05.md) | P2 / ready | S02, F08 | R08 | Quant strategy research / M | | [S06 Retire duplicate simulator paths after cutover proof](tasks/S06.md) | P2 / blocked | S03, S04, R05 | — | TypeScript trading infrastructure / M | diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index 78d8ce18..3d23c7e3 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -1,8 +1,8 @@ { "schema_version": 1, - "plan_revision": "2026-10-23.35", + "plan_revision": "2026-10-23.36", "repository_base": "b7aeca4", - "plan_status": "sixteenth_wave_in_progress", + "plan_status": "sixteenth_wave_validated", "execution_authorized": true, "execution_scope": { "authorized_by": "User: commit and continue, then stop performance work for now and continue remaining backlog (2026-10-23). S02 accepted and committed ca5abdd. S03 is the highest-priority ready non-performance task under approved ADR-005.", @@ -1037,7 +1037,7 @@ "epic": "E4", "priority": "P0", "severity": "Critical", - "status": "in_progress", + "status": "review", "dependencies": [ "S01", "C06" @@ -1066,7 +1066,7 @@ "release_gates": [], "worktree": "/tmp/stock-bot-wave16.kgaZm4/durable", "integration_base": "ca5abdde0e131ef4ec8c60ff9a4de4e277fc0820", - "integration_state": "isolated_implementation", + "integration_state": "validated_uncommitted", "implementation_slices": [ { "owner": "/root/s03_native", @@ -1080,7 +1080,10 @@ "branch": "wave16/s03-durable", "scope": "Versioned SQL custody, shared S01 decision staging, actual canonical strategy/RNG/pending-prefix recovery, one durable owner-batch outbox, migration and failure tests." } - ] + ], + "reviewed_by": "/root/s03_review", + "verification_reference": "ROADMAP.md#sixteenth-wave-execution--2026-10-23", + "review_notes": "Integrated canonical native staging and SQL custody with actual strategy/RNG/mixed-cadence recovery. Independent G1/G2 review, full repository checks, full disposable PostgreSQL/Redis suites, strict test types and final targeted/release tests passed. Source remains uncommitted. No default, feed, paper/live activation or performance work." }, { "id": "S04", @@ -5894,6 +5897,166 @@ "S03 reuses Rust financial semantics and existing SQL transaction/row-lock/journal guarantees. Native and durable owners have isolated worktrees; review is independent.", "Versioned new canonical accounts only. No implicit legacy migration, current service/default switch, operator reset, broker execution or paper feed activation.", "Native Failed outcomes with committed-prefix effects persist as terminal before surfacing error; SQL failure discards private state. Duplicate outcomes emit no duplicate effects.", - "Persist all-owner checkpoint/intent batches and mixed-cadence observation prefixes; reuse S01 staging without changing its public research recovery semantics or inventing a paper dataset hash." - ] + "Persist all-owner checkpoint/intent batches and mixed-cadence observation prefixes; reuse S01 staging without changing its public research recovery semantics or inventing a paper dataset hash.", + "S03 is validated for review, with 22 integrated source/test files. Root added actual process-kill cases at decision/checkpoint/admission/fill boundaries.", + "Exact consumed-quote decisions and persisted identity/revision checks were corrected during review. Canonical Failed prefixes persist terminal before errors surface, including failed admission batches.", + "Full repository and all 81 disposable-database tests passed. Strict test-only typing corrections preserve runtime assertions; final targeted tests and release-addon checks passed.", + "After S03 acceptance/commit, S04 is the next non-performance task. S05 is independently code/ADR-ready; R01/R11 still require ADR-006. P08 remains deferred." + ], + "sixteenth_wave_validation": { + "state": "validated_uncommitted", + "work_root": "/tmp/stock-bot-wave16.kgaZm4", + "committed_before_implementation": { + "S02": "ca5abdde0e131ef4ec8c60ff9a4de4e277fc0820", + "planning": "5e9655de0bf367ec4c740e13796dd84eb39ae6f2" + }, + "scope": [ + "Stateless native transaction adapter on existing MatchingAccount/RiskAccount", + "Exact per-effect native financial views and original replay outcomes with current checkpoints", + "Versioned canonical SQL custody and complete all-owner batch intents", + "Shared S01 strategy staging with durable JSON/RNG/pending-observation recovery", + "Explicit refusal between legacy and canonical account envelopes", + "Additive canonical batch migration and failure/recovery tests" + ], + "source_integration": { + "files": 22, + "exact_hashes": { + "apps/stock/engine/index.mjs": "cc9e8206880590baae8a988005f9bfb1b92e7dfe689ca47b81e89f2ca28ca7a3", + "apps/stock/engine/src/api/mod.rs": "b04df31c1a67e88c2533579903267425e048b0ffc134727a7f80c8e79fe19f01", + "apps/stock/engine/src/api/paper.rs": "1352a493eaa7684c06455f76a83d87e66463e3a400e33ea107f7b4a816f9766e", + "apps/stock/engine/src/api/paper/tests.rs": "03e0e935467e7aec2d1b9cb309c35a907a25ad63bdaf660cdc9e304128e47b7e", + "apps/stock/engine/src/financial/mod.rs": "66bc1a0d2455a345c4b796742ed188f85a79c04e660cce84121ae432008d205d", + "apps/stock/orchestrator/src/backtest/strategy-runtime.ts": "d72cc4749847d2506d6808be364f16b465896063c04cb5434e6c1d412c96dc8a", + "apps/stock/orchestrator/src/contracts/canonical-execution.ts": "9af274b41e8c3179d18776e249c8af1914dbb8091b63a38bc5871a4c5da7dfed", + "apps/stock/orchestrator/src/contracts/native-replay.ts": "3fc0aac64767355121e232fd71be12c80327cb49b2f2496c92c41e622a3d7f0a", + "apps/stock/orchestrator/src/execution/CanonicalPaperExecution.ts": "216f447a8922ebd328a0416aa76dfe2af0d4b22efb798a3b0b418152e8b28fe2", + "apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository.ts": "f1b43a971325fc91c8857d4c0ede35a40acacce0d354ab4907cac67ecb0a55fe", + "apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts": "992fdca2454ecf098c76ed97c8d444817ff0b939f0918b68aedeb2a6e44774d8", + "apps/stock/orchestrator/src/execution/canonical-paper.ts": "252bb14103024ad364432ddd33792b188105989389194e0052cd9f0a5dcef7f4", + "apps/stock/orchestrator/src/strategies/strategy-decision.ts": "a5c78e95447daa45d7f5fc8f5e2ab9ae1f8aa27eec5a0dd5460f8d0d4ac56b8f", + "apps/stock/web-api/src/migrations/migration-runner.ts": "7d3fcdac4ce5f6dd14b20cf143f2c49f4a87a9401c564185b0bc9a5e5b3a3ff2", + "database/postgres/init/15-canonical-paper-intents.sql": "5e4cd7b03f5194c4cd1a4d198f5dbfdbc4d7b7985ae30f848a34f4b929795bda", + "scripts/test/architecture.test.ts": "edb5524f14c2cba29d3001ad53d26a43be4f0670c1b7f679d94922840b05707c", + "scripts/test/native-bindings.test.ts": "af6a6fa3eb252d48d9cefb6e6d4fd9e87fccfd6f0075314835f6c7814f1ecf50", + "test/fixtures/canonical-paper-crash-owner.ts": "e46478ffea29ef19ccd172dfcd2dfc736048ccc71e5822f9b957052fe5b037fb", + "test/fixtures/canonical-paper.ts": "b627d3e7750b60670811d262796a2cb2fd072cf2d9cf10e2cb0572b633cd55a5", + "test/postgres/canonical-paper-crash.test.ts": "6cef77f13032d4fa91e70d6ae0f548dd88cb9aef7a1b7d3f6aae9741ac97641d", + "test/postgres/canonical-paper.test.ts": "89896f1e9635e491f4070e74be6dccb4424418ace5b1aa945093798050beab8e", + "test/postgres/migration-runner.test.ts": "7b572cfca9914c85429ed7b6b8ad624ff7c4f75e99f726f907778d3f646e3fe3" + }, + "source_archive": "/tmp/stock-bot-wave16.kgaZm4/s03-integrated-source.tar", + "source_archive_sha256": "7f63dd118a7a8aacae5c406d1722f3ec6aef606de74e6eb6e209fbf3b237943c", + "native_archive_sha256": "b6bb48ece6625b115bf28d1688b4425620a85945320dfd4a695817d2fa974e23", + "durable_archive_sha256": "48ac2501fea24d609db11710871855ea22ec4c75a61c8bdc136ff9a426c93ecb", + "test_overlays": { + "native": "77f1efcbb17f0e2b9efda92cf203c98bc78a69f5d6f872aeb6a57fbfb8d44cfc", + "durable": "38334e9cd25f4700654271bbad58f8b3867c7843db6f76b489c8e63535680b89" + }, + "note": "Production source matches independently reviewed frozen slices. Root adds four-boundary crash tests; final test-only corrections use branded decimals, discriminator narrowing, correct fixture username and explicit migration logger. No application change followed full repository validation." + }, + "review": { + "reviewer": "/root/s03_review", + "result": "G1/G2 accepted; final test-only delta reviewed with no signoff regression", + "findings_resolved": [ + "Allow exact consumed Quote Execution key without same-quote fills", + "Validate persisted envelope/context identity and revisions before callback", + "Commit native failed execution/admission prefixes before surfacing errors", + "Retain slow-owner observation prefixes and immutable callback context", + "Test all four actual process-kill boundaries including committed fill and fee" + ] + }, + "checks": [ + { + "command": "CARGO_BUILD_JOBS=2 bun run check", + "result": "passed", + "counts": { + "tooling": 82, + "utilities": 43, + "calculations": 44, + "integration": 432, + "rust": 150, + "rust_manual_ignored": 4 + }, + "log": "/tmp/stock-bot-wave16.kgaZm4/integration-check.log" + }, + { + "command": "PIPELINE_TEST_DATABASE_URL=postgres://fixture:fixture@127.0.0.1:32816/stock_bot_safety BACKTEST_TEST_REDIS_URL=redis://127.0.0.1:32815/15 bun run test:postgres", + "result": "passed", + "tests": 81, + "assertions": 545, + "log": "/tmp/stock-bot-wave16.kgaZm4/integration-postgres.log" + }, + { + "command": "bunx --no-install tsc --project /tmp/stock-bot-wave16.kgaZm4/tsconfig.s03-tests.json --noEmit", + "result": "passed", + "log": "/tmp/stock-bot-wave16.kgaZm4/integration-test-types-final.log" + }, + { + "command": "Scoped Prettier --check and ESLint --no-ignore --max-warnings 0 over integrated TypeScript except the existing architecture test; full architecture tests pass through bun run check. git diff --check.", + "result": "passed", + "log": "/tmp/stock-bot-wave16.kgaZm4/integration-format-lint.log" + }, + { + "command": "PIPELINE_TEST_DATABASE_URL=postgres://fixture:fixture@127.0.0.1:32816/stock_bot_safety bun test test/postgres/canonical-paper.test.ts test/postgres/canonical-paper-crash.test.ts test/postgres/migration-runner.test.ts scripts/test/native-bindings.test.ts", + "result": "passed after test-only typing corrections", + "tests": 38, + "assertions": 281, + "log": "/tmp/stock-bot-wave16.kgaZm4/integration-final-focused.log" + }, + { + "command": "CARGO_BUILD_JOBS=2 bun run --cwd apps/stock/engine build:release", + "result": "passed; final addon matches local target/release/libengine.so", + "log": "/tmp/stock-bot-wave16.kgaZm4/integration-release-build.log" + }, + { + "command": "bun test scripts/test/native-bindings.test.ts test/integration/strategy-runtime.test.ts test/integration/canonical-sma.test.ts", + "result": "passed against final release addon", + "tests": 38, + "assertions": 366, + "log": "/tmp/stock-bot-wave16.kgaZm4/integration-release-focused.log" + } + ], + "native": { + "debug_sha256": "75e33ffdd1e2738537879e62243a9d8f63665864835a58c46087bb4b78f274ff", + "final_profile": "release", + "final_addon_sha256": "ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103", + "local_library_matches": true, + "performance_measurements": false + }, + "economic_and_recovery_evidence": [ + "Direct Rust command tape equals staged persisted checkpoints and ordered effects", + "Same-revision owner batches reconcile shared cash reservations, owner fills and fees", + "Restart and four hard-kill boundaries match uninterrupted complete snapshots/journals", + "Actual canonical SMA buy and sell executions preserve checkpoint/journal parity after replacement", + "Failed admission batch and failed execution prefix are terminal, committed exactly once, and refuse restart mutation", + "DAY/GTC/IOC/FOK, stale quote rejection, cancellation, explicit daily risk rollover and reducing risk orders survive restart", + "Old command and quote aliases retain current financial state without duplicate observations/effects" + ], + "environment_notes": [ + "Initial NAPI sandbox EPERM required escalation; one native-owner approval wait was interrupted and root took over isolated builds.", + "Restricted database connections failed; authorized disposable-fixture tests passed outside sandbox.", + "Three initial PostgreSQL fixture expectations were corrected to existing native semantics: only supported quote events alias, stale marks reject orders requiring readmission, all owners have fee entries including zero.", + "Extra strict test compilation found test-only decimal branding/narrowing/config errors and an existing incomplete migration test container; corrections preserve production behavior.", + "Browser E2E and Python analytics were not rerun because those boundaries were unchanged.", + "No profiling, optimization, benchmark measurements, default cutover, trading operations, push or PR." + ], + "limitations": [ + "Only explicitly initialized new canonical accounts; incompatible legacy snapshots/config changes refuse conversion.", + "Trusted SQL custody: outer metadata checked on reads; opaque native receipts replay-validated before each financial transition, not fully audited by initialization alone.", + "Only configured execution-series observations; S04 owns auxiliary observation/cadence manifests, real feed alignment and operator readiness.", + "Invalid queued commands fail closed and remain pending with drain diagnostics; no automatic skip/dead-letter framework.", + "Program metadata/version/seed/initial-state binding is not retained immutable code provenance; R01/R05 own artifacts.", + "Research keeps its resident native loop; no per-event paper snapshot transport added to research." + ], + "cleanup": { + "status": "completed", + "stopped_container_ids": [ + "d915a0cd02120d8d09a7e2bb9b3fe4ad1b58e69ca6fd081fba003029f53ead23", + "02c258682d95171a7e58740bb5d24c8ba544be6789fd1382e47367ad22d0f78d" + ], + "development_resources_untouched": true, + "worktrees_and_logs_retained": true + }, + "next": "Accept/commit S03, then S04 verified paper feed/operator readiness. S05 independently ready; research-product R01/R11 require ADR-006. P08 remains deferred by owner request." + } } diff --git a/docs/development/backlog/tasks/S03.md b/docs/development/backlog/tasks/S03.md index 2ccdc96e..29220534 100644 --- a/docs/development/backlog/tasks/S03.md +++ b/docs/development/backlog/tasks/S03.md @@ -25,7 +25,7 @@ No unrelated refactor, new service or broker activation. - apps/stock/orchestrator/src/services/ExecutionService.ts - apps/stock/engine/src/api/ -Write locks: ts-execution-model, paper-transaction, financial-contract. One agent owns this change. Lock names do not override actual overlapping files. +Write locks: ts-execution-model, paper-transaction, financial-contract. The integration owner coordinates disjoint native and durable custody slices; one designated owner controls each shared contract. Lock names do not override actual overlapping files. ## Dependencies and blockers @@ -68,12 +68,22 @@ At the paper boundary, intermediate views may be reconstructed by restoring the **Durable custody:** retain the existing SQL account row lock and transaction mechanism. New explicitly canonical account IDs use a versioned outer envelope containing the opaque native checkpoint plus TS cursors/pending work. Reuse generic JSON journal/checkpoint/input storage where compatible; add only the all-owner batch-intent storage actually needed. Native order snapshots and ordered fill journal facts are authoritative persisted records; do not introduce UUID remapping or redundant financial projections. Legacy repository reads/initialization explicitly refuse canonical envelopes, and canonical initialization refuses legacy state or changed configuration. No implicit account conversion. +SQL custody is trusted. Account reads validate outer versions, identities, revision consistency and bound definitions. Rust replays and validates the opaque financial checkpoint before each financial transition; initialization alone does not certify every nested stored financial receipt. Do not introduce a second TypeScript ledger validator. + **Actual strategy recovery:** a canonical paper runner accepts trusted normalized input commands/observations and optional decision scheduling metadata. S04 supplies the real feed/calendar/scheduler; the caller cannot supply a portfolio or revision. Capture the committed native view for a decision. Restore program JSON state, RNG state/draws, decision cursors and pending observation prefixes for every owner before evaluating all due owners against that same view. Functionally extract/reuse S01 staging logic; preserve its public research diagnostics and complete-retry behavior. Never invent a historical dataset hash for paper. Atomically save all next checkpoints and one complete decision-batch intent. Dispatch that batch in a subsequent locked transaction and persist actual admission feedback with its financial snapshot/effects. Drain pending batch, then pending decision, then next input; do not admit later financial input while recovery is pending. Reject caller-supplied Submit commands on the paper input path. Per-owner pending observations must survive mixed-cadence restarts. Trusted program definitions are bound by declared metadata/version/seed/mode/initial state; immutable code artifact retention remains R01/R05. +Ordinary decisions use a Decision-phase event key. Quote-driven decisions may use the exact consumed quote's Execution key, as the existing native matcher permits; they cannot fill against that consumed quote. Never invent a later timestamp to bypass event ordering. + +This custody slice accepts observations only for configured execution series. An auxiliary feature/timeframe observation manifest and feed cadence/alignment belong to S04; this does not claim full research multi-timeframe parity. Invalid admitted commands fail closed at drain without financial advancement and remain pending for diagnosis; there is no automatic skip or dead-letter framework. S04 readiness must refuse incomplete/failed recovery, including a pending invalid input. + **Failures:** SQL failure discards all private staged changes. Native validation/restore errors with no returned transition roll back. A returned native `Failed` outcome can contain a committed financial prefix: save its failed snapshot and exact ordered effects atomically, mark the account/batch terminal, then surface failure after commit. Never report successful execution or keep a running retry state. Publication occurs after commit and cannot roll back finance; stable readable journal IDs recover notification gaps without claiming exactly-once delivery. -Port existing failure/recovery scenarios to approved canonical economics. Legacy immediate cached-quote fills, UTC implicit resets, shorts and mutable policy reloads are not canonical compatibility promises. Preserve DAY/GTC/IOC/FOK under next-eligible-event timing and explicit venue/risk sessions, and retain legacy tests unchanged. Required added cases include old-command/alias retries after later fills, failed-prefix custody, shared-revision owner batches, mixed-cadence restart, pending-input recovery, SQL decision/intent/effect failures, lost commit acknowledgement and competing producers. +Port existing failure/recovery scenarios to approved canonical economics. Legacy immediate cached-quote fills, UTC implicit resets, shorts and mutable policy reloads are not canonical compatibility promises. Preserve DAY/GTC/IOC/FOK under next-eligible-event timing and explicit venue/risk sessions, and retain legacy tests unchanged. Required added cases include old-command/alias retries after later fills, failed-prefix custody, shared-revision owner batches, mixed-cadence restart, pending-input recovery, SQL decision/intent/effect failures, lost commit acknowledgement and competing producers. Kill a separate process before decision commit, after checkpoint/batch commit, after admission commit and after fill/fee commit; compare recovered checkpoints and ordered journals with uninterrupted execution. Native and TypeScript owners work in separate worktrees with an accepted wire-schema overlay. The native owner controls the new API/schema and minimal existing-schema exports; the durable owner controls custody, shared strategy staging and canonical recovery. Root controls integration/migrations acceptance; independent review checks invariants. No default/service/feed activation or paper trading operation is authorized by this task. + +## Validation handoff — 2026-10-23 + +Implementation and independent G1/G2 review passed. The manifest records the 22-file source hashes, native artifact, commands and raw logs. Full repository checks and all 81 disposable-database tests passed; strict new-test TypeScript and 38 final targeted tests passed after test-only typing corrections. The host and native adapter are integrated but uncommitted; S04 activation and feed work remain separate. See the [sixteenth-wave record](../../ROADMAP.md#sixteenth-wave-execution--2026-10-23). diff --git a/docs/development/backlog/tasks/S04.md b/docs/development/backlog/tasks/S04.md index c3498e06..fadf18c9 100644 --- a/docs/development/backlog/tasks/S04.md +++ b/docs/development/backlog/tasks/S04.md @@ -13,6 +13,8 @@ Scheduling source of truth: [manifest entry S04](../manifest.json). No task is a Verify the real paper feed path, recovery and stale-feed/kill controls on the canonical engine. Own the minimal paper-readiness endpoint/status needed to activate safely; do not wait for optional O02 cross-service dashboards. Reuse existing monitoring routes/components for actual state, unknown rather than fake zeros. Live remains disabled. +S03 supplies transaction custody and trusted command ingestion, not feed scheduling. Define the host's observation-series/cadence manifest before accepting auxiliary feature timeframes; retain the separate native execution-series configuration. Schedule ordinary completed observations and exact consumed-quote decisions without timestamp restamping. A durably admitted invalid input remains pending and drain rejects it: readiness must fail closed until recovery succeeds, without silently skipping data or resetting capital. + ## Exclusions No unrelated refactor, new service or broker activation. diff --git a/scripts/test/architecture.test.ts b/scripts/test/architecture.test.ts index a6240a5a..4579af7b 100644 --- a/scripts/test/architecture.test.ts +++ b/scripts/test/architecture.test.ts @@ -225,6 +225,12 @@ describe('orchestrator architecture boundaries', () => { ) { expect(path).toBe('backtest/native-replay.ts'); } + if ( + !binding.isTypeOnly && + (binding.propertyName ?? binding.name).text === 'stageFinancialTransaction' + ) { + expect(path).toBe('execution/CanonicalPaperExecution.ts'); + } } } } diff --git a/scripts/test/native-bindings.test.ts b/scripts/test/native-bindings.test.ts index 9ff1b29a..d0756d61 100644 --- a/scripts/test/native-bindings.test.ts +++ b/scripts/test/native-bindings.test.ts @@ -4,9 +4,16 @@ import { BacktestEngine, FinancialReplaySession, IncrementalSMA, + stageFinancialTransaction, TechnicalIndicators, TradingEngine, } from '@stock-bot/engine'; +import { parseFinancialDecimal } from '@stock-bot/types'; +import { + financialTransactionRequestSchema, + parseFinancialTransactionResult, +} from '../../apps/stock/orchestrator/src/contracts/canonical-execution'; +import nativeReplayLoad from '../../test/fixtures/native-replay-load.json'; describe('generated native bindings', () => { it('fill P&L is an incremental delta and native FIFO commissions are allocated once', () => { @@ -72,6 +79,7 @@ describe('generated native bindings', () => { expect(binding.TechnicalIndicators).toBe(TechnicalIndicators); expect(binding.IncrementalSMA).toBe(IncrementalSMA); expect(binding.FinancialReplaySession).toBe(FinancialReplaySession); + expect(binding.stageFinancialTransaction).toBe(stageFinancialTransaction); expect(typeof FinancialReplaySession.prototype.project).toBe('function'); expect(typeof FinancialReplaySession.prototype.report).toBe('function'); }); @@ -122,3 +130,169 @@ describe('generated native bindings', () => { ).toThrow('SMA periods must satisfy'); }); }); + +describe('stateless native financial transaction contract', () => { + const config = nativeReplayLoad.config.matching; + const identity = { + sessionId: config.risk.ledger.sessionId, + accountId: config.risk.ledger.accountId, + }; + function initialized() { + const request = financialTransactionRequestSchema.parse({ + version: 1, + kind: 'initialize', + identity, + config, + }); + return parseFinancialTransactionResult( + stageFinancialTransaction(JSON.stringify(request)), + identity + ); + } + function marked() { + const init = initialized(); + const at = config.risk.ledger.riskSession.startsAt; + const command = { + commandId: 'mark', + key: { at, phase: 'Observation', instrumentId: 'X0.US', sourceSequence: 0 }, + body: { kind: 'mark', seriesId: 'X0.US:1m', price: '10', observedAt: at }, + }; + const request = financialTransactionRequestSchema.parse({ + version: 1, + kind: 'apply', + identity, + checkpoint: init.checkpoint, + command, + }); + if (request.kind !== 'apply') { + throw new Error('Expected an apply request in the mark fixture'); + } + const raw = stageFinancialTransaction(JSON.stringify(request)); + return { init, request, raw, result: parseFinancialTransactionResult(raw, identity) }; + } + it('initializes and applies with strict parsed views, checkpoint and exact journal effects', () => { + const { init, result } = marked(); + expect(init.outcome).toBeNull(); + expect(init.view.equity).toBe(parseFinancialDecimal('10000.00000000')); + expect(result.checkpoint.revision).toBe(1); + expect(result.journal).toHaveLength(1); + expect(result.journal[0]!.viewAfter.admissionRevision).toBe(0); + expect(result.view.admissionRevision).toBe(1); + expect(result.view.portfolio.cash).toBe(init.view.portfolio.cash); + }); + it('returns no journal for an old replay after a later mark', () => { + const { request, result } = marked(); + const later = { + ...request.command, + commandId: 'later', + key: { ...request.command.key, at: request.command.key.at + 1 }, + body: { + kind: 'mark', + seriesId: 'X0.US:1m', + price: '11', + observedAt: request.command.key.at + 1, + }, + }; + const advanced = parseFinancialTransactionResult( + stageFinancialTransaction( + JSON.stringify({ ...request, checkpoint: result.checkpoint, command: later }) + ), + identity + ); + const replay = parseFinancialTransactionResult( + stageFinancialTransaction(JSON.stringify({ ...request, checkpoint: advanced.checkpoint })), + identity + ); + expect(replay.journal).toEqual([]); + expect(replay.view).toEqual(advanced.view); + expect(replay.outcome!.revision).toBe(1); + expect(replay.checkpoint.revision).toBe(2); + expect(replay.checkpoint).toEqual(advanced.checkpoint); + }); + it('rejects missing fields, wrong identity/revision and altered effect journals', () => { + const { raw } = marked(); + const mutations: Array<(value: any) => void> = [ + value => { + delete value.journal[0].effect.Risk.command; + }, + value => { + delete value.journal[0].effect.Risk.outcome.financial.effects; + }, + value => { + value.identity.accountId = 'wrong'; + }, + value => { + value.view.admissionRevision = 0; + }, + value => { + value.journal[0].viewAfter.admissionRevision = 1; + }, + value => { + value.journal[0].index = 2; + }, + value => { + value.journal[0].effect.Risk.outcome.disposition = { Rejected: 'Invented' }; + }, + value => { + value.journal[0].effect.Risk.command.commandId = 'different'; + }, + ]; + for (const mutate of mutations) { + const bad = JSON.parse(raw); + mutate(bad); + expect(() => parseFinancialTransactionResult(JSON.stringify(bad), identity)).toThrow(); + } + const reordered = JSON.parse(raw); + const command = reordered.journal[0].effect.Risk.command; + reordered.journal[0].effect.Risk.command = Object.fromEntries( + Object.entries(command).reverse() + ); + expect(() => + parseFinancialTransactionResult(JSON.stringify(reordered), identity) + ).not.toThrow(); + }); + it('validates initialized metadata and rejects operator/legacy/malformed native requests', () => { + const result = initialized(); + const bad = structuredClone(result); + bad.checkpoint.cursor = { + at: 1, + phase: 'Observation', + instrumentId: 'X0.US', + sourceSequence: 0, + }; + expect(() => parseFinancialTransactionResult(JSON.stringify(bad), identity)).toThrow( + 'initialized' + ); + expect(() => + stageFinancialTransaction( + JSON.stringify({ + version: 1, + kind: 'apply', + identity, + checkpoint: { cash: 1000 }, + command: {}, + }) + ) + ).toThrow(); + expect(() => + stageFinancialTransaction(JSON.stringify({ version: 1, kind: 'reset', identity })) + ).toThrow(); + expect(() => + stageFinancialTransaction( + JSON.stringify({ + version: 1, + kind: 'initialize', + identity: { ...identity, accountId: 'other' }, + config, + }) + ) + ).toThrow('identity'); + const request = { + version: 1, + kind: 'initialize', + identity, + config: { ...config, unexpected: true }, + }; + expect(() => stageFinancialTransaction(JSON.stringify(request))).toThrow(); + }); +}); diff --git a/test/fixtures/canonical-paper-crash-owner.ts b/test/fixtures/canonical-paper-crash-owner.ts new file mode 100644 index 00000000..24393293 --- /dev/null +++ b/test/fixtures/canonical-paper-crash-owner.ts @@ -0,0 +1,77 @@ +/** Runs only in a disposable schema; the parent kills this process at a durable boundary. */ +import { Pool } from 'pg'; +import { PostgreSQLClient } from '@stock-bot/postgres'; +import type { CanonicalExecutionRepository } from '../../apps/stock/orchestrator/src/execution/canonical-paper'; +import { CanonicalPaperExecution } from '../../apps/stock/orchestrator/src/execution/CanonicalPaperExecution'; +import { PostgresCanonicalExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository'; +import { canonicalConfig, counterProgram } from './canonical-paper'; +import { logger } from './execution'; + +const url = process.env.PIPELINE_TEST_DATABASE_URL; +const schema = process.env.CANONICAL_CRASH_SCHEMA; +const phase = process.env.CANONICAL_CRASH_PHASE; +if ( + !url || + !new URL(url).pathname.startsWith('/stock_bot_safety') || + !schema || + !/^stock_bot_safety_[a-f0-9]+$/.test(schema) || + !['decision', 'checkpoint', 'dispatch', 'fill'].includes(phase ?? '') +) { + throw new Error('Unsafe canonical crash fixture'); +} +const pool = new Pool({ connectionString: url, options: '-c search_path=' + schema }); +const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, + logger +); +Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); +const durable = new PostgresCanonicalExecutionRepository(postgres); +const block = async () => { + process.send?.({ phase }); + await new Promise(() => {}); +}; +const repository: CanonicalExecutionRepository = { + initialize: (account, owners) => durable.initialize(account, owners), + async transact(accountId, work) { + let committedBoundary = false; + const result = await durable.transact(accountId, tx => + work({ + ...tx, + async putOwner(owner) { + // The callback has returned, but neither its next checkpoint nor its + // complete batch has committed. Killing here must roll both back. + if (phase === 'decision' && owner.diagnostic.nextDecisionSequence > 0) { + await block(); + } + await tx.putOwner(owner); + }, + async putBatch(batch) { + await tx.putBatch(batch); + committedBoundary = + (phase === 'checkpoint' && batch.status === 'pending') || + (phase === 'dispatch' && batch.status === 'dispatched'); + }, + async putInput(input) { + await tx.putInput(input); + if ( + phase === 'fill' && + input.status === 'applied' && + input.input.command.body.kind === 'execute' + ) { + committedBoundary = true; + } + }, + }) + ); + if (committedBoundary) { + // SQL has committed, but drain has not received its acknowledgement and + // cannot publish. Restart must use committed state without rerunning it. + await block(); + } + return result; + }, +}; +const execution = new CanonicalPaperExecution({ repository, programs: [counterProgram()] }); +await execution.initialize(canonicalConfig()); +await execution.drain(); +throw new Error('Canonical crash fixture did not reach its requested boundary'); diff --git a/test/fixtures/canonical-paper.ts b/test/fixtures/canonical-paper.ts new file mode 100644 index 00000000..84d4bbd5 --- /dev/null +++ b/test/fixtures/canonical-paper.ts @@ -0,0 +1,137 @@ +import { parseFinancialDecimal } from '@stock-bot/types'; +import type { CanonicalMatchingConfig } from '../../apps/stock/orchestrator/src/contracts/canonical-execution'; +import type { StrategyProgram } from '../../apps/stock/orchestrator/src/contracts/canonical-strategy'; +import type { CanonicalPaperInput } from '../../apps/stock/orchestrator/src/execution/canonical-paper'; + +export function canonicalConfig(owners = ['A']): CanonicalMatchingConfig { + return { + risk: { + ledger: { + version: 1, + sessionId: 'canonical-paper-test', + accountId: 'canonical-paper-test', + baseCurrency: 'USD', + reserveOwnerId: 'reserve', + ownerIds: owners, + initialCapital: '1000', + riskSession: { + calendarId: 'account', + calendarRevision: '1', + sessionId: 'risk-1', + startsAt: 0, + }, + }, + feeRate: '0.01', + maxOrderQuantity: '100', + maxPositionQuantity: '100', + maxSymbolExposure: '10000', + maxGrossExposure: '10000', + maxDailyLoss: '100', + maxDrawdownAmount: '1000', + maxMarkAgeMs: 1000, + }, + owners: owners.map(ownerId => ({ ownerId, mode: 'Target' })), + series: [{ instrumentId: 'X', seriesId: 'X:quote', mode: 'Quote' }], + halfSpreadRate: '0', + slippageRate: '0', + latencyMs: 0, + }; +} +export type CounterState = { count: number; samples: number[]; seen: number[] }; +export function counterProgram(ownerId = 'A'): StrategyProgram { + return { + ownerId, + strategyId: 'counter', + strategyVersion: '1', + mode: 'target', + seed: 7, + initialState: { count: 0, samples: [], seen: [] }, + decide(context) { + return { + nextState: { + count: context.state.count + 1, + samples: [...context.state.samples, context.random()], + seen: [...context.state.seen, ...context.observations.map(row => row.source_sequence)], + }, + intent: { + mode: 'target', + targets: [{ instrumentId: 'X', quantity: parseFinancialDecimal('2') }], + }, + }; + }, + }; +} +export function openInput(): CanonicalPaperInput { + return { + command: { + commandId: 'open', + key: { at: 0, phase: 'Observation', instrumentId: 'X', sourceSequence: 0 }, + body: { kind: 'openSession', session: { sessionId: 'venue-1', opensAt: 0, closesAt: 10000 } }, + }, + observations: [], + }; +} +export function markInput(sequence: number, ownerIds = ['A'], price = '10'): CanonicalPaperInput { + const at = sequence * 10; + return { + command: { + commandId: `mark-${sequence}`, + key: { at, phase: 'Observation', instrumentId: 'X', sourceSequence: sequence }, + body: { kind: 'mark', seriesId: 'X:quote', price, observedAt: at }, + }, + observations: [ + { + series_id: 'X:quote', + instrument_id: 'X', + interval_start: at - 1, + interval_end: at, + event_time: at, + available_at: at, + source_sequence: sequence, + open: parseFinancialDecimal(price), + high: parseFinancialDecimal(price), + low: parseFinancialDecimal(price), + close: parseFinancialDecimal(price), + volume: parseFinancialDecimal('100'), + }, + ], + ...(ownerIds.length + ? { + decision: { + commandId: `decision-${sequence}`, + key: { at, phase: 'Decision' as const, instrumentId: 'X', sourceSequence: sequence }, + barrierId: `barrier-${sequence}`, + ownerIds, + inputs: [ + { + series_id: 'X:quote', + availability: { Fresh: { event_time: at, available_at: at } }, + }, + ], + }, + } + : {}), + }; +} +export function quoteInput(sequence: number, capacity = '100', price = '10'): CanonicalPaperInput { + const at = sequence * 10 + 1; + return { + command: { + commandId: `quote-${sequence}`, + key: { at, phase: 'Execution', instrumentId: 'X', sourceSequence: sequence }, + body: { + kind: 'execute', + seriesId: 'X:quote', + observation: { + kind: 'quote', + observedAt: at, + bid: price, + ask: price, + bidSize: capacity, + askSize: capacity, + }, + }, + }, + observations: [], + }; +} diff --git a/test/postgres/canonical-paper-crash.test.ts b/test/postgres/canonical-paper-crash.test.ts new file mode 100644 index 00000000..3e28ec41 --- /dev/null +++ b/test/postgres/canonical-paper-crash.test.ts @@ -0,0 +1,165 @@ +import { fork } from 'node:child_process'; +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Pool } from 'pg'; +import { PostgreSQLClient } from '@stock-bot/postgres'; +import { parseFinancialDecimal } from '@stock-bot/types'; +import { CanonicalPaperExecution } from '../../apps/stock/orchestrator/src/execution/CanonicalPaperExecution'; +import { PostgresCanonicalExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository'; +import { + canonicalConfig, + counterProgram, + markInput, + openInput, + quoteInput, +} from '../fixtures/canonical-paper'; +import { logger } from '../fixtures/execution'; + +const url = process.env.PIPELINE_TEST_DATABASE_URL; +const cleanup: (() => Promise)[] = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); + +async function fixture() { + if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { + throw new Error('Dedicated safety database required'); + } + const schema = 'stock_bot_safety_' + randomUUID().replaceAll('-', ''); + const admin = new Pool({ connectionString: url }); + await admin.query('CREATE SCHEMA ' + schema); + const pool = new Pool({ connectionString: url, options: '-c search_path=' + schema }); + cleanup.push(async () => { + await pool.end(); + await admin.query('DROP SCHEMA ' + schema + ' CASCADE'); + await admin.end(); + }); + for (const migration of [ + '11-simulation-execution-ledger.sql', + '13-strategy-recovery.sql', + '15-canonical-paper-intents.sql', + ]) { + await pool.query( + readFileSync(new URL('../../database/postgres/init/' + migration, import.meta.url), 'utf8') + ); + } + const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, + logger + ); + Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); + const make = async (onDecision = () => {}) => { + const program = counterProgram(); + const observed: typeof program = { + ...program, + decide(context) { + onDecision(); + return program.decide(context); + }, + }; + const execution = new CanonicalPaperExecution({ + repository: new PostgresCanonicalExecutionRepository(postgres), + programs: [observed], + }); + await execution.initialize(canonicalConfig()); + return execution; + }; + return { schema, pool, make }; +} + +describe.skipIf(!url)('canonical paper process recovery on real PostgreSQL', () => { + test.each(['decision', 'checkpoint', 'dispatch', 'fill'] as const)( + 'hard kill at %s matches uninterrupted state, effects and fees', + async phase => { + const baselineFixture = await fixture(); + const baseline = await baselineFixture.make(); + const interruptedFixture = await fixture(); + const interrupted = await interruptedFixture.make(); + for (const input of [openInput(), markInput(1), quoteInput(2)]) { + await baseline.enqueue(input); + await interrupted.enqueue(input); + } + await baseline.drain(); + const expected = await baseline.snapshot(); + const expectedJournal = await baseline.journal(); + expect(expected.account.checkpoint.orders).toHaveLength(1); + expect(expected.account.checkpoint.orders[0]?.status).toBe('Filled'); + expect(expected.account.view.portfolio.cash).toBe(parseFinancialDecimal('979.80000000')); + expect(expected.account.view.equity).toBe(parseFinancialDecimal('999.80000000')); + const child = fork( + fileURLToPath(new URL('../fixtures/canonical-paper-crash-owner.ts', import.meta.url)), + [], + { + execPath: process.execPath, + execArgv: [], + stdio: ['ignore', 'ignore', 'pipe', 'ipc'], + env: { + ...process.env, + CANONICAL_CRASH_SCHEMA: interruptedFixture.schema, + CANONICAL_CRASH_PHASE: phase, + }, + } + ); + let childError = ''; + child.stderr?.on('data', chunk => { + childError += String(chunk); + }); + const exited = new Promise(resolve => child.once('exit', () => resolve())); + cleanup.push(async () => { + child.kill('SIGKILL'); + await exited; + }); + await new Promise((resolve, reject) => { + const timer = setTimeout( + () => reject(new Error('Canonical crash boundary timeout: ' + childError)), + 10000 + ); + child.once('message', message => { + clearTimeout(timer); + if ((message as { phase?: string }).phase === phase) { + resolve(); + } else { + reject(new Error('Unexpected canonical crash boundary')); + } + }); + child.once('error', error => { + clearTimeout(timer); + reject(error); + }); + child.once('exit', () => { + clearTimeout(timer); + reject(new Error('Canonical child exited before boundary: ' + childError)); + }); + }); + child.kill('SIGKILL'); + await exited; + let recoveredDecisions = 0; + const recovered = await interruptedFixture.make(() => { + recoveredDecisions++; + }); + await recovered.drain(); + expect(recoveredDecisions).toBe(phase === 'decision' ? 1 : 0); + expect(await recovered.snapshot()).toEqual(expected); + expect(await recovered.journal()).toEqual(expectedJournal); + expect(await recovered.getRecoveryStatus()).toMatchObject({ + status: 'Running', + pendingDecisionSequence: null, + pendingBatch: null, + pendingInput: null, + }); + const batches = await interruptedFixture.pool.query( + 'SELECT status FROM simulation_canonical_intents' + ); + expect(batches.rows).toEqual([{ status: 'dispatched' }]); + expect(await recovered.enqueue(markInput(1))).toBe(false); + await recovered.drain(); + expect(await recovered.snapshot()).toEqual(expected); + expect(await recovered.journal()).toEqual(expectedJournal); + }, + 20000 + ); +}); diff --git a/test/postgres/canonical-paper.test.ts b/test/postgres/canonical-paper.test.ts new file mode 100644 index 00000000..64de6297 --- /dev/null +++ b/test/postgres/canonical-paper.test.ts @@ -0,0 +1,887 @@ +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Pool } from 'pg'; +import { stageFinancialTransaction } from '@stock-bot/engine'; +import { PostgreSQLClient } from '@stock-bot/postgres'; +import { parseFinancialDecimal } from '@stock-bot/types'; +import { builtinStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy'; +import { + parseFinancialTransactionResult, + type CanonicalMatchingConfig, +} from '../../apps/stock/orchestrator/src/contracts/canonical-execution'; +import type { StrategyProgram } from '../../apps/stock/orchestrator/src/contracts/canonical-strategy'; +import type { + CanonicalExecutionRepository, + CanonicalJournalEntry, + CanonicalPaperInput, + CanonicalTransaction, +} from '../../apps/stock/orchestrator/src/execution/canonical-paper'; +import { CanonicalPaperExecution } from '../../apps/stock/orchestrator/src/execution/CanonicalPaperExecution'; +import { PostgresCanonicalExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository'; +import { PostgresExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository'; +import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-sma'; +import { + canonicalConfig, + counterProgram, + markInput, + openInput, + quoteInput, + type CounterState, +} from '../fixtures/canonical-paper'; +import { logger } from '../fixtures/execution'; + +const url = process.env.PIPELINE_TEST_DATABASE_URL; +const cleanup: (() => Promise)[] = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); + +async function fixture( + config = canonicalConfig(), + programs: readonly StrategyProgram[] = [counterProgram()] +) { + if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { + throw new Error('Dedicated stock_bot_safety database required'); + } + const schema = 'stock_bot_safety_' + randomUUID().replaceAll('-', ''); + const admin = new Pool({ connectionString: url }); + await admin.query(`CREATE SCHEMA ${schema}`); + const pool = new Pool({ + connectionString: url, + options: `-c search_path=${schema} -c statement_timeout=10000`, + }); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + for (const filename of [ + '11-simulation-execution-ledger.sql', + '13-strategy-recovery.sql', + '15-canonical-paper-intents.sql', + ]) { + const sql = readFileSync( + new URL(`../../database/postgres/init/${filename}`, import.meta.url), + 'utf8' + ); + await pool.query(sql); + await pool.query(sql); + } + const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, + logger + ); + Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); + const repository = new PostgresCanonicalExecutionRepository(postgres); + const make = async ( + options: { + repository?: CanonicalExecutionRepository; + programs?: readonly StrategyProgram[]; + publish?: (entries: readonly CanonicalJournalEntry[]) => void | Promise; + } = {} + ) => { + const host = new CanonicalPaperExecution({ repository, programs, ...options }); + await host.initialize(config); + return host; + }; + return { pool, postgres, repository, make, host: await make(), config }; +} +async function send(host: CanonicalPaperExecution, input: CanonicalPaperInput) { + await host.enqueue(input); + await host.drain(); +} +function failOnce( + delegate: CanonicalExecutionRepository, + method: keyof CanonicalTransaction, + stage: 'before' | 'after' | 'commit', + matches: (value: unknown) => boolean = () => true +): CanonicalExecutionRepository { + let armed = true; + return { + initialize: (account, owners) => delegate.initialize(account, owners), + async transact(accountId: string, work: (tx: CanonicalTransaction) => Promise) { + let hit = false; + const result = await delegate.transact(accountId, tx => + work( + new Proxy(tx, { + get(target, key: keyof CanonicalTransaction) { + const value = target[key]; + if (typeof value !== 'function') { + return value; + } + return async (...args: unknown[]) => { + if (armed && key === method && matches(args[0])) { + armed = false; + hit = true; + } + if (hit && stage === 'before') { + throw new Error('injected before commit'); + } + const result = await Reflect.apply(value, target, args); + if (hit && stage === 'after') { + throw new Error('injected before commit'); + } + return result; + }; + }, + }) + ) + ); + if (hit && stage === 'commit') { + throw new Error('lost commit acknowledgement'); + } + return result; + }, + }; +} +const isPending = (value: unknown) => (value as { status?: string })?.status === 'pending'; +const isDispatched = (value: unknown) => (value as { status?: string })?.status === 'dispatched'; + +function explicitProgram( + tif: 'DAY' | 'GTC' | 'IOC' | 'FOK', + quantity = '2' +): StrategyProgram { + return { + ...counterProgram(), + mode: 'orders', + decide: context => ({ + nextState: { count: context.state.count + 1, samples: [context.random()], seen: [] }, + intent: { + mode: 'orders', + orders: + context.state.count === 0 + ? [ + { + kind: 'market', + orderId: 'explicit-order', + instrumentId: 'X', + side: 'buy', + quantity: parseFinancialDecimal(quantity), + timeInForce: tif, + }, + ] + : [], + }, + }), + }; +} +function ordersConfig(): CanonicalMatchingConfig { + const config = canonicalConfig(); + config.owners[0]!.mode = 'Orders'; + return config; +} + +describe.skipIf(!url)('canonical paper custody on real PostgreSQL', () => { + test('real strategy state/RNG and economic postings match uninterrupted replacement and the direct Rust command tape', async () => { + const f = await fixture(); + await send(f.host, openInput()); + await send(f.host, markInput(1)); + await send(f.host, quoteInput(1, '1')); + const restored = await f.make(); + await send(restored, quoteInput(2)); + await send(restored, markInput(3)); + const snapshot = await restored.snapshot(); + expect(snapshot.owners[0]!.diagnostic.nextDecisionSequence).toBe(2); + expect(snapshot.owners[0]!.diagnostic.rng.draws).toBe(2); + expect(snapshot.account.view.portfolio.positions[0]!.quantity).toBe( + parseFinancialDecimal('2.00000000') + ); + const entries = await restored.journal(); + const identity = snapshot.account.identity; + let native = parseFinancialTransactionResult( + stageFinancialTransaction( + JSON.stringify({ version: 1, kind: 'initialize', identity, config: f.config }) + ), + identity + ); + for (const row of entries) { + if (row.payload.kind === 'command') { + const commandId = row.payload.command.commandId; + native = parseFinancialTransactionResult( + stageFinancialTransaction( + JSON.stringify({ + version: 1, + kind: 'apply', + identity, + checkpoint: native.checkpoint, + command: row.payload.command, + }) + ), + identity + ); + expect(native.outcome).toEqual(row.payload.outcome); + expect(native.view).toEqual(row.payload.view); + expect( + entries + .filter( + entry => entry.payload.kind === 'effect' && entry.payload.commandId === commandId + ) + .map(entry => (entry.payload.kind === 'effect' ? entry.payload.fact : null)) + ).toEqual(native.journal); + } + } + expect(native.checkpoint).toEqual(snapshot.account.checkpoint); + const baseline = await fixture(); + for (const input of [ + openInput(), + markInput(1), + quoteInput(1, '1'), + quoteInput(2), + markInput(3), + ]) { + await send(baseline.host, input); + } + expect(await baseline.host.snapshot()).toEqual(snapshot); + expect(await baseline.host.journal()).toEqual(entries); + expect((await f.pool.query('SELECT * FROM simulation_orders')).rows).toHaveLength(0); + expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(0); + }); + + test('competing hosts restore locked owner checkpoints and share one revision without duplicate fills or fees', async () => { + const f = await fixture(canonicalConfig(['A', 'B']), [ + counterProgram('A'), + counterProgram('B'), + ]); + const second = await f.make(); + await send(f.host, openInput()); + expect( + await Promise.all([ + f.host.enqueue(markInput(1, ['B', 'A'])), + second.enqueue(markInput(1, ['B', 'A'])), + ]) + ).toEqual([true, false]); + await Promise.all([f.host.drain(), second.drain()]); + await Promise.all([f.host.enqueue(quoteInput(1)), second.enqueue(quoteInput(1))]); + await Promise.all([f.host.drain(), second.drain()]); + const snapshot = await second.snapshot(); + expect(snapshot.owners.map(owner => owner.diagnostic.nextDecisionSequence)).toEqual([1, 1]); + expect(snapshot.account.view.portfolio.positions.map(position => position.quantity)).toEqual([ + parseFinancialDecimal('2.00000000'), + parseFinancialDecimal('2.00000000'), + ]); + const batches = (await f.pool.query('SELECT payload FROM simulation_canonical_intents')).rows; + expect(batches).toHaveLength(1); + const decisions = batches[0]!.payload.command.body.decisions; + expect(decisions[0].revision).toBe(decisions[1].revision); + expect(snapshot.account.view.portfolio.cash).toBe(parseFinancialDecimal('959.60000000')); + const conflict = markInput(1, ['A', 'B'], '12'); + await expect(second.enqueue(conflict)).rejects.toThrow('Conflicting'); + }); + + test('mixed-cadence restart retains every slow owner observation and scoped RNG prefix', async () => { + const config = canonicalConfig(['A', 'B']); + const programs = [counterProgram('A'), counterProgram('B')]; + const f = await fixture(config, programs); + await send(f.host, openInput()); + await send(f.host, markInput(1, ['A'])); + await send(f.host, markInput(2, ['A'])); + const before = await f.host.snapshot(); + expect(before.owners[1]!.pendingObservations.map(row => row.source_sequence)).toEqual([1, 2]); + const restored = await f.make(); + await send(restored, markInput(3, ['A', 'B'])); + const after = await restored.snapshot(); + expect(after.owners[1]!.diagnostic.state).toEqual({ + count: 1, + samples: [1025555898 / 4294967296], + seen: [1, 2, 3], + }); + expect(after.account.observed).toBe(3); + expect(after.owners[1]!.diagnostic.observationCount).toBe(3); + expect(after.owners[1]!.pendingObservations).toEqual([]); + }); + + test('checkpoint and complete batch SQL failure rolls back every owner decision/RNG and resumes before later input', async () => { + const config = canonicalConfig(['A', 'B']); + const programs = [counterProgram('A'), counterProgram('B')]; + const f = await fixture(config, programs); + await send(f.host, openInput()); + await f.pool + .query(`CREATE FUNCTION reject_batch() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'batch write failed'; END $$; + CREATE TRIGGER reject_batch BEFORE INSERT ON simulation_canonical_intents FOR EACH ROW EXECUTE FUNCTION reject_batch()`); + await f.host.enqueue(markInput(1, ['A', 'B'])); + await f.host.enqueue(quoteInput(1)); + await expect(f.host.drain()).rejects.toThrow('batch write failed'); + const failed = await f.host.snapshot(); + expect( + failed.owners.map(owner => [ + owner.diagnostic.nextDecisionSequence, + owner.diagnostic.rng.draws, + ]) + ).toEqual([ + [0, 0], + [0, 0], + ]); + expect(failed.owners.map(owner => owner.pendingObservations.length)).toEqual([1, 1]); + expect((await f.host.getRecoveryStatus()).pendingInput).toBe('quote-1'); + await f.pool.query('DROP TRIGGER reject_batch ON simulation_canonical_intents'); + const restored = await f.make(); + await restored.drain(); + expect((await restored.snapshot()).account.view.portfolio.positions).toHaveLength(2); + }); + + test('effect journal failure rolls back native fills, account and input; no phantom publication', async () => { + const f = await fixture(); + await send(f.host, openInput()); + await send(f.host, markInput(1)); + const before = await f.host.snapshot(); + const publications: CanonicalJournalEntry[] = []; + const host = await f.make({ + publish: entries => { + publications.push(...entries); + }, + }); + await host.enqueue(quoteInput(1)); + await f.pool.query(`CREATE FUNCTION reject_effect() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN + IF NEW.payload->>'kind' = 'effect' THEN RAISE EXCEPTION 'effect write failed'; END IF; RETURN NEW; END $$; + CREATE TRIGGER reject_effect BEFORE INSERT ON simulation_strategy_journal FOR EACH ROW EXECUTE FUNCTION reject_effect()`); + await expect(host.drain()).rejects.toThrow('effect write failed'); + expect((await host.snapshot()).account.checkpoint).toEqual(before.account.checkpoint); + expect(publications).toEqual([]); + expect((await host.getRecoveryStatus()).pendingInput).toBe('quote-1'); + await f.pool.query('DROP TRIGGER reject_effect ON simulation_strategy_journal'); + const restored = await f.make(); + await restored.drain(); + expect((await restored.snapshot()).account.view.portfolio.positions[0]!.quantity).toBe( + parseFinancialDecimal('2.00000000') + ); + }); + + test('lost checkpoint/dispatch commit acknowledgement and throwing publication cannot duplicate decisions, costs or effects', async () => { + for (const [method, matches] of [ + ['putBatch', isPending], + ['putBatch', isDispatched], + ] as const) { + const f = await fixture(); + await send(f.host, openInput()); + const host = await f.make({ + repository: failOnce(f.repository, method, 'commit', matches), + publish: () => { + throw new Error('observer failed'); + }, + }); + await host.enqueue(markInput(1)); + await host.enqueue(quoteInput(1)); + await expect(host.drain()).rejects.toThrow('lost commit acknowledgement'); + const restored = await f.make({ + publish: () => { + throw new Error('observer failed'); + }, + }); + await restored.drain(); + const before = await restored.snapshot(); + const journal = await restored.journal(); + await restored.enqueue(markInput(1)); + await restored.enqueue(quoteInput(1)); + await restored.drain(); + expect(await restored.snapshot()).toEqual(before); + expect(await restored.journal()).toEqual(journal); + expect(before.owners[0]!.diagnostic.nextDecisionSequence).toBe(1); + expect(before.account.view.portfolio.cash).toBe(parseFinancialDecimal('979.80000000')); + expect(await restored.journal(journal.at(-2)!.sequence)).toEqual(journal.slice(-1)); + } + }); + + test('failed owner callback rolls back earlier owner state/RNG, nested inputs cannot mutate another owner', async () => { + let fail = true; + let retained: unknown; + const first: StrategyProgram = { + ...counterProgram('A'), + decide(context) { + retained = context; + expect(Object.isFrozen(context.portfolio.portfolio)).toBe(true); + expect(Object.isFrozen(context.observations[0])).toBe(true); + expect(Object.isFrozen(context.state.samples)).toBe(true); + expect(() => Object.assign(context.observations[0]!, { close: '900' })).toThrow(); + return counterProgram('A').decide(context); + }, + }; + const second: StrategyProgram = { + ...counterProgram('B'), + decide(context) { + expect(context.observations[0]!.close).toBe(parseFinancialDecimal('10.00000000')); + if (fail) { + throw new Error('second owner failed'); + } + return counterProgram('B').decide(context); + }, + }; + const f = await fixture(canonicalConfig(['A', 'B']), [first, second]); + await send(f.host, openInput()); + await f.host.enqueue(markInput(1, ['A', 'B'])); + await expect(f.host.drain()).rejects.toThrow('second owner failed'); + expect((await f.host.snapshot()).owners.map(owner => owner.diagnostic.rng.draws)).toEqual([ + 0, 0, + ]); + expect(() => (retained as { random(): number }).random()).toThrow('only valid'); + fail = false; + await f.host.drain(); + expect((await f.host.snapshot()).owners.map(owner => owner.diagnostic.rng.draws)).toEqual([ + 1, 1, + ]); + }); + + test('alias receipts after later fills do not append observations, decisions or old effect journals', async () => { + const f = await fixture(); + await send(f.host, openInput()); + const quote = quoteInput(1); + quote.observations = markInput(1).observations; + quote.decision = { ...markInput(1).decision!, key: quote.command.key }; + await send(f.host, quote); + await send(f.host, quoteInput(2)); + const before = await f.host.snapshot(); + const journal = await f.host.journal(); + const alias = structuredClone(quote); + alias.command.commandId = 'old-quote-alias'; + await send(f.host, alias); + const after = await f.host.snapshot(); + expect(after.owners).toEqual(before.owners); + expect(after.account.observed).toBe(before.account.observed); + expect(after.account.view).toEqual(before.account.view); + expect(await f.host.journal()).toEqual(journal); + expect(after.account.checkpoint.receipts.length).toBe( + before.account.checkpoint.receipts.length + 1 + ); + }); + + test('exact quote cursor decisions never consume the same quote twice; only a later eligible quote fills', async () => { + const f = await fixture(); + await send(f.host, openInput()); + const quote = quoteInput(1); + quote.observations = markInput(1).observations; + quote.decision = { ...markInput(1).decision!, key: quote.command.key }; + await send(f.host, quote); + expect((await f.host.snapshot()).account.view.portfolio.positions).toHaveLength(0); + const alias = structuredClone(quote); + alias.command.commandId = 'quote-alias'; + await send(f.host, alias); + expect((await f.host.snapshot()).owners[0]!.diagnostic.nextDecisionSequence).toBe(1); + expect((await f.host.snapshot()).account.view.portfolio.positions).toHaveLength(0); + await send(f.host, quoteInput(2)); + expect((await f.host.snapshot()).account.view.portfolio.positions[0]!.quantity).toBe( + parseFinancialDecimal('2.00000000') + ); + }); + + test('version/config/seed/initial-state changes and legacy accounts explicitly refuse reinterpretation', async () => { + const f = await fixture(); + const changed = canonicalConfig(); + changed.risk.feeRate = '0.1'; + await expect(f.host.initialize(changed)).rejects.toThrow('configuration'); + for (const program of [ + { ...counterProgram(), seed: 8 }, + { ...counterProgram(), strategyVersion: '2' }, + { ...counterProgram(), initialState: { count: 1, samples: [], seen: [] } }, + ]) { + await expect(f.make({ programs: [program] })).rejects.toThrow('definition'); + } + const legacy = new PostgresExecutionRepository(f.postgres); + await expect(legacy.transact(f.config.risk.ledger.accountId, async () => null)).rejects.toThrow( + 'canonical adapter' + ); + await expect(legacy.initialize(f.config.risk.ledger.accountId, {} as never)).rejects.toThrow( + 'canonical adapter' + ); + await f.pool.query( + 'UPDATE simulation_accounts SET state = \'{"kind":"canonical-paper","version":99}\'' + ); + await expect(f.make()).rejects.toThrow('explicit migration'); + await expect(legacy.transact(f.config.risk.ledger.accountId, async () => null)).rejects.toThrow( + 'canonical adapter' + ); + await f.pool.query('UPDATE simulation_accounts SET state = \'{"cash":100}\''); + await expect(f.make()).rejects.toThrow('explicit migration'); + }); + + test('future observations, wrong availability, direct submissions and out-of-order new commands cannot reach a callback', async () => { + let called = 0; + const program: StrategyProgram = { + ...counterProgram(), + decide(context) { + called++; + return counterProgram().decide(context); + }, + }; + const f = await fixture(canonicalConfig(), [program]); + await send(f.host, openInput()); + const future = markInput(1); + future.observations[0]!.available_at = 20; + expect(() => f.host.enqueue(future)).toThrow('unavailable'); + const submit: CanonicalPaperInput = { + command: { + commandId: 'bypass', + key: markInput(1).command.key, + body: { kind: 'submit', decisions: [] }, + }, + observations: [], + }; + expect(() => f.host.enqueue(submit)).toThrow('durable'); + const wrong = markInput(1); + wrong.decision!.inputs[0]!.availability = 'Missing'; + await f.host.enqueue(wrong); + await expect(f.host.drain()).rejects.toThrow('observation prefix'); + expect(called).toBe(0); + expect((await f.host.getRecoveryStatus()).pendingInput).toBe('mark-1'); + // Invalid trusted queued inputs are retained for diagnostics; correction requires an explicit new account/tape. + const g = await fixture(); + await send(g.host, openInput()); + await send(g.host, markInput(2)); + await g.host.enqueue(markInput(1)); + await expect(g.host.drain()).rejects.toThrow(); + expect((await g.host.snapshot()).owners[0]!.diagnostic.nextDecisionSequence).toBe(1); + }); + + test('corrupt envelope/context identities fail before callback or financial changes', async () => { + const f = await fixture(); + await send(f.host, openInput()); + const host = await f.make({ repository: failOnce(f.repository, 'putOwner', 'before') }); + await host.enqueue(markInput(1)); + await expect(host.drain()).rejects.toThrow('injected'); + // Stop after the input transaction, before the actual callback. + const g = await fixture(); + await send(g.host, openInput()); + const stop = await g.make({ + repository: failOnce( + g.repository, + 'appendJournal', + 'commit', + value => (value as { kind: string }).kind === 'decision' + ), + }); + await stop.enqueue(markInput(1)); + await expect(stop.drain()).rejects.toThrow('lost commit'); + const before = (await g.pool.query('SELECT state FROM simulation_accounts')).rows[0]!.state; + await g.pool.query( + `UPDATE simulation_strategy_journal SET payload = jsonb_set(payload, '{context,barrier,revision}', '999') WHERE payload->>'kind' = 'decision'` + ); + await expect(g.host.drain()).rejects.toThrow('no longer matches'); + expect((await g.pool.query('SELECT state FROM simulation_accounts')).rows[0]!.state).toEqual( + before + ); + await g.pool.query( + `UPDATE simulation_accounts SET state = jsonb_set(state, '{identity,sessionId}', '"corrupt"')` + ); + await expect(g.host.snapshot()).rejects.toThrow('identity or revision'); + }); + + test('GTC partial fill, DAY expiry and IOC/FOK policies survive restarts under next-event timing', async () => { + for (const tif of ['GTC', 'DAY', 'IOC', 'FOK'] as const) { + const f = await fixture(ordersConfig(), [explicitProgram(tif)]); + await send(f.host, openInput()); + await send(f.host, markInput(1)); + const restored = await f.make(); + await send(restored, quoteInput(1, '1')); + let snapshot = await restored.snapshot(); + const order = snapshot.account.checkpoint.orders[0]!; + expect(order.filled).toBe(parseFinancialDecimal(tif === 'FOK' ? '0.00000000' : '1.00000000')); + expect(order.status).toBe(tif === 'IOC' || tif === 'FOK' ? 'Cancelled' : 'Open'); + if (tif === 'GTC') { + const again = await f.make(); + await send(again, quoteInput(2)); + expect((await again.snapshot()).account.checkpoint.orders[0]!.status).toBe('Filled'); + } else if (tif === 'DAY') { + await send(restored, { + command: { + commandId: 'close', + key: { at: 10000, phase: 'SessionClose', instrumentId: 'X', sourceSequence: 0 }, + body: { kind: 'closeSession', sessionId: 'venue-1' }, + }, + observations: [], + }); + snapshot = await (await f.make()).snapshot(); + expect(snapshot.account.checkpoint.orders[0]!.status).toBe('Expired'); + } + } + }); + test('portfolio reservations enforce shared cash across owners before matching', async () => { + const config = canonicalConfig(['A', 'B']); + config.risk.ledger.initialCapital = '30'; + const f = await fixture(config, [counterProgram('A'), counterProgram('B')]); + await send(f.host, openInput()); + await send(f.host, markInput(1, ['A', 'B'])); + const admitted = await f.host.snapshot(); + expect(admitted.account.checkpoint.orders.map(order => order.status)).toEqual([ + 'Open', + { Rejected: 'InsufficientCash' }, + ]); + await send(await f.make(), quoteInput(1)); + const snapshot = await f.host.snapshot(); + expect(snapshot.account.view.portfolio.cash).toBe(parseFinancialDecimal('9.80000000')); + expect(snapshot.account.view.portfolio.positions.map(position => position.ownerId)).toEqual([ + 'A', + ]); + }); + + test('daily loss survives restart, allows reductions, and requires explicit risk-session rollover', async () => { + const config = canonicalConfig(); + config.risk.maxDailyLoss = '10'; + const program: StrategyProgram = { + ...counterProgram(), + decide(context) { + const next = counterProgram().decide(context); + return { + ...next, + intent: { + mode: 'target', + targets: [ + { + instrumentId: 'X', + quantity: parseFinancialDecimal(context.state.count === 1 ? '0' : '2'), + }, + ], + }, + }; + }, + }; + const f = await fixture(config, [program]); + await send(f.host, openInput()); + await send(f.host, markInput(1)); + await send(f.host, quoteInput(1)); + await send(f.host, markInput(2, ['A'], '1')); + expect((await f.host.snapshot()).account.view.risk.dailyHalted).toBe(true); + const restored = await f.make(); + await send(restored, quoteInput(2, '100', '1')); + await send(restored, markInput(3, ['A'], '1')); + expect((await restored.snapshot()).account.checkpoint.orders.at(-1)!.status).toEqual({ + Rejected: 'DailyLoss', + }); + await send(restored, { + command: { + commandId: 'risk-rollover', + key: { at: 40, phase: 'Observation', instrumentId: 'X', sourceSequence: 4 }, + body: { + kind: 'riskSessionBoundary', + riskSession: { + calendarId: 'account', + calendarRevision: '1', + sessionId: 'risk-2', + startsAt: 40, + }, + }, + }, + observations: [], + }); + await send(await f.make(), markInput(5, ['A'], '1')); + expect((await restored.snapshot()).account.checkpoint.orders.at(-1)!.status).toBe('Open'); + }); + + test('stale quotes never fill restored orders; GTC cancellation releases reservations durably', async () => { + const f = await fixture(); + await send(f.host, openInput()); + await send(f.host, markInput(1)); + const stale = quoteInput(201); + if (stale.command.body.kind !== 'execute' || stale.command.body.observation.kind !== 'quote') { + throw new Error('fixture'); + } + stale.command.body.observation.observedAt = 10; + await send(await f.make(), stale); + expect((await f.host.snapshot()).account.view.portfolio.positions).toHaveLength(0); + expect((await f.host.snapshot()).account.checkpoint.orders[0]!.status).toEqual({ + Rejected: 'StaleMark', + }); + await send(await f.make(), markInput(202)); + await send(await f.make(), quoteInput(202)); + expect((await f.host.snapshot()).account.view.portfolio.positions[0]!.quantity).toBe( + parseFinancialDecimal('2.00000000') + ); + const program: StrategyProgram = { + ...explicitProgram('GTC'), + decide(context) { + if (context.state.count === 0) { + return explicitProgram('GTC').decide(context); + } + return { + nextState: { count: context.state.count + 1, samples: [], seen: [] }, + intent: { mode: 'orders', orders: [{ kind: 'cancel', orderId: 'explicit-order' }] }, + }; + }, + }; + const g = await fixture(ordersConfig(), [program]); + await send(g.host, openInput()); + await send(g.host, markInput(1)); + await send(g.host, quoteInput(1, '1')); + const restart = await g.make(); + await send(restart, markInput(2)); + expect((await restart.snapshot()).account.checkpoint.orders[0]!.status).toBe('Cancelled'); + expect((await restart.snapshot()).account.view.reservations).toEqual([]); + await send(restart, quoteInput(2)); + expect((await restart.snapshot()).account.view.portfolio.positions[0]!.quantity).toBe( + parseFinancialDecimal('1.00000000') + ); + }); + + test('returned native Failed prefix commits exact fees/effects once and remains terminal across restart', async () => { + const max = '792281625142643375935.43950335'; + const config = canonicalConfig(['A', 'B']); + config.owners.forEach(owner => { + owner.mode = 'Orders'; + }); + config.risk.ledger.initialCapital = '100000000000000000000'; + for (const field of [ + 'maxOrderQuantity', + 'maxPositionQuantity', + 'maxSymbolExposure', + 'maxGrossExposure', + ] as const) { + config.risk[field] = max; + } + const programs: StrategyProgram[] = ['A', 'B'].map(ownerId => ({ + ...counterProgram(ownerId), + mode: 'orders', + decide(context) { + const order = (orderId: string, side: 'buy' | 'sell', quantity: string) => ({ + kind: 'market' as const, + orderId, + instrumentId: 'X', + side, + quantity: parseFinancialDecimal(quantity), + timeInForce: 'GTC' as const, + }); + return { + nextState: { count: context.state.count + 1, samples: [context.random()], seen: [] }, + intent: { + mode: 'orders', + orders: + context.state.count === 0 + ? ownerId === 'A' + ? [order('seed', 'buy', '1')] + : [] + : [ + ownerId === 'A' + ? order('sell', 'sell', '1') + : order('overflow', 'buy', '396140812571321687967'), + ], + }, + }; + }, + })); + const f = await fixture(config, programs); + await send(f.host, openInput()); + await send(f.host, markInput(1, ['A', 'B'], '0.00000001')); + await send(f.host, quoteInput(1, '1', '0.00000001')); + await send(f.host, markInput(2, ['A', 'B'], '0.00000001')); + const failure = quoteInput(2, max, '3'); + await f.host.enqueue(failure); + await expect(f.host.drain()).rejects.toThrow('Canonical account failed'); + const snapshot = await f.host.snapshot(); + const journal = await f.host.journal(); + expect(typeof snapshot.account.checkpoint.status).toBe('object'); + expect( + snapshot.account.checkpoint.orders.find(order => order.order.orderId === 'sell')!.status + ).toBe('Filled'); + expect(snapshot.account.view.portfolio.fees).toEqual([ + { ownerId: 'A', amount: parseFinancialDecimal('0.03000000') }, + { ownerId: 'B', amount: parseFinancialDecimal('0.00000000') }, + ]); + expect( + (await f.pool.query("SELECT status FROM simulation_market_inputs WHERE id = 'quote-2'")) + .rows[0]!.status + ).toBe('applied'); + const restored = await f.make(); + await expect(restored.drain()).rejects.toThrow('Canonical account failed'); + expect(await restored.enqueue(failure)).toBe(false); + await expect(restored.enqueue(quoteInput(3))).rejects.toThrow('terminal'); + expect(await restored.snapshot()).toEqual(snapshot); + expect(await restored.journal()).toEqual(journal); + // Native can return an old successful receipt while the authoritative current checkpoint is Failed. + const old = openInput().command; + const replay = parseFinancialTransactionResult( + stageFinancialTransaction( + JSON.stringify({ + version: 1, + kind: 'apply', + identity: snapshot.account.identity, + checkpoint: snapshot.account.checkpoint, + command: old, + }) + ), + snapshot.account.identity + ); + expect(replay.outcome!.status).toBe('Running'); + expect(replay.checkpoint.status).toEqual(snapshot.account.checkpoint.status); + expect(replay.journal).toEqual([]); + }); + test('canonical SMA checkpoint and buy/sell fills exactly match uninterrupted execution after replacement', async () => { + const selection = builtinStrategySelectionSchema.parse({ + ownerId: 'A', + strategyId: 'sma_crossover', + strategyVersion: 'sma-crossover-long-only/v1', + seed: 7, + instrumentId: 'X', + seriesId: 'X:quote', + ownerBudget: '20', + parameters: { fastPeriod: 2, slowPeriod: 3 }, + }); + const run = async (restart: boolean) => { + const f = await fixture(canonicalConfig(), [createBuiltinStrategy(selection)]); + let host = f.host; + await send(host, openInput()); + for (const [index, price] of ['3', '2', '1', '4', '5', '1', '1'].entries()) { + await send(host, markInput(index + 1, ['A'], price)); + if (restart) { + host = await f.make({ programs: [createBuiltinStrategy(selection)] }); + } + await send(host, quoteInput(index + 1, '100', price)); + } + return { snapshot: await host.snapshot(), journal: await host.journal() }; + }; + const uninterrupted = await run(false); + expect(await run(true)).toEqual(uninterrupted); + const filled = uninterrupted.snapshot.account.checkpoint.orders.filter( + order => order.status === 'Filled' + ); + expect(filled.some(order => order.order.side === 'buy')).toBe(true); + expect(filled.some(order => order.order.side === 'sell')).toBe(true); + }); + test('a native failed admission prefix atomically makes its durable batch terminal', async () => { + const max = '792281625142643375935.43950335'; + const config = ordersConfig(); + config.risk.ledger.initialCapital = max; + for (const field of [ + 'maxOrderQuantity', + 'maxPositionQuantity', + 'maxSymbolExposure', + 'maxGrossExposure', + ] as const) { + config.risk[field] = max; + } + const program: StrategyProgram = { + ...explicitProgram('GTC'), + decide(context) { + return { + nextState: { count: context.state.count + 1, samples: [context.random()], seen: [] }, + intent: { + mode: 'orders', + orders: ['1', max].map((quantity, index) => ({ + kind: 'market', + orderId: `order-${index}`, + instrumentId: 'X', + side: 'buy', + quantity: parseFinancialDecimal(quantity), + timeInForce: 'GTC', + })), + }, + }; + }, + }; + const f = await fixture(config, [program]); + await send(f.host, openInput()); + await f.host.enqueue(markInput(1)); + await expect(f.host.drain()).rejects.toThrow('Canonical account failed'); + const before = await f.host.snapshot(); + const journal = await f.host.journal(); + expect(typeof before.account.checkpoint.status).toBe('object'); + expect(before.owners[0]!.diagnostic.nextDecisionSequence).toBe(1); + expect( + (await f.pool.query('SELECT status FROM simulation_canonical_intents')).rows.map( + row => row.status + ) + ).toEqual(['failed']); + const restored = await f.make(); + await expect(restored.drain()).rejects.toThrow('Canonical account failed'); + expect(await restored.snapshot()).toEqual(before); + expect(await restored.journal()).toEqual(journal); + }); +}); diff --git a/test/postgres/migration-runner.test.ts b/test/postgres/migration-runner.test.ts index fc3c0246..6837a6b9 100644 --- a/test/postgres/migration-runner.test.ts +++ b/test/postgres/migration-runner.test.ts @@ -3,7 +3,6 @@ import { readFileSync } from 'node:fs'; import { afterEach, describe, expect, test } from 'bun:test'; import type { PoolClient } from 'pg'; import { Pool } from 'pg'; -import type { IServiceContainer } from '@stock-bot/handlers'; import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { PostgreSQLClient } from '@stock-bot/postgres'; import { runMigrations } from '../../apps/stock/web-api/src/migrations/migration-runner'; @@ -18,6 +17,7 @@ const migrations = [ '12-historical-datasets.sql', '13-strategy-recovery.sql', '14-backtest-submission.sql', + '15-canonical-paper-intents.sql', ]; const cleanup: (() => Promise)[] = []; afterEach(async () => { @@ -114,7 +114,7 @@ async function fixture() { }); return { queries, - run: () => runMigrations({ postgres } as IServiceContainer), + run: () => runMigrations({ postgres, logger }), }; }; const recorded = async () =>