refactor(engine): share strict native financial views (CL18)

This commit is contained in:
Boki 2026-10-26 20:30:01 -04:00
parent 580a6de75c
commit 03518c8ae4
9 changed files with 252 additions and 99 deletions

View file

@ -0,0 +1,63 @@
//! Shared wire checks and financial projections for the trusted native hosts.
//! Host identities, envelopes and transaction boundaries remain in each adapter.
use crate::financial::{
contract::{Counter, Id},
matching::{ManagedOrder, OrderStatus},
risk::RiskAccount,
};
use napi::{Error, Result};
use serde::{de::DeserializeOwned, Serialize};
use serde_json::{json, Value};
fn error(error: impl std::fmt::Display) -> Error {
Error::from_reason(error.to_string())
}
// Some internal replay types accept unknown fields, and serde defaults missing
// Option fields to None. Comparing recursive keys keeps explicit nulls required
// at the wire boundary without changing those internal financial types.
fn keys_match(input: &Value, typed: &Value) -> bool {
match (input, typed) {
(Value::Object(a), Value::Object(b)) => {
a.len() == b.len()
&& a.iter()
.all(|(k, v)| b.get(k).is_some_and(|other| keys_match(v, other)))
}
(Value::Array(a), Value::Array(b)) => {
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| keys_match(a, b))
}
_ => true,
}
}
pub(super) fn parse<T: DeserializeOwned + Serialize>(
input: &str,
field_error: &'static str,
) -> Result<T> {
let raw: Value = serde_json::from_str(input).map_err(error)?;
let typed: T = serde_json::from_str(input).map_err(error)?;
if !keys_match(&raw, &serde_json::to_value(&typed).map_err(error)?) {
return Err(error(field_error));
}
Ok(typed)
}
// Revision is explicit: paper journals project intermediate effects at the
// pre-transaction admission revision; final/replay views use the current one.
// A lookup supports both the live matching account and paper reconstruction
// without cloning an account or changing reservation-derived order ordering.
pub(super) fn financial_view<'a>(
risk: &RiskAccount,
revision: Counter,
order: impl Fn(&Id) -> Option<&'a ManagedOrder>,
) -> Result<Value> {
Ok(json!({
"admissionRevision": revision,
"portfolio": risk.ledger().economic_snapshot(),
"equity": risk.ledger().equity().map_err(error)?,
"availableCash": risk.available_cash(),
"orders": risk.reservations().filter_map(|r| order(&r.order.order_id)).filter(|o| o.status == OrderStatus::Open).collect::<Vec<_>>(),
"reservations": risk.reservations().collect::<Vec<_>>(),
"risk": risk.state(),
}))
}

View file

@ -1,4 +1,5 @@
mod backtest;
mod canonical;
mod indicators;
mod replay;
mod paper;

View file

