feat(research): add canonical session reporting and analytics

This commit is contained in:
Boki 2026-10-23 12:05:14 -04:00
parent 1e164450c3
commit 3838295eec
28 changed files with 2402 additions and 47 deletions

View file

@ -5,6 +5,7 @@ use crate::financial::{
contract::*,
matching::OrderStatus,
replay::*,
reporting::ReportingFacts,
result::{project, FinancialProjection},
};
use napi::{Error, Result};
@ -60,6 +61,15 @@ struct ProjectionResult<'a> {
projection: FinancialProjection<'a>,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct ReportResult<'a> {
#[serde(flatten)]
financial: ProjectionResult<'a>,
reporting_version: Version,
reporting: &'a ReportingFacts,
}
fn error(error: impl std::fmt::Display) -> Error {
Error::from_reason(error.to_string())
}
@ -204,6 +214,31 @@ impl ReplayHost {
})
.map_err(error)
}
pub fn report(&self, input: String) -> Result<String> {
let identity: Identity = parse(&input)?;
self.check(&identity)?;
let replay = self.replay.as_ref().unwrap();
let reporting = replay.reporting().map_err(error)?;
serde_json::to_string(&ReportResult {
financial: ProjectionResult {
format: "report",
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)?,
},
reporting_version: Version,
reporting,
})
.map_err(error)
}
}
// NAPI's impl macro requires literal method annotations. Keep this tiny
@ -236,6 +271,10 @@ impl FinancialReplaySession {
self.0.project(input)
}
#[napi]
pub fn report(&self, input: String) -> Result<String> {
self.0.report(input)
}
#[napi]
pub fn dispose(&mut self) {
self.0.dispose();
}
@ -333,6 +372,13 @@ mod tests {
final_result
);
let projected: Value = serde_json::from_str(&compact).unwrap();
let report = native.report(identity.to_string()).unwrap();
assert_eq!(native.report(identity.to_string()).unwrap(), report);
assert_eq!(native.project(identity.to_string()).unwrap(), compact);
assert_eq!(native.replay.as_ref().unwrap().checkpoint(), before);
let reported: Value = serde_json::from_str(&report).unwrap();
assert_eq!(reported["projection"], projected["projection"]);
assert_eq!(reported["reporting"]["occupiedMs"], "120000");
assert_eq!(projected["view"], final_result["view"]);
assert!(projected.get("receipts").is_none());
let load: Load = parse(fixture).unwrap();
@ -341,8 +387,13 @@ mod tests {
projected["projection"],
serde_json::to_value(project(restored.financial().ledger()).unwrap()).unwrap()
);
assert_eq!(
reported["reporting"],
serde_json::to_value(restored.reporting().unwrap()).unwrap()
);
native.dispose();
assert!(native.finalize(identity.to_string()).is_err());
assert!(native.project(identity.to_string()).is_err());
assert!(native.report(identity.to_string()).is_err());
}
}

View file

@ -6,6 +6,7 @@ pub mod contract;
pub mod ledger;
pub mod matching;
pub mod replay;
pub mod reporting;
pub mod result;
pub mod risk;
pub mod scalar;
@ -28,6 +29,9 @@ mod replay_tests;
#[cfg(test)]
mod result_tests;
#[cfg(test)]
mod reporting_tests;
// Exercise the pure host adapter without linking every legacy NAPI export.
#[cfg(test)]
#[path = "../api/replay.rs"]

View file

@ -13,6 +13,7 @@
use super::{
contract::*,
matching::*,
reporting::{Reporting, ReportingFacts},
scalar::{Posting, ScalarError},
};
use serde::{Deserialize, Serialize};
@ -214,6 +215,7 @@ pub struct Replay {
status: ReplayStatus,
submissions: Vec<DecisionSubmission>,
matching: MatchingAccount,
reporting: Reporting,
}
impl Replay {
@ -230,6 +232,12 @@ impl Replay {
.iter()
.map(|s| s.series_id.clone())
.collect();
let reporting = Reporting::new(
&config.matching.risk.ledger.risk_session,
&config.risk_boundaries,
&input.bounds,
matching.ledger().cash(),
);
Ok(Self {
input,
config,
@ -243,6 +251,7 @@ impl Replay {
status: ReplayStatus::Running,
submissions: Vec::new(),
matching,
reporting,
})
}
fn canonicalize(input: &mut PreparedReplay, config: &mut ReplayConfig) {
@ -652,6 +661,12 @@ impl Replay {
pub fn model_limitations(&self) -> &'static [&'static str] {
MODEL_LIMITATIONS
}
pub fn reporting(&self) -> Result<&ReportingFacts, &str> {
if self.status != ReplayStatus::Complete {
return Err("only a complete replay can report successfully");
}
self.reporting.facts()
}
fn command(
&mut self,
@ -659,11 +674,13 @@ impl Replay {
key: EventKey,
body: MatchingCommandBody,
) -> Result<(), ReplayError> {
let at = key.at;
let out = self.matching.apply(&MatchingCommand {
command_id: id(("replay", index)),
key,
body,
})?;
self.reporting.committed(at, &out, self.matching.ledger());
if let AttemptStatus::Failed { diagnostic } = out.status {
self.status = ReplayStatus::Failed { diagnostic };
}
@ -766,6 +783,7 @@ impl Replay {
self.command(index, key, MatchingCommandBody::Finish)?;
if self.status == ReplayStatus::Running {
self.status = ReplayStatus::Complete;
self.reporting.finish(self.matching.ledger());
}
}
}
@ -782,6 +800,8 @@ impl Replay {
while self.status == ReplayStatus::Running && processed < budget {
let index = self.next_event;
let event = self.events[index].clone();
let at = event.key.at;
let observation = event.key.phase == EventPhase::Observation;
self.next_event += 1;
processed += 1;
if let Err(error) = self.process(index, event) {
@ -789,6 +809,15 @@ impl Replay {
diagnostic: error.to_string(),
};
}
if observation
&& self.status == ReplayStatus::Running
&& self.events.get(self.next_event).is_none_or(|next| {
next.key.at != at || next.key.phase != EventPhase::Observation
})
{
self.reporting
.after_observations(at, self.matching.ledger());
}
if let Some(barrier) = &self.pending {
return Ok(ReplayStep::Decision(barrier.clone()));
}

View file

@ -570,6 +570,158 @@ fn restore_before_and_after_every_decision_and_at_complete() {
target(&mut uninterrupted, &b, "2");
}
assert_eq!(r.checkpoint(), uninterrupted.checkpoint());
assert_eq!(r.reporting().unwrap(), uninterrupted.reporting().unwrap());
}
fn reporting_boundary(name: &str, at: i64) -> RiskSessionIdentity {
RiskSessionIdentity {
calendar_id: id("account"),
calendar_revision: id("1"),
session_id: id(name),
starts_at: t(at),
}
}
#[test]
fn two_session_marks_follow_observations_without_changing_earlier_risk_reset() {
let (mut input, mut config) = fixture();
input.bounds.trade_start = t(0);
config.risk_boundaries = vec![
reporting_boundary("risk2", 20),
reporting_boundary("risk3", 30),
];
let mut r = Replay::new(input, config).unwrap();
assert!(r.reporting().is_err());
let b = next(&mut r).unwrap();
target(&mut r, &b, "2");
let b = next(&mut r).unwrap();
assert_eq!(b.at, t(20));
// Existing reset runs before the completed observation's13 mark.
assert_eq!(
Posting::from(r.financial().risk().state().daily_baseline),
p("9999.76")
);
no_change(&mut r, &b);
complete(&mut r);
let facts = r.reporting().unwrap();
assert_eq!(facts.initial_equity, p("10000"));
assert_eq!(facts.sessions.len(), 2);
assert_eq!(facts.sessions[0].session.session_id, id("risk1"));
assert_eq!(facts.sessions[0].period_start, t(0));
assert_eq!(facts.sessions[0].period_end, t(20));
assert_eq!(facts.sessions[0].equity, p("10001.76"));
assert_eq!(facts.sessions[1].equity, p("10005.76"));
assert!(!facts
.sessions
.iter()
.any(|s| s.partial_start || s.partial_end));
assert_eq!(facts.occupied_ms, "20");
assert_eq!(facts.elapsed_ms, "30");
}
#[test]
fn reporting_clips_warmup_initial_and_final_periods_and_deduplicates_exact_end() {
for exact_start in [false, true] {
for exact_end in [false, true] {
let (input, mut config) = fixture();
config.risk_boundaries = vec![
reporting_boundary("warmup", 5),
reporting_boundary("risk2", 20),
];
if exact_start {
config.risk_boundaries.push(reporting_boundary("start", 10));
}
if exact_end {
config.risk_boundaries.push(reporting_boundary("end", 30));
}
let mut r = Replay::new(input, config).unwrap();
complete(&mut r);
let facts = r.reporting().unwrap();
assert_eq!(facts.sessions.len(), 2);
assert_eq!(
facts.sessions[0].session.session_id,
id(if exact_start { "start" } else { "warmup" })
);
assert_eq!(facts.sessions[0].period_start, t(10));
assert_eq!(facts.sessions[0].partial_start, !exact_start);
assert!(!facts.sessions[0].partial_end);
assert_eq!(facts.sessions[1].partial_end, !exact_end);
assert_eq!(facts.sessions[1].period_end, t(30));
assert!(facts.sessions.iter().all(|s| s.equity == p("10000")));
assert_eq!(facts.occupied_ms, "0");
assert!(facts.occupied_intervals.is_empty());
}
}
}
#[test]
fn reporting_boundary_without_decision_and_terminal_stale_mark_use_only_available_facts() {
let (mut input, mut config) = fixture();
config.risk_boundaries = vec![reporting_boundary("risk2", 15)];
input.bars[2].available_at = t(31); // Final close15 is not available by end30.
let mut r = Replay::new(input, config).unwrap();
let b = next(&mut r).unwrap();
target(&mut r, &b, "2");
complete(&mut r);
let facts = r.reporting().unwrap();
assert_eq!(facts.sessions[0].period_end, t(15));
assert_eq!(facts.sessions[0].equity, p("9999.76"));
// Last available authoritative mark is the open14, not the future close15.
assert_eq!(facts.sessions[1].equity, p("10003.76"));
assert_eq!(
facts.sessions[1].equity,
r.financial().ledger().equity().unwrap()
);
assert_eq!(r.observations().count(), 2);
}
#[test]
fn reporting_restore_every_event_including_partial_observation_groups() {
let (mut input, mut config) = fixture();
input.series.push(series("Y-bars", "Y"));
input
.bars
.extend(input.bars.clone().into_iter().map(|mut bar| {
bar.series_id = id("Y-bars");
bar.instrument_id = id("Y");
bar
}));
config.matching.series.push(ExecutionSeries {
instrument_id: id("Y"),
series_id: id("Y-bars"),
mode: ExecutionMode::Open,
});
config.risk_boundaries = vec![
reporting_boundary("risk2", 20),
reporting_boundary("risk3", 30),
];
let mut uninterrupted = Replay::new(input.clone(), config.clone()).unwrap();
while let Some(b) = next(&mut uninterrupted) {
target(&mut uninterrupted, &b, "2");
}
let mut resumed = Replay::new(input.clone(), config.clone()).unwrap();
loop {
let step = resumed.advance(1).unwrap();
let cp = resumed.checkpoint();
resumed = Replay::restore(input.clone(), config.clone(), &cp).unwrap();
assert_eq!(resumed.checkpoint(), cp);
match step {
ReplayStep::Decision(b) => {
target(&mut resumed, &b, "2");
resumed =
Replay::restore(input.clone(), config.clone(), &resumed.checkpoint()).unwrap();
}
ReplayStep::Complete => break,
ReplayStep::Progress { .. } => {}
other => panic!("unexpected {other:?}"),
}
}
assert_eq!(uninterrupted.checkpoint(), resumed.checkpoint());
assert_eq!(
uninterrupted.reporting().unwrap(),
resumed.reporting().unwrap()
);
assert_eq!(resumed.reporting().unwrap().sessions.len(), 2);
}
#[test]
fn altered_input_config_and_checkpoint_rejected() {
@ -808,6 +960,9 @@ fn sequential_equal_time_marks_can_latch_risk_before_synchronized_barrier() {
config.matching.risk.fee_rate = nn("0");
config.matching.risk.max_daily_loss = pos("10");
config.matching.risk.max_drawdown_amount = pos("10");
// A reporting sample uses the final observation-group equity without
// changing the existing sequential risk latch.
config.risk_boundaries.push(reporting_boundary("risk2", 20));
let mut permuted = input.clone();
permuted.bars.reverse();
let mut checkpoints = vec![];
@ -847,6 +1002,11 @@ fn sequential_equal_time_marks_can_latch_risk_before_synchronized_barrier() {
assert!(r.financial().risk().state().daily_halted);
assert!(r.financial().risk().state().drawdown_halted);
checkpoints.push(r.checkpoint());
no_change(&mut r, &b);
complete(&mut r);
assert_eq!(r.reporting().unwrap().sessions[0].equity, p("10000"));
assert!(r.financial().risk().state().daily_halted);
assert!(r.financial().risk().state().drawdown_halted);
}
assert_eq!(checkpoints[0], checkpoints[1]);
assert!(MODEL_LIMITATIONS

View file

@ -0,0 +1,238 @@
//! Reporting-only facts sampled during the existing replay. This state cannot
//! submit financial commands and is rebuilt by the normal checkpoint restore.
use super::{
contract::*,
ledger::Ledger,
matching::{MatchingEffect, MatchingOutcome},
replay::ReplayBounds,
scalar::Posting,
};
use serde::Serialize;
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionEquity {
pub session: RiskSessionIdentity,
pub period_start: EventTime,
pub period_end: EventTime,
pub partial_start: bool,
pub partial_end: bool,
pub equity: Posting,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OccupiedInterval {
pub start: EventTime,
pub end: EventTime,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReportingFacts {
pub calendar_id: Id,
pub calendar_revision: Id,
pub trade_start: EventTime,
pub trade_end: EventTime,
pub initial_equity: Posting,
pub sampling: &'static str,
pub exposure_basis: &'static str,
pub sessions: Vec<SessionEquity>,
pub occupied_intervals: Vec<OccupiedInterval>,
pub occupied_ms: String,
pub elapsed_ms: String,
}
#[derive(Debug)]
pub(super) struct Reporting {
facts: ReportingFacts,
session: RiskSessionIdentity,
period_start: EventTime,
boundaries: Vec<RiskSessionIdentity>,
next_boundary: usize,
occupied_since: Option<EventTime>,
failure: Option<String>,
complete: bool,
}
impl Reporting {
pub fn new(
initial: &RiskSessionIdentity,
boundaries: &[RiskSessionIdentity],
bounds: &ReplayBounds,
initial_equity: Posting,
) -> Self {
// Replay has already validated/canonicalized this account calendar.
let session = boundaries
.iter()
.rev()
.find(|b| b.starts_at.get() <= bounds.trade_start.get())
.unwrap_or(initial)
.clone();
Self {
facts: ReportingFacts {
calendar_id: initial.calendar_id.clone(),
calendar_revision: initial.calendar_revision.clone(),
trade_start: bounds.trade_start,
trade_end: bounds.trade_end,
initial_equity,
sampling: "account-boundary-after-observations-v1",
exposure_basis: "elapsed-calendar-time",
sessions: Vec::new(),
occupied_intervals: Vec::new(),
occupied_ms: "0".into(),
// Both endpoints are safe i64 timestamps; their difference may
// exceed JS's safe integer domain but cannot overflow i64.
elapsed_ms: (bounds.trade_end.get() - bounds.trade_start.get()).to_string(),
},
session,
period_start: bounds.trade_start,
boundaries: boundaries
.iter()
.filter(|b| b.starts_at.get() > bounds.trade_start.get())
.cloned()
.collect(),
next_boundary: 0,
occupied_since: None,
failure: None,
complete: false,
}
}
/// Called only after the complete equal-time Observation group. No extra
/// event enters Replay.events, and the earlier risk reset is untouched.
pub fn after_observations(&mut self, at: EventTime, ledger: &Ledger) {
if self.failure.is_some() || self.complete {
return;
}
let Some(boundary) = self.boundaries.get(self.next_boundary) else {
return;
};
if boundary.starts_at != at {
return;
}
let next_session = boundary.clone();
if self.sample(at, false, ledger) {
self.session = next_session;
self.period_start = at;
self.next_boundary += 1;
}
}
fn sample(&mut self, at: EventTime, partial_end: bool, ledger: &Ledger) -> bool {
match ledger.equity() {
Ok(equity) => {
self.facts.sessions.push(SessionEquity {
session: self.session.clone(),
period_start: self.period_start,
period_end: at,
partial_start: self.period_start != self.session.starts_at,
partial_end,
equity,
});
true
}
Err(error) => {
self.failure = Some(format!("reporting equity unavailable: {error}"));
false
}
}
}
/// Only a committed fill can change occupancy. Query authoritative current
/// holdings once per matching outcome; never reconstruct quantities/deltas.
pub fn committed(&mut self, at: EventTime, outcome: &MatchingOutcome, ledger: &Ledger) {
if self.failure.is_some() || self.complete || outcome.replayed {
return;
}
let filled = outcome.effects.iter().any(|effect| match effect {
MatchingEffect::Risk { outcome, .. } if !outcome.replayed => outcome
.financial
.as_ref()
.filter(|financial| !financial.replayed)
.is_some_and(|financial| {
financial
.effects
.effects
.iter()
.any(|effect| matches!(effect, FinancialEffect::FillApplied { .. }))
}),
_ => false,
});
if !filled {
return;
}
let occupied = ledger.owned_quantities().next().is_some();
match (self.occupied_since, occupied) {
(None, true) => self.occupied_since = Some(at),
(Some(start), false) => {
self.interval(start, at);
self.occupied_since = None;
}
_ => {}
}
}
fn interval(&mut self, start: EventTime, end: EventTime) {
let start = if start.get() < self.facts.trade_start.get() {
self.facts.trade_start
} else {
start
};
let end = if end.get() > self.facts.trade_end.get() {
self.facts.trade_end
} else {
end
};
if start.get() >= end.get() {
return;
}
if let Some(last) = self.facts.occupied_intervals.last_mut() {
if last.end.get() >= start.get() {
if end.get() > last.end.get() {
last.end = end;
}
return;
}
}
self.facts
.occupied_intervals
.push(OccupiedInterval { start, end });
}
pub fn finish(&mut self, ledger: &Ledger) {
if self.failure.is_some() || self.complete {
return;
}
if self.next_boundary != self.boundaries.len() {
self.failure = Some("reporting boundary was not sampled".into());
return;
}
if self.period_start.get() < self.facts.trade_end.get()
&& !self.sample(self.facts.trade_end, true, ledger)
{
return;
}
if let Some(start) = self.occupied_since.take() {
self.interval(start, self.facts.trade_end);
}
let occupied: i64 = self
.facts
.occupied_intervals
.iter()
.map(|interval| interval.end.get() - interval.start.get())
.sum();
self.facts.occupied_ms = occupied.to_string();
self.complete = true;
}
pub fn facts(&self) -> Result<&ReportingFacts, &str> {
if let Some(failure) = &self.failure {
Err(failure)
} else if !self.complete {
Err("reporting is incomplete")
} else {
Ok(&self.facts)
}
}
}

View file

@ -0,0 +1,159 @@
use super::{contract::*, ledger::Ledger, matching::*, replay::ReplayBounds, reporting::Reporting};
use serde_json::{json, Value};
fn time(at: i64) -> EventTime {
at.try_into().unwrap()
}
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 initial() -> RiskSessionIdentity {
serde_json::from_value(
json!({"calendarId":"c","calendarRevision":"1","sessionId":"d","startsAt":0}),
)
.unwrap()
}
fn reporting(ledger: &Ledger, start: i64, end: i64) -> Reporting {
let mut initial = initial();
initial.starts_at = time(start.min(0));
Reporting::new(
&initial,
&[],
&ReplayBounds {
warmup_start: time(start),
trade_start: time(start),
trade_end: time(end),
},
ledger.cash(),
)
}
fn apply(ledger: &mut Ledger, at: i64, name: &str, body: Value) -> MatchingOutcome {
let command: EngineFinancialCommand = serde_json::from_value(json!({
"version":1,"sessionId":"s","accountId":"a","commandId":name,"eventTime":at,"body":body,
}))
.unwrap();
let financial = ledger.apply(&command).unwrap();
// A reporting unit fixture wraps an actual ledger receipt, not invented deltas.
serde_json::from_value(json!({"replayed":false,"revision":1,"status":"Running","effects":[{
"Risk":{"command":{"commandId":name,"eventTime":at,"body":{"kind":"mark","instrumentId":"X","price":"10","observedAt":at}},
"outcome":{"replayed":false,"revision":1,"disposition":"Accepted","financial":financial,
"remaining":null,"releasedOrder":null,"resetBaseline":null}}
}]})).unwrap()
}
fn fill(ledger: &mut Ledger, at: i64, owner: &str, side: &str) -> MatchingOutcome {
let name = format!("{owner}-{side}-{at}");
apply(
ledger,
at,
&name,
json!({"kind":"applyFill","decision":{"ownerId":owner,"decisionId":name,"sequence":0},
"orderId":name,"fillId":name,"instrumentId":"X","side":side,"quantity":"1","price":"10",
"fee":{"feeId":name,"amount":"0"}}),
)
}
#[test]
fn overlapping_positions_open_position_exposure_and_same_time_handoff() {
let mut ledger = ledger();
apply(
&mut ledger,
0,
"mark",
json!({"kind":"mark","instrumentId":"X","price":"10"}),
);
let mut report = reporting(&ledger, 0, 50);
for (at, owner, side) in [
(10, "A", "buy"),
(20, "B", "buy"),
(25, "A", "sell"),
(30, "B", "sell"),
(30, "A", "buy"),
(40, "A", "sell"),
(40, "B", "buy"),
] {
let outcome = fill(&mut ledger, at, owner, side);
report.committed(time(at), &outcome, &ledger);
}
report.finish(&ledger);
let facts = report.facts().unwrap();
assert_eq!(facts.occupied_ms, "40");
assert_eq!(facts.elapsed_ms, "50");
assert_eq!(facts.occupied_intervals.len(), 1);
assert_eq!(facts.occupied_intervals[0].start, time(10));
assert_eq!(facts.occupied_intervals[0].end, time(50));
assert!(ledger.owned_quantities().next().is_some());
}
#[test]
fn reporting_skips_each_nested_replayed_alias_and_zero_length_occupancy() {
for level in 0..3 {
let mut ledger = ledger();
apply(
&mut ledger,
0,
"mark",
json!({"kind":"mark","instrumentId":"X","price":"10"}),
);
let mut report = reporting(&ledger, 0, 30);
let outcome = fill(&mut ledger, 10, "A", "buy");
let mut alias = outcome.clone();
if level == 0 {
alias.replayed = true;
}
let MatchingEffect::Risk { outcome: risk, .. } = &mut alias.effects[0] else {
panic!()
};
if level == 1 {
risk.replayed = true;
}
if level == 2 {
risk.financial.as_mut().unwrap().replayed = true;
}
report.committed(time(0), &alias, &ledger);
report.committed(time(10), &outcome, &ledger);
let sell = fill(&mut ledger, 10, "A", "sell");
report.committed(time(10), &sell, &ledger);
report.finish(&ledger);
assert!(report.facts().unwrap().occupied_intervals.is_empty());
assert_eq!(report.facts().unwrap().occupied_ms, "0");
}
}
#[test]
fn reporting_failure_retains_financial_state_and_cannot_return_success() {
let mut ledger = ledger();
let mut report = reporting(&ledger, 0, 20);
fill(&mut ledger, 10, "A", "buy"); // No mark: ledger equity is explicitly unavailable.
let checkpoint = ledger.checkpoint();
report.finish(&ledger);
assert!(report.facts().unwrap_err().contains("equity unavailable"));
assert_eq!(ledger.checkpoint(), checkpoint);
apply(
&mut ledger,
15,
"mark",
json!({"kind":"mark","instrumentId":"X","price":"10"}),
);
report.finish(&ledger); // A failed report cannot silently become successful later.
assert!(report.facts().is_err());
}
#[test]
fn duration_strings_cover_the_entire_safe_timestamp_domain_without_rounding() {
let ledger = ledger();
let mut report = reporting(&ledger, -9_007_199_254_740_991, 9_007_199_254_740_990);
assert!(report.facts().is_err());
report.finish(&ledger);
let facts = report.facts().unwrap();
assert_eq!(facts.elapsed_ms, "18014398509481981");
assert_eq!(facts.occupied_ms, "0");
assert!(!facts.sessions[0].partial_start && facts.sessions[0].partial_end);
}

View file

@ -2,6 +2,7 @@ import { fork, type ChildProcess } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import {
parseReplayProjectionResult,
parseReplayReportResult,
parseReplayResult,
replayConfigSchema,
replayIdentitySchema,
@ -85,9 +86,11 @@ export class NativeBacktestWorker {
if (expectedReplay) {
try {
const parse =
expectedReplay.format === 'projection'
? parseReplayProjectionResult
: parseReplayResult;
expectedReplay.format === 'report'
? parseReplayReportResult
: expectedReplay.format === 'projection'
? parseReplayProjectionResult
: parseReplayResult;
parse(message.result, expectedReplay.identity, expectedReplay.policy);
} catch (error) {
terminate(error instanceof Error ? error : new Error(String(error)));

View file

@ -0,0 +1,195 @@
import { z } from 'zod';
import {
dayMs,
drawdownAnalysis,
nullable,
ratio,
returnStatistics,
} from '@stock-bot/calculations/analytics';
import { cagr, simpleReturn } from '@stock-bot/calculations/returns';
import type {
CanonicalBacktestAnalytics,
CanonicalMetrics,
CanonicalMetricsInput,
CanonicalMetricUnavailableReason,
CanonicalSessionReturn,
} from '@stock-bot/types';
import type { ReplayReportResult } from '../contracts/native-replay';
const metricsInput = z
.object({
version: z.literal(1),
periodsPerYear: z.number().finite().positive(),
annualRiskFreeRate: z.number().finite().nullable(),
benchmark: z.null(),
})
.strict();
export interface CanonicalBacktestReport {
/** Exact validated Rust facts; never converted through the legacy DTO. */
financial: ReplayReportResult;
analytics: CanonicalBacktestAnalytics;
}
/** Consume a validated report from the native protocol parser. Financial facts
* stay untouched; only statistical reporting converts decimal equity to numbers.
* Persistence/public-result migration belongs to the separately gated R05 path. */
export function buildCanonicalBacktestReport(
financial: ReplayReportResult,
input: CanonicalMetricsInput
): CanonicalBacktestReport {
const policy = metricsInput.parse(input);
const reporting = financial.reporting;
const initial = Number(reporting.initialEquity);
const terminal = Number(financial.projection.valuation.equity);
const elapsedMs = Number(reporting.elapsedMs);
let previous = initial;
const sessionReturns: CanonicalSessionReturn[] = reporting.sessions.map(session => {
const current = Number(session.equity);
const value = previous > 0 ? nullable(simpleReturn(previous, current)) : null;
const reason =
value === null
? previous <= 0
? ('nonpositive-baseline' as const)
: ('nonfinite-result' as const)
: undefined;
previous = current;
return {
sessionId: session.session.sessionId,
periodStart: session.periodStart,
periodEnd: session.periodEnd,
partialStart: session.partialStart,
partialEnd: session.partialEnd,
value,
eligible: !session.partialStart && !session.partialEnd && value !== null,
...(reason ? { reason } : {}),
};
});
const complete = sessionReturns.filter(session => !session.partialStart && !session.partialEnd);
// One undefined complete return invalidates this statistical sequence. A later
// positive baseline must not silently turn it into a shorter, different sample.
const periodicReturns = complete.every(
(session): session is CanonicalSessionReturn & { value: number } => session.value !== null
)
? complete.map(session => session.value)
: null;
const statistics =
periodicReturns === null
? null
: returnStatistics(periodicReturns, policy.annualRiskFreeRate, policy.periodsPerYear);
const points = [
{ timestamp: reporting.tradeStart, value: initial },
...reporting.sessions.map(session => ({
timestamp: session.periodEnd,
value: Number(session.equity),
})),
];
const metrics: CanonicalMetrics = {
totalReturn: initial > 0 ? nullable(simpleReturn(initial, terminal)) : null,
cagr: initial > 0 ? cagr(initial, terminal, elapsedMs / dayMs / 365) : null,
maxDrawdown: initial > 0 ? drawdownAnalysis(points, initial).maxDrawdown : null,
exposureTime: ratio(Number(reporting.occupiedMs), elapsedMs),
volatility: statistics?.volatility ?? null,
downsideDeviation: statistics?.downsideDeviation ?? null,
sharpeRatio: statistics?.sharpeRatio ?? null,
sortinoRatio: statistics?.sortinoRatio ?? null,
var95: statistics?.var95 ?? null,
cvar95: statistics?.cvar95 ?? null,
var99: statistics?.var99 ?? null,
alpha: null,
beta: null,
informationRatio: null,
roundTripCount: null,
winRate: null,
profitFactor: null,
avgWin: null,
avgLoss: null,
};
const unavailable: CanonicalBacktestAnalytics['unavailable'] = {
alpha: 'missing-benchmark',
beta: 'missing-benchmark',
informationRatio: 'missing-benchmark',
roundTripCount: 'unsupported-round-trips',
winRate: 'unsupported-round-trips',
profitFactor: 'unsupported-round-trips',
avgWin: 'unsupported-round-trips',
avgLoss: 'unsupported-round-trips',
};
if (metrics.totalReturn === null) {
unavailable.totalReturn = initial <= 0 ? 'nonpositive-baseline' : 'nonfinite-result';
}
if (metrics.maxDrawdown === null) {
unavailable.maxDrawdown = 'nonpositive-baseline';
}
if (metrics.exposureTime === null) {
unavailable.exposureTime = elapsedMs === 0 ? 'zero-duration' : 'nonfinite-result';
}
if (metrics.cagr === null) {
unavailable.cagr =
initial <= 0
? 'nonpositive-baseline'
: elapsedMs === 0
? 'zero-duration'
: terminal < 0
? 'negative-terminal-equity'
: 'nonfinite-result';
}
const minimumPeriods = {
volatility: 2,
downsideDeviation: 2,
sharpeRatio: 2,
sortinoRatio: 2,
var95: 20,
cvar95: 20,
var99: 100,
};
for (const key of Object.keys(minimumPeriods) as (keyof typeof minimumPeriods)[]) {
if (metrics[key] !== null) {
continue;
}
let reason: CanonicalMetricUnavailableReason = 'nonfinite-result';
if (periodicReturns === null) {
reason = 'undefined-period-return';
} else if (
['downsideDeviation', 'sharpeRatio', 'sortinoRatio'].includes(key) &&
policy.annualRiskFreeRate === null
) {
reason = 'missing-risk-free';
} else if (periodicReturns.length < minimumPeriods[key]) {
reason = 'insufficient-periods';
} else if (key === 'sharpeRatio' && statistics?.volatility === 0) {
reason = 'zero-variance';
} else if (key === 'sortinoRatio' && statistics?.downsideDeviation === 0) {
reason = 'zero-downside-deviation';
}
unavailable[key] = reason;
}
return {
financial,
analytics: {
version: 1,
policy: {
...policy,
calendarId: reporting.calendarId,
calendarRevision: reporting.calendarRevision,
sampling: reporting.sampling,
marks: 'last-available-no-per-session-freshness-certification',
returnUnit: 'fraction',
variance: 'sample-n-minus-one',
riskFreeConversion: 'annual-rate-divided-by-periods-per-year',
downside: 'full-series-rms-relative-to-risk-free',
partialPeriods: 'visible-excluded-from-periodic-statistics',
drawdown: 'session-end-and-terminal-sampled',
exposureBasis: reporting.exposureBasis,
cagrBasis: 'elapsed-calendar-days-365',
zeroTerminalCagr: 'negative-one-for-positive-elapsed-time',
},
sessionReturns,
completePeriodCount: complete.length,
periodicSampleCount: periodicReturns?.length ?? 0,
fillCount: financial.projection.fills.length,
metrics,
unavailable,
},
};
}

View file

@ -8,6 +8,7 @@ import {
} from '@stock-bot/types';
import {
parseReplayProjectionValue,
parseReplayReportValue,
parseReplayResultValue,
replayConfigSchema,
replayTraceSchema,
@ -20,6 +21,7 @@ import {
type ReplayIdentity,
type ReplayOutput,
type ReplayProjectionResult,
type ReplayReportResult,
type ReplayResult,
type ReplayResultFormat,
type ReplayStep,
@ -33,6 +35,7 @@ export type {
ReplayStep,
ReplayResult,
ReplayProjectionResult,
ReplayReportResult,
ReplayOutput,
ReplayResultFormat,
DecisionContext,
@ -197,6 +200,13 @@ export class NativeReplaySession {
input => parseReplayProjectionValue(input, this.identity)
);
}
report(): ReplayReportResult {
const identity = JSON.stringify(this.identity);
return this.finish(
() => this.native.report(identity),
input => parseReplayReportValue(input, this.identity)
);
}
private finish<T>(native: () => string, validate: (input: unknown) => T): T {
let start = performance.now();
const raw = native();
@ -243,6 +253,11 @@ interface ReplayOptions {
resultFormat?: ReplayResultFormat;
}
/* eslint-disable no-redeclare -- TypeScript overloads preserve the existing trace result type. */
export function runReplayConformance(
session: NativeReplaySession,
decide: Decide,
options: ReplayOptions & { resultFormat: 'report' }
): { result: ReplayReportResult; metrics: ReplayMetrics };
export function runReplayConformance(
session: NativeReplaySession,
decide: Decide,
@ -301,7 +316,12 @@ export function runReplayConformance(
throw new Error(step.step.diagnostic);
case 'complete': {
const start = performance.now(),
result = options.resultFormat === 'projection' ? session.project() : session.finalize();
result =
options.resultFormat === 'report'
? session.report()
: options.resultFormat === 'projection'
? session.project()
: session.finalize();
metrics.finalizeMs = performance.now() - start;
metrics.finalizeNativeMs = session.finalization.nativeMs;
metrics.finalizeDecodeMs = session.finalization.decodeMs;
@ -359,6 +379,10 @@ export function runReplayConformance(
/** 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: 'report' },
onProgress?: (step: ReplayStep) => void
): { result: ReplayReportResult; metrics: ReplayMetrics };
export function executeReplayTrace(
input: ReplayTraceRequest & { resultFormat: 'projection' },
onProgress?: (step: ReplayStep) => void

View file

@ -239,9 +239,44 @@ const projectionResultSchema = resultSchema
})
.strict();
export type ReplayProjectionResult = z.infer<typeof projectionResultSchema>;
export const replayResultFormatSchema = z.enum(['trace', 'projection']);
export const replayReportingSchema = z
.object({
calendarId: id,
calendarRevision: id,
tradeStart: time,
tradeEnd: time,
initialEquity: nonnegative,
sampling: z.literal('account-boundary-after-observations-v1'),
exposureBasis: z.literal('elapsed-calendar-time'),
sessions: z.array(
z
.object({
session: riskSession,
periodStart: time,
periodEnd: time,
partialStart: z.boolean(),
partialEnd: z.boolean(),
equity: nonnegative,
})
.strict()
),
occupiedIntervals: z.array(z.object({ start: time, end: time }).strict()),
occupiedMs: z.string().regex(/^(0|[1-9][0-9]*)$/),
elapsedMs: z.string().regex(/^(0|[1-9][0-9]*)$/),
})
.strict();
const reportResultSchema = projectionResultSchema
.extend({
format: z.literal('report'),
reportingVersion: z.literal(1),
reporting: replayReportingSchema,
})
.strict();
export type ReplayReporting = z.infer<typeof replayReportingSchema>;
export type ReplayReportResult = z.infer<typeof reportResultSchema>;
export const replayResultFormatSchema = z.enum(['trace', 'projection', 'report']);
export type ReplayResultFormat = z.infer<typeof replayResultFormatSchema>;
export type ReplayOutput = ReplayResult | ReplayProjectionResult;
export type ReplayOutput = ReplayResult | ReplayProjectionResult | ReplayReportResult;
export type DecisionContext = Extract<ReplayStep['step'], { type: 'decisionBatch' }>;
export type PublishedObservation = z.infer<typeof observationSchema>;
@ -301,13 +336,16 @@ export function parseReplayProjectionValue(
): ReplayProjectionResult {
const result = projectionResultSchema.parse(input);
checkResultIdentity(result, identity, expectedPolicy);
checkProjection(result);
return result;
}
function checkProjection(result: ReplayProjectionResult | ReplayReportResult): void {
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,
@ -317,6 +355,101 @@ export function parseReplayProjectionResult(
return parseReplayProjectionValue(JSON.parse(input), identity, expectedPolicy);
}
export function parseReplayReportValue(
input: unknown,
identity: ReplayIdentity,
expectedPolicy?: ReplayConfig
): ReplayReportResult {
const result = reportResultSchema.parse(input);
checkResultIdentity(result, identity, expectedPolicy);
checkProjection(result);
const report = result.reporting;
const bounds = z.object({ tradeStart: time, tradeEnd: time }).parse(result.manifest.bounds);
const initial = result.policy.matching.risk.ledger;
if (
report.tradeStart !== bounds.tradeStart ||
report.tradeEnd !== bounds.tradeEnd ||
report.tradeStart >= report.tradeEnd ||
report.calendarId !== initial.riskSession.calendarId ||
report.calendarRevision !== initial.riskSession.calendarRevision ||
report.initialEquity !== initial.initialCapital ||
report.sessions.at(-1)?.equity !== result.view.equity
) {
throw new Error('Native replay reporting identity or terminal value mismatch');
}
// Check calendar partition/labels, not equity arithmetic or financial accounting.
const boundaries = [...result.policy.risk_boundaries].sort((a, b) => a.startsAt - b.startsAt);
let session = initial.riskSession;
let start = report.tradeStart,
index = 0;
for (const boundary of boundaries) {
if (boundary.startsAt <= report.tradeStart) {
session = boundary;
continue;
}
if (boundary.startsAt > report.tradeEnd) {
break;
}
const actual = report.sessions[index++];
if (
!actual ||
JSON.stringify(actual.session) !== JSON.stringify(session) ||
actual.periodStart !== start ||
actual.periodEnd !== boundary.startsAt ||
actual.partialStart !== (start !== session.startsAt) ||
actual.partialEnd
) {
throw new Error('Native replay reporting session partition mismatch');
}
start = boundary.startsAt;
session = boundary;
}
if (start < report.tradeEnd) {
const actual = report.sessions[index++];
if (
!actual ||
JSON.stringify(actual.session) !== JSON.stringify(session) ||
actual.periodStart !== start ||
actual.periodEnd !== report.tradeEnd ||
actual.partialStart !== (start !== session.startsAt) ||
!actual.partialEnd
) {
throw new Error('Native replay reporting final session mismatch');
}
}
if (index !== report.sessions.length) {
throw new Error('Native replay reporting has extra sessions');
}
let occupied = 0n,
previousEnd: number | undefined;
for (const interval of report.occupiedIntervals) {
if (
interval.start < report.tradeStart ||
interval.end > report.tradeEnd ||
interval.start >= interval.end ||
(previousEnd !== undefined && interval.start <= previousEnd)
) {
throw new Error('Native replay reporting intervals are not a clipped union');
}
occupied += BigInt(interval.end) - BigInt(interval.start);
previousEnd = interval.end;
}
if (
report.occupiedMs !== String(occupied) ||
report.elapsedMs !== String(BigInt(report.tradeEnd) - BigInt(report.tradeStart))
) {
throw new Error('Native replay reporting duration mismatch');
}
return result;
}
export function parseReplayReportResult(
input: string,
identity: ReplayIdentity,
expectedPolicy?: ReplayConfig
): ReplayReportResult {
return parseReplayReportValue(JSON.parse(input), identity, expectedPolicy);
}
export const replayTraceSchema = z
.object({
type: z.literal('runReplayTrace'),