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

11 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

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. The failed-retry continuation satisfies the remaining acceptance below; final integration evidence is recorded in its validated handoff.

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 was excluded from this first component; its continuation below supplies the remaining diagnostics/fencing acceptance.

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 was deferred from this first component to the continuation below.

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 first component is committed as 6f64ef6; it did not alone complete the full task or release its downstream dependencies.

Failed-trial retry continuation — 2026-10-24

The retained-input experiment component is committed as 6f64ef6. This continuation completes its failed-trial retry acceptance using the same immutable logical run. POST /api/v2/experiments/:id/trials/:runId/retry requires a stable idempotency key and both observed attempt/retry counters. GET the corresponding /retries path returns append-only snapshots captured by accepted manual retries.

The new receipt retains the prior failure directly from SQL before clearing execution state; PostgreSQL timestamp precision is preserved. Current original-version approval and retained build/data eligibility are rechecked for fresh acceptance, with current approval recorded separately from the immutable original request. Completed/cancelled/result-bearing trials and cancelled experiments cannot be retried. Receipt replay precedes current eligibility checks.

Lock order is parent → experiment → run → strategy family. Atomic acceptance increments manual_retry_count, resets execution fields and makes the existing outbox due; attempt_number remains monotonic and the worker supplies a fresh UUID. Manual retry does not reset the existing lifetime automatic-recovery budget. History is explicitly previous failure snapshots preserved by manual retries, not invented history of every old automatic attempt. Existing simulator/financial semantics remain unchanged.

Validated retry handoff

R06's retained-input acceptance is complete and independently reviewed; status is review / validated_uncommitted. Existing bounded expansion/cancellation/compact comparison behavior is preserved. Full repository gates, PostgreSQL (190 tests / 1609 assertions) and Chromium (11 workflows / 285 assertions) passed. Exact source hashes and logs: manifest.json → twenty_eighth_wave_validation.

The retry suite proves exact failure snapshots, duplicate/stale intent handling, lifetime counter monotonicity, rollback, old-attempt fencing, Redis recovery, current original-version approval and actual Rust completion with one result. SQL23 adds guards only to experiment retry semantics; ordinary run lifecycle behavior remains intact. No engine or dispatcher changes were required. Downstream R08 remains blocked until acceptance/commit; broader R05 cutover is still separate.