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

85 lines
8.6 KiB
Markdown

# R12 — Reproduce an original run separately from rerunning current settings
Parent epic: E6. Priority/severity: P1 / High. Relative complexity: S. Recommended specialization: Full-stack reproducible research.
Scheduling source of truth: [manifest entry R12](../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
- **WEB-03 — Verified:** Definition creation auto-starts by default and catches submission failure; run creation has no client submission key. Re-run uses current definition rather than immutable original input. [apps/stock/web-api/src/services/backtest-v2.service.ts:105](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L105); [apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx:173](../../../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx#L173).
- **WEB-04 — Verified:** Existing results snapshot configuration and datasets but do not capture an immutable strategy artifact/engine build/model/seed bundle. Legacy projection can fall back to mutable definition fields. [libs/core/types/src/backtest-run.ts:4](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107).
- **KEEP-02 — Verified:** Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190).
## Intended behavior and implementation scope
Add reproduce-original endpoint/action that copies the retained versioned input bundle including dataset/artifact/engine policies into a new durable run. Keep rerun-current a separate labelled action. Verify retained artifacts and compatible engine availability before admission; no fallback to current source or provider history.
Measurable benefit: Makes exact experiment repetition a user-visible, verifiable capability.
## Exclusions
No downloading/executing arbitrary historic binaries, silent economics downgrade or overwriting original results.
## Likely files and ownership
- apps/stock/web-api/src/routes/backtests-v2.routes.ts
- apps/stock/web-api/src/services/backtest-v2.service.ts
- apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx
- apps/stock/web-app/src/features/backtest/components/RunControlsCompact.tsx
Write locks: web-backtest-service, web-backtest-detail. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires the accepted retained-input/single-asset durable execution component of [R05](R05.md) (`618fb9e`), plus [W04](W04.md) and the integrated R01/R10/F08/S02/D01/W03/C06 prerequisites. Provider-to-v2 preparation and broader R05 cutover are independent; R05 remains incomplete. This component dependency was verified and recorded by the planning owner on 2026-10-24 under the owner's continuation authorization.
Architecture decisions: ADR-006. 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
- Original reproduction after template/provider/strategy changes yields the same economic hash on the same supported build/policy.
- A missing original artifact or unsupported old engine produces an explicit error; old result remains viewable.
- UI previews exact original inputs and links source/reproduction runs without mutating either.
## Mandatory tests
- reproduce_after_template_provider_change, missing_original_artifact, unsupported_engine_version, economic_hash_parity.
- Browser original-vs-current action and duplicate-submit idempotency.
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
Legacy provenance may be insufficient; fail explicitly instead of pretending exact reproducibility.
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.
## Web/API contract and user states
- API: POST /api/v2/runs/:id/reproduce with idempotency key; response links originalRunId and new run. Rerun-current uses ordinary submit.
- Backend/data dependencies: R05 retained input bundle and R10 artifact integrity; require available approved engine build.
- Loading/error/empty behavior: Preview/loading; missing artifact or version error; accepted pending run; hash match/mismatch after completion.
- User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope.
## 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.
## Pinned execution scope — 2026-10-24
Reproduce completed retained canonical single-asset built-in runs on the exact installed worker/native/runtime build. Add immutable `original_run_id` lineage; use the existing durable runner, submission receipts and outbox. Missing/corrupt inputs or unsupported historical builds fail explicitly. No historical executable provisioning, source inference or default activation.
A fresh reproduction requires active parent/original strategy family and current approval of the **original** version, even if the template now selects another version. Copy the original request, changing only fresh run/session/account identities and the current approval receipt. Preserve all economic inputs. Receipt retries precede current eligibility checks; ordinary and reproduction intents use distinct hashes under the same principal/key uniqueness. SQL must enforce the source-copy relationship and retained identity alongside ordinary admission.
Expose read-only preview, POST reproduction and read-only result comparison. Compare versioned canonical hashes of the complete validated frozen request, financial envelope and analytics, normalizing only run/account identity and admission-review fields. Keep real market-session IDs, ownership, ordered fills, monetary strings, nulls and limitations. Do not recalculate finances or rewrite retained results. The UI separates original reproduction from current-settings submission, preserves retry keys after ambiguous responses and shows lineage/comparison after reload.
Root owns shared DTO/comparison and integration; backend/frontend worktrees have disjoint actual files. Current assignment, authority and validation live in the manifest.
## Implemented handoff — 2026-10-24
The pinned scope is implemented and independently reviewed; scheduling remains `review` / `validated_uncommitted` in the manifest. Shared preview/comparison DTOs live in `apps/stock/config/src/contracts/canonical-research.ts`; `run-reproduction.ts` checks retained admission eligibility and `reproduction-comparison.ts` hashes validated economic inputs/outputs. Migration 21 protects source-copy lineage and financial identity. GET `/api/v2/runs/:id/reproduction`, POST `/api/v2/runs/:id/reproduce` and GET `/api/v2/runs/:id/reproduction-comparison` are authenticated. POST accepts only an empty object plus an idempotency key; it returns 202 and Location for the new or previously accepted run.
`RunReproduction.tsx` consumes the same APIs, shows exact retained inputs, preserves keys after ambiguous submissions and displays source lineage and comparison. Current-settings submission is separate. The expanded Chromium research flow mutates the template, reproduces the original native result, retries the same receipt, reopens lineage, then proves a new ordinary run uses changed settings. PostgreSQL tests cover current original-version approval, direct SQL guards, retention, upgrade, corruption, concurrent receipts and economic parity/mismatch. Full gate outcomes and source hashes are recorded in the twenty-sixth-wave roadmap/manifest handoff.
No old binary provisioning or inference of missing provenance was added. R05 remains partial and R06/S06 gates remain intact.