stock-bot/docs/development/architecture/research-product.md

12 KiB
Raw Blame History

Integrated research product contracts

Status: approved under ADR-006 on 2026-10-23. This is the minimum product model, not a general laboratory system.

Existing paths to preserve

Minimum entities

Entity Minimum contents / relationships Mutability
strategies (new) ID, owner principal, name/status/docs, clone lineage, optional project Metadata editable/archiveable
strategy_versions (new) Strategy ID, version ID, source/bundle and retained artifact, hashes, parameter schema, checkpoint/API version, review status Published executable content immutable; review decisions audited separately
research_projects (new) ID, owner, title/description/status Editable/archiveable
hypotheses (new) Project ID, proposition, author kind/ID, state, validation criteria Revisioned narrative; evidence state cannot be self-asserted by AI
backtests (existing) Saved editable configuration template, optional version/project links Edits do not change historical runs
experiments (new) Optional project/hypothesis links, version(s), bounded grid, seed, partitions, cost/risk policies, selection rule; immutable validation report when completed Inputs frozen at submission; reports append-only; clone to change
runs (existing) Existing request/attempt/lease/cancel fields; experiment ID, trial key, frozen version/provenance, actor Inputs immutable; execution state fenced
backtest_results (existing) One terminal result per run, economics/metrics versions, full retained provenance, limitations and correctness-test policy/version references Append-only; no silent metric rewrites
analysis_artifacts (new) Kind (note/finding), revisioned narrative, authorship, exact run/version/retained-artifact references; reference experiment validation reports rather than storing a second copy Versioned; evidence refs protected
paper_deployments (later) Human approval, version/account/policy/evidence IDs, activation history Explicit transitions; no live deployment in this plan

Project/hypothesis links are optional. Add their nullable foreign keys only when the referenced tables exist; R01/R06 must work without R03 or placeholder research rows. Keep any cross-epic additive link migration under one integrator-owned SQL lock.

A run is a durable logical trial; attempts already exist on it. Do not add a competing job/attempt table. Run/experiment many-strategy configuration is a frozen list of strategy-version + instance + parameter + budget records. Artifact hashes alone are insufficient: retain retrievable source/bundle/model bytes and dependency/build identity.

