feat(research): add financial contracts and availability-aware datasets

Implement reviewed F01/D01 foundations without changing active trading runtimes. Validate strict Rust/TypeScript financial wire contracts, decimal postings, versioned datasets, explicit calendars, provenance, and v1 compatibility.
This commit is contained in:
Boki 2026-10-22 20:51:25 -04:00
parent 243e9ab43f
commit b4af840d4e
25 changed files with 4071 additions and 43 deletions

803
test/fixtures/economics/contracts.json vendored Normal file
View file

@ -0,0 +1,803 @@
{
"schemaVersion": 1,
"valid": [
{
"id": "fillCommand",
"owningTask": "F01",
"assumptions": "Wire-shape example only; no simulated transition or engine certification.",
"handCalculation": "Parse and serialize without changing explicit identity, decimal values, or effect order.",
"type": "command",
"input": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "command-fill-1",
"eventTime": 1704292260000,
"body": {
"kind": "applyFill",
"decision": {
"ownerId": "strategy:A",
"decisionId": "decision-1",
"sequence": 1
},
"orderId": "order-1",
"fillId": "fill-1",
"instrumentId": "A^P.US",
"side": "buy",
"quantity": "3.00000000",
"price": "2.00000000",
"fee": {
"feeId": "fee-1",
"amount": "0.06000000"
}
}
},
"canonical": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "command-fill-1",
"eventTime": 1704292260000,
"body": {
"kind": "applyFill",
"decision": {
"ownerId": "strategy:A",
"decisionId": "decision-1",
"sequence": 1
},
"orderId": "order-1",
"fillId": "fill-1",
"instrumentId": "A^P.US",
"side": "buy",
"quantity": "3.00000000",
"price": "2.00000000",
"fee": {
"feeId": "fee-1",
"amount": "0.06000000"
}
}
}
},
{
"id": "markCommand",
"owningTask": "F01",
"assumptions": "Wire-shape example only; no simulated transition or engine certification.",
"handCalculation": "Parse and serialize without changing explicit identity, decimal values, or effect order.",
"type": "command",
"input": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "command-mark-1",
"eventTime": 1704292260000,
"body": {
"kind": "mark",
"instrumentId": "A^P.US",
"price": "2.00000000"
}
},
"canonical": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "command-mark-1",
"eventTime": 1704292260000,
"body": {
"kind": "mark",
"instrumentId": "A^P.US",
"price": "2.00000000"
}
}
},
{
"id": "boundaryCommand",
"owningTask": "F01",
"assumptions": "Wire-shape example only; no simulated transition or engine certification.",
"handCalculation": "Parse and serialize without changing explicit identity, decimal values, or effect order.",
"type": "command",
"input": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "boundary-1",
"eventTime": 1704292200000,
"body": {
"kind": "riskSessionBoundary",
"riskSession": {
"calendarId": "XNYS",
"calendarRevision": "2024-a",
"sessionId": "2024-01-03",
"startsAt": 1704292200000
}
}
},
"canonical": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "boundary-1",
"eventTime": 1704292200000,
"body": {
"kind": "riskSessionBoundary",
"riskSession": {
"calendarId": "XNYS",
"calendarRevision": "2024-a",
"sessionId": "2024-01-03",
"startsAt": 1704292200000
}
}
}
},
{
"id": "targetDecision",
"owningTask": "F01",
"assumptions": "Wire-shape example only; no simulated transition or engine certification.",
"handCalculation": "Parse and serialize without changing explicit identity, decimal values, or effect order.",
"type": "decision",
"input": {
"version": 1,
"sessionId": "research:run-1",
"barrierId": "barrier-1",
"revision": 0,
"decision": {
"ownerId": "strategy:A",
"decisionId": "decision-1",
"sequence": 1
},
"intent": {
"mode": "target",
"targets": [
{
"instrumentId": "A^P.US",
"quantity": "3.00000000"
},
{
"instrumentId": "B.US",
"quantity": "0.00000000"
}
]
}
},
"canonical": {
"version": 1,
"sessionId": "research:run-1",
"barrierId": "barrier-1",
"revision": 0,
"decision": {
"ownerId": "strategy:A",
"decisionId": "decision-1",
"sequence": 1
},
"intent": {
"mode": "target",
"targets": [
{
"instrumentId": "A^P.US",
"quantity": "3.00000000"
},
{
"instrumentId": "B.US",
"quantity": "0.00000000"
}
]
}
}
},
{
"id": "orderDecision",
"owningTask": "F01",
"assumptions": "Wire-shape example only; no simulated transition or engine certification.",
"handCalculation": "Parse and serialize without changing explicit identity, decimal values, or effect order.",
"type": "decision",
"input": {
"version": 1,
"sessionId": "research:run-1",
"barrierId": "barrier-1",
"revision": 0,
"decision": {
"ownerId": "strategy:A",
"decisionId": "decision-1",
"sequence": 1
},
"intent": {
"mode": "orders",
"orders": [
{
"kind": "market",
"orderId": "order-2",
"instrumentId": "A.US",
"side": "buy",
"quantity": "1.00000000",
"timeInForce": "GTC"
},
{
"kind": "limit",
"orderId": "order-3",
"instrumentId": "B.US",
"side": "sell",
"quantity": "1.00000000",
"price": "2.00000000",
"timeInForce": "DAY"
},
{
"kind": "cancel",
"orderId": "order-4"
}
]
}
},
"canonical": {
"version": 1,
"sessionId": "research:run-1",
"barrierId": "barrier-1",
"revision": 0,
"decision": {
"ownerId": "strategy:A",
"decisionId": "decision-1",
"sequence": 1
},
"intent": {
"mode": "orders",
"orders": [
{
"kind": "market",
"orderId": "order-2",
"instrumentId": "A.US",
"side": "buy",
"quantity": "1.00000000",
"timeInForce": "GTC"
},
{
"kind": "limit",
"orderId": "order-3",
"instrumentId": "B.US",
"side": "sell",
"quantity": "1.00000000",
"price": "2.00000000",
"timeInForce": "DAY"
},
{
"kind": "cancel",
"orderId": "order-4"
}
]
}
}
},
{
"id": "snapshot",
"owningTask": "F01",
"assumptions": "Wire-shape example only; no simulated transition or engine certification.",
"handCalculation": "Assume100 initial cash;3*2=6 notional,0.06 fee; cash93.94 and remaining basis6. Ordered example includes independent mark/boundary/rejection effects to cover tags.",
"type": "snapshot",
"input": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"revision": 1,
"baseCurrency": "USD",
"reserveOwnerId": "reserve",
"cash": "93.94000000",
"positions": [
{
"ownerId": "strategy:A",
"instrumentId": "A^P.US",
"quantity": "3.00000000",
"remainingCost": "6.00000000",
"realizedGrossPnl": "0.00000000"
}
],
"fees": [
{
"ownerId": "strategy:A",
"amount": "0.06000000"
}
],
"riskSession": {
"calendarId": "XNYS",
"calendarRevision": "2024-a",
"sessionId": "2024-01-03",
"startsAt": 1704292200000
}
},
"canonical": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"revision": 1,
"baseCurrency": "USD",
"reserveOwnerId": "reserve",
"cash": "93.94000000",
"positions": [
{
"ownerId": "strategy:A",
"instrumentId": "A^P.US",
"quantity": "3.00000000",
"remainingCost": "6.00000000",
"realizedGrossPnl": "0.00000000"
}
],
"fees": [
{
"ownerId": "strategy:A",
"amount": "0.06000000"
}
],
"riskSession": {
"calendarId": "XNYS",
"calendarRevision": "2024-a",
"sessionId": "2024-01-03",
"startsAt": 1704292200000
}
}
},
{
"id": "effects",
"owningTask": "F01",
"assumptions": "Wire-shape example only; no simulated transition or engine certification.",
"handCalculation": "Assume100 initial cash;3*2=6 notional,0.06 fee; cash93.94 and remaining basis6. Ordered example includes independent mark/boundary/rejection effects to cover tags.",
"type": "effects",
"input": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "command-fill-1",
"eventTime": 1704292260000,
"revision": 1,
"effects": [
{
"kind": "fillApplied",
"ownerId": "strategy:A",
"orderId": "order-1",
"fillId": "fill-1",
"instrumentId": "A^P.US",
"price": "2.00000000",
"cashDelta": "-6.00000000",
"quantityDelta": "3.00000000",
"releasedBasis": "0.00000000",
"realizedGrossPnl": "0.00000000"
},
{
"kind": "feeApplied",
"ownerId": "strategy:A",
"fillId": "fill-1",
"feeId": "fee-1",
"amount": "0.06000000"
},
{
"kind": "markUpdated",
"instrumentId": "A^P.US",
"price": "2.00000000"
},
{
"kind": "riskSessionChanged",
"riskSession": {
"calendarId": "XNYS",
"calendarRevision": "2024-a",
"sessionId": "2024-01-03",
"startsAt": 1704292200000
}
},
{
"kind": "rejected",
"code": "insufficientCash"
}
]
},
"canonical": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "command-fill-1",
"eventTime": 1704292260000,
"revision": 1,
"effects": [
{
"kind": "fillApplied",
"ownerId": "strategy:A",
"orderId": "order-1",
"fillId": "fill-1",
"instrumentId": "A^P.US",
"price": "2.00000000",
"cashDelta": "-6.00000000",
"quantityDelta": "3.00000000",
"releasedBasis": "0.00000000",
"realizedGrossPnl": "0.00000000"
},
{
"kind": "feeApplied",
"ownerId": "strategy:A",
"fillId": "fill-1",
"feeId": "fee-1",
"amount": "0.06000000"
},
{
"kind": "markUpdated",
"instrumentId": "A^P.US",
"price": "2.00000000"
},
{
"kind": "riskSessionChanged",
"riskSession": {
"calendarId": "XNYS",
"calendarRevision": "2024-a",
"sessionId": "2024-01-03",
"startsAt": 1704292200000
}
},
{
"kind": "rejected",
"code": "insufficientCash"
}
]
}
},
{
"id": "unicodeIdentity",
"owningTask": "F01",
"assumptions": "Identity text is preserved; instrument is a supported synthetic listing. No actual index execution implied.",
"handCalculation": "Parse and serialize without changing explicit identity, decimal values, or effect order.",
"type": "command",
"input": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "命令:α",
"eventTime": 1704292260000,
"body": {
"kind": "mark",
"instrumentId": "A^P.US",
"price": "2.00000000"
}
},
"canonical": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "命令:α",
"eventTime": 1704292260000,
"body": {
"kind": "mark",
"instrumentId": "A^P.US",
"price": "2.00000000"
}
}
}
],
"invalid": [
{
"id": "unknown_version",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["version"],
"value": 2
},
{
"id": "unknown_outer_key",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["unexpected"],
"value": true
},
{
"id": "unknown_body_key",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["body", "unexpected"],
"value": true
},
{
"id": "unknown_nested_key",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["body", "fee", "unexpected"],
"value": true
},
{
"id": "empty_owner",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["body", "decision", "ownerId"],
"value": ""
},
{
"id": "control_id",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["commandId"],
"value": "a\nb"
},
{
"id": "zero_fill_quantity",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["body", "quantity"],
"value": "0"
},
{
"id": "negative_fill_quantity",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["body", "quantity"],
"value": "-1"
},
{
"id": "numeric_price",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["body", "price"],
"value": 2
},
{
"id": "zero_price",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["body", "price"],
"value": "0"
},
{
"id": "negative_fee",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["body", "fee", "amount"],
"value": "-0.01"
},
{
"id": "excess_precision",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["body", "quantity"],
"value": "1.000000000"
},
{
"id": "unsafe_sequence",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["body", "decision", "sequence"],
"value": 9007199254740992
},
{
"id": "negative_sequence",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["body", "decision", "sequence"],
"value": -1
},
{
"id": "future_command_kind",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "fillCommand",
"path": ["body", "kind"],
"value": "deposit"
},
{
"id": "negative_cash",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "snapshot",
"path": ["cash"],
"value": "-1"
},
{
"id": "negative_long_quantity",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "snapshot",
"path": ["positions", "0", "quantity"],
"value": "-1"
},
{
"id": "negative_basis",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "snapshot",
"path": ["positions", "0", "remainingCost"],
"value": "-1"
},
{
"id": "mixed_intents",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "targetDecision",
"path": ["intent", "orders"],
"value": []
},
{
"id": "negative_target",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "targetDecision",
"path": ["intent", "targets", "0", "quantity"],
"value": "-1"
},
{
"id": "unsupported_stop",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "orderDecision",
"path": ["intent", "orders", "0", "kind"],
"value": "stop"
},
{
"id": "unsafe_revision",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "snapshot",
"path": ["revision"],
"value": 9007199254740992
},
{
"id": "unknown_snapshot_version",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "snapshot",
"path": ["version"],
"value": 2
},
{
"id": "unknown_decision_version",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "targetDecision",
"path": ["version"],
"value": 2
},
{
"id": "unknown_effect_version",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "effects",
"path": ["version"],
"value": 2
},
{
"id": "invalid_effect_price",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "effects",
"path": ["effects", "0", "price"],
"value": "0"
},
{
"id": "negative_release",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "effects",
"path": ["effects", "0", "releasedBasis"],
"value": "-1"
},
{
"id": "null_risk_session",
"owningTask": "F01",
"assumptions": "Mutation of a valid contract; rejects before contextual engine admission.",
"handCalculation": "No economic calculation; malformed transport must fail identically in Rust and TypeScript.",
"base": "snapshot",
"path": ["riskSession"],
"value": null
},
{
"id": "nul_identity",
"owningTask": "F01",
"assumptions": "Identifiers cannot contain ASCII control characters.",
"handCalculation": "Reject NUL in identity, without restricting legitimate Unicode text.",
"base": "fillCommand",
"path": ["commandId"],
"value": "a\u0000b"
}
],
"numeric": {
"id": "safe_json_number_parity",
"owningTask": "F01",
"assumptions": "Use parsed JSON number semantics across languages; counters nonnegative and timestamps signed; both JS-safe integers.",
"handCalculation": "Integral1.0 and1e0 equal1; abs(value)>9007199254740991, fractional/type-coerced values reject.",
"cases": [
{
"raw": "0",
"counterValid": true,
"timestampValid": true
},
{
"raw": "-0",
"counterValid": true,
"timestampValid": true
},
{
"raw": "1.0",
"counterValid": true,
"timestampValid": true
},
{
"raw": "1e0",
"counterValid": true,
"timestampValid": true
},
{
"raw": "9007199254740991",
"counterValid": true,
"timestampValid": true
},
{
"raw": "9007199254740992",
"counterValid": false,
"timestampValid": false
},
{
"raw": "1.5",
"counterValid": false,
"timestampValid": false
},
{
"raw": "-1",
"counterValid": false,
"timestampValid": true
},
{
"raw": "\"1\"",
"counterValid": false,
"timestampValid": false
},
{
"raw": "true",
"counterValid": false,
"timestampValid": false
},
{
"raw": "null",
"counterValid": false,
"timestampValid": false
},
{
"raw": "-9007199254740991",
"counterValid": false,
"timestampValid": true
},
{
"raw": "-9007199254740992",
"counterValid": false,
"timestampValid": false
}
]
}
}