@ -1,11 +1,12 @@
//! Stateless trusted durable-host seam. SQL owns custody and commit/publication;
//! MatchingAccount owns all financial transitions. No process-resident mutation.
use super::canonical::{financial_view, parse};
use crate::financial::{contract::*, matching::*, risk::RiskAccount};
use napi::{Error, Result};
#[cfg(not(test))]
use napi_derive::napi;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use serde_json::Value;
use std::collections::BTreeMap;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@ -49,35 +50,6 @@ struct Response {
fn error(error: impl std::fmt::Display) -> Error {
Error::from_reason(error.to_string())
}
// Option fields in checkpoints are required wire fields, including explicit nulls.
fn keys_match(input: &Value, typed: &Value) -> bool {
match (input, typed) {
(Value::Object(a), Value::Object(b)) => {
a.len() == b.len()
&& a.iter()
.all(|(k, v)| b.get(k).is_some_and(|other| keys_match(v, other)))
}
(Value::Array(a), Value::Array(b)) => {
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| keys_match(a, b))
}
_ => true,
}
}
fn view(
risk: &RiskAccount,
orders: &BTreeMap<Id, ManagedOrder>,
revision: Counter,
) -> Result<Value> {
Ok(json!({
"admissionRevision": revision,
"portfolio": risk.ledger().economic_snapshot(),
"equity": risk.ledger().equity().map_err(error)?,
"availableCash": risk.available_cash(),
"orders": risk.reservations().filter_map(|r|orders.get(&r.order.order_id)).filter(|o|o.status == OrderStatus::Open).collect::<Vec<_>>(),
"reservations": risk.reservations().collect::<Vec<_>>(),
"risk": risk.state(),
}))
}
fn order_map(orders: impl IntoIterator<Item = ManagedOrder>) -> BTreeMap<Id, ManagedOrder> {
orders
.into_iter()
@ -141,7 +113,7 @@ fn stage(request: Request) -> Result<Response> {
journal.push(JournalEntry {
index: (index as u64).try_into().map_err(error)?,
effect: effect.clone(),
view_after: view(&risk, &orders, before.revision)?,
view_after: financial_view(&risk, before.revision, |id| orders.get(id))?,
});
}
if risk.checkpoint() != checkpoint.risk
@ -151,11 +123,7 @@ fn stage(request: Request) -> Result<Response> {
}
}
}
let final_view = view(
account.risk(),
&order_map(checkpoint.orders.clone()),
checkpoint.revision,
)?;
let final_view = financial_view(account.risk(), checkpoint.revision, |id| account.order(id))?;
Ok(Response {
version: Version,
identity,
@ -171,11 +139,7 @@ fn stage(request: Request) -> Result<Response> {
/// Replayed outcomes retain the original receipt but always emit an empty journal.
#[cfg_attr(not(test), napi)]
pub fn stage_financial_transaction(input: String) -> Result<String> {
let raw: Value = serde_json::from_str(&input).map_err(error)?;
let request: Request = serde_json::from_str(&input).map_err(error)?;
if !keys_match(&raw, &serde_json::to_value(&request).map_err(error)?) {
return Err(error("unexpected or missing financial transaction fields"));
}
let request: Request = parse(&input, "unexpected or missing financial transaction fields")?;
serde_json::to_string(&stage(request)?).map_err(error)
}

View file

@ -1,5 +1,6 @@
use super::*;
use crate::financial::scalar::MAX_POSTING;
use serde_json::json;
fn config() -> Value {
json!({
@ -62,10 +63,10 @@ impl Harness {
assert_eq!(result.checkpoint, self.direct.checkpoint());
assert_eq!(
result.view,
view(
financial_view(
self.direct.risk(),
&order_map(self.direct.orders().cloned()),
self.direct.admission_revision()
self.direct.admission_revision(),
|id| self.direct.order(id),
)
.unwrap()
);

View file

@ -1,9 +1,9 @@
//! 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 super::canonical::{financial_view, parse as parse_contract};
use crate::financial::{
contract::*,
matching::OrderStatus,
replay::*,
reporting::ReportingFacts,
result::{project, FinancialProjection},
@ -73,28 +73,8 @@ struct ReportResult<'a> {
fn error(error: impl std::fmt::Display) -> Error {
Error::from_reason(error.to_string())
}
// Internal replay types intentionally were not wire contracts. Reject unknown
// keys recursively at this adapter without changing their financial semantics.
fn keys_match(input: &Value, typed: &Value) -> bool {
match (input, typed) {
(Value::Object(a), Value::Object(b)) => {
a.len() == b.len()
&& a.iter()
.all(|(k, v)| b.get(k).is_some_and(|other| keys_match(v, other)))
}
(Value::Array(a), Value::Array(b)) => {
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| keys_match(a, b))
}
_ => true,
}
}
fn parse<T: DeserializeOwned + Serialize>(input: &str) -> Result<T> {
let raw: Value = serde_json::from_str(input).map_err(error)?;
let typed: T = serde_json::from_str(input).map_err(error)?;
if !keys_match(&raw, &serde_json::to_value(&typed).map_err(error)?) {
return Err(error("unexpected or missing session contract fields"));
}
Ok(typed)
parse_contract(input, "unexpected or missing session contract fields")
}
pub struct ReplayHost {
@ -296,20 +276,45 @@ impl ReplayHost {
fn view(replay: &Replay) -> Result<Value> {
let matching = replay.financial();
Ok(json!({
"admissionRevision":matching.admission_revision(),
"portfolio":matching.ledger().economic_snapshot(),
"equity":matching.ledger().equity().map_err(error)?,
"availableCash":matching.risk().available_cash(),
"orders":matching.risk().reservations().filter_map(|reservation| matching.order(&reservation.order.order_id)).filter(|order| order.status == OrderStatus::Open).collect::<Vec<_>>(),
"reservations":matching.risk().reservations().collect::<Vec<_>>(),
"risk":matching.risk().state()
}))
financial_view(matching.risk(), matching.admission_revision(), |id| {
matching.order(id)
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::financial::native_paper_tests::stage_financial_transaction;
// Drive the paper host from the same financial commands as replay. Compare
// every published boundary, including open reservations, fills and finish.
fn assert_paper_view(replay: &Replay, identity: &Value, paper: &mut Value) {
let delivered = paper["checkpoint"]["receipts"].as_array().unwrap().len();
for receipt in &replay.financial().receipts()[delivered..] {
let crate::financial::matching::MatchingInput::Engine(command) = &receipt.input else {
panic!("fixture unexpectedly contains an operator command");
};
*paper = serde_json::from_str(
&stage_financial_transaction(
json!({
"version": 1,
"kind": "apply",
"identity": identity,
"checkpoint": paper["checkpoint"],
"command": command,
})
.to_string(),
)
.unwrap(),
)
.unwrap();
}
assert_eq!(paper["view"], view(replay).unwrap());
assert_eq!(
paper["checkpoint"],
serde_json::to_value(replay.financial().checkpoint()).unwrap()
);
}
#[test]
fn native_intent_trace_matches_direct_replay_receipts() {
@ -317,11 +322,29 @@ mod tests {
// load; compare the NAPI pull transport with direct authoritative replay.
let fixture = include_str!("../../../../../test/fixtures/native-replay-load.json");
let load: Load = parse(fixture).unwrap();
let paper_identity = json!({
"sessionId": load.identity.session_id,
"accountId": load.config.matching.risk.ledger.account_id,
});
let mut paper: Value = serde_json::from_str(
&stage_financial_transaction(
json!({
"version": 1,
"kind": "initialize",
"identity": paper_identity,
"config": load.config.matching,
})
.to_string(),
)
.unwrap(),
)
.unwrap();
let mut direct = Replay::new(load.prepared, load.config).unwrap();
let mut native = ReplayHost::new(fixture.into()).unwrap();
let identity = serde_json::to_value(&load.identity).unwrap();
let mut sequence = 0;
loop {
assert_paper_view(native.replay.as_ref().unwrap(), &paper_identity, &mut paper);
let raw = native
.advance(json!({"identity":identity,"eventBudget":1}).to_string())
.unwrap();
@ -355,6 +378,7 @@ mod tests {
ReplayStep::Failed { diagnostic } => panic!("{diagnostic}"),
}
}
assert_paper_view(native.replay.as_ref().unwrap(), &paper_identity, &mut paper);
let final_result: Value =
serde_json::from_str(&native.finalize(identity.to_string()).unwrap()).unwrap();
assert_eq!(

View file

@ -42,7 +42,10 @@ mod result_tests;
#[cfg(test)]
mod reporting_tests;
// Exercise the pure host adapter without linking every legacy NAPI export.
// Exercise the pure host adapters and shared helpers without linking every legacy NAPI export.
#[cfg(test)]
#[path = "../api/canonical.rs"]
mod canonical;
#[cfg(test)]
#[path = "../api/replay.rs"]
mod native_replay_tests;

View file

@ -1,8 +1,8 @@
{
"schema_version": 1,
"plan_revision": "2026-10-26.81",
"plan_revision": "2026-10-26.82",
"repository_base": "b7aeca4",
"plan_status": "orchestrator_engine_cleanup_first_wave_complete",
"plan_status": "orchestrator_engine_cleanup_remaining_wave",
"execution_authorized": true,
"execution_scope": {
"authorized_by": "Owner: commit and continue with the rest of the tasks till 100%",
@ -2854,7 +2854,7 @@
"epic": "E11",
"priority": "P2",
"severity": "Medium",
"status": "ready",
"status": "in_progress",
"dependencies": [
"CL14"
],
@ -2875,13 +2875,13 @@
"apps/stock/web-api/src/services/stored-dataset-preparation.ts",
"test/integration/intraday-storage.test.ts"
],
"assignment": null,
"branch": null,
"assignment": "/root/implement_cl17",
"branch": "cleanup/cl17-historical-reader",
"completed_commit": null,
"blocker": null,
"release_gates": [],
"integration_state": "not_started",
"integration_base": "700ee09c",
"integration_state": "implementing",
"integration_base": "580a6de7",
"completion_evidence": "orchestrator-engine-cleanup.md"
},
{
@ -2890,7 +2890,7 @@
"epic": "E11",
"priority": "P2",
"severity": "Medium",
"status": "ready",
"status": "done",
"dependencies": [
"CL15"
],
@ -2912,14 +2912,20 @@
"apps/stock/engine/src/financial/mod.rs",
"scripts/test/native-bindings.test.ts"
],
"assignment": null,
"branch": null,
"assignment": "/root/implement_cl18",
"branch": "cleanup/cl18-native-helpers",
"completed_commit": null,
"blocker": null,
"release_gates": [],
"integration_state": "not_started",
"integration_base": "700ee09c",
"completion_evidence": "orchestrator-engine-cleanup.md"
"integration_state": "validated_pending_commit",
"integration_base": "580a6de7",
"completion_evidence": "orchestrator-engine-cleanup.md",
"reviewer": "/root/review_cl18",
"validation": {
"rust": "150 passed, 4 existing ignored",
"native": "28 passed, 227 assertions; rebuilt integrated addon",
"review": "Accepted by /root/review_cl18; root integration checks passed"
}
},
{
"id": "CL19",
@ -2927,7 +2933,7 @@
"epic": "E11",
"priority": "P2",
"severity": "Medium",
"status": "ready",
"status": "in_progress",
"dependencies": [],
"decision_dependencies": [],
"task_file": "backlog/tasks/CL19.md",
@ -2949,13 +2955,13 @@
"apps/stock/orchestrator/src/execution/strategy-recovery.ts",
"apps/stock/orchestrator/src/paper/feed.ts"
],
"assignment": null,
"branch": null,
"assignment": "/root/implement_cl19",
"branch": "cleanup/cl19-strategy-bookkeeping",
"completed_commit": null,
"blocker": null,
"release_gates": [],
"integration_state": "not_started",
"integration_base": "700ee09c",
"integration_state": "implementing",
"integration_base": "580a6de7",
"completion_evidence": "orchestrator-engine-cleanup.md"
},
{
@ -2964,7 +2970,7 @@
"epic": "E11",
"priority": "P2",
"severity": "Medium",
"status": "ready",
"status": "in_progress",
"dependencies": [
"CL14"
],
@ -2986,13 +2992,13 @@
"apps/stock/orchestrator/src/backtest/native-worker-protocol.ts",
"test/integration/retained-strategy-worker.test.ts"
],
"assignment": null,
"branch": null,
"assignment": "/root/implement_cl20",
"branch": "cleanup/cl20-typed-worker",
"completed_commit": null,
"blocker": null,
"release_gates": [],
"integration_state": "not_started",
"integration_base": "700ee09c",
"integration_state": "implementing",
"integration_base": "580a6de7",
"completion_evidence": "orchestrator-engine-cleanup.md"
},
{

View file

@ -50,3 +50,10 @@ Combined `CARGO_BUILD_JOBS=2 bun run check` passed on CL14+CL15+CL16: 132 toolin
CL14 implementation commit: `21666242`. First wave completes CL14, CL15 and CL16; CL17–CL20 are the next ready tasks and CL21 remains conditional. Prior 68 task records retain their pre-wave state.
CL16 implementation commit: `8546fce4`. Disposable test containers were stopped/removed after validation. Main checkout is the integrated source; isolated worktrees and logs are retained for inspection.
### CL18 — accepted
Replay and paper hosts now share private strict parsing and financial-view helpers. Host identities/errors stay separate; required nullable fields, reservation ordering, and paper intermediate versus final admission revisions are preserved. No financial kernel, wire version or economic policy changed.
Implemented by `/root/implement_cl18`, independently accepted by `/root/review_cl18`, integrated by `/root`. Local and root Rust gates: 150 passed, 4 existing ignored. Root rebuilt the integrated addon and ran native-bindings/native-replay/native-replay-report: 28 passed, 227 assertions. Added replay-to-paper checkpoint/view parity at each fixture boundary and nested/missing/null negatives. Explicit authored-test types, lint, format and diff checks passed. Sandbox-blocked child-worker test was stopped; the authorized rerun passed. Logs: `/tmp/stock-bot-engine-cleanup-20261026/cl18-root-{build,tests-accepted,cargo}.log`. Combined repository gate follows integration of the remaining independent stories.

View file

@ -250,6 +250,90 @@ describe('stateless native financial transaction contract', () => {
parseFinancialTransactionResult(JSON.stringify(reordered), identity)
).not.toThrow();
});
it('rejects nested unknown, missing and null configuration fields through both native hosts', () => {
const mutations: Array<(value: any) => void> = [
value => {
value.risk.ledger.riskSession.extra = true;
},
value => {
delete value.risk.ledger.riskSession.calendarRevision;
},
value => {
value.risk.ledger.riskSession.calendarRevision = null;
},
value => {
value.owners[0].extra = true;
},
value => {
delete value.owners[0].mode;
},
value => {
value.owners[0].mode = null;
},
];
for (const mutate of mutations) {
const bad = structuredClone(config);
mutate(bad);
expect(() =>
stageFinancialTransaction(
JSON.stringify({
version: 1,
kind: 'initialize',
identity,
config: bad,
})
)
).toThrow();
expect(
() =>
new FinancialReplaySession(
JSON.stringify({
...nativeReplayLoad,
config: { ...nativeReplayLoad.config, matching: bad },
})
)
).toThrow();
}
});
it('requires explicit null checkpoint fields and rejects nested receipt additions', () => {
const { request, result } = marked();
// The untouched initialized checkpoint has a required null cursor.
expect(request.checkpoint.cursor).toBeNull();
expect(() => stageFinancialTransaction(JSON.stringify(request))).not.toThrow();
const omitted = structuredClone(request) as any;
delete omitted.checkpoint.cursor;
expect(() => stageFinancialTransaction(JSON.stringify(omitted))).toThrow(
'missing financial transaction fields'
);
const retry = { ...request, checkpoint: result.checkpoint };
expect(retry.checkpoint.receipts[0]).toMatchObject({
outcome: { effects: [{ Risk: { outcome: { remaining: null } } }] },
});
const mutations: Array<(value: any) => void> = [
value => {
value.checkpoint.receipts[0].outcome.effects[0].Risk.outcome.extra = true;
},
value => {
delete value.checkpoint.receipts[0].outcome.effects[0].Risk.outcome.remaining;
},
value => {
value.checkpoint.receipts[0].outcome.effects[0].Risk.outcome.disposition = null;
},
];
for (const mutate of mutations) {
const bad = structuredClone(retry);
mutate(bad);
expect(() => stageFinancialTransaction(JSON.stringify(bad))).toThrow();
}
const replay = parseFinancialTransactionResult(
stageFinancialTransaction(JSON.stringify(retry)),
identity
);
expect(replay.view).toEqual(result.view);
expect(replay.checkpoint).toEqual(result.checkpoint);
expect(replay.journal).toEqual([]);
});
it('validates initialized metadata and rejects operator/legacy/malformed native requests', () => {
const result = initialized();
const bad = structuredClone(result);