# R06 — Create immutable experiments and bounded sweep expansion Parent epic: E6. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Full-stack research product. Scheduling source of truth: [manifest entry R06](../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-01 — Verified:** The real backtest list/detail/API/SQL flow already exists. Strategy/project/experiment work should extend it; App strategy/analytics views are placeholders. [apps/stock/web-app/src/app/App.tsx:24](../../../../apps/stock/web-app/src/app/App.tsx#L24); [apps/stock/web-api/src/services/backtest-v2.service.ts:211](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211). - **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 Expand immutable bounded experiment grids into existing durable runs with unique trial keys and one pinned dataset hash. Reuse outbox/lease/attempt machinery. A retry-failed action creates a new fenced attempt for the same immutable failed logical run, only when no terminal result exists; append prior attempt diagnostics before clearing the active error. Do not overwrite completed results or create a duplicate candidate/attempt framework. Provide a minimal SQL summary projection excluding OHLC/trade arrays now; P05 later owns only profiled large-detail optimization. Project/hypothesis linkage is optional and must not require R03 tables or placeholder records. Add nullable foreign-key links only when both entity tables exist, in a coordinated additive migration; standalone versions/experiments work first. ## Exclusions No general workflow framework, browser IDE, multi-tenant identity platform or second simulator. ## Likely files and ownership - database/postgres/init/ (new migration) - apps/stock/web-api/src/routes/ (experiment endpoints) - apps/stock/web-api/src/services/ (experiment expansion) - apps/stock/orchestrator/src/backtest/run-repository.ts Write locks: sql-migrations, experiment-api. One agent owns this change. Lock names do not override actual overlapping files. ## Dependencies and blockers Implementation requires [R05](R05.md) integrated. 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 - Repeated expansion has identical ordered candidate fingerprints and creates no duplicate logical runs. - Failed retry preserves run inputs/trial key and prior error/attempt history; stale attempts cannot commit. Completed/cancelled stored results are not silently overwritten. - Experiment summary lists all outcomes and metrics/provenance without reading/transmitting full trade/OHLC blobs. - Batch cancellation stops new admission and requests active child cancellation; all candidates use the same frozen data for comparable windows. ## Mandatory tests - deterministic_grid, duplicate_expand_race, retry_failed_preserves_attempt_history, stale_retry_fenced, completed_result_retry_rejected. - summary_excludes_detail_payload, partial_batch_failure, cancel_batch, one_dataset_hash_for_all_trials; disposable DB/queue failure tests. 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 Schema/API backward compatibility, historical provenance and UI state regression. 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/GET /api/v2/experiments; GET /experiments/:id/trials; POST cancel/retry; preview validates grid and returns count. - Backend/data dependencies: Experiments table; nullable experiment_id/trial_key on runs; existing result storage. - Loading/error/empty behavior: API distinguishes empty/unsubmitted, partial, cancelled and terminal states; never averages missing failed trials away. - 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.