View file

@ -0,0 +1,118 @@
{
"basis": {
"id": "basis_residual_spec",
"owningTask": "F02",
"assumptions": "Three owned shares have exact remaining cost5, no fees. Sell one share each time; basis rounds half-away at8dp. Final disposal releases exact residue.",
"handCalculation": "First5/3 rounds1.66666667; remaining3.33333333. Second3.33333333/2=1.666666665 rounds1.66666667; remaining1.66666666. Final release1.66666666. Sum exactly5, not3*roundedaverage=5.00000001.",
"initialQuantity": "3.00000000",
"initialCost": "5.00000000",
"releases": ["1.66666667", "1.66666667", "1.66666666"],
"remainingCosts": ["3.33333333", "1.66666666", "0.00000000"]
},
"commandIds": {
"id": "command_id_conflict_spec",
"owningTask": "F02",
"assumptions": "Command identity is tuple(sessionId,accountId,commandId); canonical typed payload comparison ignores object key order and decimal padding. Decision IDs are owner-scoped within session; no concatenated identifier collisions.",
"handCalculation": "Same identity+same canonical payload =>retry; same identity+changed fee=>conflict; different session=>independent. F01 checks this specification, not a runtime dedup store.",
"original": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "command-fill-1",
"eventTime": 1704292260000,
"body": {
"kind": "applyFill",
"decision": {
"ownerId": "strategy:A",
"decisionId": "decision-1",
"sequence": 1
},
"orderId": "order-1",
"fillId": "fill-1",
"instrumentId": "A^P.US",
"side": "buy",
"quantity": "3.00000000",
"price": "2.00000000",
"fee": {
"feeId": "fee-1",
"amount": "0.06000000"
}
}
},
"retry": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "command-fill-1",
"eventTime": 1704292260000,
"body": {
"kind": "applyFill",
"decision": {
"ownerId": "strategy:A",
"decisionId": "decision-1",
"sequence": 1
},
"orderId": "order-1",
"fillId": "fill-1",
"instrumentId": "A^P.US",
"side": "buy",
"quantity": "3",
"price": "2.00000000",
"fee": {
"feeId": "fee-1",
"amount": "0.06000000"
}
}
},
"conflict": {
"version": 1,
"sessionId": "research:run-1",
"accountId": "account-1",
"commandId": "command-fill-1",
"eventTime": 1704292260000,
"body": {
"kind": "applyFill",
"decision": {
"ownerId": "strategy:A",
"decisionId": "decision-1",
"sequence": 1
},
"orderId": "order-1",
"fillId": "fill-1",
"instrumentId": "A^P.US",
"side": "buy",
"quantity": "3.00000000",
"price": "2.00000000",
"fee": {
"feeId": "fee-1",
"amount": "0.07000000"
}
}
},
"independent": {
"version": 1,
"sessionId": "research:run-2",
"accountId": "account-1",
"commandId": "command-fill-1",
"eventTime": 1704292260000,
"body": {
"kind": "applyFill",
"decision": {
"ownerId": "strategy:A",
"decisionId": "decision-1",
"sequence": 1
},
"orderId": "order-1",
"fillId": "fill-1",
"instrumentId": "A^P.US",
"side": "buy",
"quantity": "3.00000000",
"price": "2.00000000",
"fee": {
"feeId": "fee-1",
"amount": "0.06000000"
}
}
}
}
}

