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({
|
||||
|
|
|
|||
|
|
@ -1,14 +1,14 @@
|
|||
# Revised development roadmap
|
||||
|
||||
Baseline `b7aeca4` · handoff 2026-10-23 · **F07 reviewed, validated and committed**
|
||||
Baseline `b7aeca4` · execution 2026-10-23 · **F09/P07 reviewed and validated; uncommitted**
|
||||
|
||||
Authorization update: the owner accepted and committed the reviewed F07 changes as `e3635f2` on 2026-10-23. The accompanying performance question requests assessment, not optimization implementation. No other ADR or multi-asset mark policy is approved. Pushes, PRs, trading operations and further task implementation remain outside scope.
|
||||
Authorization update: after committing F07 (`e3635f2`, completion record `19e9dad`), the owner requested performance stories and continuation. This authorizes F09 compact projections and P07 profiling, preserving existing financial semantics. F08 retains separate historical reporting work. No other ADR or multi-asset mark policy is approved; new commits, pushes, PRs and trading/default-engine operations remain outside scope.
|
||||
|
||||
## Strategy and review outcome
|
||||
|
||||
Use TypeScript for strategies, research and the web product; one Rust kernel owns money, risk, matching and replay. Preserve durable decisions/checkpoints, transactional execution, frozen datasets, reviewed calculations and failure-oriented tests.
|
||||
|
||||
The skeptical review consolidates **52 separate task definitions into 43 scheduled tasks plus 5 conditional tasks**. Four old IDs remain merged redirects, not extra work. This is a smaller delivery plan, not a smaller correctness standard. See [review findings and dispositions](REVIEW.md), [complete index](backlog/README.md) and [canonical manifest](backlog/manifest.json).
|
||||
The skeptical review established 43 scheduled tasks, 5 conditional tasks and 4 merged redirects. The measured F09/P07 additions bring the current plan to **45 scheduled + 5 conditional + 4 merged = 54 retained IDs**. See [review findings and dispositions](REVIEW.md), [complete index](backlog/README.md) and [canonical manifest](backlog/manifest.json).
|
||||
|
||||
The existing web workbench improves during engine migration. Legacy results remain labelled; fixing controls or terminal valuation does not make same-bar economics trustworthy. C06 blocks shared-runtime legacy research rather than building another soon-to-be-retired simulator runtime.
|
||||
|
||||
|
|
@ -35,7 +35,7 @@ Long-only is the approved first canonical model, not deletion of short history o
|
|||
| --- | --- | --- |
|
||||
| M0: safe interim behavior | C01/C02/C03/C04/C06; O01; P01 | Scoped terminal/funding/input fixes; failed init cleans up; shared-runtime research rejected; migration lock and honest baseline measurements |
|
||||
| M1: usable current workbench | W01–W04 | Save, submit, cancel, inspect and reopen tested in browser; unsupported controls hidden; legacy economic limitations visible |
|
||||
| M2: canonical Rust/TS research | F01/F02/F04–F08, D01, S01/S02; R01/R10/W03/C06 then R05 | Owner-aware finance, deterministic replay, one TS strategy and retained input provenance work through durable runs |
|
||||
| M2: canonical Rust/TS research | F01/F02/F04–F09, D01, S01/S02; R01/R10/W03/C06 then R05; P07 measurements | Owner-aware finance, deterministic replay, compact results, one TS strategy and retained input provenance work through durable runs |
|
||||
| M3: useful research product | R02/R03/R04/R11/R12 | Catalog/workspace/dataset selection and original reproduction; metadata/UI proceed alongside engine work |
|
||||
| M4: batch research and validation | R06–R09, P04; S05 when ready | Bounded sweeps, summary comparisons, OOS/reset-segment walk-forward and measured worker scaling; regime panels only with S05 |
|
||||
| M5: paper parity and AI research | S03/S04, A01–A04 | Recovery parity, operator readiness, isolated bounded AI experiments and evidence-linked human paper promotion |
|
||||
|
|
@ -52,6 +52,8 @@ flowchart LR
|
|||
D01[Availability-aware eligible datasets] --> F06
|
||||
P01[Existing-path measurements] --> F06
|
||||
F06 --> F07[Bounded NAPI sessions] --> S01[TS decisions] --> S02[One SMA]
|
||||
F07 --> F09[Compact financial projections] --> F08
|
||||
F07 --> P07[Representative replay profiling]
|
||||
C02[Boundary integrity] --> F07
|
||||
F06 --> F08[Canonical projections + reviewed TS statistics]
|
||||
S02 --> R05[Durable canonical runs]
|
||||
|
|
@ -271,6 +273,40 @@ Limits remain explicit: trusted host interface, not an untrusted-code sandbox; n
|
|||
|
||||
Only the two named disposable fixture containers and their recreatable synthetic data were removed; development services were untouched. Worktree/logs retained. Browser/Python suites were not rerun because those boundaries did not change. **F07 is committed. Next recommended: F08 canonical metrics/result projections**, now code/ADR-ready but not yet authorized. S01 requires ADR-005 approval. No push, PR, default cutover or trading operation occurred.
|
||||
|
||||
## Twelfth-wave handoff — 2026-10-23
|
||||
|
||||
Two focused performance stories replace a broad optimization request: [F09](backlog/tasks/F09.md) emits compact authoritative terminal values/owned fills with optional complete diagnostics; [P07](backlog/tasks/P07.md) profiles no-trade, sparse and high-turnover workloads using the existing harness. F08 consumes F09 and later adds explicit session sampling/exposure/statistical policies. No session-close values are inferred from risk baselines, and fills are not relabelled completed trades.
|
||||
|
||||
Base `19e9dad`; isolated worktrees under `/tmp/stock-bot-wave12.F9Rlh4/`. One native/result contract owner, one disjoint benchmark owner, root planning/integration and independent review. Baseline profiling was measured on F07; compact comparisons used the accepted F09 contract. Internal journals/recovery, legacy/default paths and all mark-policy release gates remain. No framework, DSL, cache, worker-pool or web-pagination expansion.
|
||||
|
||||
Both stories are independently reviewed and `review` / `validated_uncommitted`. Root integrated 14 source/test files with exact reviewed hashes. F09's accepted contract was overlaid into P07's isolated worktree before compact comparison work; neither owner independently changed the other's contract.
|
||||
|
||||
- **F09:** native `project()` returns the existing authoritative ledger valuation and actual owned fills copied from committed commands/effects. It skips replay aliases and retains separate gross cash movement and fee postings, signed owner contributions and residual cost basis. Typed serialization borrows journal facts; no checkpoint copying, financial replay or TypeScript accounting is introduced. Complete-state/identity/format/cancellation guards cover the compact path. Full `finalize()` output, defaults, internal journals and recovery are preserved.
|
||||
- **P07:** the existing harness now selects no-trade, sparse and turnover profiles with identical callback cadence, plus trace/projection/both output. It records native-finalization, decoding, validation and disposal separately. Comparisons require the same dataset, policy, strategy, artifact, terminal view and actual fill facts. Full per-format hashes remain independent; no TypeScript valuation is fabricated to compare formats. A 200,000-fill regression prevents a benchmark-only JavaScript argument-limit failure.
|
||||
|
||||
Validation: full `CARGO_BUILD_JOBS=2 bun run check` passed build/types/contracts/lint/audit, 63 tooling, 43 utility, 35 calculation, 359 integration and **136 Rust tests**, zero failures; four existing manual benchmarks remain intentionally ignored. After the final benchmark files were integrated, all **72 tooling tests / 10,184 assertions** passed. Extra strict test/script TypeScript, scoped ESLint, rustfmt and diff checks passed. Disposable PostgreSQL/Redis suites passed **58 tests / 345 assertions** before and after integration. Independent debug and integrated release native/worker checks each passed **23 tests / 198 assertions**. These focused tests overlap larger suites. No browser/Python rerun was needed for unchanged boundaries.
|
||||
|
||||
Paired release results below use identical frozen source and addon `d98308d0…`, two fresh processes with two fresh native sessions each, including reversed callback order. Numbers are median **replay/decision/finalization/disposal time**, excluding native construction and benchmark-only oracle/hash work. Bars are total across assets. Preparation/imports, whole-trial time, all phase timings, RSS, hashes and raw report paths are recorded in the manifest. This is synthetic component conformance throughput on a shared host, not durable-job latency or an isolated-host SLA.
|
||||
|
||||
| Total bars | Profile | Assets / owners | Full trace | Compact | Reduction |
|
||||
| --- | --- | --- | ---: | ---: | ---: |
|
||||
| 10,000 | No trade | 1 / 1 | 1.142s | 0.744s | 34.9% |
|
||||
| 10,000 | No trade | 10 / 2 | 0.599s | 0.296s | 50.7% |
|
||||
| 10,000 | Sparse | 1 / 1 | 1.184s | 0.835s | 29.5% |
|
||||
| 10,000 | Sparse | 10 / 2 | 0.720s | 0.419s | 41.8% |
|
||||
| 10,000 | Turnover | 1 / 1 | 2.105s | 1.467s | 30.3% |
|
||||
| 10,000 | Turnover | 10 / 2 | 2.598s | 1.804s | 30.6% |
|
||||
| 100,000 | Sparse | 1 / 1 | 11.918s | 8.097s | 32.1% |
|
||||
| 100,000 | Sparse | 10 / 2 | 7.312s | 4.245s | 41.9% |
|
||||
| 100,000 | Turnover | 1 / 1 | 21.027s | 14.821s | 29.5% |
|
||||
| 100,000 | Turnover | 10 / 2 | 26.501s | 18.743s | 29.3% |
|
||||
|
||||
Every selected comparison passed independent economic oracles, complete result repeatability and common financial equality. All six 10k diagnostic hashes also match the historical F07 baseline. That intermediate extended harness's source bodies were not retained, only their hashes, so historical timings are contextual; speedup claims use the final paired source, which is archived with all 21 changed files as measured. Final planning edits follow the measurements; application source remains identical. No 100k no-trade run is claimed.
|
||||
|
||||
At 10k turnover, output falls from **66.7MB to 9.8MB** single and **103.6MB to 19.4MB** multi. At 100k turnover it falls from 672MB/1.044GB to 98.6MB/195.8MB. Full diagnostics remain available; this is an export reduction, not deletion of retained history. Compact 10k advance/submit accounts for 70–88% of run time. Those mixed timers should be profiled before selecting another optimization. Fixture TS decisions take only 0.9–3.5%; these results do not justify a DSL. Compact schema validation and disposal remain measured costs; removing checks or recovery history is not the next step.
|
||||
|
||||
Only the two exact disposable fixture containers and their synthetic data were removed; development services were untouched. Worktrees, logs and measured-source archive remain available. No commits, pushes, PRs, default cutover or trading operation occurred. **Next after acceptance: F08 historical equity/session/exposure and versioned statistics**, with explicit sampling conventions. S01 and product/AI work retain their pending ADR gates; the equal-time multi-asset risk-mark restriction remains unresolved.
|
||||
|
||||
## Deferred and rejected
|
||||
|
||||
Conditional: shared feature cache D04; cross-trial resident datasets P03; large-detail pagination/storage P05; tiny DSL P06; expanded cross-service monitoring O02. Each has a measured/real-need trigger and is not a prerequisite for scheduled work.
|
||||
|
|
|
|||
|
|
@ -1,12 +1,12 @@
|
|||
# Canonical development backlog
|
||||
|
||||
**First eleven waves reviewed, validated and committed.** F07 was accepted and committed as `e3635f2`. Consult manifest execution_scope, [ROADMAP](../ROADMAP.md), [skeptical review](../REVIEW.md) and [first-wave handoff](../FIRST-WAVE.md). ADR-002/003/004 are approved. Other tasks/policies remain gated; the latest performance question does not authorize implementation.
|
||||
**First eleven waves committed; F09/P07 reviewed, validated and uncommitted.** F09 adds optional compact terminal/fill projection; P07 proves matching finances and measured speedups at 10k/100k bars. F08 retains historical metrics. Consult manifest execution_scope and [handoff](../ROADMAP.md#twelfth-wave-handoff--2026-10-23). ADR-002/003/004 are approved; other policies/default cutovers remain gated.
|
||||
|
||||
## One source of truth
|
||||
|
||||
[manifest.json](manifest.json) owns scheduling metadata: status, priorities, dependencies, ADR approvals, assignments and write locks. Task Markdown owns implementation scope/evidence/acceptance. This index and the [graph](dependencies.mmd) are derived views. Only the planning/integration owner updates scheduling state.
|
||||
|
||||
**43 scheduled + 5 deferred + 4 merged IDs = 52 retained IDs.** Merged records preserve traceability; never execute them separately. Deferred work requires its stated trigger and explicit activation.
|
||||
**45 scheduled + 5 deferred + 4 merged IDs = 54 retained IDs.** F09/P07 add the measured projection/profiling work. Merged records preserve traceability; never execute them separately. Deferred work requires its stated trigger and explicit activation.
|
||||
|
||||
States: ready, claimed, in_progress, review, done, blocked, deferred, merged. “Ready” means no code/ADR prerequisite, not execution authority. Implementation dependencies require accepted integration. `release_gates` govern enabling an end-to-end feature, not component coding or integration; conditional gates apply only to the named capability. F05 may integrate before F06, but its replay behavior is not released until F06 proves it.
|
||||
|
||||
|
|
@ -36,7 +36,8 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
|
|||
| [F05 Unify matching and order lifecycle on the ledger](tasks/F05.md) | P0 / done | F04, ADR-003 | F06 | Rust execution semantics / L |
|
||||
| [F06 Implement deterministic replay once, with linear historical traversal](tasks/F06.md) | P0 / done | F05, D01, P01, ADR-003 | — | Rust deterministic replay / M |
|
||||
| [F07 Expose bounded Rust step sessions through existing NAPI workers](tasks/F07.md) | P0 / done | F06, C02, ADR-004 | — | Rust/TypeScript integration / M |
|
||||
| [F08 Publish canonical metrics and versioned result projections](tasks/F08.md) | P1 / ready | F06, ADR-002, ADR-003 | — | Quant analytics/Rust integration / M |
|
||||
| [F08 Publish canonical metrics and versioned result projections](tasks/F08.md) | P1 / blocked | F06, F09, ADR-002, ADR-003 | — | Quant analytics/Rust integration / M |
|
||||
| [F09 Return compact canonical replay projections](tasks/F09.md) | P1 / review | F07, ADR-002, ADR-003, ADR-004 | — | Rust/TypeScript financial integration / M |
|
||||
|
||||
### E3 — Point-in-time datasets and features
|
||||
|
||||
|
|
@ -94,6 +95,7 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
|
|||
| [P04 Schedule deterministic batches across a bounded worker pool](tasks/P04.md) | P2 / blocked | F07, R06, C06, P01, ADR-008 | — | Performance/infrastructure engineering / M |
|
||||
| [P05 Separate result summaries from paged detail payloads](tasks/P05.md) | P2 / deferred | R06, P01 | — | Performance/infrastructure engineering / M |
|
||||
| [P06 Conditionally add a minimal Rust-executed strategy plan](tasks/P06.md) | P2 / deferred | P04, S01, ADR-008 | — | Rust/TS performance compiler boundary / M |
|
||||
| [P07 Profile representative canonical replay workloads](tasks/P07.md) | P1 / review | F07, P01 | F09 for compact comparisons | Performance/test infrastructure / M |
|
||||
|
||||
### E8 — Authorized, isolated AI research
|
||||
|
||||
|
|
@ -115,4 +117,4 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
|
|||
|
||||
Before any wave: unique IDs; existing task/ADR references; acyclic implementation graph; no scheduled task dependent on merged/deferred work; approvals/readiness; actual file locks; isolated native build outputs/workspace dependencies and test databases. Release gates are checked separately at activation.
|
||||
|
||||
The first eleven waves are independently reviewed, validated and committed with owner approval; see the [eleventh-wave handoff](../ROADMAP.md#eleventh-wave-handoff--2026-10-23) and manifest evidence. Next recommended: **F08 canonical metrics/result projections**, whose code and ADR prerequisites are satisfied; readiness is not execution authority. S01 still needs ADR-005 and R01 needs ADR-006. The unresolved multi-asset mark-policy gate still blocks default activation, not additive components. No push, PR, trading operation or further task implementation is authorized.
|
||||
The first eleven waves are independently reviewed, validated and committed. Current authorization covers **F09 compact projections and P07 profiling** only. P07 baseline files can progress in parallel; paired projection measurements consume the accepted F09 contract afterward. F08 adds historical sampling/statistics next, without reconstructing accounting in TS. S01 needs ADR-005 and R01 needs ADR-006. The unresolved multi-asset mark-policy gate still blocks default activation. No new commit, push, PR or trading operation is authorized.
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ flowchart TD
|
|||
F06["F06: Implement deterministic replay once, with linear historical traversal"]
|
||||
F07["F07: Expose bounded Rust step sessions through existing NAPI workers"]
|
||||
F08["F08: Publish canonical metrics and versioned result projections"]
|
||||
F09["F09: Return compact canonical replay projections"]
|
||||
end
|
||||
subgraph E3["E3: Point-in-time datasets and features"]
|
||||
D01["D01: Introduce availability-aware dataset v2"]
|
||||
|
|
@ -55,6 +56,7 @@ flowchart TD
|
|||
P04["P04: Schedule deterministic batches across a bounded worker pool"]
|
||||
P05["P05: Separate result summaries from paged detail payloads (conditional)"]
|
||||
P06["P06: Conditionally add a minimal Rust-executed strategy plan (conditional)"]
|
||||
P07["P07: Profile representative canonical replay workloads"]
|
||||
end
|
||||
subgraph E8["E8: Authorized, isolated AI research"]
|
||||
A01["A01: Add research-only principals and durable job budgets"]
|
||||
|
|
@ -86,8 +88,13 @@ flowchart TD
|
|||
C02 --> F07
|
||||
ADR004 --> F07
|
||||
F06 --> F08
|
||||
F09 --> F08
|
||||
ADR002 --> F08
|
||||
ADR003 --> F08
|
||||
F07 --> F09
|
||||
ADR002 --> F09
|
||||
ADR003 --> F09
|
||||
ADR004 --> F09
|
||||
ADR003 --> D01
|
||||
D01 --> D02
|
||||
S01 --> D04
|
||||
|
|
@ -169,6 +176,9 @@ flowchart TD
|
|||
P04 --> P06
|
||||
S01 --> P06
|
||||
ADR008 --> P06
|
||||
F07 --> P07
|
||||
P01 --> P07
|
||||
F09 -. compact comparisons only .-> P07
|
||||
R06 --> A01
|
||||
O01 --> A01
|
||||
ADR007 --> A01
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -13,19 +13,23 @@ Scheduling source of truth: [manifest entry F08](../manifest.json). No task is a
|
|||
|
||||
## Intended behavior and implementation scope
|
||||
|
||||
F09 now supplies the independently deliverable compact terminal/owned-fill projection. F08 consumes it and adds historical sampling/statistical reporting; do not duplicate its native transport work. F09 is not completion of this story.
|
||||
|
||||
Use canonical Rust ledger postings, owned fills, occupied intervals and session-ending marks as the sole financial inputs. Reuse reviewed TypeScript statistical functions in `libs/calculations/src/analytics/` for return ratios and reports; do not port them to Rust merely for language uniformity. Add a small adapter for the engine-declared session calendar rather than blindly regrouping every venue by UTC date.
|
||||
|
||||
Version economics and metrics independently. Define sampling, annualization, benchmark and risk-free conventions in the result policy. Missing benchmark/risk-free inputs must not silently become invented measurements. Undefined or unsupported metrics are null with reasons. Adapt existing result DTOs without rewriting old rows.
|
||||
|
||||
Measurable benefit: comparable, independently checked rankings without a second ledger or a needless analytics rewrite.
|
||||
|
||||
Before implementation, pin reporting-only conventions in the handoff: account boundaries currently execute before equal-time observations and are not automatically close-equity samples; partial final sessions must be explicit; exposure needs a declared elapsed/venue-time denominator; the reviewed statistics currently assume 252 periods and default to 2% risk-free, so the adapter must pass a supported explicit policy and diagnose omitted inputs. These choices must not alter financial event ordering or risk semantics. Fills are not round trips.
|
||||
|
||||
## Exclusions
|
||||
|
||||
No accounting/fill recomputation in TypeScript, statistical library rewrite, forced native port, new service, or silent reinterpretation of historical results. Native analytics remain an option only if measured as a bottleneck.
|
||||
|
||||
## Likely files and ownership
|
||||
|
||||
- apps/stock/engine/src/backtest/simple_results.rs (authoritative projections, not new statistical formulas)
|
||||
- apps/stock/engine/src/financial/result.rs and replay reporting hooks (canonical outputs; legacy simple_results.rs remains separate)
|
||||
- apps/stock/orchestrator/src/backtest/native-result.ts
|
||||
- apps/stock/orchestrator/src/backtest/BacktestReport.ts
|
||||
- libs/calculations/src/analytics/return-statistics.ts
|
||||
|
|
@ -36,7 +40,7 @@ Write locks: result-contract. One agent owns this change. Lock names do not over
|
|||
|
||||
## Dependencies and blockers
|
||||
|
||||
Implementation requires [F06](F06.md) integrated.
|
||||
Implementation requires [F06](F06.md) and [F09](F09.md) integrated.
|
||||
|
||||
Architecture decisions: ADR-002, ADR-003. Agents may not independently amend their policies.
|
||||
|
||||
|
|
|
|||
48
docs/development/backlog/tasks/F09.md
Normal file
48
docs/development/backlog/tasks/F09.md
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
# F09 — Return compact canonical replay projections
|
||||
|
||||
Parent epic: E2. Priority/severity: P1 / High. Complexity: M. Specialist: Rust/TypeScript financial integration.
|
||||
|
||||
Story: As a researcher, I can obtain authoritative terminal holdings, P&L and actual fills without serializing the complete nested execution journal, while retaining full diagnostics when needed.
|
||||
|
||||
Scheduling and ownership: [manifest F09](../manifest.json). This is the independently deliverable projection portion of F08, not a replacement for its historical metrics.
|
||||
|
||||
## Evidence and root cause
|
||||
|
||||
- **PER-01 / KEEP-02 — Verified:** [full native finalization](../../../../apps/stock/engine/src/api/replay.rs#L165) exports every nested matching receipt through a JSON value tree. The recorded F07 release workload emits 66.7MB/103.6MB at 10k total bars; finalization averages 0.963s/1.377s, approximately 35–39% of trial time. This is conformance output, not useful minimal research output.
|
||||
- **FIN-05 — Verified:** [Ledger::valuation](../../../../apps/stock/engine/src/financial/ledger.rs#L674), [FinancialEffect](../../../../apps/stock/engine/src/financial/contract.rs#L327) and existing ledger receipts already contain authoritative terminal values, realized basis/P&L, actual fees and ownership. Recomputing these in TypeScript would create competing financial authority.
|
||||
|
||||
## Scope and pinned contract
|
||||
|
||||
- Add a small Rust projection module. Emit the existing terminal snapshot/view, checked Ledger valuation and owner contributions, plus flattened actual fills copied from committed commands/effects in authoritative order. Retain IDs, event time, owner/decision/order/fill, side/quantity/price, fee, cash/quantity deltas, released basis and realized gross P&L. Fills are not completed round trips.
|
||||
- `cashDelta` preserves the ledger effect's gross notional movement; the fee is a separate posting, not an additional fee already included in that delta. Valuation owner contributions include reserve capital and can be negative. Schema coherence checks compare the returned cash/equity strings with the existing view without reproducing accounting arithmetic.
|
||||
- Iterate borrowed ledger receipts once, skipping replay-labelled aliases. A read-only ledger receipt accessor and serialization derives for existing valuation types are allowed. No checkpoint cloning, ledger reconstruction, replay or financial arithmetic duplication to produce output. Preserve internal receipts, idempotency indexes and restore behavior.
|
||||
- Add native `project(identityJson)` beside the unchanged full diagnostic `finalize(identityJson)`. Compact output has `format: "projection"`, `projectionVersion: 1`, `financialVersion: 1`, the same identity/status/manifest/policy/view/limitations, and `projection: { valuation, fills }`; it has no nested `receipts`. Use typed serialization with borrowed metadata where practical.
|
||||
- TS adds a strict projection parser and typed `NativeReplaySession.project()`. The existing conformance loop may select `resultFormat: "projection" | "trace"`; old omitted-format calls and the existing diagnostic parser retain their trace behavior. No second loop. New compact consumers explicitly select projection; active legacy/durable defaults do not change.
|
||||
- The existing fixed-trace worker request may carry the optional format; the parent captures expected format with identity/policy and rejects mismatched responses. Both formats share completion, failure, disposal and cancellation guards.
|
||||
- Extend observational metrics with finalization native-call time (including Rust work/serialization), JSON decode time, schema-validation time and disposal time. Keep these outside economic outputs and deterministic hashes; do not call them pure crossing measurements. Expose unavailable internal Rust/GC splits honestly.
|
||||
|
||||
## Exclusions
|
||||
|
||||
No session-close equity curve, return ratios, Sharpe/Sortino, exposure percentage, round-trip win rate, invented defaults or legacy DTO coercion: these remain F08. No journal deletion/compaction, new accounting, risk/timing changes, new persistence/service, pagination, DSL, cache or default engine/paper/live cutover.
|
||||
|
||||
## Files and ownership
|
||||
|
||||
- `apps/stock/engine/src/financial/result.rs` and tests; `ledger.rs` read-only accessor/valuation serialization; module registration.
|
||||
- `apps/stock/engine/src/api/replay.rs` and generated binding verification.
|
||||
- `apps/stock/orchestrator/src/contracts/native-replay.ts`, `backtest/native-replay.ts`, existing worker supervisor/dispatch as needed.
|
||||
- Focused native/projection/worker fixtures and tests. Benchmark files belong to P07; root coordinates final paired comparisons.
|
||||
|
||||
Write locks: financial-projection, native-public-api, worker-protocol, result-contract. One owner. Dependencies: F07; approved ADR-002/003/004. P07 baseline work is independent; benchmark integration uses the frozen projection contract, not concurrent reinterpretation.
|
||||
|
||||
## Acceptance and mandatory tests
|
||||
|
||||
1. `compact_full_financial_parity`: terminal snapshot/valuation/flattened fills agree with the retained full trace and independent hand-calculated fixtures; all amounts remain canonical decimal strings.
|
||||
2. `projection_aliases_once`, `partial_fill_projection`, `two_owner_projection`: duplicate command/fill aliases do not duplicate output, partial fills remain distinct, owner attribution and fees reconcile, including final residual basis. No-trade output has zero fills and honest terminal values.
|
||||
3. `projection_is_read_only`: repeated project/finalize calls preserve state/checkpoints and original diagnostic output; restored sessions produce the same projection. Full-trace fixture hashes remain unchanged.
|
||||
4. `projection_terminal_guard`, `projection_identity_policy_format`: incomplete/failed/disposed sessions cannot return successful compact output; malformed identities, policies and requested formats reject, including worker races/cancellation and post-result abort.
|
||||
5. Strict TS/schema/architecture/native gates pass. No receipt/future-data leakage into strategy contexts; no broadening of worker-only native reachability.
|
||||
6. Paired release measurements on the same frozen dataset/config/decisions show identical financial projection hashes and reduced output bytes/finalization cost. Preserve full trace as an explicit diagnostic oracle. Record actual before/after; no timing threshold in CI and no promised speedup. P07 supplies representative workload variants.
|
||||
|
||||
Regression risk: alias double counting, effect-to-fee mispairing, silently changed output semantics or a successful result from failed state. Review G1/G2 independently; retain existing F07 regressions and disposable worker/runner durability gates. Rollback is additive API deployment, not weaker financial policies.
|
||||
|
||||
Definition of done: reviewed source, exact integrated test/benchmark evidence and canonical manifest handoff. No commit/push/PR without separate authorization.
|
||||
42
docs/development/backlog/tasks/P07.md
Normal file
42
docs/development/backlog/tasks/P07.md
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
# P07 — Profile representative canonical replay workloads
|
||||
|
||||
Parent epic: E7. Priority/severity: P1 / High. Complexity: M. Specialist: performance/test infrastructure.
|
||||
|
||||
Story: As a platform developer, I can distinguish replay, financial turnover, result transport and diagnostic overhead before choosing the next optimization.
|
||||
|
||||
Scheduling and ownership: [manifest P07](../manifest.json). Extend P01's existing harness; do not create another benchmark framework.
|
||||
|
||||
## Evidence and root cause
|
||||
|
||||
- **PER-01 — Verified:** the F07 [turnover profile](../../../../scripts/benchmark-replay.ts#L100) alternates positions at every barrier. At 10k total bars it creates 9,999/19,980 fills; 2.65–3.61s is not the cost of merely reading bars.
|
||||
- In the original F07 measurement, finalization consumed approximately 35–39%; fixture decisions less than 2%; native creation approximately 3%. Before F09, the [adapter](../../../../apps/stock/orchestrator/src/backtest/native-replay.ts#L184) combined native work and JSON validation, without a separate disposal timer. These measurements did not establish a pure NAPI overhead, Rust bottleneck, or need for a DSL.
|
||||
|
||||
## Scope
|
||||
|
||||
- Extend `scripts/benchmark-replay.ts`, `scripts/benchmark-research.ts` and their tests only. Reuse frozen fixture generation, source/addon/host/runtime hashes and cold-process/fresh-session structure.
|
||||
- Add `none` (same callbacks/cadence, no targets), `sparse` (one opening and one closing fill per owner/asset), and `turnover` (existing alternating unit targets) profiles. Preserve existing invocation behavior; expose explicit CLI profile/format selection and an opt-in 100k size. No new application input limits.
|
||||
- Measure verified dataset preparation, native load, actual advance/submit/decision/finalization/disposal phases, emitted bytes, observed fills/decisions/calls, wall time and process RSS. Consume optional finalization subphase metrics only after the contract owner publishes them. Do not infer internal Rust/GC time from an unexplained residual.
|
||||
- Independent integer-based fixture oracles remain test/benchmark-only. Repeated runs/reversed callback evaluation must preserve economic output. Full trace keeps exact normalized-result hash validation; compact/full comparisons use the same canonical financial projection, not unlike wire-envelope hashes.
|
||||
- Baseline profiles work against committed F07 independently. Paired compact runs are enabled only after F09's contract is frozen/accepted by root; do not edit adapter/schema/native files to make the benchmark fit. Record the exact source/artifact for each baseline/candidate.
|
||||
- Run selected 10k and explicitly requested 100k workloads sequentially. Report unavailable measurements/resource failures honestly rather than silently trimming data/traces. Full-history 100k diagnostic output can be large; no throughput claim for cases not run.
|
||||
|
||||
## Exclusions
|
||||
|
||||
No financial semantic change, arbitrary hot-loop refactor, native dataset cache, shared feature framework, worker pool, DSL, new service, web paging or journal deletion. Select a concrete next optimization from evidence; implementation beyond F09 requires a scoped follow-up.
|
||||
|
||||
## Dependencies, locks and parallelism
|
||||
|
||||
Code prerequisites: F07 and P01. No new economic policy or ADR-008 approval is needed for measurements alone. P03/P04/P06 remain gated. Write lock: benchmark-harness, with the three explicit files above. Safe parallel work with F09's separate core/adapter files. Compact comparison is a conditional integration gate requiring F09; baseline compilation/tests must not depend on unmerged native APIs.
|
||||
|
||||
## Acceptance and mandatory tests
|
||||
|
||||
1. `profile_none`, `profile_sparse`, `profile_turnover` pin deterministic call/fill/fee/basis/terminal-equity expectations, including multiple owners/assets and retained session gaps.
|
||||
2. `benchmark_profile_arguments` rejects unsupported flags/combinations; existing P01/F07 invocation and tiny tests still work.
|
||||
3. `profile_identity_mismatch` rejects changed dataset/policy/strategy/native result identity; profile/result format is included in provenance. Different profiles are never compared as equivalent economics.
|
||||
4. `compact_trace_projection_parity` and reversed callback order agree on authoritative projection; diagnostics remain complete and independently testable.
|
||||
5. No fake zero/unavailable timings, no timing-flaky assertions. Print raw repeated rows and a concise breakdown with timing boundaries/build profile. Distinguish first process/setup from reused prepared JS inputs and fresh native sessions.
|
||||
6. Integrated evidence documents measured candidate effects, remaining unattributed costs and the smallest justified next action. No unsupported 10x/100x claim.
|
||||
|
||||
Regression risk: benchmark oracle mistakes, comparing different policies/profiles, or profiling work inside a purported engine-only timer. Mandatory focused tooling/native fixtures, strict TypeScript and scoped lint; financial/result owner reviews oracle/parity independently. No native rebuild concurrent with another agent's artifact review.
|
||||
|
||||
Definition of done: reproducible script/tests, baseline and accepted-candidate measurements, independent review and root manifest handoff. Missing resource-dependent large runs must be explicit; not a pass. No commits/pushes/PRs without authorization.
|
||||
|
|
@ -1,11 +1,35 @@
|
|||
/** F07 extension of P01, invoked only through benchmark-research.ts --session. */
|
||||
import { createHash } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import type { ReplayResult } from '../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
import type { FinancialEffects } from '@stock-bot/types';
|
||||
import type {
|
||||
ReplayOutput,
|
||||
ReplayProjectionResult,
|
||||
ReplayResultFormat,
|
||||
} from '../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
|
||||
type SessionWorkload = { totalBars: number; assets: number; owners: number; eventBudget: number };
|
||||
export const replayProfiles = ['none', 'sparse', 'turnover'] as const;
|
||||
export type ReplayProfile = (typeof replayProfiles)[number];
|
||||
export type SessionOptions = {
|
||||
profiles: ReplayProfile[];
|
||||
resultFormat: ReplayResultFormat | 'both';
|
||||
totalBars?: number;
|
||||
};
|
||||
type SessionWorkload = {
|
||||
totalBars: number;
|
||||
assets: number;
|
||||
owners: number;
|
||||
eventBudget: number;
|
||||
profile: ReplayProfile;
|
||||
resultFormat: ReplayResultFormat;
|
||||
};
|
||||
const hash = (value: string) => createHash('sha256').update(value).digest('hex');
|
||||
const capital = '1000000.00000000';
|
||||
const profileDefinitions: Record<ReplayProfile, string> = {
|
||||
none: 'no-targets-v1',
|
||||
sparse: 'first-last-unit-target-v1',
|
||||
turnover: 'alternating-unit-target-v1',
|
||||
};
|
||||
|
||||
function cents(value: bigint): string {
|
||||
const magnitude = value < 0n ? -value : value;
|
||||
|
|
@ -15,7 +39,12 @@ function cents(value: bigint): string {
|
|||
/** Independent integer-cent oracle for this fixture only, not a second simulator.
|
||||
* One unit per owner/asset alternates buy/sell at opens 1..N-1, with a 1% fee.
|
||||
* Final position is marked at last close (open+1); no invented liquidation. */
|
||||
export function turnoverOracle(barsPerAsset: number, assets: number, owners: number) {
|
||||
export function profileOracle(
|
||||
profile: ReplayProfile,
|
||||
barsPerAsset: number,
|
||||
assets: number,
|
||||
owners: number
|
||||
) {
|
||||
if (
|
||||
![barsPerAsset, assets, owners].every(Number.isSafeInteger) ||
|
||||
barsPerAsset < 3 ||
|
||||
|
|
@ -25,15 +54,26 @@ export function turnoverOracle(barsPerAsset: number, assets: number, owners: num
|
|||
throw new Error('Expected at least three bars and positive asset/owner counts');
|
||||
}
|
||||
let cashDelta = 0n,
|
||||
fee = 0n;
|
||||
for (let step = 1; step < barsPerAsset; step++) {
|
||||
const price = BigInt(10 + (step % 20) * 2);
|
||||
cashDelta += (step % 2 ? -price : price) * 100n - price;
|
||||
fee += price;
|
||||
fee = 0n,
|
||||
fillsPerBook = 0;
|
||||
const lastOpen = BigInt(10 + ((barsPerAsset - 1) % 20) * 2);
|
||||
if (profile === 'turnover') {
|
||||
for (let step = 1; step < barsPerAsset; step++) {
|
||||
const price = BigInt(10 + (step % 20) * 2);
|
||||
cashDelta += (step % 2 ? -price : price) * 100n - price;
|
||||
fee += price;
|
||||
}
|
||||
fillsPerBook = barsPerAsset - 1;
|
||||
} else if (profile === 'sparse') {
|
||||
// Exactly one unit bought at first eligible open12 and sold at last open.
|
||||
cashDelta = (lastOpen - 12n) * 100n - 12n - lastOpen;
|
||||
fee = 12n + lastOpen;
|
||||
fillsPerBook = 2;
|
||||
} else if (profile !== 'none') {
|
||||
throw new Error('Unknown replay profile');
|
||||
}
|
||||
const books = BigInt(assets * owners),
|
||||
holding = (barsPerAsset - 1) % 2;
|
||||
const lastOpen = BigInt(10 + ((barsPerAsset - 1) % 20) * 2);
|
||||
holding = profile === 'turnover' ? (barsPerAsset - 1) % 2 : 0;
|
||||
const cash = 100_000_000n + cashDelta * books;
|
||||
return {
|
||||
cash: cents(cash),
|
||||
|
|
@ -41,13 +81,154 @@ export function turnoverOracle(barsPerAsset: number, assets: number, owners: num
|
|||
feePerOwner: cents(fee * BigInt(assets)),
|
||||
quantity: `${holding}.00000000`,
|
||||
remainingCost: cents(BigInt(holding) * lastOpen * 100n),
|
||||
fills: (barsPerAsset - 1) * assets * owners,
|
||||
fills: fillsPerBook * assets * owners,
|
||||
decisions: (barsPerAsset - 1) * owners,
|
||||
};
|
||||
}
|
||||
|
||||
function assertEconomics(result: ReplayResult, workload: SessionWorkload) {
|
||||
const expected = turnoverOracle(
|
||||
export function turnoverOracle(barsPerAsset: number, assets: number, owners: number) {
|
||||
return profileOracle('turnover', barsPerAsset, assets, owners);
|
||||
}
|
||||
|
||||
/** A desired unit target only, not an accounting/fill model. null means hold. */
|
||||
export function profileTarget(
|
||||
profile: ReplayProfile,
|
||||
decision: number,
|
||||
barsPerAsset: number
|
||||
): 0 | 1 | null {
|
||||
if (profile === 'none') {
|
||||
return null;
|
||||
}
|
||||
if (profile === 'turnover') {
|
||||
return decision % 2 ? 0 : 1;
|
||||
}
|
||||
if (decision === 0) {
|
||||
return 1;
|
||||
}
|
||||
return decision === barsPerAsset - 2 ? 0 : null;
|
||||
}
|
||||
|
||||
type SharedFill = Pick<
|
||||
ReplayProjectionResult['projection']['fills'][number],
|
||||
| 'commandId'
|
||||
| 'eventTime'
|
||||
| 'ownerId'
|
||||
| 'orderId'
|
||||
| 'fillId'
|
||||
| 'instrumentId'
|
||||
| 'price'
|
||||
| 'cashDelta'
|
||||
| 'quantityDelta'
|
||||
| 'releasedBasis'
|
||||
| 'realizedGrossPnl'
|
||||
| 'fee'
|
||||
>;
|
||||
|
||||
function sharedFill(fill: SharedFill): SharedFill {
|
||||
return {
|
||||
commandId: fill.commandId,
|
||||
eventTime: fill.eventTime,
|
||||
ownerId: fill.ownerId,
|
||||
orderId: fill.orderId,
|
||||
fillId: fill.fillId,
|
||||
instrumentId: fill.instrumentId,
|
||||
price: fill.price,
|
||||
cashDelta: fill.cashDelta,
|
||||
quantityDelta: fill.quantityDelta,
|
||||
releasedBasis: fill.releasedBasis,
|
||||
realizedGrossPnl: fill.realizedGrossPnl,
|
||||
fee: { feeId: fill.fee.feeId, amount: fill.fee.amount },
|
||||
};
|
||||
}
|
||||
|
||||
/** Benchmark-only copy of shared authoritative fields. No valuation, fee or P&L
|
||||
* arithmetic. The trace has no LedgerValuation; that extra compact projection
|
||||
* remains covered by Rust/independent fixtures, not synthesized in this hash. */
|
||||
export function commonFinancialProjection(result: ReplayOutput) {
|
||||
const fills: SharedFill[] = [];
|
||||
if ('projection' in result) {
|
||||
for (const fill of result.projection.fills) {
|
||||
fills.push(sharedFill(fill));
|
||||
}
|
||||
} else {
|
||||
for (const receipt of result.receipts) {
|
||||
if (receipt.outcome.replayed) {
|
||||
continue;
|
||||
}
|
||||
for (const effect of receipt.outcome.effects) {
|
||||
if (!('Risk' in effect)) {
|
||||
continue;
|
||||
}
|
||||
const risk = effect.Risk as {
|
||||
outcome: {
|
||||
replayed: boolean;
|
||||
disposition: unknown;
|
||||
financial: null | { replayed: boolean; effects: FinancialEffects };
|
||||
};
|
||||
};
|
||||
if (risk.outcome.replayed) {
|
||||
continue;
|
||||
}
|
||||
if (risk.outcome.disposition !== 'Accepted') {
|
||||
throw new Error('Unexpected benchmark risk rejection');
|
||||
}
|
||||
const financial = risk.outcome.financial;
|
||||
if (!financial || financial.replayed) {
|
||||
continue;
|
||||
}
|
||||
const applied = financial.effects.effects.filter(e => e.kind === 'fillApplied');
|
||||
const fees = financial.effects.effects.filter(e => e.kind === 'feeApplied');
|
||||
if (!applied.length && !fees.length) {
|
||||
continue;
|
||||
}
|
||||
const fill = applied[0],
|
||||
fee = fees[0];
|
||||
if (
|
||||
applied.length !== 1 ||
|
||||
fees.length !== 1 ||
|
||||
!fill ||
|
||||
!fee ||
|
||||
fill.ownerId !== fee.ownerId ||
|
||||
fill.fillId !== fee.fillId
|
||||
) {
|
||||
throw new Error('Malformed trace fill/fee pair');
|
||||
}
|
||||
fills.push(
|
||||
sharedFill({
|
||||
...fill,
|
||||
commandId: financial.effects.commandId,
|
||||
eventTime: financial.effects.eventTime,
|
||||
fee: { feeId: fee.feeId, amount: fee.amount },
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
identity: result.identity,
|
||||
status: result.status,
|
||||
manifest: result.manifest,
|
||||
policy: result.policy,
|
||||
view: result.view,
|
||||
limitations: result.limitations,
|
||||
modelLimitations: result.modelLimitations,
|
||||
fills,
|
||||
};
|
||||
}
|
||||
|
||||
export function assertResultFormat(result: ReplayOutput, expected: ReplayResultFormat): void {
|
||||
if (('projection' in result ? 'projection' : 'trace') !== expected) {
|
||||
throw new Error('Benchmark result format mismatch');
|
||||
}
|
||||
}
|
||||
|
||||
function assertEconomics(
|
||||
result: ReplayOutput,
|
||||
workload: SessionWorkload,
|
||||
fills: readonly SharedFill[]
|
||||
) {
|
||||
const expected = profileOracle(
|
||||
workload.profile,
|
||||
workload.totalBars / workload.assets,
|
||||
workload.assets,
|
||||
workload.owners
|
||||
|
|
@ -56,7 +237,8 @@ function assertEconomics(result: ReplayResult, workload: SessionWorkload) {
|
|||
if (
|
||||
portfolio.cash !== expected.cash ||
|
||||
result.view.equity !== expected.equity ||
|
||||
portfolio.positions.length !== workload.assets * workload.owners ||
|
||||
portfolio.positions.length !==
|
||||
(workload.profile === 'none' ? 0 : workload.assets * workload.owners) ||
|
||||
portfolio.positions.some(
|
||||
p => p.quantity !== expected.quantity || p.remainingCost !== expected.remainingCost
|
||||
) ||
|
||||
|
|
@ -67,42 +249,10 @@ function assertEconomics(result: ReplayResult, workload: SessionWorkload) {
|
|||
) {
|
||||
throw new Error('Canonical benchmark failed independent cash/equity/owner/basis/fee oracle');
|
||||
}
|
||||
let fills = 0,
|
||||
fees = 0;
|
||||
for (const receipt of result.receipts) {
|
||||
for (const effect of receipt.outcome.effects) {
|
||||
if (!('Risk' in effect)) {
|
||||
continue;
|
||||
}
|
||||
const risk = effect.Risk as {
|
||||
outcome: {
|
||||
disposition: unknown;
|
||||
financial: null | { replayed: boolean; effects: { effects: { kind: string }[] } };
|
||||
};
|
||||
};
|
||||
if (risk.outcome.disposition !== 'Accepted') {
|
||||
throw new Error('Unexpected benchmark risk rejection');
|
||||
}
|
||||
if (!risk.outcome.financial) {
|
||||
continue;
|
||||
}
|
||||
if (risk.outcome.financial.replayed) {
|
||||
throw new Error('Unexpected benchmark duplicate effect');
|
||||
}
|
||||
for (const financial of risk.outcome.financial.effects.effects) {
|
||||
if (financial.kind === 'fillApplied') {
|
||||
fills++;
|
||||
}
|
||||
if (financial.kind === 'feeApplied') {
|
||||
fees++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (fills !== expected.fills || fees !== fills) {
|
||||
if (fills.length !== expected.fills) {
|
||||
throw new Error('Unexpected benchmark fill/fee count');
|
||||
}
|
||||
return { ...expected, fees };
|
||||
return { ...expected, fees: fills.length };
|
||||
}
|
||||
|
||||
export async function sessionChild(workload: SessionWorkload) {
|
||||
|
|
@ -121,6 +271,10 @@ export async function sessionChild(workload: SessionWorkload) {
|
|||
const { nativeReplayFixture } = await import('../test/fixtures/native-replay');
|
||||
const { parseFinancialDecimal } = await import('@stock-bot/types');
|
||||
const applicationImportMs = elapsed();
|
||||
const nativeSha256 = createHash('sha256')
|
||||
.update(readFileSync(new URL('../apps/stock/engine/dist/engine.node', import.meta.url)))
|
||||
.digest('hex');
|
||||
const artifactIdentityMs = elapsed();
|
||||
await import('@stock-bot/engine');
|
||||
const addonImportMs = elapsed();
|
||||
const { prepareReplayLoad, NativeReplaySession, runReplayConformance } = await import(
|
||||
|
|
@ -163,19 +317,33 @@ export async function sessionChild(workload: SessionWorkload) {
|
|||
owner => {
|
||||
const decision = counts.get(owner) ?? 0;
|
||||
counts.set(owner, decision + 1);
|
||||
const quantity = profileTarget(
|
||||
workload.profile,
|
||||
decision,
|
||||
workload.totalBars / workload.assets
|
||||
);
|
||||
return {
|
||||
mode: 'target',
|
||||
targets: fixture.instruments.map(instrumentId => ({
|
||||
instrumentId,
|
||||
quantity: decision % 2 ? zero : one,
|
||||
})),
|
||||
targets:
|
||||
quantity === null
|
||||
? []
|
||||
: fixture.instruments.map(instrumentId => ({
|
||||
instrumentId,
|
||||
quantity: quantity === 0 ? zero : one,
|
||||
})),
|
||||
};
|
||||
},
|
||||
{ eventBudget: workload.eventBudget, reverseCallbacks: repeat === 1 }
|
||||
{
|
||||
eventBudget: workload.eventBudget,
|
||||
reverseCallbacks: repeat === 1,
|
||||
resultFormat: workload.resultFormat,
|
||||
}
|
||||
);
|
||||
const runWallMs = performance.now() - runStart;
|
||||
const validationStart = performance.now();
|
||||
const economic = assertEconomics(result, workload);
|
||||
assertResultFormat(result, workload.resultFormat);
|
||||
const common = commonFinancialProjection(result);
|
||||
const economic = assertEconomics(result, workload, common.fills);
|
||||
const decisions = [...counts.values()].reduce((a, b) => a + b, 0);
|
||||
if (decisions !== economic.decisions) {
|
||||
throw new Error('Unexpected benchmark decision count');
|
||||
|
|
@ -183,12 +351,14 @@ export async function sessionChild(workload: SessionWorkload) {
|
|||
// Exact complete normalized result bytes include provenance, ordered receipts,
|
||||
// policy and terminal holdings, not just a selectively hashed P&L summary.
|
||||
const resultHash = hash(JSON.stringify(result));
|
||||
const commonFinancialHash = hash(JSON.stringify(common));
|
||||
const validationAndHashMs = performance.now() - validationStart;
|
||||
const wallMs = performance.now() - trialStart;
|
||||
trials.push({
|
||||
repeat,
|
||||
reverseCallbacks: repeat === 1,
|
||||
resultHash,
|
||||
commonFinancialHash,
|
||||
economic,
|
||||
calls: {
|
||||
create: 1,
|
||||
|
|
@ -213,6 +383,18 @@ export async function sessionChild(workload: SessionWorkload) {
|
|||
submit: metrics.submitMs,
|
||||
decisions: metrics.decisionMs,
|
||||
finalize: metrics.finalizeMs,
|
||||
finalizeNative: metrics.finalizeNativeMs,
|
||||
finalizeDecode: metrics.finalizeDecodeMs,
|
||||
finalizeValidation: metrics.finalizeValidationMs,
|
||||
dispose: metrics.disposeMs,
|
||||
// This is measured time outside the named phases, not an inferred GC cost.
|
||||
unattributedLoop:
|
||||
runWallMs -
|
||||
metrics.advanceMs -
|
||||
metrics.submitMs -
|
||||
metrics.decisionMs -
|
||||
metrics.finalizeMs -
|
||||
metrics.disposeMs,
|
||||
runWallMs,
|
||||
validationAndHashMs,
|
||||
wallMs,
|
||||
|
|
@ -236,15 +418,20 @@ export async function sessionChild(workload: SessionWorkload) {
|
|||
: null;
|
||||
return {
|
||||
workload,
|
||||
nativeSha256,
|
||||
profile: workload.profile,
|
||||
resultFormat: workload.resultFormat,
|
||||
strategyHash: hash(profileDefinitions[workload.profile]),
|
||||
datasetHash: dataset.manifest.hash,
|
||||
policyHash: hash(
|
||||
JSON.stringify({ config: load.config, strategy: 'alternating-unit-target-v1' })
|
||||
JSON.stringify({ config: load.config, strategy: profileDefinitions[workload.profile] })
|
||||
),
|
||||
datasetBytes: Buffer.byteLength(wireDataset),
|
||||
policy: load.config,
|
||||
phasesMs: {
|
||||
entryUptimeMs,
|
||||
applicationImportMs,
|
||||
artifactIdentityMs,
|
||||
addonImportMs,
|
||||
adapterImportMs,
|
||||
fixtureGenerationMs,
|
||||
|
|
@ -261,43 +448,121 @@ export async function sessionChild(workload: SessionWorkload) {
|
|||
}
|
||||
|
||||
export function verifySessionRepeats(
|
||||
samples: { datasetHash: string; policyHash: string; trials: { resultHash: string }[] }[]
|
||||
samples: {
|
||||
datasetHash: string;
|
||||
policyHash: string;
|
||||
nativeSha256: string;
|
||||
profile: ReplayProfile;
|
||||
resultFormat: ReplayResultFormat;
|
||||
strategyHash: string;
|
||||
trials: { resultHash: string; commonFinancialHash: string }[];
|
||||
}[],
|
||||
expectedNativeHash?: string
|
||||
) {
|
||||
const first = samples[0],
|
||||
expected = first?.trials[0]?.resultHash;
|
||||
if (!first || !expected) {
|
||||
if (!first || !expected || !first.trials[0]?.commonFinancialHash) {
|
||||
throw new Error('Missing canonical benchmark samples');
|
||||
}
|
||||
for (const sample of samples) {
|
||||
if (
|
||||
sample.datasetHash !== first.datasetHash ||
|
||||
sample.policyHash !== first.policyHash ||
|
||||
sample.nativeSha256 !== first.nativeSha256 ||
|
||||
(expectedNativeHash !== undefined && sample.nativeSha256 !== expectedNativeHash) ||
|
||||
sample.profile !== first.profile ||
|
||||
sample.resultFormat !== first.resultFormat ||
|
||||
sample.strategyHash !== first.strategyHash ||
|
||||
!sample.trials.length ||
|
||||
sample.trials.some(trial => trial.resultHash !== expected)
|
||||
sample.trials.some(
|
||||
trial =>
|
||||
trial.resultHash !== expected ||
|
||||
trial.commonFinancialHash !== first.trials[0]?.commonFinancialHash
|
||||
)
|
||||
) {
|
||||
throw new Error('Canonical dataset/policy/result mismatch; no timing comparison is valid');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type SessionSample = Parameters<typeof verifySessionRepeats>[0][number];
|
||||
export function verifyProjectionParity(
|
||||
trace: SessionSample[],
|
||||
projection: SessionSample[]
|
||||
): string {
|
||||
verifySessionRepeats(trace);
|
||||
verifySessionRepeats(projection);
|
||||
const a = trace[0],
|
||||
b = projection[0],
|
||||
sharedHash = a?.trials[0]?.commonFinancialHash;
|
||||
if (
|
||||
!a ||
|
||||
!b ||
|
||||
!sharedHash ||
|
||||
a.resultFormat !== 'trace' ||
|
||||
b.resultFormat !== 'projection' ||
|
||||
a.datasetHash !== b.datasetHash ||
|
||||
a.policyHash !== b.policyHash ||
|
||||
a.strategyHash !== b.strategyHash ||
|
||||
a.profile !== b.profile ||
|
||||
a.nativeSha256 !== b.nativeSha256 ||
|
||||
sharedHash !== b.trials[0]?.commonFinancialHash
|
||||
) {
|
||||
throw new Error('Compact/trace financial projection or provenance mismatch');
|
||||
}
|
||||
return sharedHash;
|
||||
}
|
||||
|
||||
function median(values: number[]): number {
|
||||
const sorted = [...values].sort((a, b) => a - b),
|
||||
middle = Math.floor(sorted.length / 2),
|
||||
upper = sorted[middle],
|
||||
lower = sorted[Math.max(0, middle - 1)];
|
||||
if (upper === undefined || lower === undefined) {
|
||||
throw new Error('Missing measurement samples');
|
||||
}
|
||||
return sorted.length % 2 ? upper : (lower + upper) / 2;
|
||||
}
|
||||
|
||||
export async function sessionBenchmark(
|
||||
root: string,
|
||||
entry: string,
|
||||
metadata: object,
|
||||
metadata: { native: { sha256: string } },
|
||||
measured: boolean,
|
||||
large: boolean
|
||||
large: boolean,
|
||||
options: SessionOptions = { profiles: ['turnover'], resultFormat: 'trace' }
|
||||
) {
|
||||
const workloads = (measured ? (large ? [1000, 10000, 100000] : [1000, 10000]) : [8]).flatMap(
|
||||
bars => [
|
||||
{ totalBars: bars, assets: 1, owners: 1, eventBudget: 64 },
|
||||
{
|
||||
totalBars: measured ? bars : bars * 2,
|
||||
assets: measured ? 10 : 2,
|
||||
owners: 2,
|
||||
eventBudget: 64,
|
||||
},
|
||||
]
|
||||
);
|
||||
const sizes = options.totalBars
|
||||
? [options.totalBars]
|
||||
: measured
|
||||
? large
|
||||
? [1000, 10000, 100000]
|
||||
: [1000, 10000]
|
||||
: [8];
|
||||
const formats: ReplayResultFormat[] =
|
||||
options.resultFormat === 'both' ? ['trace', 'projection'] : [options.resultFormat];
|
||||
const workloads = options.profiles
|
||||
.flatMap(profile =>
|
||||
sizes.flatMap(bars => [
|
||||
{
|
||||
totalBars: bars,
|
||||
assets: 1,
|
||||
owners: 1,
|
||||
eventBudget: 64,
|
||||
profile,
|
||||
resultFormat: 'trace' as const,
|
||||
},
|
||||
{
|
||||
totalBars: measured ? bars : bars * 2,
|
||||
assets: measured ? 10 : 2,
|
||||
owners: 2,
|
||||
eventBudget: 64,
|
||||
profile,
|
||||
resultFormat: 'trace' as const,
|
||||
},
|
||||
])
|
||||
)
|
||||
.flatMap(workload => formats.map(resultFormat => ({ ...workload, resultFormat })));
|
||||
const measurements = [];
|
||||
for (const workload of workloads) {
|
||||
const samples = [];
|
||||
|
|
@ -331,21 +596,59 @@ export async function sessionBenchmark(
|
|||
processBarsPerSecond: (workload.totalBars * sample.trials.length) / (processWallMs / 1000),
|
||||
});
|
||||
}
|
||||
verifySessionRepeats(samples);
|
||||
measurements.push({ workload, repeatedResultHashesMatch: true, samples });
|
||||
verifySessionRepeats(samples, metadata.native.sha256);
|
||||
const trials = samples.flatMap(sample => sample.trials),
|
||||
firstTrial = trials[0];
|
||||
if (!firstTrial) {
|
||||
throw new Error('Missing measurement trials');
|
||||
}
|
||||
const breakdown = {
|
||||
samples: trials.length,
|
||||
medianMs: Object.fromEntries(
|
||||
Object.keys(firstTrial.timingsMs).map(key => [
|
||||
key,
|
||||
median(trials.map(trial => trial.timingsMs[key as keyof typeof trial.timingsMs])),
|
||||
])
|
||||
),
|
||||
resultBytes: firstTrial.bytes.finalizeResponse,
|
||||
};
|
||||
measurements.push({ workload, repeatedResultHashesMatch: true, breakdown, samples });
|
||||
process.stderr.write(
|
||||
`Verified canonical ${workload.totalBars} bars / ${workload.assets} assets / ${workload.owners} owners, 2 fresh processes × 2 fresh sessions\n`
|
||||
`Verified canonical ${workload.profile}/${workload.resultFormat}: ${workload.totalBars} bars / ${workload.assets} assets / ${workload.owners} owners, 2 fresh processes × 2 fresh sessions\n`
|
||||
);
|
||||
}
|
||||
const comparisons = [];
|
||||
if (options.resultFormat === 'both') {
|
||||
for (let index = 0; index < measurements.length; index += 2) {
|
||||
const trace = measurements[index],
|
||||
projection = measurements[index + 1];
|
||||
if (!trace || !projection) {
|
||||
throw new Error('Missing paired measurements');
|
||||
}
|
||||
const commonFinancialHash = verifyProjectionParity(trace.samples, projection.samples);
|
||||
comparisons.push({
|
||||
profile: trace.workload.profile,
|
||||
totalBars: trace.workload.totalBars,
|
||||
assets: trace.workload.assets,
|
||||
owners: trace.workload.owners,
|
||||
commonFinancialHash,
|
||||
trace: trace.breakdown,
|
||||
projection: projection.breakdown,
|
||||
});
|
||||
}
|
||||
}
|
||||
process.stdout.write(
|
||||
JSON.stringify(
|
||||
{
|
||||
schemaVersion: 1,
|
||||
schemaVersion: 2,
|
||||
path: 'canonical-pull-session',
|
||||
mode: measured ? 'measurement' : 'self-test',
|
||||
...metadata,
|
||||
strategy: {
|
||||
definition: 'alternating-unit-target-v1',
|
||||
profiles: options.profiles.map(profile => ({
|
||||
profile,
|
||||
definition: profileDefinitions[profile],
|
||||
})),
|
||||
randomness: 'None; controlled deterministic fixture/decision counters',
|
||||
},
|
||||
unavailable: {
|
||||
|
|
@ -359,6 +662,8 @@ export async function sessionBenchmark(
|
|||
parallelism: 'Sequential trials; no parallel simulation.',
|
||||
perCallDistribution:
|
||||
'Mean and total latency only; no latency histogram or cancellation wall-time claim.',
|
||||
nativeInternals:
|
||||
'Native-call timers include Rust work/serialization and NAPI; no Rust compute/serialization/allocation split.',
|
||||
},
|
||||
limitations: [
|
||||
'Component conformance throughput, not a production strategy or durable research run; no comparison/speedup against legacy economics.',
|
||||
|
|
@ -366,10 +671,14 @@ export async function sessionBenchmark(
|
|||
'First session and repeat are reported separately; no explicit warmup. Every repeated result, including reversed callback order, must match exactly.',
|
||||
'Advance response bytes include immutable context, observation deltas and protocol envelopes; they are not feature payload bytes alone.',
|
||||
'Financial oracle uses integer cents for this fixed-price/unit/1%-fee fixture only. Multi-asset sequential-mark risk semantics remain unchanged.',
|
||||
'Full retained receipts are finalized and parsed; RSS is process-wide, not native residency. Metadata hashing and parent aggregation are outside child timings.',
|
||||
'Trace returns full retained receipts; projection returns compact authoritative fields. Neither mode compacts internal journals. RSS is process-wide, not native residency.',
|
||||
'Source/parent metadata hashing and aggregation are outside child timings. The child addon hash is measured separately in artifactIdentityMs and included in childWallMs.',
|
||||
'Each format retains its own full normalized result hash. Cross-format comparison hashes shared provenance/view and copied fill/effect/fee fields; projection-only LedgerValuation is not recomputed in TypeScript.',
|
||||
'Whole-trial time includes benchmark oracle and both result/projection hashes. runWallMs excludes that benchmark-only validation and includes separately measured disposal. Unattributed loop time is not labelled native work or GC.',
|
||||
'An event budget bounds event count, not elapsed time. JSON throughput and actual decision costs are measured together with boundary work.',
|
||||
],
|
||||
measurements,
|
||||
comparisons,
|
||||
},
|
||||
null,
|
||||
2
|
||||
|
|
|
|||
|
|
@ -5,6 +5,8 @@
|
|||
* bun run scripts/benchmark-research.ts --measure --large # additionally 100k (quadratic queue)
|
||||
* bun run scripts/benchmark-research.ts --session # canonical pull-session self-test
|
||||
* bun run scripts/benchmark-research.ts --session --measure # 1k/10k bars, actual TS decisions
|
||||
* bun run scripts/benchmark-research.ts --session --measure --profile=sparse --bars=10000
|
||||
* bun run scripts/benchmark-research.ts --session --measure --profile=all --format=both --bars=10000
|
||||
* Build workspace libraries/config and the local engine first. JSON stdout; diagnostics stderr.
|
||||
*/
|
||||
import { createHash } from 'node:crypto';
|
||||
|
|
@ -336,6 +338,77 @@ export function verifyRepeats(
|
|||
}
|
||||
}
|
||||
|
||||
/** Explicit benchmark selections, not application dataset/input limits. */
|
||||
export function parseBenchmarkArguments(args: string[]) {
|
||||
const options = {
|
||||
session: false,
|
||||
measured: false,
|
||||
large: false,
|
||||
selfTest: false,
|
||||
profile: 'turnover' as 'none' | 'sparse' | 'turnover' | 'all',
|
||||
resultFormat: 'trace' as 'trace' | 'projection' | 'both',
|
||||
totalBars: undefined as number | undefined,
|
||||
};
|
||||
const seen = new Set<string>();
|
||||
for (const argument of args) {
|
||||
const [flag, value] = argument.split('=');
|
||||
if (!flag || seen.has(flag)) {
|
||||
throw new Error('Duplicate or invalid benchmark flag');
|
||||
}
|
||||
seen.add(flag);
|
||||
switch (flag) {
|
||||
case '--session':
|
||||
options.session = true;
|
||||
break;
|
||||
case '--measure':
|
||||
options.measured = true;
|
||||
break;
|
||||
case '--large':
|
||||
options.large = true;
|
||||
break;
|
||||
case '--self-test':
|
||||
options.selfTest = true;
|
||||
break;
|
||||
case '--profile':
|
||||
if (!['none', 'sparse', 'turnover', 'all'].includes(value ?? '')) {
|
||||
throw new Error('Unknown benchmark profile');
|
||||
}
|
||||
options.profile = value as typeof options.profile;
|
||||
break;
|
||||
case '--format':
|
||||
if (!['trace', 'projection', 'both'].includes(value ?? '')) {
|
||||
throw new Error('Unknown benchmark result format');
|
||||
}
|
||||
options.resultFormat = value as typeof options.resultFormat;
|
||||
break;
|
||||
case '--bars':
|
||||
if (!['1000', '10000', '100000'].includes(value ?? '')) {
|
||||
throw new Error('Benchmark --bars must be1000,10000 or100000');
|
||||
}
|
||||
options.totalBars = Number(value);
|
||||
break;
|
||||
default:
|
||||
throw new Error('Unknown benchmark flag');
|
||||
}
|
||||
if (!['--profile', '--format', '--bars'].includes(flag) && value !== undefined) {
|
||||
throw new Error('Boolean benchmark flags do not accept values');
|
||||
}
|
||||
if (argument.split('=').length > 2) {
|
||||
throw new Error('Invalid benchmark flag value');
|
||||
}
|
||||
}
|
||||
if ((options.large && !options.measured) || (options.selfTest && options.measured)) {
|
||||
throw new Error('Use no flags/--self-test, --measure, or --measure --large');
|
||||
}
|
||||
if (!options.session && ['--profile', '--format', '--bars'].some(flag => seen.has(flag))) {
|
||||
throw new Error('Profile, format and bar selections require --session');
|
||||
}
|
||||
if (options.totalBars !== undefined && (!options.measured || options.large)) {
|
||||
throw new Error('--bars requires --measure and cannot be combined with --large');
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
async function main(args: string[]) {
|
||||
if (args[0] === '--session-child') {
|
||||
const { sessionChild } = await import('./benchmark-replay');
|
||||
|
|
@ -346,25 +419,23 @@ async function main(args: string[]) {
|
|||
process.stdout.write(JSON.stringify(await child(JSON.parse(args[1] ?? ''))) + '\n');
|
||||
return;
|
||||
}
|
||||
if (
|
||||
args.some(a => !['--self-test', '--measure', '--large', '--session'].includes(a)) ||
|
||||
(args.includes('--large') && !args.includes('--measure')) ||
|
||||
(args.includes('--self-test') && args.includes('--measure'))
|
||||
) {
|
||||
throw new Error(
|
||||
'Use no flags/--self-test, --measure, or --measure --large; optionally --session'
|
||||
);
|
||||
}
|
||||
const selection = parseBenchmarkArguments(args);
|
||||
const metadata = identity(); // Excluded from workload timings.
|
||||
const measured = args.includes('--measure');
|
||||
if (args.includes('--session')) {
|
||||
const measured = selection.measured;
|
||||
if (selection.session) {
|
||||
const { sessionBenchmark } = await import('./benchmark-replay');
|
||||
await sessionBenchmark(
|
||||
root,
|
||||
fileURLToPath(import.meta.url),
|
||||
metadata,
|
||||
measured,
|
||||
args.includes('--large')
|
||||
selection.large,
|
||||
{
|
||||
profiles:
|
||||
selection.profile === 'all' ? ['none', 'sparse', 'turnover'] : [selection.profile],
|
||||
resultFormat: selection.resultFormat,
|
||||
totalBars: selection.totalBars,
|
||||
}
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,100 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { turnoverOracle, verifySessionRepeats } from '../benchmark-replay';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import { executeReplayTrace } from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import { nativeReplayFixture } from '../../test/fixtures/native-replay';
|
||||
import {
|
||||
assertResultFormat,
|
||||
commonFinancialProjection,
|
||||
profileOracle,
|
||||
profileTarget,
|
||||
turnoverOracle,
|
||||
verifyProjectionParity,
|
||||
verifySessionRepeats,
|
||||
} from '../benchmark-replay';
|
||||
import { parseBenchmarkArguments } from '../benchmark-research';
|
||||
|
||||
test('canonical benchmark integer-cent oracle includes fees and terminal marks', () => {
|
||||
test('profile_none invokes the same cadence without orders, fees or position books', () => {
|
||||
expect(profileOracle('none', 602, 2, 2)).toEqual({
|
||||
cash: '1000000.00000000',
|
||||
equity: '1000000.00000000',
|
||||
feePerOwner: '0.00000000',
|
||||
quantity: '0.00000000',
|
||||
remainingCost: '0.00000000',
|
||||
fills: 0,
|
||||
decisions: 1202,
|
||||
});
|
||||
for (let decision = 0; decision < 601; decision++) {
|
||||
expect(profileTarget('none', decision, 602)).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
test('profile_sparse buys first and sells last across retained session gaps', () => {
|
||||
expect(profileOracle('sparse', 602, 2, 2)).toEqual({
|
||||
cash: '999999.04000000',
|
||||
equity: '999999.04000000',
|
||||
feePerOwner: '0.48000000',
|
||||
quantity: '0.00000000',
|
||||
remainingCost: '0.00000000',
|
||||
fills: 8,
|
||||
decisions: 1202,
|
||||
});
|
||||
expect(profileTarget('sparse', 0, 602)).toBe(1);
|
||||
expect(profileTarget('sparse', 600, 602)).toBe(0);
|
||||
for (let decision = 1; decision < 600; decision++) {
|
||||
expect(profileTarget('sparse', decision, 602)).toBeNull();
|
||||
}
|
||||
expect(profileOracle('sparse', 4, 1, 1).cash).toBe('1000003.72000000');
|
||||
});
|
||||
|
||||
test('benchmark_profile_arguments preserves defaults and rejects unsupported combinations', () => {
|
||||
expect(parseBenchmarkArguments([])).toMatchObject({
|
||||
session: false,
|
||||
measured: false,
|
||||
profile: 'turnover',
|
||||
resultFormat: 'trace',
|
||||
});
|
||||
expect(parseBenchmarkArguments(['--session'])).toMatchObject({
|
||||
session: true,
|
||||
profile: 'turnover',
|
||||
});
|
||||
expect(
|
||||
parseBenchmarkArguments([
|
||||
'--session',
|
||||
'--measure',
|
||||
'--profile=all',
|
||||
'--format=trace',
|
||||
'--bars=100000',
|
||||
])
|
||||
).toMatchObject({
|
||||
session: true,
|
||||
measured: true,
|
||||
profile: 'all',
|
||||
resultFormat: 'trace',
|
||||
totalBars: 100000,
|
||||
});
|
||||
for (const resultFormat of ['trace', 'projection', 'both'] as const) {
|
||||
expect(parseBenchmarkArguments(['--session', `--format=${resultFormat}`]).resultFormat).toBe(
|
||||
resultFormat
|
||||
);
|
||||
}
|
||||
for (const args of [
|
||||
['--profile=none'],
|
||||
['--session', '--profile=unknown'],
|
||||
['--session', '--format=unknown'],
|
||||
['--session', '--bars=10000'],
|
||||
['--session', '--measure', '--bars=99'],
|
||||
['--large'],
|
||||
['--session', '--measure', '--large', '--bars=10000'],
|
||||
['--self-test', '--measure'],
|
||||
['--session=yes'],
|
||||
['--session', '--session'],
|
||||
['--session', '--profile=none=extra'],
|
||||
]) {
|
||||
expect(() => parseBenchmarkArguments(args)).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
test('profile_turnover integer-cent oracle includes fees and terminal marks', () => {
|
||||
expect(turnoverOracle(3, 1, 1)).toEqual({
|
||||
cash: '1000001.74000000',
|
||||
equity: '1000001.74000000',
|
||||
|
|
@ -27,18 +120,261 @@ test('canonical benchmark rejects any changed provenance or complete result hash
|
|||
const sample = {
|
||||
datasetHash: 'dataset',
|
||||
policyHash: 'policy',
|
||||
trials: [{ resultHash: 'result' }, { resultHash: 'result' }],
|
||||
nativeSha256: 'native',
|
||||
profile: 'turnover' as const,
|
||||
resultFormat: 'trace' as const,
|
||||
strategyHash: 'strategy',
|
||||
trials: [
|
||||
{ resultHash: 'result', commonFinancialHash: 'common' },
|
||||
{ resultHash: 'result', commonFinancialHash: 'common' },
|
||||
],
|
||||
};
|
||||
expect(() => verifySessionRepeats([sample, structuredClone(sample)])).not.toThrow();
|
||||
for (const changed of [
|
||||
{ ...sample, datasetHash: 'changed' },
|
||||
{ ...sample, policyHash: 'changed' },
|
||||
{ ...sample, trials: [{ resultHash: 'changed' }] },
|
||||
{ ...sample, nativeSha256: 'changed' },
|
||||
{ ...sample, strategyHash: 'changed' },
|
||||
{ ...sample, profile: 'none' as const },
|
||||
{ ...sample, resultFormat: 'projection' as const },
|
||||
{ ...sample, trials: [{ resultHash: 'changed', commonFinancialHash: 'common' }] },
|
||||
{ ...sample, trials: [{ resultHash: 'result', commonFinancialHash: 'changed' }] },
|
||||
{ ...sample, trials: [] },
|
||||
]) {
|
||||
expect(() => verifySessionRepeats([sample, changed])).toThrow('mismatch');
|
||||
}
|
||||
expect(() => verifySessionRepeats([])).toThrow('Missing');
|
||||
expect(() =>
|
||||
verifySessionRepeats([
|
||||
{ ...sample, trials: [{ resultHash: 'result', commonFinancialHash: '' }] },
|
||||
])
|
||||
).toThrow('Missing');
|
||||
expect(() => verifySessionRepeats([sample], 'different-artifact')).toThrow('mismatch');
|
||||
});
|
||||
|
||||
function normalizerFixture() {
|
||||
const fixture = nativeReplayFixture();
|
||||
const input = {
|
||||
type: 'runReplayTrace' as const,
|
||||
version: 1 as const,
|
||||
dataset: fixture.dataset,
|
||||
config: fixture.config,
|
||||
eventBudget: 1,
|
||||
trace: [
|
||||
{
|
||||
at: fixture.start + fixture.minute,
|
||||
ownerId: 'A',
|
||||
intent: {
|
||||
mode: 'target' as const,
|
||||
targets: [{ instrumentId: 'X0.US', quantity: parseFinancialDecimal('2') }],
|
||||
},
|
||||
},
|
||||
{
|
||||
at: fixture.start + 2 * fixture.minute,
|
||||
ownerId: 'A',
|
||||
intent: { mode: 'target' as const, targets: [] },
|
||||
},
|
||||
],
|
||||
};
|
||||
return {
|
||||
trace: executeReplayTrace(input).result,
|
||||
projection: executeReplayTrace({ ...input, resultFormat: 'projection' }).result,
|
||||
};
|
||||
}
|
||||
|
||||
test('common financial projection copies authoritative fill facts without valuing positions', () => {
|
||||
const { trace, projection } = normalizerFixture();
|
||||
const common = commonFinancialProjection(trace);
|
||||
expect(commonFinancialProjection(projection)).toEqual(common);
|
||||
expect(common).not.toHaveProperty('valuation');
|
||||
expect(common.fills).toHaveLength(1);
|
||||
expect(common.fills[0]).toMatchObject({
|
||||
cashDelta: '-24.00000000',
|
||||
fee: { amount: '0.24000000' },
|
||||
});
|
||||
for (const field of [
|
||||
'commandId',
|
||||
'eventTime',
|
||||
'ownerId',
|
||||
'orderId',
|
||||
'fillId',
|
||||
'instrumentId',
|
||||
'price',
|
||||
'cashDelta',
|
||||
'quantityDelta',
|
||||
'releasedBasis',
|
||||
'realizedGrossPnl',
|
||||
] as const) {
|
||||
const changed = structuredClone(projection);
|
||||
const fill = changed.projection.fills[0]!;
|
||||
Object.assign(fill, {
|
||||
[field]: typeof fill[field] === 'number' ? Number(fill[field]) + 1 : 'changed',
|
||||
});
|
||||
expect(commonFinancialProjection(changed)).not.toEqual(common);
|
||||
}
|
||||
for (const field of ['feeId', 'amount'] as const) {
|
||||
const changed = structuredClone(projection);
|
||||
Object.assign(changed.projection.fills[0]!.fee, { [field]: 'changed' });
|
||||
expect(commonFinancialProjection(changed)).not.toEqual(common);
|
||||
}
|
||||
expect(() => assertResultFormat(trace, 'trace')).not.toThrow();
|
||||
expect(() => assertResultFormat(projection, 'projection')).not.toThrow();
|
||||
expect(() => assertResultFormat(trace, 'projection')).toThrow('format mismatch');
|
||||
expect(() => assertResultFormat(projection, 'trace')).toThrow('format mismatch');
|
||||
});
|
||||
|
||||
test('common projection skips matching, risk and financial replay aliases independently', () => {
|
||||
const { trace } = normalizerFixture();
|
||||
const receipt = trace.receipts.find(r =>
|
||||
r.outcome.effects.some((effect: any) =>
|
||||
effect.Risk?.outcome.financial?.effects.effects.some((e: any) => e.kind === 'fillApplied')
|
||||
)
|
||||
)!;
|
||||
expect(receipt).toBeDefined();
|
||||
for (const level of ['matching', 'risk', 'financial']) {
|
||||
const alias = structuredClone(receipt);
|
||||
const risk: any = alias.outcome.effects.find((effect: any) =>
|
||||
effect.Risk?.outcome.financial?.effects.effects.some((e: any) => e.kind === 'fillApplied')
|
||||
)!.Risk;
|
||||
if (level === 'matching') {
|
||||
alias.outcome.replayed = true;
|
||||
} else if (level === 'risk') {
|
||||
risk.outcome.replayed = true;
|
||||
} else {
|
||||
risk.outcome.financial.replayed = true;
|
||||
}
|
||||
expect(commonFinancialProjection({ ...trace, receipts: [receipt, alias] }).fills).toHaveLength(
|
||||
1
|
||||
);
|
||||
expect(commonFinancialProjection({ ...trace, receipts: [alias] }).fills).toHaveLength(0);
|
||||
}
|
||||
});
|
||||
|
||||
test('common projection handles 100k multi-owner turnover without argument spreading', () => {
|
||||
const { projection } = normalizerFixture();
|
||||
projection.projection.fills = Array.from(
|
||||
{ length: 200000 },
|
||||
() => projection.projection.fills[0]!
|
||||
);
|
||||
const common = commonFinancialProjection(projection);
|
||||
expect(common.fills).toHaveLength(200000);
|
||||
expect(common.fills.at(-1)).toEqual(common.fills[0]!);
|
||||
});
|
||||
|
||||
test('common projection rejects missing, duplicate or mismatched financial fee pairs', () => {
|
||||
const { trace } = normalizerFixture();
|
||||
for (const change of ['missing', 'extra', 'owner', 'fill', 'rejection']) {
|
||||
const invalid = structuredClone(trace);
|
||||
const risk: any = invalid.receipts
|
||||
.flatMap(r => r.outcome.effects)
|
||||
.map(effect => effect.Risk)
|
||||
.find((r: any) =>
|
||||
r?.outcome.financial?.effects.effects.some((e: any) => e.kind === 'fillApplied')
|
||||
);
|
||||
const effects = risk.outcome.financial.effects.effects;
|
||||
const fee = effects.find((e: any) => e.kind === 'feeApplied');
|
||||
if (change === 'missing') {
|
||||
effects.splice(effects.indexOf(fee), 1);
|
||||
} else if (change === 'extra') {
|
||||
effects.push(structuredClone(fee));
|
||||
} else if (change === 'owner') {
|
||||
fee.ownerId = 'other';
|
||||
} else if (change === 'fill') {
|
||||
fee.fillId = 'other';
|
||||
} else {
|
||||
risk.outcome.disposition = { Rejected: 'fixture' };
|
||||
}
|
||||
expect(() => commonFinancialProjection(invalid)).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
test('paired comparison requires shared economics and provenance while retaining distinct full hashes', () => {
|
||||
const trace = {
|
||||
datasetHash: 'dataset',
|
||||
policyHash: 'policy',
|
||||
nativeSha256: 'native',
|
||||
profile: 'sparse' as const,
|
||||
resultFormat: 'trace' as const,
|
||||
strategyHash: 'strategy',
|
||||
trials: [{ resultHash: 'full-trace', commonFinancialHash: 'common' }],
|
||||
};
|
||||
const projection = {
|
||||
...trace,
|
||||
resultFormat: 'projection' as const,
|
||||
trials: [{ resultHash: 'compact-projection', commonFinancialHash: 'common' }],
|
||||
};
|
||||
expect(verifyProjectionParity([trace], [projection])).toBe('common');
|
||||
for (const changed of [
|
||||
{ ...projection, datasetHash: 'changed' },
|
||||
{ ...projection, policyHash: 'changed' },
|
||||
{ ...projection, nativeSha256: 'changed' },
|
||||
{ ...projection, strategyHash: 'changed' },
|
||||
{ ...projection, profile: 'none' as const },
|
||||
{ ...projection, resultFormat: 'trace' as const },
|
||||
{
|
||||
...projection,
|
||||
trials: [{ resultHash: 'compact-projection', commonFinancialHash: 'changed' }],
|
||||
},
|
||||
]) {
|
||||
expect(() => verifyProjectionParity([trace], [changed])).toThrow('mismatch');
|
||||
}
|
||||
});
|
||||
|
||||
test('all tiny replay profiles pin financial expectations and distinct strategy identities', async () => {
|
||||
const worker = Bun.spawn(
|
||||
[
|
||||
process.execPath,
|
||||
'scripts/benchmark-research.ts',
|
||||
'--session',
|
||||
'--profile=all',
|
||||
'--format=both',
|
||||
],
|
||||
{
|
||||
cwd: new URL('../..', import.meta.url).pathname,
|
||||
stdout: 'pipe',
|
||||
stderr: 'pipe',
|
||||
}
|
||||
);
|
||||
const [stdout, stderr, exit] = await Promise.all([
|
||||
new Response(worker.stdout).text(),
|
||||
new Response(worker.stderr).text(),
|
||||
worker.exited,
|
||||
]);
|
||||
expect(exit, stderr).toBe(0);
|
||||
const report = JSON.parse(stdout);
|
||||
expect(report.measurements).toHaveLength(12);
|
||||
expect(report.comparisons).toHaveLength(6);
|
||||
for (const comparison of report.comparisons) {
|
||||
expect(comparison.commonFinancialHash).toMatch(/^[a-f0-9]{64}$/);
|
||||
expect(comparison.projection.resultBytes).toBeLessThan(comparison.trace.resultBytes);
|
||||
}
|
||||
expect(new Set(report.measurements.map((m: any) => m.samples[0].strategyHash)).size).toBe(3);
|
||||
for (const measurement of report.measurements) {
|
||||
verifySessionRepeats(measurement.samples, report.native.sha256);
|
||||
const workload = measurement.workload;
|
||||
const expected = profileOracle(
|
||||
workload.profile,
|
||||
workload.totalBars / workload.assets,
|
||||
workload.assets,
|
||||
workload.owners
|
||||
);
|
||||
for (const sample of measurement.samples) {
|
||||
expect(sample.profile).toBe(workload.profile);
|
||||
expect(sample.resultFormat).toBe(workload.resultFormat);
|
||||
for (const trial of sample.trials) {
|
||||
expect(trial.economic).toEqual({ ...expected, fees: expected.fills });
|
||||
for (const value of Object.values(trial.timingsMs) as number[]) {
|
||||
expect(Number.isFinite(value)).toBe(true);
|
||||
expect(value).toBeGreaterThanOrEqual(0);
|
||||
}
|
||||
expect(trial.timingsMs.finalize).toBeGreaterThanOrEqual(
|
||||
trial.timingsMs.finalizeNative +
|
||||
trial.timingsMs.finalizeDecode +
|
||||
trial.timingsMs.finalizeValidation
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('canonical self-test measures real sessions and verifies repeated full-result hashes', async () => {
|
||||
|
|
|
|||
|
|
@ -72,6 +72,7 @@ describe('generated native bindings', () => {
|
|||
expect(binding.TechnicalIndicators).toBe(TechnicalIndicators);
|
||||
expect(binding.IncrementalSMA).toBe(IncrementalSMA);
|
||||
expect(binding.FinancialReplaySession).toBe(FinancialReplaySession);
|
||||
expect(typeof FinancialReplaySession.prototype.project).toBe('function');
|
||||
});
|
||||
|
||||
it('MACD keeps full-length EMA series aligned without out-of-bounds access', () => {
|
||||
|
|
|
|||
11
test/fixtures/native-replay-worker.ts
vendored
11
test/fixtures/native-replay-worker.ts
vendored
|
|
@ -7,9 +7,16 @@ function send(message: unknown): Promise<void> {
|
|||
);
|
||||
}
|
||||
process.once('message', async (input: unknown) => {
|
||||
const request = replayTraceSchema.parse(input),
|
||||
{ result } = executeReplayTrace(request);
|
||||
const request = replayTraceSchema.parse(input);
|
||||
const mode = request.config.matching.risk.ledger.accountId;
|
||||
const { result } = executeReplayTrace(
|
||||
mode === 'wrong-format'
|
||||
? {
|
||||
...request,
|
||||
resultFormat: request.resultFormat === 'projection' ? 'trace' : 'projection',
|
||||
}
|
||||
: request
|
||||
);
|
||||
await send({ type: 'progress', progress: 0, message: 'Fixture ready' });
|
||||
switch (mode) {
|
||||
case 'wrong-version':
|
||||
|
|
|
|||
265
test/integration/native-replay-projection.test.ts
Normal file
265
test/integration/native-replay-projection.test.ts
Normal file
|
|
@ -0,0 +1,265 @@
|
|||
import type { ChildProcess } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { FinancialReplaySession } from '@stock-bot/engine';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import {
|
||||
executeReplayTrace,
|
||||
NativeReplaySession,
|
||||
prepareReplayLoad,
|
||||
runReplayConformance,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker';
|
||||
import {
|
||||
parseReplayProjectionResult,
|
||||
parseReplayResult,
|
||||
replayConfigSchema,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
const intent = (quantity = '2') => ({
|
||||
mode: 'target' as const,
|
||||
targets: [{ instrumentId: 'X0.US', quantity: parseFinancialDecimal(quantity) }],
|
||||
});
|
||||
const hold = () => ({ mode: 'target' as const, targets: [] });
|
||||
function request() {
|
||||
const f = nativeReplayFixture();
|
||||
return {
|
||||
type: 'runReplayTrace' as const,
|
||||
version: 1 as const,
|
||||
dataset: f.dataset,
|
||||
config: replayConfigSchema.parse(f.config),
|
||||
eventBudget: 1,
|
||||
trace: [
|
||||
{ at: f.start + f.minute, ownerId: 'A', intent: intent() },
|
||||
{ at: f.start + 2 * f.minute, ownerId: 'A', intent: hold() },
|
||||
],
|
||||
};
|
||||
}
|
||||
describe('compact canonical replay projection', () => {
|
||||
test('compact_full_financial_parity and unchanged diagnostic hash', () => {
|
||||
const input = request(),
|
||||
trace = executeReplayTrace(input),
|
||||
compact = executeReplayTrace({ ...input, resultFormat: 'projection' });
|
||||
// Captured from committed F07 before implementing this projection.
|
||||
expect(createHash('sha256').update(JSON.stringify(trace.result)).digest('hex')).toBe(
|
||||
'bb46165ddfe2de122689bdc47d5b1cc4065d55fdfc58a991cb3a61a91f4ad880'
|
||||
);
|
||||
expect(compact.result.view).toEqual(trace.result.view);
|
||||
expect(compact.result.policy).toEqual(trace.result.policy);
|
||||
expect(compact.result.manifest).toEqual(trace.result.manifest);
|
||||
expect(compact.result.limitations).toEqual(trace.result.limitations);
|
||||
expect(compact.result.modelLimitations).toEqual(trace.result.modelLimitations);
|
||||
expect(compact.result).not.toHaveProperty('receipts');
|
||||
expect<string>(compact.result.projection.valuation.cash).toBe('9975.76000000');
|
||||
expect<string>(compact.result.projection.valuation.equity).toBe('10005.76000000');
|
||||
expect<string>(compact.result.projection.valuation.fees).toBe('0.24000000');
|
||||
expect(compact.result.projection.fills).toHaveLength(1);
|
||||
const fill = compact.result.projection.fills[0]!;
|
||||
expect<string>(fill.cashDelta).toBe('-24.00000000');
|
||||
expect<string>(fill.fee.amount).toBe('0.24000000');
|
||||
expect<string>(fill.releasedBasis).toBe('0.00000000');
|
||||
expect(fill.ownerId).toBe('A');
|
||||
expect(fill.decision.ownerId).toBe('A');
|
||||
const fullEffects = trace.result.receipts
|
||||
.flatMap(r => (r.outcome.replayed ? [] : r.outcome.effects))
|
||||
.flatMap((effect: any) =>
|
||||
effect.Risk?.outcome.replayed || effect.Risk?.outcome.financial?.replayed
|
||||
? []
|
||||
: (effect.Risk?.outcome.financial?.effects.effects ?? [])
|
||||
);
|
||||
const applied = fullEffects.filter((e: any) => e.kind === 'fillApplied');
|
||||
const fee = fullEffects.filter((e: any) => e.kind === 'feeApplied');
|
||||
expect(applied).toHaveLength(1);
|
||||
expect(fee).toHaveLength(1);
|
||||
for (const key of [
|
||||
'ownerId',
|
||||
'orderId',
|
||||
'fillId',
|
||||
'instrumentId',
|
||||
'price',
|
||||
'cashDelta',
|
||||
'quantityDelta',
|
||||
'releasedBasis',
|
||||
'realizedGrossPnl',
|
||||
] as const) {
|
||||
expect(fill[key]).toEqual(applied[0][key]);
|
||||
}
|
||||
expect(fill.fee.amount).toEqual(fee[0].amount);
|
||||
expect(fill.fee.feeId).toEqual(fee[0].feeId);
|
||||
expect(compact.metrics.resultBytes).toBeLessThan(trace.metrics.resultBytes);
|
||||
for (const metrics of [compact.metrics, trace.metrics]) {
|
||||
for (const value of [
|
||||
metrics.finalizeNativeMs,
|
||||
metrics.finalizeDecodeMs,
|
||||
metrics.finalizeValidationMs,
|
||||
metrics.disposeMs,
|
||||
]) {
|
||||
expect(Number.isFinite(value)).toBe(true);
|
||||
expect(value).toBeGreaterThanOrEqual(0);
|
||||
}
|
||||
}
|
||||
expect(JSON.stringify(compact.result)).not.toContain('finalizeNativeMs');
|
||||
});
|
||||
test('two owners share one financial projection and reverse callbacks preserve it', () => {
|
||||
const f = nativeReplayFixture(3, 1, ['B', 'A']);
|
||||
const run = (reverseCallbacks: boolean) =>
|
||||
runReplayConformance(
|
||||
new NativeReplaySession(prepareReplayLoad(f.dataset, f.config)),
|
||||
(_owner, c) => (c.barrier.at === f.start + f.minute ? intent('1') : hold()),
|
||||
{ resultFormat: 'projection', reverseCallbacks }
|
||||
).result;
|
||||
const output = run(false);
|
||||
expect(run(true)).toEqual(output);
|
||||
expect(output.projection.fills.map(f => f.ownerId)).toEqual(['A', 'B']);
|
||||
expect<string>(output.projection.valuation.fees).toBe('0.24000000');
|
||||
expect<string>(output.projection.valuation.equity).toBe('10005.76000000');
|
||||
});
|
||||
test('projection_is_read_only preserves native diagnostic bytes across repeated projections', () => {
|
||||
const f = nativeReplayFixture(),
|
||||
load = prepareReplayLoad(f.dataset, f.config);
|
||||
const native = new FinancialReplaySession(JSON.stringify(load)),
|
||||
identity = JSON.stringify(load.identity);
|
||||
let sequence = 0;
|
||||
try {
|
||||
for (;;) {
|
||||
const response = JSON.parse(
|
||||
native.advance(JSON.stringify({ identity: load.identity, eventBudget: 100 }))
|
||||
);
|
||||
if (response.step.type === 'complete') {
|
||||
break;
|
||||
}
|
||||
if (response.step.type === 'failed') {
|
||||
throw new Error(response.step.diagnostic);
|
||||
}
|
||||
if (response.step.type === 'decisionBatch') {
|
||||
const barrier = response.step.barrier;
|
||||
native.submit(
|
||||
JSON.stringify({
|
||||
identity: load.identity,
|
||||
barrierId: barrier.barrier_id,
|
||||
decisions: [
|
||||
{
|
||||
version: 1,
|
||||
sessionId: load.identity.sessionId,
|
||||
barrierId: barrier.barrier_id,
|
||||
revision: barrier.revision,
|
||||
decision: {
|
||||
ownerId: 'A',
|
||||
decisionId: `native-${sequence}`,
|
||||
sequence: sequence++,
|
||||
},
|
||||
intent: barrier.at === f.start + f.minute ? intent() : hold(),
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
const before = native.finalize(identity),
|
||||
first = native.project(identity);
|
||||
expect(native.project(identity)).toBe(first);
|
||||
expect(native.finalize(identity)).toBe(before);
|
||||
expect(JSON.parse(first).view).toEqual(JSON.parse(before).view);
|
||||
expect(JSON.parse(first).projection.fills).toHaveLength(1);
|
||||
} finally {
|
||||
native.dispose();
|
||||
}
|
||||
});
|
||||
test('projection_terminal_guard covers incomplete, failed, disposed and wrong identity', () => {
|
||||
const f = nativeReplayFixture(),
|
||||
load = prepareReplayLoad(f.dataset, f.config);
|
||||
load.prepared.bars[0]!.high = '792281625142643375935.43950335';
|
||||
load.prepared.bars[0]!.close = '792281625142643375935.43950335';
|
||||
const native = new FinancialReplaySession(JSON.stringify(load)),
|
||||
identity = JSON.stringify(load.identity);
|
||||
expect(() => native.project(identity)).toThrow('complete');
|
||||
expect(() => native.project(JSON.stringify({ ...load.identity, version: 2 }))).toThrow();
|
||||
expect(() => native.project(JSON.stringify({ ...load.identity, sessionId: 'wrong' }))).toThrow(
|
||||
'identity'
|
||||
);
|
||||
const step = JSON.parse(
|
||||
native.advance(JSON.stringify({ identity: load.identity, eventBudget: 100 }))
|
||||
);
|
||||
const submission = JSON.parse(
|
||||
native.submit(
|
||||
JSON.stringify({
|
||||
identity: load.identity,
|
||||
barrierId: step.step.barrier.barrier_id,
|
||||
decisions: [
|
||||
{
|
||||
version: 1,
|
||||
sessionId: load.identity.sessionId,
|
||||
barrierId: step.step.barrier.barrier_id,
|
||||
revision: step.step.barrier.revision,
|
||||
decision: { ownerId: 'A', decisionId: 'overflow', sequence: 0 },
|
||||
intent: intent(),
|
||||
},
|
||||
],
|
||||
})
|
||||
)
|
||||
);
|
||||
expect(submission.outcome.status).toHaveProperty('Failed');
|
||||
expect(() => native.project(identity)).toThrow('complete');
|
||||
native.dispose();
|
||||
expect(() => native.project(identity)).toThrow('disposed');
|
||||
});
|
||||
test('projection_identity_policy_format rejects incompatible and inconsistent payloads', () => {
|
||||
const input = request(),
|
||||
trace = executeReplayTrace(input).result,
|
||||
output = executeReplayTrace({ ...input, resultFormat: 'projection' }).result;
|
||||
expect(() => parseReplayProjectionResult(JSON.stringify(trace), output.identity)).toThrow();
|
||||
expect(() => parseReplayResult(JSON.stringify(output), output.identity)).toThrow();
|
||||
for (const mutate of [
|
||||
(r: any) => (r.projectionVersion = 2),
|
||||
(r: any) => (r.financialVersion = 2),
|
||||
(r: any) => (r.receipts = []),
|
||||
(r: any) => (r.projection.valuation.cash = '1'),
|
||||
(r: any) => (r.projection.valuation.equity = '1'),
|
||||
(r: any) => (r.projection.fills[0].ownerId = 'B'),
|
||||
(r: any) => (r.projection.fills[0].fee.amount = '-1'),
|
||||
(r: any) => (r.policy.matching.risk.feeRate = '0.5'),
|
||||
]) {
|
||||
const bad = structuredClone(output);
|
||||
mutate(bad);
|
||||
expect(() =>
|
||||
parseReplayProjectionResult(JSON.stringify(bad), output.identity, input.config)
|
||||
).toThrow();
|
||||
}
|
||||
});
|
||||
test('worker captures projection format and preserves post-result cancellation', async () => {
|
||||
const input = { ...request(), resultFormat: 'projection' as const },
|
||||
worker = new NativeBacktestWorker();
|
||||
const expected = executeReplayTrace(input).result;
|
||||
const mutable: { resultFormat: 'projection' | 'trace' } & typeof input = { ...input };
|
||||
const raw = await worker.execute(mutable, new AbortController().signal, () => {
|
||||
(mutable as { resultFormat: string }).resultFormat = 'trace';
|
||||
});
|
||||
expect(parseReplayProjectionResult(raw, expected.identity, input.config)).toEqual(expected);
|
||||
const fixture = new NativeBacktestWorker(
|
||||
new URL('../fixtures/native-replay-worker.ts', import.meta.url)
|
||||
);
|
||||
for (const resultFormat of ['projection', 'trace'] as const) {
|
||||
const bad = { ...request(), resultFormat };
|
||||
bad.config.matching.risk.ledger.accountId = 'wrong-format';
|
||||
await expect(fixture.execute(bad, new AbortController().signal, () => {})).rejects.toThrow();
|
||||
}
|
||||
const blocked = { ...request(), resultFormat: 'projection' as const };
|
||||
blocked.config.matching.risk.ledger.accountId = 'result-then-block';
|
||||
const cancel = new AbortController();
|
||||
let observed = false;
|
||||
const running = fixture.execute(blocked, cancel.signal, () => {});
|
||||
const child = (fixture as unknown as { active: ChildProcess }).active;
|
||||
child.on('message', (message: any) => {
|
||||
if (message.type === 'result') {
|
||||
observed = true;
|
||||
cancel.abort(new Error('compact result cancelled'));
|
||||
}
|
||||
});
|
||||
await expect(running).rejects.toThrow('compact result cancelled');
|
||||
expect(observed).toBe(true);
|
||||
expect(
|
||||
JSON.parse(await fixture.execute(input, new AbortController().signal, () => {})).format
|
||||
).toBe('projection');
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue