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

100 lines
12 KiB
Markdown

# R08 — Add bounded chronological and reset-segment validation
Parent epic: E6. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Quantitative research integrity.
Scheduling source of truth: [manifest entry R08](../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
- **RES-01 — Verified:** Experimental Python feature preprocessing uses full-sample medians/quantiles; shuffled returns preserve ordinary Sharpe. These routines must not silently become validation evidence. [apps/stock/analytics/src/ml/feature_engineering.py:386](../../../../apps/stock/analytics/src/ml/feature_engineering.py#L386); [apps/stock/analytics/src/analysis/statistical_validation.py:168](../../../../apps/stock/analytics/src/analysis/statistical_validation.py#L168).
- **DAT-01 — Verified:** Dataset v1 has one bar timestamp and interval in the manifest, without explicit bar-end/availability semantics. Session dates cannot safely be treated as observation times. [libs/core/types/src/historical-data.ts:90](../../../../libs/core/types/src/historical-data.ts#L90); [apps/stock/orchestrator/src/services/StorageService.ts:177](../../../../apps/stock/orchestrator/src/services/StorageService.ts#L177).
- **FIN-07 — Verified:** Daily return grouping, Sharpe/Sortino conventions and placeholder exposure/VaR produce incomparable or misleading native metrics. [apps/stock/engine/src/backtest/simple_results.rs:374](../../../../apps/stock/engine/src/backtest/simple_results.rs#L374); [apps/stock/engine/src/backtest/simple_results.rs:542](../../../../apps/stock/engine/src/backtest/simple_results.rs#L542).
## Intended behavior and implementation scope
First implement bounded chronological parameter selection and nonoverlapping walk-forward recipes for deterministic registered strategies. Explicit warmup and evaluation windows; each validation segment starts from its declared initial capital and empty positions with warmed indicators, not carried money/state. Aggregate segment returns as a labelled reset-segment research series, never claim one continuous tradable equity curve. Cost/parameter sensitivity reuses grid expansion. Reject trainable/overlapping-label models until their fit-artifact and declared horizon/embargo contracts are supplied; do not invent general ML infrastructure for SMA.
Persist the immutable validation manifest/report as experiment-owned JSON on the R06 experiment (or a focused child row if immutability requires it), keyed by experiment/report version and containing every contributing run ID, selection rule and segment policy. This is not R03 research-findings storage. Reopening an experiment must recover the same report; new inputs require a new experiment/report identity.
## Exclusions
No general workflow framework, browser IDE, multi-tenant identity platform or second simulator.
## Likely files and ownership
- apps/stock/web-api/src/services/ (validation recipes)
- apps/stock/orchestrator/src/backtest/
- test/integration/ (research validation tests)
- database/postgres/init/ and reviewed migration registry (only if experiment report persistence needs an additive column/table)
Write locks: validation-contract, sql-migrations. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [R06](R06.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
- Training/validation/test inputs and selection rule are frozen before execution. Test values cannot affect earlier parameter selection or fitted inputs.
- Every segment declares capital/reset/warmup policy; warmup has no orders/fills; OOS intervals do not overlap.
- All tried candidates and holdout accesses remain visible. Independent segment cash accounts are not summed/stitched as a continuous portfolio.
- Immutable experiment-owned reports reopen without any project/hypothesis/findings records or R03 API; conflicting attempts cannot overwrite a completed report.
- For a later declared nonzero label horizon require gap/purge >= horizon; unsupported/missing horizon/trainable fit metadata rejects rather than leaking future data.
## Mandatory tests
- chronological_selection, test_suffix_cannot_change_selection, warmup_no_trades, nonoverlapping_windows, reset_segment_accounting.
- experiment_report_without_research_metadata, immutable_report_reopen, conflicting_report_write_rejected.
- reject_uncontracted_trainable_model, horizon_gap_validation, bounded_cost_grid; fixed seeds and retained selected-parameter artifacts.
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: Validation recipe and immutable report under the existing experiment API; report includes every contributing run and declared segment/warmup policy.
- Backend/data dependencies: R06 experiments/runs and experiment-owned JSON reports. No R03 analysis_artifacts dependency or separate optimization service.
- Loading/error/empty behavior: Typed invalid-window/insufficient-warmup errors; validation failures are not profitable candidates.
- 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 first component — 2026-10-24
R06 is accepted/committed as `b373410`. Begin with a read-only chronological preflight using the existing approved canonical template, bounded grid and retained source dataset. POST `/api/v2/experiments/validation/preview` prepares explicit train/validation/test slices, availability-aware warmup diagnostics, exact source/phase hashes and reset-account requests. The existing experiment editor exposes this input check without a submit/save control.
The fixed future selection protocol maximizes every candidate's finite comparable training total return, breaking ties by original candidate index. Failed/missing/incomparable/null candidates block later selection. Validation and test assess that same winner; neither retunes. Only deterministic unfitted built-ins and zero label horizon are supported. Warmup can overlap prior phases; evaluation intervals cannot overlap. No financial policy is recalculated; only dataset identity and calendar-derived risk-session clocks change per phase.
This component is explicitly **prepared input, not durable experiment evidence**. It writes no datasets, runs, experiments or reports and performs no selection or holdout execution. Existing SQL22/23 require one dataset per experiment; changing that admission/retry contract belongs to the next coordinated durable slice. Full R08 remains incomplete until frozen recipe, selection gating, reports, reset-segment validation and cost-sensitivity acceptance are met. No findings/regime integration or performance work is included.
### Validated preflight handoff
The first component is independently reviewed and `component_validated_uncommitted`; full R08 remains `in_progress`. Exact bars and legacy conversion provenance survive slicing; immediate source lineage stays in the outer preview. Warmup diagnostics respect actual availability and retained strategy ordering, including observations at/after the evaluation end. Existing account-clock calculation is reused for each phase without changing financial policy.
Full repository checks passed (786 integration /150 Rust tests), PostgreSQL (194 tests /1655 assertions), Chromium (12 workflows /306 assertions), strict test types, lint and formatting. Native regressions prove independent initial cash/positions/state, no warmup orders/fills and earlier-phase invariance to a changed test suffix. Browser/database tests prove preview makes no retained-data/job/template writes. Hashes and logs: `manifest.json` → `twenty_ninth_wave_validation`.
Next: immutable experiment-owned recipe and guarded staged admission, with all candidate training evidence complete before a write-once winner selection and validation/test admission. Existing ordinary experiment/retry behavior must remain intact. This preflight does not satisfy immutable report reopening, holdout access history, walk-forward aggregation or cost-sensitivity execution; R09 remains blocked.
## Authorized durable single-recipe component — 2026-10-24
Preflight is accepted and committed as `67ab30c`. Extend the training experiment with the immutable preparation manifest and write-once selection/report. Validation and test are ordinary singleton child experiments linked to the root, preserving existing run, outbox and retry contracts. Reuse full `getRunResults` financial/analytics validation before sealing evidence; compact UI summaries are insufficient.
Explicit receipt-bearing submit, select-and-admit and finalize endpoints; GET remains read-only. Retain all three slices atomically with training admission. All training candidates must complete and be comparable before selection. Freeze selection and both same-winner heldout experiments/runs/outbox in one transaction. Each phase resets capital/state as declared. Accepted receipt replay precedes current eligibility checks; current original approval/build gates new execution only. Finalization assembles verified historical evidence even after archival/build changes. Root cancellation propagates through existing cancellation routes and SQL guards.
The web supports saved validations, training admission, selection, heldout progress and report reopen; ambiguous requests retain exact intent/key and exclude conflicting editor actions. Child experiment links reuse existing retry/history UI. SQL guards protect recipe lineage, phase linkage, candidate completeness, selection and report immutability. Test native full lifecycle, prefix independence, all-candidate failures, atomic rollback, concurrent receipts/cancellation, upgrade preservation and browser recovery. No new scheduler, simulator, run schema, AI/candidate activation or performance work. Multi-window walk-forward/reset-series aggregation and cost sensitivity remain outstanding after this component.
### Validated durable handoff
The single-recipe component is independently accepted and `component_validated_uncommitted`. Shared Rust economics, ordinary runs/outbox, SQL22/23 retry semantics and original evidence are preserved. All repository gates pass (825 integration /150 Rust tests), PostgreSQL/Redis 205 tests /1773 assertions, Chromium 13 workflows /357 assertions, strict test types and lint. Exact source hashes and review evidence: `manifest.json` → `thirtieth_wave_validation`.
The UI supports the complete staged lifecycle and immutable report reopening. Native regressions prove unchanged training scores/winner after modifying only future test prices; malformed or missing candidate evidence cannot seal selection. Atomicity, SQL tamper, receipt/cancel races, migration preservation and phase retries pass. Full R08 remains incomplete for repeated walk-forward windows/reset-series aggregation and bounded cost sensitivity. R09 remains blocked. No performance or trading/default/AI activation occurred.