feat(engine): expose canonical replay sessions through native workers
This commit is contained in:
parent
417a7bd21e
commit
e3635f23cf
26 changed files with 2693 additions and 33 deletions
280
apps/stock/engine/src/api/replay.rs
Normal file
280
apps/stock/engine/src/api/replay.rs
Normal file
|
|
@ -0,0 +1,280 @@
|
|||
//! 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 napi::{Error, Result};
|
||||
#[cfg(not(test))]
|
||||
use napi_derive::napi;
|
||||
use serde::{de::DeserializeOwned, Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct Identity {
|
||||
version: Version,
|
||||
session_id: Id,
|
||||
dataset_hash: String,
|
||||
}
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct Load {
|
||||
identity: Identity,
|
||||
prepared: PreparedReplay,
|
||||
config: ReplayConfig,
|
||||
manifest: Value,
|
||||
}
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct Advance {
|
||||
identity: Identity,
|
||||
event_budget: Counter,
|
||||
}
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct Submit {
|
||||
identity: Identity,
|
||||
barrier_id: Id,
|
||||
decisions: Vec<StrategyDecision>,
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
pub struct ReplayHost {
|
||||
replay: Option<Replay>,
|
||||
identity: Identity,
|
||||
manifest: Value,
|
||||
config: ReplayConfig,
|
||||
delivered: usize,
|
||||
}
|
||||
|
||||
impl ReplayHost {
|
||||
pub fn new(input: String) -> Result<Self> {
|
||||
let load: Load = parse(&input)?;
|
||||
let hash = &load.identity.dataset_hash;
|
||||
if hash.len() != 64
|
||||
|| !hash
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
|
||||
|| load.identity.session_id != load.config.matching.risk.ledger.session_id
|
||||
|| serde_json::to_value(&load.prepared.dataset_id).map_err(error)? != json!(hash)
|
||||
|| load.manifest.get("hash") != Some(&json!(hash))
|
||||
|| load.manifest.get("version") != Some(&json!(2))
|
||||
{
|
||||
return Err(error("session/dataset identity or version mismatch"));
|
||||
}
|
||||
let replay = Replay::new(load.prepared, load.config.clone()).map_err(error)?;
|
||||
Ok(Self {
|
||||
replay: Some(replay),
|
||||
identity: load.identity,
|
||||
manifest: load.manifest,
|
||||
config: load.config,
|
||||
delivered: 0,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn advance(&mut self, input: String) -> Result<String> {
|
||||
let request: Advance = parse(&input)?;
|
||||
self.check(&request.identity)?;
|
||||
let replay = self.replay.as_mut().unwrap();
|
||||
let step = replay
|
||||
.advance(usize::try_from(request.event_budget.get()).map_err(error)?)
|
||||
.map_err(error)?;
|
||||
// Borrow a delta, not checkpoint/history clones. Only published bars can
|
||||
// enter this array; the future vector is never serialized to callbacks.
|
||||
let observations: Vec<_> = replay.observations_since(self.delivered).collect();
|
||||
let delivered = self.delivered + observations.len();
|
||||
let payload = match step {
|
||||
ReplayStep::Progress { processed } => json!({"type":"progress", "processed":processed}),
|
||||
ReplayStep::Decision(barrier) => {
|
||||
json!({"type":"decisionBatch", "barrier":barrier, "view":view(replay)?})
|
||||
}
|
||||
ReplayStep::Complete => json!({"type":"complete"}),
|
||||
ReplayStep::Failed { diagnostic } => json!({"type":"failed", "diagnostic":diagnostic}),
|
||||
};
|
||||
let output = serde_json::to_string(
|
||||
&json!({"identity":self.identity,"step":payload,"observations":observations}),
|
||||
)
|
||||
.map_err(error)?;
|
||||
self.delivered = delivered;
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
pub fn submit(&mut self, input: String) -> Result<String> {
|
||||
let request: Submit = parse(&input)?;
|
||||
self.check(&request.identity)?;
|
||||
let outcome = self
|
||||
.replay
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.submit(DecisionSubmission {
|
||||
barrier_id: request.barrier_id,
|
||||
decisions: request.decisions,
|
||||
})
|
||||
.map_err(error)?;
|
||||
serde_json::to_string(&json!({"identity":self.identity,"outcome":outcome})).map_err(error)
|
||||
}
|
||||
|
||||
pub fn finalize(&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 finalize successfully"));
|
||||
}
|
||||
serde_json::to_string(&json!({
|
||||
"identity":self.identity,"status":"complete", "manifest":self.manifest,
|
||||
"policy":self.config,"view":view(replay)?,
|
||||
"receipts":replay.financial().receipts(),
|
||||
"limitations":replay.limitations(),"modelLimitations":replay.model_limitations()
|
||||
}))
|
||||
.map_err(error)
|
||||
}
|
||||
|
||||
pub fn dispose(&mut self) {
|
||||
self.replay = None;
|
||||
}
|
||||
}
|
||||
|
||||
// NAPI's impl macro requires literal method annotations. Keep this tiny
|
||||
// delegation out of Rust unit tests; ReplayHost is the exact production host.
|
||||
#[cfg(not(test))]
|
||||
#[napi]
|
||||
pub struct FinancialReplaySession(ReplayHost);
|
||||
|
||||
#[cfg(not(test))]
|
||||
#[napi]
|
||||
impl FinancialReplaySession {
|
||||
#[napi(constructor)]
|
||||
pub fn new(input: String) -> Result<Self> {
|
||||
Ok(Self(ReplayHost::new(input)?))
|
||||
}
|
||||
#[napi]
|
||||
pub fn advance(&mut self, input: String) -> Result<String> {
|
||||
self.0.advance(input)
|
||||
}
|
||||
#[napi]
|
||||
pub fn submit(&mut self, input: String) -> Result<String> {
|
||||
self.0.submit(input)
|
||||
}
|
||||
#[napi]
|
||||
pub fn finalize(&self, input: String) -> Result<String> {
|
||||
self.0.finalize(input)
|
||||
}
|
||||
#[napi]
|
||||
pub fn dispose(&mut self) {
|
||||
self.0.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
impl ReplayHost {
|
||||
fn check(&self, identity: &Identity) -> Result<()> {
|
||||
if self.replay.is_none() {
|
||||
return Err(error("replay session is disposed"));
|
||||
}
|
||||
if identity.session_id != self.identity.session_id
|
||||
|| identity.dataset_hash != self.identity.dataset_hash
|
||||
{
|
||||
return Err(error("session/dataset identity mismatch"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn native_intent_trace_matches_direct_replay_receipts() {
|
||||
// The TS fixture asserts its verified D01 adaptation equals this exact
|
||||
// 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 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 {
|
||||
let raw = native
|
||||
.advance(json!({"identity":identity,"eventBudget":1}).to_string())
|
||||
.unwrap();
|
||||
let response: Value = serde_json::from_str(&raw).unwrap();
|
||||
match direct.advance(1).unwrap() {
|
||||
ReplayStep::Progress { .. } => assert_eq!(response["step"]["type"], "progress"),
|
||||
ReplayStep::Decision(barrier) => {
|
||||
assert_eq!(
|
||||
response["step"]["barrier"],
|
||||
serde_json::to_value(&barrier).unwrap()
|
||||
);
|
||||
let decisions:Vec<StrategyDecision>=serde_json::from_value(json!([{
|
||||
"version":1,"sessionId":"f07-fixture","barrierId":barrier.barrier_id,"revision":barrier.revision,
|
||||
"decision":{"ownerId":"A","decisionId":serde_json::to_string(&json!(["trace",sequence,"A"])).unwrap(),"sequence":sequence},
|
||||
"intent":{"mode":"target","targets":if sequence==0 {json!([{"instrumentId":"X0.US","quantity":"2.00000000"}])} else {json!([])}}
|
||||
}])).unwrap();
|
||||
let native_out:Value=serde_json::from_str(&native.submit(json!({"identity":identity,"barrierId":barrier.barrier_id,"decisions":decisions}).to_string()).unwrap()).unwrap();
|
||||
let outcome = direct
|
||||
.submit(DecisionSubmission {
|
||||
barrier_id: barrier.barrier_id,
|
||||
decisions,
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
native_out["outcome"],
|
||||
serde_json::to_value(outcome).unwrap()
|
||||
);
|
||||
sequence += 1;
|
||||
}
|
||||
ReplayStep::Complete => break,
|
||||
ReplayStep::Failed { diagnostic } => panic!("{diagnostic}"),
|
||||
}
|
||||
}
|
||||
let final_result: Value =
|
||||
serde_json::from_str(&native.finalize(identity.to_string()).unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
final_result["receipts"],
|
||||
serde_json::to_value(direct.financial().receipts()).unwrap()
|
||||
);
|
||||
assert_eq!(final_result["view"]["portfolio"]["cash"], "9975.76000000");
|
||||
assert_eq!(final_result["view"]["equity"], "10005.76000000");
|
||||
native.dispose();
|
||||
assert!(native.finalize(identity.to_string()).is_err());
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue