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");
|
||||
}
|
||||
|
|
@ -1,9 +1,11 @@
|
|||
import { fork, type ChildProcess } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import {
|
||||
parseReplayProjectionResult,
|
||||
parseReplayResult,
|
||||
replayConfigSchema,
|
||||
replayIdentitySchema,
|
||||
replayResultFormatSchema,
|
||||
} from '../contracts/native-replay';
|
||||
import { nativeWorkerMessageSchema, type NativeWorkerRequest } from './native-worker-protocol';
|
||||
import { BacktestConflictError } from './run-repository';
|
||||
|
|
@ -39,6 +41,7 @@ export class NativeBacktestWorker {
|
|||
datasetHash: (request.dataset as { manifest?: { hash?: unknown } })?.manifest?.hash,
|
||||
}),
|
||||
policy: replayConfigSchema.parse(request.config),
|
||||
format: replayResultFormatSchema.parse(request.resultFormat ?? 'trace'),
|
||||
}
|
||||
: undefined;
|
||||
const child = fork(fileURLToPath(this.workerUrl), [], {
|
||||
|
|
@ -81,7 +84,11 @@ export class NativeBacktestWorker {
|
|||
} else if (message.type === 'result') {
|
||||
if (expectedReplay) {
|
||||
try {
|
||||
parseReplayResult(message.result, expectedReplay.identity, expectedReplay.policy);
|
||||
const parse =
|
||||
expectedReplay.format === 'projection'
|
||||
? parseReplayProjectionResult
|
||||
: parseReplayResult;
|
||||
parse(message.result, expectedReplay.identity, expectedReplay.policy);
|
||||
} catch (error) {
|
||||
terminate(error instanceof Error ? error : new Error(String(error)));
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -7,7 +7,8 @@ import {
|
|||
type FinancialStrategyIntent,
|
||||
} from '@stock-bot/types';
|
||||
import {
|
||||
parseReplayResult,
|
||||
parseReplayProjectionValue,
|
||||
parseReplayResultValue,
|
||||
replayConfigSchema,
|
||||
replayTraceSchema,
|
||||
sameIdentity,
|
||||
|
|
@ -17,7 +18,10 @@ import {
|
|||
type PublishedObservation,
|
||||
type ReplayConfig,
|
||||
type ReplayIdentity,
|
||||
type ReplayOutput,
|
||||
type ReplayProjectionResult,
|
||||
type ReplayResult,
|
||||
type ReplayResultFormat,
|
||||
type ReplayStep,
|
||||
type ReplayTraceRequest,
|
||||
} from '../contracts/native-replay';
|
||||
|
|
@ -28,6 +32,9 @@ export type {
|
|||
ReplayIdentity,
|
||||
ReplayStep,
|
||||
ReplayResult,
|
||||
ReplayProjectionResult,
|
||||
ReplayOutput,
|
||||
ReplayResultFormat,
|
||||
DecisionContext,
|
||||
PublishedObservation,
|
||||
ReplayTraceRequest,
|
||||
|
|
@ -144,6 +151,7 @@ export class NativeReplaySession {
|
|||
submitResponseBytes: 0,
|
||||
resultBytes: 0,
|
||||
};
|
||||
readonly finalization = { nativeMs: 0, decodeMs: 0, validationMs: 0 };
|
||||
constructor(load: ReturnType<typeof prepareReplayLoad>) {
|
||||
this.identity = freeze({ ...load.identity });
|
||||
this.native = new FinancialReplaySession(JSON.stringify(load));
|
||||
|
|
@ -176,9 +184,31 @@ export class NativeReplaySession {
|
|||
return freeze(result.outcome);
|
||||
}
|
||||
finalize(): ReplayResult {
|
||||
const raw = this.native.finalize(JSON.stringify(this.identity));
|
||||
const identity = JSON.stringify(this.identity);
|
||||
return this.finish(
|
||||
() => this.native.finalize(identity),
|
||||
input => parseReplayResultValue(input, this.identity)
|
||||
);
|
||||
}
|
||||
project(): ReplayProjectionResult {
|
||||
const identity = JSON.stringify(this.identity);
|
||||
return this.finish(
|
||||
() => this.native.project(identity),
|
||||
input => parseReplayProjectionValue(input, this.identity)
|
||||
);
|
||||
}
|
||||
private finish<T>(native: () => string, validate: (input: unknown) => T): T {
|
||||
let start = performance.now();
|
||||
const raw = native();
|
||||
this.finalization.nativeMs += performance.now() - start;
|
||||
this.transport.resultBytes += Buffer.byteLength(raw);
|
||||
return parseReplayResult(raw, this.identity);
|
||||
start = performance.now();
|
||||
const decoded: unknown = JSON.parse(raw);
|
||||
this.finalization.decodeMs += performance.now() - start;
|
||||
start = performance.now();
|
||||
const result = validate(decoded);
|
||||
this.finalization.validationMs += performance.now() - start;
|
||||
return result;
|
||||
}
|
||||
dispose(): void {
|
||||
this.native.dispose();
|
||||
|
|
@ -196,22 +226,46 @@ export interface ReplayMetrics {
|
|||
submitMs: number;
|
||||
decisionMs: number;
|
||||
finalizeMs: number;
|
||||
finalizeNativeMs: number;
|
||||
finalizeDecodeMs: number;
|
||||
finalizeValidationMs: number;
|
||||
disposeMs: number;
|
||||
}
|
||||
type Decide = (
|
||||
ownerId: string,
|
||||
context: DecisionContext,
|
||||
observations: readonly PublishedObservation[]
|
||||
) => FinancialStrategyIntent;
|
||||
interface ReplayOptions {
|
||||
eventBudget?: number;
|
||||
reverseCallbacks?: boolean;
|
||||
onProgress?: (step: ReplayStep) => void;
|
||||
resultFormat?: ReplayResultFormat;
|
||||
}
|
||||
/* eslint-disable no-redeclare -- TypeScript overloads preserve the existing trace result type. */
|
||||
export function runReplayConformance(
|
||||
session: NativeReplaySession,
|
||||
decide: Decide,
|
||||
options: ReplayOptions & { resultFormat: 'projection' }
|
||||
): { result: ReplayProjectionResult; metrics: ReplayMetrics };
|
||||
export function runReplayConformance(
|
||||
session: NativeReplaySession,
|
||||
decide: Decide,
|
||||
options?: ReplayOptions & { resultFormat?: 'trace' }
|
||||
): { result: ReplayResult; metrics: ReplayMetrics };
|
||||
export function runReplayConformance(
|
||||
session: NativeReplaySession,
|
||||
decide: Decide,
|
||||
options: ReplayOptions
|
||||
): { result: ReplayOutput; metrics: ReplayMetrics };
|
||||
/** Conformance driver only. No persisted strategy states/RNG, dynamic code, or
|
||||
* production strategy framework. Shared view is frozen before any fixture runs. */
|
||||
export function runReplayConformance(
|
||||
session: NativeReplaySession,
|
||||
decide: (
|
||||
ownerId: string,
|
||||
context: DecisionContext,
|
||||
observations: readonly PublishedObservation[]
|
||||
) => FinancialStrategyIntent,
|
||||
options: {
|
||||
eventBudget?: number;
|
||||
reverseCallbacks?: boolean;
|
||||
onProgress?: (step: ReplayStep) => void;
|
||||
} = {}
|
||||
decide: Decide,
|
||||
options: ReplayOptions = {}
|
||||
) {
|
||||
/* eslint-enable no-redeclare */
|
||||
const metrics: ReplayMetrics = {
|
||||
advanceCalls: 0,
|
||||
submitCalls: 0,
|
||||
|
|
@ -223,6 +277,10 @@ export function runReplayConformance(
|
|||
submitMs: 0,
|
||||
decisionMs: 0,
|
||||
finalizeMs: 0,
|
||||
finalizeNativeMs: 0,
|
||||
finalizeDecodeMs: 0,
|
||||
finalizeValidationMs: 0,
|
||||
disposeMs: 0,
|
||||
};
|
||||
let observations: PublishedObservation[] = [];
|
||||
let sequence = 0;
|
||||
|
|
@ -243,8 +301,11 @@ export function runReplayConformance(
|
|||
throw new Error(step.step.diagnostic);
|
||||
case 'complete': {
|
||||
const start = performance.now(),
|
||||
result = session.finalize();
|
||||
result = options.resultFormat === 'projection' ? session.project() : session.finalize();
|
||||
metrics.finalizeMs = performance.now() - start;
|
||||
metrics.finalizeNativeMs = session.finalization.nativeMs;
|
||||
metrics.finalizeDecodeMs = session.finalization.decodeMs;
|
||||
metrics.finalizeValidationMs = session.finalization.validationMs;
|
||||
metrics.contextBytes = session.transport.advanceResponseBytes;
|
||||
metrics.submissionBytes = session.transport.submitRequestBytes;
|
||||
metrics.outcomeBytes = session.transport.submitResponseBytes;
|
||||
|
|
@ -290,15 +351,31 @@ export function runReplayConformance(
|
|||
}
|
||||
}
|
||||
} finally {
|
||||
const start = performance.now();
|
||||
session.dispose();
|
||||
metrics.disposeMs = performance.now() - start;
|
||||
}
|
||||
}
|
||||
|
||||
/** Bounded fixed intent trace for conformance/debug, not a declarative strategy DSL. */
|
||||
/* eslint-disable no-redeclare -- TypeScript overloads narrow the selected result format. */
|
||||
export function executeReplayTrace(
|
||||
input: ReplayTraceRequest & { resultFormat: 'projection' },
|
||||
onProgress?: (step: ReplayStep) => void
|
||||
): { result: ReplayProjectionResult; metrics: ReplayMetrics };
|
||||
export function executeReplayTrace(
|
||||
input: ReplayTraceRequest & { resultFormat?: 'trace' },
|
||||
onProgress?: (step: ReplayStep) => void
|
||||
): { result: ReplayResult; metrics: ReplayMetrics };
|
||||
export function executeReplayTrace(
|
||||
input: ReplayTraceRequest,
|
||||
onProgress?: (step: ReplayStep) => void
|
||||
): { result: ReplayOutput; metrics: ReplayMetrics };
|
||||
export function executeReplayTrace(
|
||||
input: ReplayTraceRequest,
|
||||
onProgress: (step: ReplayStep) => void = () => {}
|
||||
) {
|
||||
/* eslint-enable no-redeclare */
|
||||
const request = replayTraceSchema.parse(input),
|
||||
load = prepareReplayLoad(request.dataset, request.config);
|
||||
const trace = new Map<string, FinancialStrategyIntent>();
|
||||
|
|
@ -322,6 +399,7 @@ export function executeReplayTrace(
|
|||
},
|
||||
{
|
||||
eventBudget: request.eventBudget,
|
||||
resultFormat: request.resultFormat,
|
||||
onProgress: step => {
|
||||
if (step.step.type === 'complete' && trace.size) {
|
||||
throw new Error('Unused trace decisions');
|
||||
|
|
|
|||
|
|
@ -176,6 +176,72 @@ const resultSchema = z
|
|||
.strict();
|
||||
export type ReplayStep = z.infer<typeof stepSchema>;
|
||||
export type ReplayResult = z.infer<typeof resultSchema>;
|
||||
const nonnegative = decimal.refine(value => !value.startsWith('-'));
|
||||
const positive = nonnegative.refine(value => value !== '0.00000000');
|
||||
const ownerValuationSchema = z
|
||||
.object({
|
||||
ownerId: id,
|
||||
initialCapital: nonnegative,
|
||||
markedHoldings: nonnegative,
|
||||
remainingCost: nonnegative,
|
||||
realizedGrossPnl: decimal,
|
||||
unrealizedPnl: decimal,
|
||||
fees: nonnegative,
|
||||
equityContribution: decimal,
|
||||
})
|
||||
.strict();
|
||||
export const financialProjectionSchema = z
|
||||
.object({
|
||||
valuation: z
|
||||
.object({
|
||||
cash: nonnegative,
|
||||
markedHoldings: nonnegative,
|
||||
equity: nonnegative,
|
||||
remainingCost: nonnegative,
|
||||
realizedGrossPnl: decimal,
|
||||
unrealizedPnl: decimal,
|
||||
fees: nonnegative,
|
||||
owners: z.array(ownerValuationSchema),
|
||||
})
|
||||
.strict(),
|
||||
fills: z.array(
|
||||
z
|
||||
.object({
|
||||
commandId: id,
|
||||
eventTime: time,
|
||||
ownerId: id,
|
||||
decision: z.object({ ownerId: id, decisionId: id, sequence: counter }).strict(),
|
||||
orderId: id,
|
||||
fillId: id,
|
||||
instrumentId: id,
|
||||
side: z.enum(['buy', 'sell']),
|
||||
quantity: positive,
|
||||
price: positive,
|
||||
fee: z.object({ feeId: id, amount: nonnegative }).strict(),
|
||||
// Gross notional cash movement; the separate fee posting is not included.
|
||||
cashDelta: decimal,
|
||||
quantityDelta: decimal,
|
||||
releasedBasis: nonnegative,
|
||||
realizedGrossPnl: decimal,
|
||||
})
|
||||
.strict()
|
||||
.refine(fill => fill.ownerId === fill.decision.ownerId, 'Fill ownership mismatch')
|
||||
),
|
||||
})
|
||||
.strict();
|
||||
const projectionResultSchema = resultSchema
|
||||
.omit({ receipts: true })
|
||||
.extend({
|
||||
format: z.literal('projection'),
|
||||
projectionVersion: z.literal(1),
|
||||
financialVersion: z.literal(1),
|
||||
projection: financialProjectionSchema,
|
||||
})
|
||||
.strict();
|
||||
export type ReplayProjectionResult = z.infer<typeof projectionResultSchema>;
|
||||
export const replayResultFormatSchema = z.enum(['trace', 'projection']);
|
||||
export type ReplayResultFormat = z.infer<typeof replayResultFormatSchema>;
|
||||
export type ReplayOutput = ReplayResult | ReplayProjectionResult;
|
||||
export type DecisionContext = Extract<ReplayStep['step'], { type: 'decisionBatch' }>;
|
||||
export type PublishedObservation = z.infer<typeof observationSchema>;
|
||||
|
||||
|
|
@ -193,7 +259,14 @@ export function parseReplayResult(
|
|||
identity: ReplayIdentity,
|
||||
expectedPolicy?: ReplayConfig
|
||||
): ReplayResult {
|
||||
const result = resultSchema.parse(JSON.parse(input));
|
||||
return parseReplayResultValue(JSON.parse(input), identity, expectedPolicy);
|
||||
}
|
||||
|
||||
function checkResultIdentity(
|
||||
result: ReplayOutput,
|
||||
identity: ReplayIdentity,
|
||||
expectedPolicy?: ReplayConfig
|
||||
): void {
|
||||
sameIdentity(result.identity, identity);
|
||||
const ledger = result.policy.matching.risk.ledger,
|
||||
portfolio = result.view.portfolio;
|
||||
|
|
@ -210,8 +283,39 @@ export function parseReplayResult(
|
|||
) {
|
||||
throw new Error('Native replay result identity mismatch');
|
||||
}
|
||||
}
|
||||
|
||||
export function parseReplayResultValue(
|
||||
input: unknown,
|
||||
identity: ReplayIdentity,
|
||||
expectedPolicy?: ReplayConfig
|
||||
): ReplayResult {
|
||||
const result = resultSchema.parse(input);
|
||||
checkResultIdentity(result, identity, expectedPolicy);
|
||||
return result;
|
||||
}
|
||||
export function parseReplayProjectionValue(
|
||||
input: unknown,
|
||||
identity: ReplayIdentity,
|
||||
expectedPolicy?: ReplayConfig
|
||||
): ReplayProjectionResult {
|
||||
const result = projectionResultSchema.parse(input);
|
||||
checkResultIdentity(result, identity, expectedPolicy);
|
||||
if (
|
||||
result.projection.valuation.cash !== result.view.portfolio.cash ||
|
||||
result.projection.valuation.equity !== result.view.equity
|
||||
) {
|
||||
throw new Error('Native replay projection does not match terminal view');
|
||||
}
|
||||
return result;
|
||||
}
|
||||
export function parseReplayProjectionResult(
|
||||
input: string,
|
||||
identity: ReplayIdentity,
|
||||
expectedPolicy?: ReplayConfig
|
||||
): ReplayProjectionResult {
|
||||
return parseReplayProjectionValue(JSON.parse(input), identity, expectedPolicy);
|
||||
}
|
||||
|
||||
export const replayTraceSchema = z
|
||||
.object({
|
||||
|
|
@ -220,6 +324,7 @@ export const replayTraceSchema = z
|
|||
dataset: z.unknown(),
|
||||
config: replayConfigSchema,
|
||||
eventBudget: counter.positive(),
|
||||
resultFormat: replayResultFormatSchema.optional(),
|
||||
trace: z.array(
|
||||
z
|
||||
.object({
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue