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

15 KiB
Raw Blame History

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. 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

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. Parameter sensitivity reuses the existing bounded grid. Cost sensitivity needs a separate explicit immutable financial-policy admission contract; costs are not strategy parameters and must not mutate saved templates. 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 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. 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 committed as 67ab30c; 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 committed as abd1c5b. 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.

Authorized repeated-window component — 2026-10-24

The durable single-window workflow is accepted and committed as abd1c5b. Implement bounded walk-forward series now; cost sensitivity remains separate because it needs an explicit financial-policy admission branch. Freeze 2–10 ordered recipes and common source/build/grid/policies before any member runs. Count every planned training candidate and both future holdouts against the 100-run bound. Training starts cannot decrease, training cutoffs strictly increase, and each test end must be no later than the next validation start. Existing per-window boundary/warmup checks remain authoritative.

A focused series header and immutable train-root memberships preserve existing single-window semantics; SQL22–24 files remain unchanged. Admission of all member roots/slices/runs/outbox is atomic. Reuse per-window actions and ordinary retries; no bulk-select scheduler or general workflow framework. Whole-series cancellation reaches all windows, while local member cancellation only blocks series completion. Historical finalization verifies every sealed report and its canonical result facts, copying ordered validation/test reset segments without new financial or statistical formulas. Receipt replay precedes mutable eligibility.

The web provides explicit windows, preview, submission, member links, report save/reopen and honest missing/failed/cancelled states. Required proofs include total budget/chronology, later-suffix independence, partial-admission rollback, exact immutable membership, receipt/cancel races, old evidence preservation, pool1 transactions and the full two-window native browser lifecycle. Full R08 remains partial for bounded cost scenarios after this component.

Validated walk-forward handoff

The repeated-window component is independently accepted and component_validated_uncommitted. Forty-one source/test/config files preserve the existing Rust financial engine, worker/run/outbox model and SQL22–24 behavior. New SQL25 headers and exact train-root membership guards keep all-window admission atomic; full native evidence is checked again before sealing an immutable ordered reset-segment report. Member cancellation stays local; series cancellation prevents new member actions without changing completed evidence.

The web supports explicit 2–10-window recipes, full promised-run counts, synchronous shared submission ownership, member actions through existing pages, and saved report reopen. Native tests prove future-suffix independence, unchanged old migrations/receipts/leases, partial-admission rollback, actual lock contention, finalization receipt races and rejection of corrupted financial/analytics evidence. Repository test gates pass (882 integration /150 Rust), PostgreSQL/Redis 215 tests /1881 assertions, Chromium 14 workflows /412 assertions; final source and authored-test lint/types pass. Exact commands, formatting-only corrections and old fixture lint limitations are recorded in manifest.json → thirty_first_wave_validation.

Full R08 remains partial for bounded cost sensitivity; R09 remains blocked. Next scope should define supported fee/slippage scenarios as immutable execution-policy inputs and reuse canonical runs/results, without template mutation, strategy-parameter hacks, a second simulator or a window×cost scheduler. No regime/finding integration, performance work or AI/default/trading activation is included.