83 lines
11 KiB
Markdown
83 lines
11 KiB
Markdown
# S01 — Run deterministic TypeScript decisions on Rust sessions
|
||
|
||
Parent epic: E4. Priority/severity: P0 / Critical. Relative complexity: M. Recommended specialization: TypeScript trading infrastructure.
|
||
|
||
Scheduling source of truth: [manifest entry S01](../manifest.json). No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
|
||
|
||
## Evidence and root cause
|
||
|
||
- **FIN-05 — Verified:** Rust and TypeScript separately implement fill/accounting behavior; the exposed native TypeScript callback method explicitly rejects callbacks. [apps/stock/engine/src/api/backtest.rs:63](../../../../apps/stock/engine/src/api/backtest.rs#L63); [apps/stock/orchestrator/src/execution/SimulationExecution.ts:114](../../../../apps/stock/orchestrator/src/execution/SimulationExecution.ts#L114).
|
||
- **STR-01 — Verified:** Registry is a useful small boundary, but its factories receive mode/execution services; BaseStrategy mixes author decisions, order submission and hidden signal filtering. [apps/stock/orchestrator/src/strategies/StrategyRegistry.ts:7](../../../../apps/stock/orchestrator/src/strategies/StrategyRegistry.ts#L7); [apps/stock/orchestrator/src/strategies/BaseStrategy.ts:315](../../../../apps/stock/orchestrator/src/strategies/BaseStrategy.ts#L315).
|
||
- **KEEP-01 — Verified:** Preserve transaction-scoped account locking, idempotent fills/event fingerprints, durable decisions and recovery checkpoints; these are real behavior, not interfaces alone. [apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts:46](../../../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts#L46); [apps/stock/orchestrator/src/execution/StrategyRecovery.ts:151](../../../../apps/stock/orchestrator/src/execution/StrategyRecovery.ts#L151).
|
||
|
||
## Intended behavior and implementation scope
|
||
|
||
Implement deterministic-by-contract TS decisions with prefix-only observations plus existing reviewed incremental calculations; shared feature caching is not a prerequisite. Use the F07 tagged step/barrier API, owner-stamped IDs, explicit decision cadence and seeded randomness. Stage next strategy states and RNG cursors until the barrier is submitted. Decision exceptions discard staged states and abort the attempt; rejected financial intents still commit the observation/state transition and return feedback.
|
||
|
||
## Exclusions
|
||
|
||
No unrelated refactor, new service or broker activation.
|
||
|
||
## Likely files and ownership
|
||
|
||
- apps/stock/orchestrator/src/strategies/
|
||
- apps/stock/orchestrator/src/backtest/native-worker.ts
|
||
- apps/stock/orchestrator/src/backtest/strategy-plan.ts
|
||
- libs/core/types/src/
|
||
|
||
Write locks: strategy-contract, worker-protocol. Review concrete file overlap; first-wave writable paths are further restricted by FIRST-WAVE.md.
|
||
|
||
## Dependencies and blockers
|
||
|
||
Implementation requires [F07](F07.md) integrated.
|
||
|
||
Architecture decisions: ADR-004, ADR-005. Agents may not independently amend their policies.
|
||
|
||
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
|
||
|
||
## Acceptance criteria
|
||
|
||
- On the pinned supported runtime/build, controlled clock/random inputs and identical state yield identical fixture decision traces and economic hashes.
|
||
- Each strategy sees its own state/positions and the same barrier portfolio snapshot, not a state mutated by another callback's early admission.
|
||
- Retry restores strategy state, RNG position and decision sequence; quantity rejection does not pretend the observation never occurred.
|
||
- Contract/type checks prohibit broker/account mutation services; trusted callbacks are not a security sandbox. No claim that repeated tests prove arbitrary TS deterministic.
|
||
|
||
## Mandatory tests
|
||
|
||
- same_seed_trace, all_callbacks_same_barrier_view, exception_restores_state_rng, rejected_order_feedback, repeated_target_no_duplicate.
|
||
- Compile-time context tests and preserved strategy-recovery scenarios; P01 adds actual TS decision costs.
|
||
|
||
Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests.
|
||
|
||
## Regression risks and rollback
|
||
|
||
Compatibility or lifecycle regression; preserve frozen inputs, old results and existing failure tests.
|
||
Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
|
||
|
||
## Handoff
|
||
|
||
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.
|
||
|
||
## Execution contract — 2026-10-23
|
||
|
||
The owner accepted F08 and requested continuation after the handoff explicitly named S01 and linked ADR-005. Base `3838295`; manifest revision `2026-10-23.31`. Root reserves the strategy contract/shared pull driver/native feedback parser to one owner; independent test author owns disjoint test/measurement files after the API is pinned. No Rust financial semantics, worker request protocol, active legacy registry, SQL/paper operation or default cutover changes.
|
||
|
||
- Add `runStrategyReplay(load, programs, options)` as a trusted host primitive. Programs have owner ID, strategy ID/version, fixed target/orders mode, explicit uint32 seed, initial JSON state and a synchronous `decide(context) -> {nextState, intent}`. Owner IDs are unique and exactly match native configuration; strategy IDs/versions may repeat for independent instances. Capture/detach inputs at attempt creation. Do not pass execution services, native handles, future data or state belonging to other owners into author callbacks.
|
||
- Context contains the engine time/barrier, the same frozen portfolio view for every due callback, owned positions, newly available observations since that owner's prior decision, previous admission feedback, readonly typed state and a scoped `random()`. Cadence controls scheduling; it must not discard another owner's pending observations. Warmup is consumed through the same prefix. Account information remains visible for portfolio-aware strategies; isolated state/feedback belongs only to its owner.
|
||
- Extract one internal pull loop used by the existing conformance wrapper and the new runtime. Keep existing trace IDs, output hashes, observation delivery and format defaults stable for conformance. The runtime stages all due decisions/states before one native batch; only a validated successful response commits all prepared state/RNG/observation/sequence slots. A native risk rejection is a valid state transition; a failed/ambiguous submit disposes the attempt.
|
||
- Per-owner RNG uses versioned `lcg32-v1`, the existing unsigned 32-bit `Math.imul(state,1664525)+1013904223` recurrence, divided by 2^32. Track state/draw count and safe decision counters. Invalidate the scoped RNG function immediately after the synchronous callback, including exceptions. This is reproducible fixture randomness, not a cryptographic or statistical-independence claim.
|
||
- Reject non-JSON, lossy/nonfinite state, async outputs, invalid intents and wrong modes before admission. Detach/freeze input and returned state; do not let caller mutation or retained callback references rewrite a committed snapshot. Copying small strategy state is acceptable; never clone native financial history per observation.
|
||
- Admission feedback copies validated native `Order` effects for the owner, including native rejection reasons and cancellation of that owner's earlier decisions. `Running` is not proof of order acceptance. Feedback is available at that owner's next decision and retained in terminal diagnostics. This is not a complete fill-event stream: subsequent fills appear in authoritative positions/open orders; S01 does not invent execution events or accounting.
|
||
- Return `{result, metrics, diagnostics}`. Versioned diagnostic snapshots contain identity, committed barrier count/last ID, sorted owner records with state, next decision sequence, RNG state/draw count, consumed observation count and previous admission feedback. `StrategyReplayError` carries the last confirmed committed diagnostics and cause, never a successful financial result. Fault tests may spy on the native host submit method; no generic session factory is needed.
|
||
- Retry means an entirely fresh native session with the original frozen inputs, detached initial states and per-owner seeds. Recompute every cursor and decision. Diagnostic TS snapshots are **not resumable financial checkpoints**. Do not expose a TS-only restore API or add native checkpoint transport for this task. Existing Rust reconstruction and paper checkpoints remain intact.
|
||
- Direct trusted program objects suffice here. S02 supplies the first real SMA strategy and trusted worker composition; R01/A02 own immutable/untrusted artifacts and isolation. Keep the existing legacy `StrategyRegistry` instead of broadening its execution-service factory into the canonical author API.
|
||
|
||
Required regression scenarios include mixed owner cadence/warmup, reversed callback order and independent RNG draws, prefix/future-suffix integrity, late callback failure after a committed barrier, ambiguous post-native-submit failure, risk-rejection feedback with state advancement, repeated/partial targets, owned cancellation feedback, frozen/retained-reference isolation, invalid state/Promise/mode rejection, and compile-time absence of financial mutation services. Fresh retries must equal uninterrupted decision/state/RNG/economic results. Preserve existing conformance/result hashes and paper recovery tests. Measure deterministic strategy staging on representative release workloads without a DSL/cache or an unrelated hot-loop optimization.
|
||
|
||
## Reviewed implementation handoff — 2026-10-23
|
||
|
||
Implemented the pinned contract in `contracts/canonical-strategy.ts`, `backtest/strategy-runtime.ts`, the shared native replay loop and a narrow native order-feedback decoder. The exact architecture allowlist adds only the new trusted host runtime; direct native entry points remain unchanged. `tsconfig.contracts.json` permanently includes the author type tests.
|
||
|
||
Independent review found and fixed two issues before acceptance: rejected async callbacks could leave unhandled rejections, and optional-looking Zod unknown fields accepted an empty feedback tag. Actual Promises are now observed without awaiting; arbitrary thenables remain invalid and uninvoked. Feedback tags require object payloads while nested financial diagnostics stay opaque. Subprocess regressions cover immediate, delayed and foreign-realm rejection; native failure tests prove all-owner atomic diagnostic state.
|
||
|
||
Full repository checks passed (78 tooling, 43 utility, 44 calculation, 390 integration, 144 Rust tests), plus 58 disposable recovery tests, 43 focused release tests and extra strict test TypeScript/lint/formatting. The 48-session paired benchmark preserves every financial ID/hash; measured stateful overhead is 14–313 ms across six 10,000-total-bar workloads. This includes validation/staging/feedback, not pure callback cost. See the [wave handoff](../../ROADMAP.md#fourteenth-wave-execution--2026-10-23) and canonical manifest for exact commands, hashes and measurement limitations. New S01 implementation remains uncommitted.
|