stock-bot/docs/development/backlog/tasks/S03.md

11 KiB

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. 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

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. The integration owner coordinates disjoint native and durable custody slices; one designated owner controls each shared contract. Lock names do not override actual overlapping files.

Dependencies and blockers

Implementation requires S01, C06 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; 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.

SQL custody is trusted. Account reads validate outer versions, identities, revision consistency and bound definitions. Rust replays and validates the opaque financial checkpoint before each financial transition; initialization alone does not certify every nested stored financial receipt. Do not introduce a second TypeScript ledger validator.

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.

Ordinary decisions use a Decision-phase event key. Quote-driven decisions may use the exact consumed quote's Execution key, as the existing native matcher permits; they cannot fill against that consumed quote. Never invent a later timestamp to bypass event ordering.

This custody slice accepts observations only for configured execution series. An auxiliary feature/timeframe observation manifest and feed cadence/alignment belong to S04; this does not claim full research multi-timeframe parity. Invalid admitted commands fail closed at drain without financial advancement and remain pending for diagnosis; there is no automatic skip or dead-letter framework. S04 readiness must refuse incomplete/failed recovery, including a pending invalid input.

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. Kill a separate process before decision commit, after checkpoint/batch commit, after admission commit and after fill/fee commit; compare recovered checkpoints and ordered journals with uninterrupted execution.

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.

Validation handoff — 2026-10-23

Implementation and independent G1/G2 review passed. The manifest records the 22-file source hashes, native artifact, commands and raw logs. Full repository checks and all 81 disposable-database tests passed; strict new-test TypeScript and 38 final targeted tests passed after test-only typing corrections. The host and native adapter are integrated but uncommitted; S04 activation and feed work remain separate. See the sixteenth-wave record.