erDiagram
  RESEARCH_PROJECT ||--o{ HYPOTHESIS : contains
  RESEARCH_PROJECT o|--o{ STRATEGY : organizes
  STRATEGY ||--o{ STRATEGY_VERSION : versions
  RESEARCH_PROJECT o|--o{ EXPERIMENT : contains
  HYPOTHESIS o|--o{ EXPERIMENT : motivates
  BACKTEST_TEMPLATE ||--o{ RUN : snapshots
  EXPERIMENT o|--o{ RUN : groups
  STRATEGY_VERSION }o--o{ RUN : frozen_configuration
  RUN ||--o| BACKTEST_RESULT : produces
  RUN }o--o{ ANALYSIS_ARTIFACT : supports

The many-version/run relationship can initially live in validated frozen configuration JSON with referential validation; introduce a join table only if query or referential-integrity needs justify it. Findings' run references must have DB-enforced retention/integrity (small reference relation if needed), not only free-text links.

API rules shared by browser and AI

Keep /api/v2 and current operator sessions. New APIs follow the task-specific contracts, not a parallel /ai/backtests path.

  • IDs are stable opaque IDs; every write records owner/actor. Server derives actor, never trusts submitted privilege fields.
  • Save template and submit run are explicit separate actions. Submit uses an idempotency key + input fingerprint; identical retry returns same run, different payload returns409.
  • Use typed errors:400/422 input,401/403 auth,404 missing,409 immutable/conflict/reference,429 AI budget,503 unavailable dependency. Async accepted work returns202 + run/experiment URL.
  • Persisted state is authoritative. Cancel acceptance is not completed cancellation; failed/incomplete runs cannot masquerade as successful zero return.
  • Existing run diagnostics remain authoritative. W01 exposes shared cancellation; native-unsupported pause/resume/speed controls are absent/disabled. Add per-run support metadata only when a real second supported control path needs it, not a generic capability registry.
  • Results distinguish financial engine, strategy execution mode, metrics/economics policy versions and provenance completeness. Maintain compatibility fields for old clients.
  • Reproduce-original pins original inputs; rerun-current creates a new request. Missing original code/dataset/model is a clear failure, not a fallback.
  • Comparison must surface mismatched costs, datasets, windows, engines and failed candidates; default ranking uses comparable completed project-gated runs.
  • Batch submission requires a resolved frozen dataset hash shared by its candidates. A single run may first prepare a new source request; individual sweep trials must not independently reload provider history.
  • Retention is archive-first. Referenced runs/versions/datasets/artifacts cannot disappear through an existing cascade.
  • UI/API do not calculate competing equity, fees or fills. Display-only formatting/downsampling never changes financial results.

Product increments

Slice User journey Tasks Engine prerequisite
M1 exploratory workbench Select supported existing strategy -> save/configure -> durable submit -> status/cancel -> results/trades -> reopen W01–W04 Existing engines, explicitly limited/legacy/ungated
M2 organized research Create project/hypothesis -> select immutable registered version -> run -> save evidence-qualified finding R01–R04/R10 Can ship alongside engine migration
M3 reproducible canonical run Choose version/dataset/cost/risk -> Rust run with TS decisions -> inspect -> reproduce original F01/F02/F04–F08, D01, S01/S02, R05/R11/R12 Canonical economics + explicit correctness tests
M4 experiment loop Preview sweep -> run -> compare -> validate out of sample/costs/regimes R06–R09/S05 M3
M5 AI loop AI candidate -> bounded isolated experiments -> evidence -> human review -> paper promotion A01–A04/S03/S04 M4 + isolated code + verified paper path

Do not delay M1/M2 for the entire Rust migration. Conversely, delivering those screens does not make old financial results trustworthy. M1 release requires C06 runtime isolation; exploratory labels never excuse interference with paper state.

Dataset selection R11 lists retained manifests without loading bar payloads. A selected existing hash is pinned at submission. A new source request freezes query parameters then prepares asynchronously through the existing runner; only after a fenced atomic dataset binding is it reproducible input. No strategy execution occurs before that binding. Retries reuse the pinned dataset, not a fresh provider query. The UI must distinguish these phases.

Example: bounded AI-assisted multi-strategy research

Illustrative workflow, not a claim of profitable results:

  1. An authorized agent registers the hypothesis “trend and mean-reversion components benefit from different volatility budgets” in a project. It specifies validation criteria before seeing held-out results.
  2. It selects immutable SMA and mean-reversion versions (or submits isolated candidate artifacts), two strategy instances per asset, a frozen multi-asset dataset, a fixed seed and long-only account/risk policy. The execution series is 1m; 5m/1h inputs are feature-only. Model/threshold fits use training data only.
  3. It previews a bounded grid: 3 fast windows × 2 slow windows × 2 high-volatility multipliers = 12 candidate portfolios. A declared 30-trial research budget admits those 12, with all failures retained.
  4. It selects at most two candidates using the recorded validation criterion, then requests 3 cost scenarios each (6 runs) and 4 chronological walk-forward segments each (8 runs). Two final held-out runs bring the total to 28; each admission still checks remaining budget. The held-out data is not exposed to candidate code before its designated phase.
  5. It compares aggregate and per-owner equity/P&L, regime sample counts, turnover, cost sensitivity and failed execution diagnostics. A finding cites the exact 28 run IDs/configurations and distinguishes exploratory selection from held-out evidence. Failure to outperform the baseline remains a valid finding.
  6. The user opens the same experiment in the web app, inspects trades/positions, reproduces an original run, requests further validation if desired and explicitly approves a version for paper trading only after S04 readiness. The agent cannot activate paper or live trading.

No extra AI database, simulator or agent framework is needed for this workflow.

UI conventions and tests

Reuse current Card/Dialog/DataTable/layout/chart/metric components and responsive layouts. Add only research/strategy/experiment navigation. Preserve draft input on errors, show loading separate from empty, label incomplete/cancelled/legacy/ungated results, and allow reopening exact saved URLs. Do not replace working components for cosmetic consistency.

Existing analytics-ui tests use server rendering. W04 now supplies the shared Playwright workflow harness, real authenticated Hono routes, disposable SQL/Redis, durable dispatch and native smoke coverage. Extend it for research-product flows instead of creating a second harness.

R11 exposes retained v1 metadata and exact hash selection in both backtest forms. Catalog coverage is unknown and full content integrity is not verified by metadata inspection; the runner validates retained bytes before binding/execution. The current web runner remains legacy/v1, so v2 entries are visibly unsupported until R05. Source requests remain unpinned until prepared asynchronously. These product capabilities do not remove the existing economics qualifications.

Review clarifications

  • Metrics are derived by one reviewed reporting path from Rust ledger/session marks; the browser does not recalculate finances.
  • R06 provides small SQL summaries now. Full result pagination/storage normalization is deferred P05.
  • Project/catalog/dataset screens are not prerequisites for backend experiments or an AI client. Release still requires the applicable browser story and isolation gates.
  • Walk-forward v1 uses explicitly reset accounts/state per segment with indicator warmup. Display segment returns and reset semantics; do not label stitched independent capital as one continuous executable portfolio.
  • AI narratives cite run/version/metric paths. Traceable evidence is not automatic validation of an arbitrary natural-language conclusion.

Validation reports (R08) are immutable experiment-owned outputs, not research findings. Their display must work before R03. R09 enables save/link-finding only when R03 evidence APIs are present; the finding references the exact report and contributing runs, without moving financial truth into a second store.