79 lines
9.2 KiB
Markdown
79 lines
9.2 KiB
Markdown
# S03 — Adapt durable paper transactions to Rust financial reducers
|
|
|
|
Parent epic: E4. Priority/severity: P0 / Critical. Relative complexity: L. Recommended specialization: Durable execution/Rust integration.
|
|
|
|
Scheduling source of truth: [manifest entry S03](../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
|
|
|
|
- **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).
|
|
- **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).
|
|
|
|
## Intended behavior and implementation scope
|
|
|
|
Preserve the existing PostgreSQL row lock, checkpoint+intent commit and per-effect journal. Rehydrate a private Rust staged state, call the same in-place financial kernel used by research, persist returned snapshot/effects atomically, publish after commit. Do not serialize/rebuild resident research state per event merely to satisfy paper staging. Metrics/UI are not transaction prerequisites. Before paper cutover, retain supported current order/TIF and recovery semantics or explicitly refuse incompatible outstanding state.
|
|
|
|
## Exclusions
|
|
|
|
No unrelated refactor, new service or broker activation.
|
|
|
|
## Likely files and ownership
|
|
|
|
- apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts
|
|
- apps/stock/orchestrator/src/execution/SimulationExecution.ts
|
|
- apps/stock/orchestrator/src/execution/StrategyRecovery.ts
|
|
- apps/stock/orchestrator/src/services/ExecutionService.ts
|
|
- apps/stock/engine/src/api/
|
|
|
|
Write locks: ts-execution-model, paper-transaction, financial-contract. One agent owns this change. Lock names do not override actual overlapping files.
|
|
|
|
## Dependencies and blockers
|
|
|
|
Implementation requires [S01](S01.md), [C06](C06.md) integrated.
|
|
|
|
Architecture decisions: 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
|
|
|
|
- Rollback discards staged native changes; crash before/after commit/publish has no duplicate fee/order or lost checkpoint.
|
|
- Restore includes owner cost residuals, open-order policies/reservations, event cursor, strategy/RNG state and IDs.
|
|
- Existing PostgreSQL failure cases and legacy supported DAY/GTC/IOC/FOK behavior pass the canonical path; incompatible old snapshot versions fail with a migration instruction.
|
|
- Research and paper reducers match economic postings for the same event/intent trace; different live data/timing is not claimed to produce identical trades.
|
|
|
|
## Mandatory tests
|
|
|
|
- Port all existing PostgreSQL order-execution and strategy-recovery failure cases.
|
|
- fault_before_commit, fault_after_commit_before_publish, multi_owner_lock, same_id_conflict, snapshot_restore_parity.
|
|
|
|
Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist.
|
|
|
|
## 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 stopped performance work and requested the remaining backlog after S02 was committed as `ca5abdd`. S03 is authorized under ADR-005; P08 is deferred. No profiling, throughput optimization or performance measurements belong to this wave.
|
|
|
|
**Native staging:** expose one stateless JSON `stageFinancialTransaction` boundary with initialize/apply variants, explicit version/session/account identity, canonical matching config or checkpoint, and one matching command. Rehydrate a private `MatchingAccount`, use its existing `apply`, and return the new checkpoint, native view, outcome and ordered per-effect views. No operator-reset or broker capability. Research retains its existing resident loop.
|
|
|
|
At the paper boundary, intermediate views may be reconstructed by restoring the pre-command private Rust `RiskAccount` and applying the exact retained effect commands through the same reducer, plus native managed-order updates. Compare every reconstructed outcome and final risk checkpoint/order state with the authoritative matcher. No TS accounting or final-view substitution. A replayed outcome emits no new effect rows; persist any native alias receipt without replaying historical effects into current state. Intermediate views are recovery facts, not decision-barrier tokens.
|
|
|
|
**Durable custody:** retain the existing SQL account row lock and transaction mechanism. New explicitly canonical account IDs use a versioned outer envelope containing the opaque native checkpoint plus TS cursors/pending work. Reuse generic JSON journal/checkpoint/input storage where compatible; add only the all-owner batch-intent storage actually needed. Native order snapshots and ordered fill journal facts are authoritative persisted records; do not introduce UUID remapping or redundant financial projections. Legacy repository reads/initialization explicitly refuse canonical envelopes, and canonical initialization refuses legacy state or changed configuration. No implicit account conversion.
|
|
|
|
**Actual strategy recovery:** a canonical paper runner accepts trusted normalized input commands/observations and optional decision scheduling metadata. S04 supplies the real feed/calendar/scheduler; the caller cannot supply a portfolio or revision. Capture the committed native view for a decision. Restore program JSON state, RNG state/draws, decision cursors and pending observation prefixes for every owner before evaluating all due owners against that same view. Functionally extract/reuse S01 staging logic; preserve its public research diagnostics and complete-retry behavior. Never invent a historical dataset hash for paper.
|
|
|
|
Atomically save all next checkpoints and one complete decision-batch intent. Dispatch that batch in a subsequent locked transaction and persist actual admission feedback with its financial snapshot/effects. Drain pending batch, then pending decision, then next input; do not admit later financial input while recovery is pending. Reject caller-supplied Submit commands on the paper input path. Per-owner pending observations must survive mixed-cadence restarts. Trusted program definitions are bound by declared metadata/version/seed/mode/initial state; immutable code artifact retention remains R01/R05.
|
|
|
|
**Failures:** SQL failure discards all private staged changes. Native validation/restore errors with no returned transition roll back. A returned native `Failed` outcome can contain a committed financial prefix: save its failed snapshot and exact ordered effects atomically, mark the account/batch terminal, then surface failure after commit. Never report successful execution or keep a running retry state. Publication occurs after commit and cannot roll back finance; stable readable journal IDs recover notification gaps without claiming exactly-once delivery.
|
|
|
|
Port existing failure/recovery scenarios to approved canonical economics. Legacy immediate cached-quote fills, UTC implicit resets, shorts and mutable policy reloads are not canonical compatibility promises. Preserve DAY/GTC/IOC/FOK under next-eligible-event timing and explicit venue/risk sessions, and retain legacy tests unchanged. Required added cases include old-command/alias retries after later fills, failed-prefix custody, shared-revision owner batches, mixed-cadence restart, pending-input recovery, SQL decision/intent/effect failures, lost commit acknowledgement and competing producers.
|
|
|
|
Native and TypeScript owners work in separate worktrees with an accepted wire-schema overlay. The native owner controls the new API/schema and minimal existing-schema exports; the durable owner controls custody, shared strategy staging and canonical recovery. Root controls integration/migrations acceptance; independent review checks invariants. No default/service/feed activation or paper trading operation is authorized by this task.
|