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

85 lines
7.2 KiB
Markdown

# R10 — Protect retained research evidence and artifact integrity
Parent epic: E6. Priority/severity: P1 / High. Relative complexity: M. Recommended specialization: Full-stack research product.
Scheduling source of truth: [manifest entry R10](../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
- **WEB-05 — Verified:** SQL deletion cascades from definitions to runs/results; evidence retention must be defined before research findings reference those results. [database/postgres/init/08-create-runs-table.sql:13](../../../../database/postgres/init/08-create-runs-table.sql#L13); [database/postgres/init/06-create-backtest-tables.sql:25](../../../../database/postgres/init/06-create-backtest-tables.sql#L25).
- **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](../../../../libs/core/types/src/backtest-run.ts#L4); [apps/stock/web-api/src/services/backtest-result.ts:107](../../../../apps/stock/web-api/src/services/backtest-result.ts#L107).
## Intended behavior and implementation scope
Archive existing templates and retain their entire run history rather than cascading deletion; protect immutable strategy versions, datasets and artifact references established by R01. Add checksum verification on retrieval. R03 subsequently adds finding-reference constraints using the same retention rule. No automatic purge; explicit operator purge later needs a reference check and confirmation.
Measurable benefit: Prevents accidental loss of reproducibility.
## 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/services/backtest-v2.service.ts
- apps/stock/web-api/src/routes/backtests-v2.routes.ts
- apps/stock/web-api/src/services/ (artifact references)
Write locks: sql-migrations, web-backtest-service. One agent owns this change. Lock names do not override actual overlapping files.
## Dependencies and blockers
Implementation requires [R01](R01.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
- Deleting a definition with retained runs cannot cascade-delete those runs/results.
- Unreferenced legacy deletion behavior is explicitly tested/documented; archived history stays readable and existing replay limitations stay explicit.
- Missing/corrupt artifact produces an actionable integrity error; no fallback to current source.
## Mandatory tests
- retained_run_delete_restricted_postgres, archive_preserves_replay, artifact_checksum, legacy_delete_compatibility.
Apply the relevant [quality gates](../../QUALITY-GATES.md); submit exact commands, outcomes and skipped checks. Named cases above are required regression scenarios, not claims that those tests already exist.
## 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: Archive actions and409 reference details on destructive API attempts; retained read APIs stay stable.
- Backend/data dependencies: Foreign keys/restrictions on existing run/result relationships and new artifact references.
- Loading/error/empty behavior: Archive confirmation; referenced-delete explanation; read-only archived details; missing-artifact error.
- 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.
## Predecessor capability — R01
R01 already protects strategy versions/review events from update/delete and verifies retained artifact/lock checksums on retrieval. Reuse those paths. R10's remaining work is existing template/run/result/dataset retention and compatibility; do not create a second artifact store or repeat the catalog implementation. R01 currently has no run-to-version link; add references only with the task that introduces them.
## Wave21 execution contract
R01 accepted in `4a2e5ad`; owner authorized R10 continuation. Archive templates only, with a reversible `archivedAt` timestamp. Do not add an independent run-archive state. `POST /api/v2/backtests/:id/archive` takes strict `{ archived: boolean }`; default lists hide archived templates and `includeArchived=true` includes both. Detail/run/result URLs stay readable.
New submissions and template edits return 409 until restored. Existing accepted jobs may finish, recover or be cancelled; idempotent receipt replay occurs before archive admission checks. Template deletion with any retained run returns409 with the retained run count and archive guidance; runless/missing deletion keeps204 compatibility. SQL guards protect runs/results/datasets without blocking leases, progress, cancellation or initial dataset binding. Keep legacy NULL snapshot backfill working.
Reuse existing R01 artifact/lock and dataset retrieval checksum verification. No full catalog payload hashing, purge framework or invented historical provenance. Corruption tests insert historical malformed records initially instead of disabling protections or editing retained evidence.
## Validated handoff — 2026-10-23
Migration 17, archive/restore API, deletion conflicts and the web workflow are integrated and independently accepted. All accepted runs/results/datasets are retained; only runless templates can be hard-deleted. Worker claims, recovery, cancellation and completion continue on archived templates. Original keyed submission receipts remain replayable.
Database tests cover raw DELETE/UPDATE/TRUNCATE protections, admission races/direct repository entry, migration repeat/backfill, terminal writes and legacy NULL history. Missing and corrupt dataset fixtures run through the actual runner and fail without provider fallback or saved results. Existing strategy artifact checksums remain in R01. Browser tests cover confirmation, read-only settings, hidden/visible archived lists, saved trades/results, cancellation and restore/new admission.
Validation: full repository check passed (520 integration,150 Rust plus supporting gates), 131 PostgreSQL tests and 7 browser workflows. Evidence, reviewed 20-file hashes, environment limitations and commands: `manifest.json` → `twenty_first_wave_validation`. Validated but uncommitted; no default-engine/trading activation or performance work.