299
test/fixtures/economics/scalars.json vendored Normal file
View file

@ -0,0 +1,299 @@
{
"schemaVersion": 1,
"grammar": "^-?(0|[1-9][0-9]*)(\\.[0-9]{1,8})?$",
"range": "[-792281625142643375935.43950335, 792281625142643375935.43950335]",
"canonical": "Exactly eight fractional digits; signed zero becomes zero. External excess precision rejects, including trailing zeroes. No exponent, whitespace, plus, leading zeroes or numeric coercion.",
"cases": [
{
"id": "integer",
"owningTask": "F01",
"assumptions": "Strict external posting string; no computation.",
"handCalculation": "Pad to eight places without changing value; normalize signed zero.",
"input": "3",
"canonical": "3.00000000"
},
{
"id": "fraction",
"owningTask": "F01",
"assumptions": "Strict external posting string; no computation.",
"handCalculation": "Pad to eight places without changing value; normalize signed zero.",
"input": "-1.25",
"canonical": "-1.25000000"
},
{
"id": "negative_zero",
"owningTask": "F01",
"assumptions": "Strict external posting string; no computation.",
"handCalculation": "Pad to eight places without changing value; normalize signed zero.",
"input": "-0.00000000",
"canonical": "0.00000000"
},
{
"id": "maximum",
"owningTask": "F01",
"assumptions": "Strict external posting string; no computation.",
"handCalculation": "Pad to eight places without changing value; normalize signed zero.",
"input": "792281625142643375935.43950335",
"canonical": "792281625142643375935.43950335"
},
{
"id": "minimum",
"owningTask": "F01",
"assumptions": "Strict external posting string; no computation.",
"handCalculation": "Pad to eight places without changing value; normalize signed zero.",
"input": "-792281625142643375935.43950335",
"canonical": "-792281625142643375935.43950335"
},
{
"id": "near_max_padding",
"owningTask": "F01",
"assumptions": "Strict external posting string; no computation.",
"handCalculation": "Pad to eight places without changing value; normalize signed zero.",
"input": "792281625142643375935.4",
"canonical": "792281625142643375935.40000000"
},
{
"id": "invalid_0",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "1e2",
"canonical": null
},
{
"id": "invalid_1",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "1E2",
"canonical": null
},
{
"id": "invalid_2",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "+1",
"canonical": null
},
{
"id": "invalid_3",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": " 1",
"canonical": null
},
{
"id": "invalid_4",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "1 ",
"canonical": null
},
{
"id": "invalid_5",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "01",
"canonical": null
},
{
"id": "invalid_6",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "1.",
"canonical": null
},
{
"id": "invalid_7",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": ".1",
"canonical": null
},
{
"id": "invalid_8",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "1.000000000",
"canonical": null
},
{
"id": "invalid_9",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "NaN",
"canonical": null
},
{
"id": "invalid_10",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "Infinity",
"canonical": null
},
{
"id": "invalid_11",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "-Infinity",
"canonical": null
},
{
"id": "invalid_12",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "792281625142643375935.43950336",
"canonical": null
},
{
"id": "invalid_13",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "-792281625142643375935.43950336",
"canonical": null
},
{
"id": "invalid_14",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": "792281625142643375936",
"canonical": null
},
{
"id": "invalid_15",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": 1,
"canonical": null
},
{
"id": "invalid_16",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": null,
"canonical": null
},
{
"id": "invalid_17",
"owningTask": "F01",
"assumptions": "Strict decimal-string ingress only.",
"handCalculation": "Reject unsupported syntax/type/precision or fixed-eight coefficient overflow; do not round.",
"input": true,
"canonical": null
},
{
"id": "terminal_line_separator_0",
"owningTask": "F01",
"assumptions": "Strict entire-string decimal ingress; JavaScript dollar-anchor alone is insufficient.",
"handCalculation": "Reject trailing line separators rather than padding malformed text.",
"input": "1\n",
"canonical": null
},
{
"id": "terminal_line_separator_1",
"owningTask": "F01",
"assumptions": "Strict entire-string decimal ingress; JavaScript dollar-anchor alone is insufficient.",
"handCalculation": "Reject trailing line separators rather than padding malformed text.",
"input": "1\r\n",
"canonical": null
},
{
"id": "terminal_line_separator_2",
"owningTask": "F01",
"assumptions": "Strict entire-string decimal ingress; JavaScript dollar-anchor alone is insufficient.",
"handCalculation": "Reject trailing line separators rather than padding malformed text.",
"input": "1
",
"canonical": null
},
{
"id": "terminal_line_separator_3",
"owningTask": "F01",
"assumptions": "Strict entire-string decimal ingress; JavaScript dollar-anchor alone is insufficient.",
"handCalculation": "Reject trailing line separators rather than padding malformed text.",
"input": "1
",
"canonical": null
}
],
"rounding": [
{
"id": "positive_tie",
"owningTask": "F01",
"assumptions": "Exact internal decimal, not an accepted external command.",
"handCalculation": "Round nearest at eight places; midpoint chooses larger absolute value.",
"input": "1.234567885",
"expected": "1.23456789"
},
{
"id": "negative_tie",
"owningTask": "F01",
"assumptions": "Exact internal decimal, not an accepted external command.",
"handCalculation": "Round nearest at eight places; midpoint chooses larger absolute value.",
"input": "-1.234567885",
"expected": "-1.23456789"
},
{
"id": "positive_below",
"owningTask": "F01",
"assumptions": "Exact internal decimal, not an accepted external command.",
"handCalculation": "Round nearest at eight places; midpoint chooses larger absolute value.",
"input": "1.234567884",
"expected": "1.23456788"
},
{
"id": "negative_below",
"owningTask": "F01",
"assumptions": "Exact internal decimal, not an accepted external command.",
"handCalculation": "Round nearest at eight places; midpoint chooses larger absolute value.",
"input": "-1.234567884",
"expected": "-1.23456788"
},
{
"id": "zero_tie",
"owningTask": "F01",
"assumptions": "Exact internal decimal, not an accepted external command.",
"handCalculation": "Round nearest at eight places; midpoint chooses larger absolute value.",
"input": "0.000000005",
"expected": "0.00000001"
},
{
"id": "negative_zero_tie",
"owningTask": "F01",
"assumptions": "Exact internal decimal, not an accepted external command.",
"handCalculation": "Round nearest at eight places; midpoint chooses larger absolute value.",
"input": "-0.000000005",
"expected": "-0.00000001"
},
{
"id": "negative_underflow",
"owningTask": "F01",
"assumptions": "Exact internal decimal, not an accepted external command.",
"handCalculation": "Round nearest at eight places; midpoint chooses larger absolute value.",
"input": "-0.000000004",
"expected": "0.00000000"
}
],
"overflow": {
"id": "overflow_rejected",
"owningTask": "F01",
"assumptions": "Fixed-eight 96-bit coefficient; calculations must fail rather than saturate or silently rescale.",
"handCalculation": "Max+0.00000001 and Min-0.00000001 overflow. Exact internal magnitude792281625142643375935.5 already exceeds max; reject before quantization.",
"maximum": "792281625142643375935.43950335",
"quantum": "0.00000001",
"roundingOverflow": "792281625142643375935.5"
}
}

85
test/fixtures/historical-v2/dataset.ts vendored Normal file
View file

@ -0,0 +1,85 @@
import type { HistoricalDatasetInputV2 } from '../../../libs/core/types/src/historical-data';
const time = (value: string) => Date.parse(value);
/** Synthetic retained table for regression testing, not a production calendar authority. */
export function datasetInput(): HistoricalDatasetInputV2 {
return {
metadata: {
calendars: [
{
id: 'test-us-equities',
venue: 'XNYS',
timeZone: 'America/New_York',
revision: 'test-sessions-2024-v1',
source: 'synthetic-regression-fixture',
startDate: '2024-03-01',
endDate: '2024-12-01',
sessions: [
{
date: '2024-03-08',
open: time('2024-03-08T14:30:00Z'),
close: time('2024-03-08T21:00:00Z'),
},
{
date: '2024-03-11',
open: time('2024-03-11T13:30:00Z'),
close: time('2024-03-11T20:00:00Z'),
},
{
date: '2024-11-29',
open: time('2024-11-29T14:30:00Z'),
close: time('2024-11-29T18:00:00Z'),
},
],
},
],
series: [
{
id: 'A.US:daily:raw',
instrumentId: 'A.US',
interval: '1d',
calendarId: 'test-us-equities',
venue: 'XNYS',
source: { provider: 'eod', revision: 'historical-normalization-v1' },
timestamp: 'session-date',
availability: 'interval-end-assumption',
adjustment: 'raw',
},
],
executionSeries: [{ instrumentId: 'A.US', seriesId: 'A.US:daily:raw' }],
bounds: {
warmupStart: time('2024-03-08T14:30:00Z'),
tradeStart: time('2024-03-11T13:30:00Z'),
tradeEnd: time('2024-11-29T18:00:00Z'),
},
universe: {
selection: 'point-in-time',
asOf: time('2024-03-01T00:00:00Z'),
revision: 'test-universe-v1',
instrumentIds: ['A.US'],
},
corporateActions: [
{
instrumentId: 'A.US',
status: 'action-free',
start: time('2024-03-01T00:00:00Z'),
end: time('2024-12-01T00:00:00Z'),
revision: 'test-action-coverage-v1',
actions: [],
},
],
},
bars: ['2024-03-08', '2024-03-11', '2024-11-29'].map((timestamp, sourceSequence) => ({
seriesId: 'A.US:daily:raw',
timestamp,
sourceSequence,
open: 100,
high: 110,
low: 90,
close: 105,
volume: 1000,
...(sourceSequence === 1 ? { vwap: 101 } : {}),
})),
};
}

View file

@ -0,0 +1,159 @@
import { expect, test } from 'bun:test';
import {
parseEngineFinancialCommand,
parseFinancialDecimal,
parseFinancialEffects,
parseFinancialSnapshot,
parseFinancialStrategyDecision,
} from '../../libs/core/types/src/financial-engine';
import contracts from '../fixtures/economics/contracts.json';
import ledgerSpecs from '../fixtures/economics/ledger-specs.json';
import scalars from '../fixtures/economics/scalars.json';
function parse(kind: string, value: unknown): unknown {
switch (kind) {
case 'command':
return parseEngineFinancialCommand(value);
case 'decision':
return parseFinancialStrategyDecision(value);
case 'snapshot':
return parseFinancialSnapshot(value);
case 'effects':
return parseFinancialEffects(value);
default:
throw new Error(`Unknown contract fixture ${kind}`);
}
}
function annotate(value: {
id: string;
owningTask: string;
assumptions: string;
handCalculation: string;
}) {
for (const key of ['id', 'owningTask', 'assumptions', 'handCalculation'] as const) {
expect(value[key].length).toBeGreaterThan(0);
}
}
test('rust_ts_fixture_parse_parity: shared scalar and versioned wire fixtures', () => {
for (const fixture of scalars.cases) {
annotate(fixture);
if (fixture.canonical === null) {
expect(() => parseFinancialDecimal(fixture.input)).toThrow();
} else {
expect(String(parseFinancialDecimal(fixture.input))).toBe(fixture.canonical);
}
}
for (const fixture of contracts.valid) {
annotate(fixture);
const result = parse(fixture.type, fixture.input);
expect(result).toEqual(fixture.canonical);
expect(parse(fixture.type, JSON.parse(JSON.stringify(result)))).toEqual(result);
}
for (const fixture of contracts.invalid) {
annotate(fixture);
const base = contracts.valid.find(candidate => candidate.id === fixture.base)!;
const input: unknown = structuredClone(base.input);
let parent = input as Record<string, unknown>;
for (const key of fixture.path.slice(0, -1)) {
parent = parent[key] as Record<string, unknown>;
}
parent[fixture.path.at(-1)!] = fixture.value;
expect(() => parse(base.type, input)).toThrow();
}
});
test('safe_integer_json_number_parity: integral lexical forms and exact boundaries', () => {
annotate(contracts.numeric);
const base = contracts.valid.find(candidate => candidate.id === 'fillCommand')!.input;
const snapshot = contracts.valid.find(candidate => candidate.id === 'snapshot')!.input;
for (const fixture of contracts.numeric.cases) {
const value: unknown = JSON.parse(fixture.raw);
const command = parseEngineFinancialCommand(base);
const timestamp = () => parseEngineFinancialCommand({ ...command, eventTime: value });
const sequence = () =>
parseEngineFinancialCommand({
...command,
body: { ...command.body, decision: { ownerId: 'A', decisionId: 'd', sequence: value } },
});
const revision = () => parseFinancialSnapshot({ ...snapshot, revision: value });
if (fixture.timestampValid) {
expect(value === 0 ? 0 : value).toBe(timestamp().eventTime);
} else {
expect(timestamp).toThrow();
}
for (const counter of [sequence, revision]) {
if (fixture.counterValid) {
expect(counter).not.toThrow();
} else {
expect(counter).toThrow();
}
}
}
});
test('rounding_ties_positive_negative: TypeScript rejects internal-only precision', () => {
for (const fixture of scalars.rounding) {
annotate(fixture);
expect(() => parseFinancialDecimal(fixture.input)).toThrow();
expect(String(parseFinancialDecimal(fixture.expected))).toBe(fixture.expected);
}
});
test('overflow_rejected: exact lexical bound with no floating-point conversion', () => {
annotate(scalars.overflow);
expect(String(parseFinancialDecimal(scalars.overflow.maximum))).toBe(scalars.overflow.maximum);
expect(() => parseFinancialDecimal('792281625142643375935.43950336')).toThrow();
expect(() => parseFinancialDecimal('-792281625142643375935.43950336')).toThrow();
expect(() => parseFinancialDecimal(scalars.overflow.roundingOverflow)).toThrow();
});
test('basis_residual_spec: F02 owns transition behavior, TS validates documented values only', () => {
annotate(ledgerSpecs.basis);
expect(ledgerSpecs.basis.owningTask).toBe('F02');
expect(ledgerSpecs.basis.releases).toEqual(['1.66666667', '1.66666667', '1.66666666']);
expect(ledgerSpecs.basis.remainingCosts).toEqual(['3.33333333', '1.66666666', '0.00000000']);
for (const value of [...ledgerSpecs.basis.releases, ...ledgerSpecs.basis.remainingCosts]) {
expect(String(parseFinancialDecimal(value))).toBe(value);
}
});
test('command_id_conflict_spec: typed canonical payload, not a second dedup engine', () => {
annotate(ledgerSpecs.commandIds);
expect(ledgerSpecs.commandIds.owningTask).toBe('F02');
const original = parseEngineFinancialCommand(ledgerSpecs.commandIds.original);
const retry = parseEngineFinancialCommand(ledgerSpecs.commandIds.retry);
const conflict = parseEngineFinancialCommand(ledgerSpecs.commandIds.conflict);
const independent = parseEngineFinancialCommand(ledgerSpecs.commandIds.independent);
expect(retry).toEqual(original);
expect([conflict.sessionId, conflict.accountId, conflict.commandId]).toEqual([
original.sessionId,
original.accountId,
original.commandId,
]);
expect(conflict.body).not.toEqual(original.body);
expect(independent.sessionId).not.toBe(original.sessionId);
expect(independent.body).toEqual(original.body);
});
test('strategy submission contract cannot accept internal financial mutations', () => {
const command = contracts.valid.find(candidate => candidate.id === 'fillCommand')!.input;
const decision = contracts.valid.find(candidate => candidate.id === 'targetDecision')!.input;
expect(() => parseFinancialStrategyDecision(command)).toThrow();
expect(() => parseEngineFinancialCommand(decision)).toThrow();
});
test('non-JSON sparse arrays cannot become valid wire contracts', () => {
const snapshot = contracts.valid.find(candidate => candidate.id === 'snapshot')!.input;
expect(() => parseFinancialSnapshot({ ...snapshot, positions: Array(1) })).toThrow();
});
test('identity text must round-trip through Rust UTF-8 without losing Unicode identifiers', () => {
const command = contracts.valid.find(candidate => candidate.id === 'markCommand')!.input;
for (const commandId of ['\ud800', '\udfff', 'a\ud800b']) {
expect(() => parseEngineFinancialCommand({ ...command, commandId })).toThrow();
}
expect(parseEngineFinancialCommand({ ...command, commandId: '命令:🧪' }).commandId).toBe(
'命令:🧪'
);
});

View file

@ -0,0 +1,374 @@
import { describe, expect, test } from 'bun:test';
import { createHash } from 'node:crypto';
import { validateDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset';
import {
assertDatasetV2Executable,
convertDatasetV1ToV2,
createDatasetV2,
validateDatasetV2,
} from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
import type {
HistoricalDataset,
HistoricalDatasetInputV2,
} from '../../libs/core/types/src/historical-data';
import { datasetInput } from '../fixtures/historical-v2/dataset';
type Mutable<T> = T extends readonly (infer V)[]
? Mutable<V>[]
: T extends object
? { -readonly [K in keyof T]: Mutable<T[K]> }
: T;
const input = () => structuredClone(datasetInput()) as Mutable<HistoricalDatasetInputV2>;
function legacyFixture(): HistoricalDataset {
const bars = datasetInput().bars.map(row => ({
symbol: 'A.US',
timestamp: Date.parse(String(row.timestamp)),
open: row.open,
high: row.high,
low: row.low,
close: row.close,
volume: row.volume,
vwap: 101,
}));
const manifest = {
version: 1 as const,
instruments: [{ id: 'A.US', symbol: 'A', exchange: 'US' }],
startDate: '2024-03-08T00:00:00.000Z',
endDate: '2024-11-30T00:00:00.000Z',
interval: '1d',
policy: { adjustment: 'raw' as const, timestamp: 'utc-session-date' as const },
volumePolicy: 'reported' as const,
qualityPolicy: 'reject-invalid-no-interpolation' as const,
sources: [
{ instrumentId: 'A.US', provider: 'eod' as const, revision: 'historical-normalization-v1' },
],
barCount: bars.length,
};
return {
manifest: {
...manifest,
hash: createHash('sha256').update(JSON.stringify({ manifest, bars })).digest('hex'),
},
bars,
};
}
describe('availability-aware dataset v2', () => {
test('dataset_v1_compatibility: old hashes/read semantics stay unchanged and conversion is explicit', () => {
const old = legacyFixture(),
before = structuredClone(old);
const validated = validateDataset(old);
expect(validated).toEqual(before);
const converted = convertDatasetV1ToV2(old, input().metadata);
expect(converted.manifest.version).toBe(2);
expect(converted.manifest.parentDatasetHash).toBe(old.manifest.hash);
expect(converted.manifest.hash).not.toBe(old.manifest.hash);
expect(converted.bars.every(bar => bar.vwap === null)).toBe(true);
expect(converted.manifest.limitations.some(value => value.includes('VWAP provenance'))).toBe(
true
);
expect(validateDataset(old)).toEqual(before);
expect(old).toEqual(before);
expect(() => validateDataset(converted)).toThrow();
expect(() => validateDatasetV2(old)).toThrow();
const changed = input().metadata;
changed.series[0]!.source.revision = 'different-source';
expect(() => convertDatasetV1ToV2(old, changed)).toThrow('matching');
});
test('dataset_v2_hash: stable canonical serialization includes calendar and policy provenance', () => {
const first = createDatasetV2(input());
const reordered = JSON.parse(JSON.stringify(input()), (_key, value) =>
value && typeof value === 'object' && !Array.isArray(value)
? Object.fromEntries(Object.entries(value).reverse())
: value
);
reordered.bars.reverse();
expect(createDatasetV2(reordered)).toEqual(first);
expect(validateDatasetV2(JSON.parse(JSON.stringify(first)))).toEqual(first);
const { hash, ...manifest } = first.manifest;
expect(
createHash('sha256')
.update(JSON.stringify({ manifest, bars: first.bars }))
.digest('hex')
).toBe(hash);
for (const change of [
(value: ReturnType<typeof input>) => {
value.metadata.calendars[0]!.revision = 'v2';
},
(value: ReturnType<typeof input>) => {
value.metadata.calendars[0]!.source = 'another-retained-source';
},
(value: ReturnType<typeof input>) => {
value.metadata.universe.revision = 'new-universe';
},
(value: ReturnType<typeof input>) => {
value.metadata.bounds.tradeStart++;
},
(value: ReturnType<typeof input>) => {
value.bars[0]!.volume++;
},
]) {
const changed = input();
change(changed);
expect(createDatasetV2(changed).manifest.hash).not.toBe(hash);
}
});
test('DST_half_day: labels map only through retained session boundaries', () => {
const dataset = createDatasetV2(input());
expect(dataset.bars.map(b => new Date(b.availableAt).toISOString())).toEqual([
'2024-03-08T21:00:00.000Z',
'2024-03-11T20:00:00.000Z',
'2024-11-29T18:00:00.000Z',
]);
expect(dataset.bars.map(b => new Date(b.intervalStart).toISOString())).toEqual([
'2024-03-08T14:30:00.000Z',
'2024-03-11T13:30:00.000Z',
'2024-11-29T14:30:00.000Z',
]);
const bad = input();
bad.bars[0]!.timestamp = '2024-03-09';
expect(() => createDatasetV2(bad)).toThrow('session mapping');
bad.bars[0]!.timestamp = '2024-02-30';
expect(() => createDatasetV2(bad)).toThrow();
const wrongDate = input();
wrongDate.metadata.calendars[0]!.sessions[0]!.open = Date.parse('2024-03-08T01:00:00Z');
expect(() => createDatasetV2(wrongDate)).toThrow('calendar session');
});
test('missing_vwap: preserve missingness and genuine supplied values without interpolation', () => {
const result = createDatasetV2(input());
expect(result.bars.map(b => b.vwap)).toEqual([null, 101, null]);
expect(result.bars).toHaveLength(3);
expect(result.manifest.qualityPolicy).toBe('reject-invalid-no-interpolation');
});
test('conflicting_duplicate: interval identity cannot be evaded through availability or sequence', () => {
const duplicate = input();
duplicate.bars.push({ ...duplicate.bars[0]!, sourceSequence: 99 });
expect(() => createDatasetV2(duplicate)).toThrow('Duplicate or conflicting');
const conflicting = input();
conflicting.metadata.series[0]!.availability = 'explicit';
conflicting.bars = conflicting.bars.map((bar, i) => ({
...bar,
availableAt: conflicting.metadata.calendars[0]!.sessions[i]!.close,
}));
conflicting.bars.push({
...conflicting.bars[0]!,
volume: 7,
availableAt: conflicting.bars[0]!.availableAt! + 1,
sourceSequence: 100,
});
expect(() => createDatasetV2(conflicting)).toThrow('Duplicate or conflicting');
const sequence = input();
sequence.bars[1]!.sourceSequence = 0;
expect(() => createDatasetV2(sequence)).toThrow('source sequence');
});
test('future_suffix_mutation: prior available observations and per-series sequence stay identical', () => {
const first = input();
first.metadata.series[0]!.availability = 'explicit';
first.bars = first.bars.map((bar, i) => ({
...bar,
availableAt: first.metadata.calendars[0]!.sessions[i]!.close + 1000,
}));
const last = input().metadata.calendars[0]!.sessions[1]!.close + 1000;
const before = createDatasetV2(first);
const changed = structuredClone(first);
changed.bars[2]!.volume = 9_000_000;
changed.bars[2]!.close = 109;
const after = createDatasetV2(changed);
expect(after.manifest.hash).not.toBe(before.manifest.hash);
expect(after.bars.filter(bar => bar.availableAt <= last)).toEqual(
before.bars.filter(bar => bar.availableAt <= last)
);
expect(before.bars.filter(bar => bar.availableAt <= last - 1)).toHaveLength(1);
expect(before.manifest.bounds.warmupStart).toBeLessThan(before.manifest.bounds.tradeStart);
expect(
before.bars.filter(bar => bar.availableAt < before.manifest.bounds.tradeStart)
).toHaveLength(1);
});
test('detaches and deeply freezes every nested value; untrusted mutation never uses cached validation', () => {
const source = input(),
dataset = createDatasetV2(source);
function frozen(value: unknown): void {
if (value && typeof value === 'object') {
expect(Object.isFrozen(value)).toBe(true);
for (const child of Object.values(value)) {
frozen(child);
}
}
}
frozen(dataset);
expect(validateDatasetV2(dataset)).toBe(dataset);
source.bars[0]!.volume = 999;
expect(dataset.bars[0]!.volume).toBe(1000);
const tampered = structuredClone(dataset) as Mutable<typeof dataset>;
tampered.bars[0]!.volume++;
expect(() => validateDatasetV2(tampered)).toThrow('hash/content');
expect(() => {
(dataset.bars[0] as Mutable<(typeof dataset.bars)[number]>).volume++;
}).toThrow();
});
test('canonical validation rechecks timing and derived eligibility even with recomputed hash', () => {
const tampered = structuredClone(createDatasetV2(input())) as Mutable<
ReturnType<typeof createDatasetV2>
>;
tampered.bars[0]!.availableAt = tampered.bars[0]!.intervalStart;
const { hash: _hash, ...manifest } = tampered.manifest;
tampered.manifest.hash = createHash('sha256')
.update(JSON.stringify({ manifest, bars: tampered.bars }))
.digest('hex');
expect(() => assertDatasetV2Executable(tampered)).toThrow('availability');
const changed = structuredClone(createDatasetV2(input())) as Mutable<
ReturnType<typeof createDatasetV2>
>;
changed.manifest.eligibility = 'ineligible';
expect(() => validateDatasetV2(changed)).toThrow('derived policy');
});
test('parent hash rejects trailing newline even when the current hash is recomputed', () => {
const tampered = structuredClone(
convertDatasetV1ToV2(legacyFixture(), input().metadata)
) as Mutable<ReturnType<typeof createDatasetV2>>;
tampered.manifest.parentDatasetHash += '\n';
const { hash: _hash, ...manifest } = tampered.manifest;
tampered.manifest.hash = createHash('sha256')
.update(JSON.stringify({ manifest, bars: tampered.bars }))
.digest('hex');
expect(tampered.bars.every(bar => bar.vwap === null)).toBe(true);
expect(() => validateDatasetV2(tampered)).toThrow();
});
test('availability assumptions are retained; explicit input cannot silently default to the close', () => {
const assumed = createDatasetV2(input());
expect(assumed.manifest.limitations.some(s => s.includes('zero data delay'))).toBe(true);
const explicit = input();
explicit.metadata.series[0]!.availability = 'explicit';
expect(() => createDatasetV2(explicit)).toThrow('requires availableAt');
const early = input();
early.bars[0]!.availableAt = early.metadata.calendars[0]!.sessions[0]!.close - 1;
expect(() => createDatasetV2(early)).toThrow('availability');
const lateAssumption = input();
lateAssumption.bars[0]!.availableAt =
lateAssumption.metadata.calendars[0]!.sessions[0]!.close + 1;
expect(() => createDatasetV2(lateAssumption)).toThrow('availability');
});
test('unknown coverage is exploratory; known unsupported actions and adjusted execution fail closed', () => {
expect(assertDatasetV2Executable(createDatasetV2(input())).manifest.eligibility).toBe(
'eligible'
);
const unknown = input();
unknown.metadata.corporateActions[0]!.status = 'unknown';
expect(assertDatasetV2Executable(createDatasetV2(unknown)).manifest.eligibility).toBe(
'exploratory'
);
const action = input();
action.metadata.corporateActions[0]!.status = 'known-actions';
action.metadata.corporateActions[0]!.actions.push({
effectiveAt: action.metadata.bounds.tradeStart,
kind: 'split',
reference: 'test-split',
});
expect(() => assertDatasetV2Executable(createDatasetV2(action))).toThrow(
'Unsupported corporate actions'
);
const adjusted = input();
adjusted.metadata.series[0]!.adjustment = 'provider-adjusted';
expect(() => assertDatasetV2Executable(createDatasetV2(adjusted))).toThrow('Adjusted prices');
const universe = input();
universe.metadata.universe.selection = 'current-constituents';
expect(createDatasetV2(universe).manifest.eligibility).toBe('exploratory');
const future = input();
future.metadata.universe.asOf = future.metadata.bounds.tradeEnd;
expect(() => createDatasetV2(future)).toThrow('universe/as-of');
});
test('one execution series per instrument; adjusted feature series cannot duplicate liquidity selection', () => {
const value = input();
value.metadata.series.push({
...value.metadata.series[0]!,
id: 'feature',
adjustment: 'provider-adjusted',
});
value.bars.push(...value.bars.map(bar => ({ ...bar, seriesId: 'feature' })));
const dataset = createDatasetV2(value);
expect(dataset.manifest.executionSeries).toHaveLength(1);
expect(dataset.manifest.eligibility).toBe('eligible');
value.metadata.executionSeries.push({ instrumentId: 'A.US', seriesId: 'feature' });
expect(() => createDatasetV2(value)).toThrow('execution instrument');
const missing = input();
missing.metadata.executionSeries[0]!.seriesId = 'missing';
expect(() => createDatasetV2(missing)).toThrow('exactly one');
});
test('intraday explicit start/end semantics agree, partial session bars reject', () => {
const start = input();
start.metadata.series[0]!.interval = '1h';
start.metadata.series[0]!.timestamp = 'interval-start';
start.bars = start.bars.map((bar, i) => ({
...bar,
timestamp: start.metadata.calendars[0]!.sessions[i]!.open,
}));
const end = structuredClone(start);
end.metadata.series[0]!.timestamp = 'interval-end';
end.bars = end.bars.map(bar => ({ ...bar, timestamp: Number(bar.timestamp) + 3_600_000 }));
expect(createDatasetV2(start).bars).toEqual(createDatasetV2(end).bars);
const overlapping = structuredClone(start);
overlapping.bars.push({
...overlapping.bars[0]!,
sourceSequence: 99,
timestamp: Number(overlapping.bars[0]!.timestamp) + 30_000,
});
expect(() => createDatasetV2(overlapping)).toThrow('Overlapping intervals');
start.bars[2]!.timestamp = start.metadata.calendars[0]!.sessions[2]!.close - 30 * 60_000;
expect(() => createDatasetV2(start)).toThrow('session interval');
});
test('terminal boundary retains the completed interval, not a new interval or decision permission', () => {
const value = input(),
dataset = createDatasetV2(value);
expect(dataset.bars.at(-1)!.intervalEnd).toBe(dataset.manifest.bounds.tradeEnd);
expect(dataset.bars.at(-1)!.availableAt).toBe(dataset.manifest.bounds.tradeEnd);
value.metadata.bounds.tradeEnd--;
expect(() => createDatasetV2(value)).toThrow('session interval');
});
test('rejects invalid bars, uncovered ranges, identity mappings and malformed metadata', () => {
for (const change of [
(value: ReturnType<typeof input>) => {
value.metadata.series[0]!.calendarId = 'unknown';
},
(value: ReturnType<typeof input>) => {
value.metadata.series[0]!.venue = 'guessed';
},
(value: ReturnType<typeof input>) => {
value.metadata.calendars[0]!.endDate = '2024-11-01';
},
(value: ReturnType<typeof input>) => {
value.metadata.bounds.tradeEnd = value.metadata.bounds.tradeStart;
},
(value: ReturnType<typeof input>) => {
value.metadata.corporateActions[0]!.end = value.metadata.bounds.tradeStart;
},
(value: ReturnType<typeof input>) => {
value.bars[0]!.close = NaN;
},
(value: ReturnType<typeof input>) => {
value.bars[0]!.volume = -1;
},
(value: ReturnType<typeof input>) => {
value.bars[0]!.sourceSequence = Number.MAX_SAFE_INTEGER + 1;
},
]) {
const value = input();
change(value);
expect(() => createDatasetV2(value)).toThrow();
}
});
});