perf(research): add compact replay projections and representative profiling
This commit is contained in:
parent
19e9dad68b
commit
e3bd722e31
21 changed files with 2830 additions and 130 deletions
|
|
@ -1,7 +1,12 @@
|
|||
//! 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 crate::financial::{contract::*, matching::OrderStatus, replay::*};
|
||||
use crate::financial::{
|
||||
contract::*,
|
||||
matching::OrderStatus,
|
||||
replay::*,
|
||||
result::{project, FinancialProjection},
|
||||
};
|
||||
use napi::{Error, Result};
|
||||
#[cfg(not(test))]
|
||||
use napi_derive::napi;
|
||||
|
|
@ -37,6 +42,24 @@ struct Submit {
|
|||
decisions: Vec<StrategyDecision>,
|
||||
}
|
||||
|
||||
/// Borrow retained provenance and flattened financial facts instead of building
|
||||
/// a serde_json::Value tree for the entire nested journal.
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ProjectionResult<'a> {
|
||||
format: &'static str,
|
||||
projection_version: Version,
|
||||
financial_version: Version,
|
||||
identity: &'a Identity,
|
||||
status: &'static str,
|
||||
manifest: &'a Value,
|
||||
policy: &'a ReplayConfig,
|
||||
view: Value,
|
||||
limitations: &'a [String],
|
||||
model_limitations: &'static [&'static str],
|
||||
projection: FinancialProjection<'a>,
|
||||
}
|
||||
|
||||
fn error(error: impl std::fmt::Display) -> Error {
|
||||
Error::from_reason(error.to_string())
|
||||
}
|
||||
|
|
@ -158,6 +181,29 @@ impl ReplayHost {
|
|||
pub fn dispose(&mut self) {
|
||||
self.replay = None;
|
||||
}
|
||||
|
||||
pub fn project(&self, input: String) -> Result<String> {
|
||||
let identity: Identity = parse(&input)?;
|
||||
self.check(&identity)?;
|
||||
let replay = self.replay.as_ref().unwrap();
|
||||
if replay.status() != &ReplayStatus::Complete {
|
||||
return Err(error("only a complete replay can project successfully"));
|
||||
}
|
||||
serde_json::to_string(&ProjectionResult {
|
||||
format: "projection",
|
||||
projection_version: Version,
|
||||
financial_version: Version,
|
||||
identity: &self.identity,
|
||||
status: "complete",
|
||||
manifest: &self.manifest,
|
||||
policy: &self.config,
|
||||
view: view(replay)?,
|
||||
limitations: replay.limitations(),
|
||||
model_limitations: replay.model_limitations(),
|
||||
projection: project(replay.financial().ledger()).map_err(error)?,
|
||||
})
|
||||
.map_err(error)
|
||||
}
|
||||
}
|
||||
|
||||
// NAPI's impl macro requires literal method annotations. Keep this tiny
|
||||
|
|
@ -186,6 +232,10 @@ impl FinancialReplaySession {
|
|||
self.0.finalize(input)
|
||||
}
|
||||
#[napi]
|
||||
pub fn project(&self, input: String) -> Result<String> {
|
||||
self.0.project(input)
|
||||
}
|
||||
#[napi]
|
||||
pub fn dispose(&mut self) {
|
||||
self.0.dispose();
|
||||
}
|
||||
|
|
@ -274,7 +324,25 @@ mod tests {
|
|||
);
|
||||
assert_eq!(final_result["view"]["portfolio"]["cash"], "9975.76000000");
|
||||
assert_eq!(final_result["view"]["equity"], "10005.76000000");
|
||||
let before = native.replay.as_ref().unwrap().checkpoint();
|
||||
let compact = native.project(identity.to_string()).unwrap();
|
||||
assert_eq!(native.project(identity.to_string()).unwrap(), compact);
|
||||
assert_eq!(native.replay.as_ref().unwrap().checkpoint(), before);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Value>(&native.finalize(identity.to_string()).unwrap()).unwrap(),
|
||||
final_result
|
||||
);
|
||||
let projected: Value = serde_json::from_str(&compact).unwrap();
|
||||
assert_eq!(projected["view"], final_result["view"]);
|
||||
assert!(projected.get("receipts").is_none());
|
||||
let load: Load = parse(fixture).unwrap();
|
||||
let restored = Replay::restore(load.prepared, load.config, &before).unwrap();
|
||||
assert_eq!(
|
||||
projected["projection"],
|
||||
serde_json::to_value(project(restored.financial().ledger()).unwrap()).unwrap()
|
||||
);
|
||||
native.dispose();
|
||||
assert!(native.finalize(identity.to_string()).is_err());
|
||||
assert!(native.project(identity.to_string()).is_err());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -67,7 +67,8 @@ pub struct LedgerCheckpoint {
|
|||
pub receipts: Vec<LedgerReceipt>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct OwnerValuation {
|
||||
pub owner_id: Id,
|
||||
pub initial_capital: Posting,
|
||||
|
|
@ -81,7 +82,8 @@ pub struct OwnerValuation {
|
|||
pub equity_contribution: Posting,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LedgerValuation {
|
||||
pub cash: Posting,
|
||||
pub marked_holdings: Posting,
|
||||
|
|
@ -693,6 +695,12 @@ impl Ledger {
|
|||
})
|
||||
}
|
||||
|
||||
/// Read-only accepted financial history, including replay-labelled aliases.
|
||||
/// Reporting must skip aliases; this does not copy a restorable checkpoint.
|
||||
pub fn receipts(&self) -> &[LedgerReceipt] {
|
||||
&self.receipts
|
||||
}
|
||||
|
||||
pub fn checkpoint(&self) -> LedgerCheckpoint {
|
||||
LedgerCheckpoint {
|
||||
version: Version,
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ pub mod contract;
|
|||
pub mod ledger;
|
||||
pub mod matching;
|
||||
pub mod replay;
|
||||
pub mod result;
|
||||
pub mod risk;
|
||||
pub mod scalar;
|
||||
|
||||
|
|
@ -24,6 +25,9 @@ mod matching_tests;
|
|||
#[cfg(test)]
|
||||
mod replay_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod result_tests;
|
||||
|
||||
// Exercise the pure host adapter without linking every legacy NAPI export.
|
||||
#[cfg(test)]
|
||||
#[path = "../api/replay.rs"]
|
||||
|
|
|
|||
115
apps/stock/engine/src/financial/result.rs
Normal file
115
apps/stock/engine/src/financial/result.rs
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
//! Read-only reporting from committed financial facts. No matching, accounting,
|
||||
//! history replay, checkpoint copies or statistical/round-trip interpretation.
|
||||
use super::{
|
||||
contract::*,
|
||||
ledger::{Ledger, LedgerError, LedgerValuation},
|
||||
scalar::Posting,
|
||||
};
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct OwnedFill<'a> {
|
||||
pub command_id: &'a Id,
|
||||
pub event_time: EventTime,
|
||||
pub owner_id: &'a Id,
|
||||
pub decision: &'a DecisionIdentity,
|
||||
pub order_id: &'a Id,
|
||||
pub fill_id: &'a Id,
|
||||
pub instrument_id: &'a Id,
|
||||
pub side: Side,
|
||||
pub quantity: Positive,
|
||||
pub price: Positive,
|
||||
pub fee: &'a Fee,
|
||||
pub cash_delta: Posting,
|
||||
pub quantity_delta: Posting,
|
||||
pub released_basis: NonNegative,
|
||||
pub realized_gross_pnl: Posting,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FinancialProjection<'a> {
|
||||
pub valuation: LedgerValuation,
|
||||
pub fills: Vec<OwnedFill<'a>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ProjectionError {
|
||||
#[error(transparent)]
|
||||
Ledger(#[from] LedgerError),
|
||||
#[error("committed fill receipt has inconsistent financial effects")]
|
||||
InconsistentReceipt,
|
||||
}
|
||||
|
||||
pub fn project(ledger: &Ledger) -> Result<FinancialProjection<'_>, ProjectionError> {
|
||||
let valuation = ledger.valuation()?;
|
||||
let mut fills = Vec::new();
|
||||
for receipt in ledger.receipts() {
|
||||
if receipt.outcome.replayed {
|
||||
continue;
|
||||
}
|
||||
let EngineCommandBody::ApplyFill {
|
||||
decision,
|
||||
order_id,
|
||||
fill_id,
|
||||
instrument_id,
|
||||
side,
|
||||
quantity,
|
||||
price,
|
||||
fee,
|
||||
} = &receipt.command.body
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let [FinancialEffect::FillApplied {
|
||||
owner_id: effect_owner,
|
||||
order_id: effect_order,
|
||||
fill_id: effect_fill,
|
||||
instrument_id: effect_instrument,
|
||||
price: effect_price,
|
||||
cash_delta,
|
||||
quantity_delta,
|
||||
released_basis,
|
||||
realized_gross_pnl,
|
||||
}, FinancialEffect::FeeApplied {
|
||||
owner_id: fee_owner,
|
||||
fill_id: fee_fill,
|
||||
fee_id,
|
||||
amount,
|
||||
}] = receipt.outcome.effects.effects.as_slice()
|
||||
else {
|
||||
return Err(ProjectionError::InconsistentReceipt);
|
||||
};
|
||||
if effect_owner != &decision.owner_id
|
||||
|| effect_order != order_id
|
||||
|| effect_fill != fill_id
|
||||
|| effect_instrument != instrument_id
|
||||
|| effect_price != price
|
||||
|| fee_owner != effect_owner
|
||||
|| fee_fill != fill_id
|
||||
|| fee_id != &fee.fee_id
|
||||
|| amount != &fee.amount
|
||||
{
|
||||
return Err(ProjectionError::InconsistentReceipt);
|
||||
}
|
||||
fills.push(OwnedFill {
|
||||
command_id: &receipt.command.command_id,
|
||||
event_time: receipt.command.event_time,
|
||||
owner_id: &decision.owner_id,
|
||||
decision,
|
||||
order_id,
|
||||
fill_id,
|
||||
instrument_id,
|
||||
side: *side,
|
||||
quantity: *quantity,
|
||||
price: *price,
|
||||
fee,
|
||||
cash_delta: *cash_delta,
|
||||
quantity_delta: *quantity_delta,
|
||||
released_basis: *released_basis,
|
||||
realized_gross_pnl: *realized_gross_pnl,
|
||||
});
|
||||
}
|
||||
Ok(FinancialProjection { valuation, fills })
|
||||
}
|
||||
146
apps/stock/engine/src/financial/result_tests.rs
Normal file
146
apps/stock/engine/src/financial/result_tests.rs
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
use super::{contract::*, ledger::*, result::project};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
fn ledger() -> Ledger {
|
||||
Ledger::new(
|
||||
serde_json::from_value(json!({
|
||||
"version":1,"sessionId":"s","accountId":"a","baseCurrency":"USD",
|
||||
"reserveOwnerId":"reserve","ownerIds":["A","B"],"initialCapital":"10000",
|
||||
"riskSession":{"calendarId":"c","calendarRevision":"1","sessionId":"d","startsAt":0}
|
||||
}))
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
fn apply(ledger: &mut Ledger, id: &str, at: i64, body: Value) -> EngineFinancialCommand {
|
||||
let command = serde_json::from_value(json!({"version":1,"sessionId":"s","accountId":"a",
|
||||
"commandId":id,"eventTime":at,"body":body}))
|
||||
.unwrap();
|
||||
ledger.apply(&command).unwrap();
|
||||
command
|
||||
}
|
||||
fn fill(
|
||||
owner: &str,
|
||||
order: &str,
|
||||
fill: &str,
|
||||
side: &str,
|
||||
quantity: &str,
|
||||
price: &str,
|
||||
fee: &str,
|
||||
) -> Value {
|
||||
json!({"kind":"applyFill","decision":{"ownerId":owner,"decisionId":order,"sequence":0},
|
||||
"orderId":order,"fillId":fill,"instrumentId":"X","side":side,"quantity":quantity,
|
||||
"price":price,"fee":{"feeId":format!("fee-{fill}"),"amount":fee}})
|
||||
}
|
||||
fn output(ledger: &Ledger) -> Value {
|
||||
serde_json::to_value(project(ledger).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projection_aliases_once_and_is_read_only_after_restore() {
|
||||
let mut ledger = ledger();
|
||||
apply(
|
||||
&mut ledger,
|
||||
"mark",
|
||||
0,
|
||||
json!({"kind":"mark","instrumentId":"X","price":"12"}),
|
||||
);
|
||||
let command = apply(
|
||||
&mut ledger,
|
||||
"fill",
|
||||
1,
|
||||
fill("A", "buy", "f1", "buy", "2", "12", "0.24"),
|
||||
);
|
||||
assert!(ledger.apply(&command).unwrap().replayed);
|
||||
let mut alias = command;
|
||||
alias.command_id = serde_json::from_value(json!("alias")).unwrap();
|
||||
assert!(ledger.apply(&alias).unwrap().replayed);
|
||||
assert_eq!(ledger.receipts().len(), 3);
|
||||
let before = ledger.checkpoint();
|
||||
let projection = output(&ledger);
|
||||
assert_eq!(projection["fills"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(projection["fills"][0]["commandId"], "fill");
|
||||
assert_eq!(projection["fills"][0]["fee"]["amount"], "0.24000000");
|
||||
// cashDelta is gross; fee remains a distinct canonical posting.
|
||||
assert_eq!(projection["fills"][0]["cashDelta"], "-24.00000000");
|
||||
assert_eq!(projection["valuation"]["cash"], "9975.76000000");
|
||||
assert_eq!(projection["valuation"]["equity"], "9999.76000000");
|
||||
assert_eq!(output(&ledger), projection);
|
||||
assert_eq!(ledger.checkpoint(), before);
|
||||
assert_eq!(output(&Ledger::restore(before).unwrap()), projection);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_fill_projection_retains_final_basis_residual_and_actual_fees() {
|
||||
let mut ledger = ledger();
|
||||
apply(
|
||||
&mut ledger,
|
||||
"mark",
|
||||
0,
|
||||
json!({"kind":"mark","instrumentId":"X","price":"3"}),
|
||||
);
|
||||
for (index, body) in [
|
||||
fill("A", "buy", "b1", "buy", "1", "1", "0.01"),
|
||||
fill("A", "buy", "b2", "buy", "2", "2", "0.04"),
|
||||
fill("A", "sell", "s1", "sell", "1", "3", "0.03"),
|
||||
fill("A", "sell", "s2", "sell", "1", "3", "0.03"),
|
||||
fill("A", "sell", "s3", "sell", "1", "3", "0.03"),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
apply(
|
||||
&mut ledger,
|
||||
&format!("command-{index}"),
|
||||
index as i64 + 1,
|
||||
body,
|
||||
);
|
||||
}
|
||||
let projection = output(&ledger);
|
||||
let fills = projection["fills"].as_array().unwrap();
|
||||
assert_eq!(fills.len(), 5);
|
||||
assert_eq!(fills[2]["releasedBasis"], "1.66666667");
|
||||
assert_eq!(fills[3]["releasedBasis"], "1.66666667");
|
||||
assert_eq!(fills[4]["releasedBasis"], "1.66666666");
|
||||
assert_eq!(projection["valuation"]["remainingCost"], "0.00000000");
|
||||
assert_eq!(projection["valuation"]["realizedGrossPnl"], "4.00000000");
|
||||
assert_eq!(projection["valuation"]["fees"], "0.14000000");
|
||||
assert_eq!(projection["valuation"]["equity"], "10003.86000000");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_owner_projection_retains_negative_contribution_and_empty_results() {
|
||||
let mut ledger = ledger();
|
||||
let empty = output(&ledger);
|
||||
assert_eq!(empty["fills"], json!([]));
|
||||
assert_eq!(empty["valuation"]["equity"], "10000.00000000");
|
||||
apply(
|
||||
&mut ledger,
|
||||
"mark",
|
||||
0,
|
||||
json!({"kind":"mark","instrumentId":"X","price":"10"}),
|
||||
);
|
||||
apply(
|
||||
&mut ledger,
|
||||
"a",
|
||||
1,
|
||||
fill("A", "a-buy", "a-fill", "buy", "1", "10", "1"),
|
||||
);
|
||||
apply(
|
||||
&mut ledger,
|
||||
"b",
|
||||
2,
|
||||
fill("B", "b-buy", "b-fill", "buy", "2", "8", "0.5"),
|
||||
);
|
||||
let projection = output(&ledger);
|
||||
let owners = projection["valuation"]["owners"].as_array().unwrap();
|
||||
assert_eq!(owners[0]["ownerId"], "A");
|
||||
assert_eq!(owners[0]["equityContribution"], "-1.00000000");
|
||||
assert_eq!(owners[1]["ownerId"], "B");
|
||||
assert_eq!(owners[1]["equityContribution"], "3.50000000");
|
||||
assert_eq!(owners[2]["ownerId"], "reserve");
|
||||
assert_eq!(owners[2]["equityContribution"], "10000.00000000");
|
||||
assert_eq!(projection["valuation"]["equity"], "10002.50000000");
|
||||
assert_eq!(projection["fills"][0]["ownerId"], "A");
|
||||
assert_eq!(projection["fills"][1]["decision"]["ownerId"], "B");
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue