8.6 KiB
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. 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-api/src/services/backtest-v2.service.ts:211.
- 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; apps/stock/web-api/src/services/backtest-result.ts:107.
- 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/backtest/BacktestRunner.ts:190.
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
The retained-input component requires the accepted R05 durable-run/provenance slice plus R01/R10/F08/S02/D01/W03/C06/R12. The manifest records that narrower prerequisite; provider preparation and broader default cutover remain outside it. Full R06 still requires the failed-retry acceptance below.
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. 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.
Authorized component — 2026-10-24
Retained-input single-asset experiments depend on the accepted R05 runner/provenance component (618fb9e), not provider preparation or default cutover. One atomic bounded grid uses a current approved retained built-in, one eligible dataset and installed build, and fixed financial/reporting policy. Preview commits to exact inputs; submission receipts survive current eligibility changes. Existing runs/outbox/worker own execution. Failed retry is excluded from this component; full R06 remains incomplete until retry diagnostics/fencing acceptance is met.
Pinned experiment contract
@stock-bot/stock-config/experiments owns shared request/result DTOs. POST /api/v2/experiments/preview validates a saved canonical template plus bounded parameter grid; POST /api/v2/experiments requires its exact preview hash and an idempotency key. GET collection/detail exposes every frozen candidate and scalar result evidence; POST /:id/cancel is idempotent. Existing authenticated reads and credential mutations apply. Preview includes retained dataset manifest, current approved built-in package, complete financial/reporting policies and installed build. A template/review/build change before submission invalidates the preview. An accepted receipt is replayed before rechecking eligibility.
All children and outbox rows commit with the immutable experiment in one transaction. The initial bound is 100 trials; it bounds atomic admission and does not introduce a parallel scheduler. Only parameters and new run/account/session identities vary. experiment_id/trial_key/trial_index are immutable and mutually exclusive with new-run reproduction lineage. Child submission receipts are null; the experiment owns the unique principal/key receipt. SQL reconstructs exact trial requests from the manifest and preserves ordinary/reproduction admission guards. No template cloning/edit loop or separate financial engine.
Cancellation latches once, cancels pending children and requests worker acknowledgement for active children, preserving terminal outcomes. Counts are derived from actual children; the frozen candidate count exposes missing rows. Compact summaries validate retained provenance and statistical conventions, preserve null reasons and list inconsistent results as incomparable. No detail-array loading or financial recalculation is needed. Failed-run retry remains absent until history/fencing tests are implemented.
Validated component handoff
The retained-input component is implemented and independently reviewed. Full repository, PostgreSQL and Chromium gates passed; exact source hashes and logs are in manifest.json → twenty_seventh_wave_validation. See the twenty-seventh-wave roadmap handoff. This component is uncommitted and does not complete the full task or release its downstream dependencies.