refactor(engine): share strict native financial views (CL18)
This commit is contained in:
parent
580a6de75c
commit
03518c8ae4
9 changed files with 252 additions and 99 deletions
63
apps/stock/engine/src/api/canonical.rs
Normal file
63
apps/stock/engine/src/api/canonical.rs
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
//! Shared wire checks and financial projections for the trusted native hosts.
|
||||
//! Host identities, envelopes and transaction boundaries remain in each adapter.
|
||||
use crate::financial::{
|
||||
contract::{Counter, Id},
|
||||
matching::{ManagedOrder, OrderStatus},
|
||||
risk::RiskAccount,
|
||||
};
|
||||
use napi::{Error, Result};
|
||||
use serde::{de::DeserializeOwned, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
fn error(error: impl std::fmt::Display) -> Error {
|
||||
Error::from_reason(error.to_string())
|
||||
}
|
||||
|
||||
// Some internal replay types accept unknown fields, and serde defaults missing
|
||||
// Option fields to None. Comparing recursive keys keeps explicit nulls required
|
||||
// at the wire boundary without changing those internal financial types.
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn parse<T: DeserializeOwned + Serialize>(
|
||||
input: &str,
|
||||
field_error: &'static str,
|
||||
) -> Result<T> {
|
||||
let raw: Value = serde_json::from_str(input).map_err(error)?;
|
||||
let typed: T = serde_json::from_str(input).map_err(error)?;
|
||||
if !keys_match(&raw, &serde_json::to_value(&typed).map_err(error)?) {
|
||||
return Err(error(field_error));
|
||||
}
|
||||
Ok(typed)
|
||||
}
|
||||
|
||||
// Revision is explicit: paper journals project intermediate effects at the
|
||||
// pre-transaction admission revision; final/replay views use the current one.
|
||||
// A lookup supports both the live matching account and paper reconstruction
|
||||
// without cloning an account or changing reservation-derived order ordering.
|
||||
pub(super) fn financial_view<'a>(
|
||||
risk: &RiskAccount,
|
||||
revision: Counter,
|
||||
order: impl Fn(&Id) -> Option<&'a ManagedOrder>,
|
||||
) -> Result<Value> {
|
||||
Ok(json!({
|
||||
"admissionRevision": revision,
|
||||
"portfolio": risk.ledger().economic_snapshot(),
|
||||
"equity": risk.ledger().equity().map_err(error)?,
|
||||
"availableCash": risk.available_cash(),
|
||||
"orders": risk.reservations().filter_map(|r| order(&r.order.order_id)).filter(|o| o.status == OrderStatus::Open).collect::<Vec<_>>(),
|
||||
"reservations": risk.reservations().collect::<Vec<_>>(),
|
||||
"risk": risk.state(),
|
||||
}))
|
||||
}
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
mod backtest;
|
||||
mod canonical;
|
||||
mod indicators;
|
||||
mod replay;
|
||||
mod paper;
|
||||
|
|
|
|||
|
|
@ -1,11 +1,12 @@
|
|||
//! Stateless trusted durable-host seam. SQL owns custody and commit/publication;
|
||||
//! MatchingAccount owns all financial transitions. No process-resident mutation.
|
||||
use super::canonical::{financial_view, parse};
|
||||
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 serde_json::Value;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
|
|
@ -49,35 +50,6 @@ struct Response {
|
|||
fn error(error: impl std::fmt::Display) -> Error {
|
||||
Error::from_reason(error.to_string())
|
||||
}
|
||||
// Option fields in checkpoints are required wire fields, including explicit nulls.
|
||||
fn keys_match(input: &Value, typed: &Value) -> bool {
|
||||
match (input, typed) {
|
||||
(Value::Object(a), Value::Object(b)) => {
|
||||
a.len() == b.len()
|
||||
&& a.iter()
|
||||
.all(|(k, v)| b.get(k).is_some_and(|other| keys_match(v, other)))
|
||||
}
|
||||
(Value::Array(a), Value::Array(b)) => {
|
||||
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| keys_match(a, b))
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
fn view(
|
||||
risk: &RiskAccount,
|
||||
orders: &BTreeMap<Id, ManagedOrder>,
|
||||
revision: Counter,
|
||||
) -> Result<Value> {
|
||||
Ok(json!({
|
||||
"admissionRevision": revision,
|
||||
"portfolio": risk.ledger().economic_snapshot(),
|
||||
"equity": risk.ledger().equity().map_err(error)?,
|
||||
"availableCash": risk.available_cash(),
|
||||
"orders": risk.reservations().filter_map(|r|orders.get(&r.order.order_id)).filter(|o|o.status == OrderStatus::Open).collect::<Vec<_>>(),
|
||||
"reservations": risk.reservations().collect::<Vec<_>>(),
|
||||
"risk": risk.state(),
|
||||
}))
|
||||
}
|
||||
fn order_map(orders: impl IntoIterator<Item = ManagedOrder>) -> BTreeMap<Id, ManagedOrder> {
|
||||
orders
|
||||
.into_iter()
|
||||
|
|
@ -141,7 +113,7 @@ fn stage(request: Request) -> Result<Response> {
|
|||
journal.push(JournalEntry {
|
||||
index: (index as u64).try_into().map_err(error)?,
|
||||
effect: effect.clone(),
|
||||
view_after: view(&risk, &orders, before.revision)?,
|
||||
view_after: financial_view(&risk, before.revision, |id| orders.get(id))?,
|
||||
});
|
||||
}
|
||||
if risk.checkpoint() != checkpoint.risk
|
||||
|
|
@ -151,11 +123,7 @@ fn stage(request: Request) -> Result<Response> {
|
|||
}
|
||||
}
|
||||
}
|
||||
let final_view = view(
|
||||
account.risk(),
|
||||
&order_map(checkpoint.orders.clone()),
|
||||
checkpoint.revision,
|
||||
)?;
|
||||
let final_view = financial_view(account.risk(), checkpoint.revision, |id| account.order(id))?;
|
||||
Ok(Response {
|
||||
version: Version,
|
||||
identity,
|
||||
|
|
@ -171,11 +139,7 @@ fn stage(request: Request) -> Result<Response> {
|
|||
/// Replayed outcomes retain the original receipt but always emit an empty journal.
|
||||
#[cfg_attr(not(test), napi)]
|
||||
pub fn stage_financial_transaction(input: String) -> Result<String> {
|
||||
let raw: Value = serde_json::from_str(&input).map_err(error)?;
|
||||
let request: Request = serde_json::from_str(&input).map_err(error)?;
|
||||
if !keys_match(&raw, &serde_json::to_value(&request).map_err(error)?) {
|
||||
return Err(error("unexpected or missing financial transaction fields"));
|
||||
}
|
||||
let request: Request = parse(&input, "unexpected or missing financial transaction fields")?;
|
||||
serde_json::to_string(&stage(request)?).map_err(error)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
use super::*;
|
||||
use crate::financial::scalar::MAX_POSTING;
|
||||
use serde_json::json;
|
||||
|
||||
fn config() -> Value {
|
||||
json!({
|
||||
|
|
@ -62,10 +63,10 @@ impl Harness {
|
|||
assert_eq!(result.checkpoint, self.direct.checkpoint());
|
||||
assert_eq!(
|
||||
result.view,
|
||||
view(
|
||||
financial_view(
|
||||
self.direct.risk(),
|
||||
&order_map(self.direct.orders().cloned()),
|
||||
self.direct.admission_revision()
|
||||
self.direct.admission_revision(),
|
||||
|id| self.direct.order(id),
|
||||
)
|
||||
.unwrap()
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
//! Trusted host-only NAPI adapter. The TS loader authenticates D01 data with
|
||||
//! validateDatasetV2; this envelope binds identity but is not a second normalizer
|
||||
//! or an untrusted-code sandbox. No mutable financial/clock handles are exported.
|
||||
use super::canonical::{financial_view, parse as parse_contract};
|
||||
use crate::financial::{
|
||||
contract::*,
|
||||
matching::OrderStatus,
|
||||
replay::*,
|
||||
reporting::ReportingFacts,
|
||||
result::{project, FinancialProjection},
|
||||
|
|
@ -73,28 +73,8 @@ struct ReportResult<'a> {
|
|||
fn error(error: impl std::fmt::Display) -> Error {
|
||||
Error::from_reason(error.to_string())
|
||||
}
|
||||
// Internal replay types intentionally were not wire contracts. Reject unknown
|
||||
// keys recursively at this adapter without changing their financial semantics.
|
||||
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 parse<T: DeserializeOwned + Serialize>(input: &str) -> Result<T> {
|
||||
let raw: Value = serde_json::from_str(input).map_err(error)?;
|
||||
let typed: T = serde_json::from_str(input).map_err(error)?;
|
||||
if !keys_match(&raw, &serde_json::to_value(&typed).map_err(error)?) {
|
||||
return Err(error("unexpected or missing session contract fields"));
|
||||
}
|
||||
Ok(typed)
|
||||
parse_contract(input, "unexpected or missing session contract fields")
|
||||
}
|
||||
|
||||
pub struct ReplayHost {
|
||||
|
|
@ -296,20 +276,45 @@ impl ReplayHost {
|
|||
|
||||
fn view(replay: &Replay) -> Result<Value> {
|
||||
let matching = replay.financial();
|
||||
Ok(json!({
|
||||
"admissionRevision":matching.admission_revision(),
|
||||
"portfolio":matching.ledger().economic_snapshot(),
|
||||
"equity":matching.ledger().equity().map_err(error)?,
|
||||
"availableCash":matching.risk().available_cash(),
|
||||
"orders":matching.risk().reservations().filter_map(|reservation| matching.order(&reservation.order.order_id)).filter(|order| order.status == OrderStatus::Open).collect::<Vec<_>>(),
|
||||
"reservations":matching.risk().reservations().collect::<Vec<_>>(),
|
||||
"risk":matching.risk().state()
|
||||
}))
|
||||
financial_view(matching.risk(), matching.admission_revision(), |id| {
|
||||
matching.order(id)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::financial::native_paper_tests::stage_financial_transaction;
|
||||
|
||||
// Drive the paper host from the same financial commands as replay. Compare
|
||||
// every published boundary, including open reservations, fills and finish.
|
||||
fn assert_paper_view(replay: &Replay, identity: &Value, paper: &mut Value) {
|
||||
let delivered = paper["checkpoint"]["receipts"].as_array().unwrap().len();
|
||||
for receipt in &replay.financial().receipts()[delivered..] {
|
||||
let crate::financial::matching::MatchingInput::Engine(command) = &receipt.input else {
|
||||
panic!("fixture unexpectedly contains an operator command");
|
||||
};
|
||||
*paper = serde_json::from_str(
|
||||
&stage_financial_transaction(
|
||||
json!({
|
||||
"version": 1,
|
||||
"kind": "apply",
|
||||
"identity": identity,
|
||||
"checkpoint": paper["checkpoint"],
|
||||
"command": command,
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(paper["view"], view(replay).unwrap());
|
||||
assert_eq!(
|
||||
paper["checkpoint"],
|
||||
serde_json::to_value(replay.financial().checkpoint()).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_intent_trace_matches_direct_replay_receipts() {
|
||||
|
|
@ -317,11 +322,29 @@ mod tests {
|
|||
// load; compare the NAPI pull transport with direct authoritative replay.
|
||||
let fixture = include_str!("../../../../../test/fixtures/native-replay-load.json");
|
||||
let load: Load = parse(fixture).unwrap();
|
||||
let paper_identity = json!({
|
||||
"sessionId": load.identity.session_id,
|
||||
"accountId": load.config.matching.risk.ledger.account_id,
|
||||
});
|
||||
let mut paper: Value = serde_json::from_str(
|
||||
&stage_financial_transaction(
|
||||
json!({
|
||||
"version": 1,
|
||||
"kind": "initialize",
|
||||
"identity": paper_identity,
|
||||
"config": load.config.matching,
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut direct = Replay::new(load.prepared, load.config).unwrap();
|
||||
let mut native = ReplayHost::new(fixture.into()).unwrap();
|
||||
let identity = serde_json::to_value(&load.identity).unwrap();
|
||||
let mut sequence = 0;
|
||||
loop {
|
||||
assert_paper_view(native.replay.as_ref().unwrap(), &paper_identity, &mut paper);
|
||||
let raw = native
|
||||
.advance(json!({"identity":identity,"eventBudget":1}).to_string())
|
||||
.unwrap();
|
||||
|
|
@ -355,6 +378,7 @@ mod tests {
|
|||
ReplayStep::Failed { diagnostic } => panic!("{diagnostic}"),
|
||||
}
|
||||
}
|
||||
assert_paper_view(native.replay.as_ref().unwrap(), &paper_identity, &mut paper);
|
||||
let final_result: Value =
|
||||
serde_json::from_str(&native.finalize(identity.to_string()).unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
|
|
|
|||
|
|
@ -42,7 +42,10 @@ mod result_tests;
|
|||
#[cfg(test)]
|
||||
mod reporting_tests;
|
||||
|
||||
// Exercise the pure host adapter without linking every legacy NAPI export.
|
||||
// Exercise the pure host adapters and shared helpers without linking every legacy NAPI export.
|
||||
#[cfg(test)]
|
||||
#[path = "../api/canonical.rs"]
|
||||
mod canonical;
|
||||
#[cfg(test)]
|
||||
#[path = "../api/replay.rs"]
|
||||
mod native_replay_tests;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue