123 lines
16 KiB
Markdown
123 lines
16 KiB
Markdown
# R05 — Freeze complete provenance and cut over durable canonical runs
|
|
|
|
Parent epic: E6. Priority/severity: P0 / Critical. Relative complexity: M. Recommended specialization: Full-stack research product.
|
|
|
|
Scheduling source of truth: [manifest entry R05](../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-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).
|
|
- **KEEP-02 — Verified:** Preserve frozen/hash-verified historical snapshots and fenced durable runner attempts; extend them instead of creating a second job engine. [apps/stock/orchestrator/src/data/historical-dataset.ts:98](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L98); [apps/stock/orchestrator/src/backtest/BacktestRunner.ts:190](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190).
|
|
- **FIN-05 — Updated after S01/S02/F08:** Canonical TypeScript decisions on Rust sessions and canonical reports already exist. The durable runner still calls the legacy `runBacktest` path; the canonical worker constructs the current built-in implementation by identity. R05 must connect retained executable identity and canonical results to durable admission, not introduce another strategy engine. [native-worker.ts:26](../../../../apps/stock/orchestrator/src/backtest/native-worker.ts#L26), [strategy-runtime.ts:224](../../../../apps/stock/orchestrator/src/backtest/strategy-runtime.ts#L224), [canonical-result.ts:37](../../../../apps/stock/orchestrator/src/backtest/canonical-result.ts#L37), [BacktestRunner.ts:191](../../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L191).
|
|
|
|
## Intended behavior and implementation scope
|
|
|
|
Freeze strategy/model artifact IDs, parameters, seed, code/lockfile/build hashes and execution policies at submission. For a selected frozen dataset, pin its hash immediately; for a source request, retain the immutable query and atomically attach the first prepared dataset/hash before replay begins. Expose preparing versus reproducibility-finalized state. Wire the canonical Rust session with existing registered TS strategies into the durable runner and versioned result DTO. Exact reproduction API/UI is R12.
|
|
|
|
Consume F08's additive canonical analytics/report contract here. Version the persisted/public projection so canonical fractions, genuine zero exposure and null reasons bypass legacy percentage conversion/placeholder suppression. Preserve owner books and distinguish fills from round trips. Additional position valuations needed by the UI must come from Rust or be explicitly unavailable; do not invent marks, average-price basis or unrealized P&L in TypeScript merely to satisfy the old DTO. Keep historical readers unchanged and prove reopen/render compatibility during this cutover.
|
|
|
|
R02 now saves catalog versions and validated parameters with execution blocked at API, repository and SQL boundaries. Replace those gates only for verified supported execution. Before parallel implementation, pin the executable artifact/build binding: a retained bundle hash must never certify execution of a different current `createBuiltinStrategy` implementation. Verify the exact executable identity before the first decision; mismatches fail closed without a legacy-name fallback. Start with a trusted built-in single-asset vertical slice, retaining candidate isolation and multi-asset policy gates. That milestone alone does not complete all R05 requirements or authorize default activation.
|
|
|
|
Measurable benefit: Creates reproducible, project-gated runs usable by humans and AI.
|
|
|
|
## Exclusions
|
|
|
|
No general workflow framework, browser IDE, multi-tenant identity platform or second simulator.
|
|
|
|
## Likely files and ownership
|
|
|
|
- apps/stock/orchestrator/src/backtest/BacktestRunner.ts
|
|
- apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts
|
|
- apps/stock/web-api/src/services/backtest-v2.service.ts
|
|
- libs/core/types/src/backtest-run.ts
|
|
|
|
Write locks: result-contract, web-backtest-service, web-backtest-detail. One agent owns this change. Lock names do not override actual overlapping files.
|
|
|
|
## Dependencies and blockers
|
|
|
|
Implementation requires [F08](F08.md), [S02](S02.md), [R01](R01.md), [R10](R10.md), [D01](D01.md), [W03](W03.md), [C06](C06.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
|
|
|
|
- Changing template, strategy source or provider history after dataset freezing cannot alter an admitted run. A source query alone is not labelled a frozen dataset.
|
|
- No strategy decision executes before artifact verification and atomic dataset binding; failed preparation remains diagnosed and retry-safe.
|
|
- A retained-version/current-build mismatch rejects before execution; successful provenance identifies the executable that actually ran. Changing the current built-in implementation cannot silently change a retained version's behavior.
|
|
- New results declare financialEngine=rust and strategyExecution separately; correctness-gate evidence requires approved engine/data gates, not a UI flag.
|
|
- Before making canonical multi-asset research the default, obtain explicit owner disposition of sequential equal-time mark risk: either accept the disclosed versioned approximation or approve a coordinated atomic-mark policy/implementation with independent fixtures. F04/F05 currently evaluate each ordered mark; F06 demonstrates offsetting simultaneous moves can latch intermediate loss/drawdown halts. A passing deterministic replay suite alone does not resolve this material modeling issue. Single-asset component work and additive native integration need not wait for this decision.
|
|
|
|
## Mandatory tests
|
|
|
|
- mutate_template_after_submit, freeze_before_first_decision, frozen_seed_replay, provider_change_after_dataset_bind.
|
|
- retained_artifact_executable_binding, current_builtin_mismatch_rejected_before_decision, catalog_version_never_falls_back_to_legacy_name.
|
|
- Full durable runner restart/lease/cancel suite and result contract compatibility.
|
|
- Canonical reporting fractions/zero/null reasons, owner attribution and fill-versus-round-trip semantics survive persistence/reopen/UI rendering; existing legacy rows retain their prior interpretation.
|
|
- Multi-asset default activation rejects while the mark-policy disposition is absent; accepted policy/version/limitations are frozen in provenance, with offsetting-mark regression evidence.
|
|
|
|
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: Run/results expose immutable request plus resolved dataset binding, provenance and preparation state. No exact-reproduce endpoint until R12.
|
|
- Backend/data dependencies: Existing request_snapshot/dataset_hash/results extended with retained provenance and engine correctness-gate evidence metadata.
|
|
- Loading/error/empty behavior: API distinguishes preparing, dataset-pinned, running, failed and completed. W02/R11 render these fields without fabricated provenance.
|
|
- 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.
|
|
|
|
## First vertical slice — 2026-10-23
|
|
|
|
The additive slice connects the approved, server-seeded catalog built-ins to the existing durable runner and canonical Rust session. It supports one eligible retained v2 dataset, one series/asset/owner, explicit USD cash-funded long-only execution and reporting settings. HTTP-published or cloned candidates remain excluded even if reviewed. R05 is **not complete**: source-request preparation into eligible v2 data and broader cutover remain outstanding. No multi-asset/default activation is implied.
|
|
|
|
The pinned request is `canonical-research/v1` in `apps/stock/config/src/contracts/canonical-research.ts`. It retains the full checksummed executable package and dependency lock, normalized parameters, review receipt, dataset hash, seed, complete replay/financial/reporting policies and installed worker/native/runtime build identity. Admission and review/archive serialize on the strategy-family row; accepted receipt replay precedes current eligibility checks. Later edits or review revocation affect new submissions only. Account risk boundaries use actual retained calendar opens, including warmup and DST; daily bounds remain exact UTC instants.
|
|
|
|
The child imports the retained ESM bytes through a temporary Blob URL, verifies the package/build before strategy factory execution, and runs the existing deterministic TypeScript callback loop against Rust. The current built-in constructor is not a fallback. Durable claiming, heartbeat, cancellation/reaping, lease fencing and atomic result persistence are shared with legacy work. A build mismatch, corrupt dataset or runner without canonical capability fails with a durable diagnostic and no legacy/provider fallback.
|
|
|
|
Migration 19 adds `canonical_result` to existing results and strengthens admission/result identity guards; it preserves retention triggers. `canonical-result/v1` bypasses legacy percentage conversion and placeholder metrics. Existing required legacy JSON columns contain JSON null for canonical results. F08 remains the statistical evaluator; exact Rust financial facts, zeros, unavailable reasons, owner books and fills survive reopening. Reporting policy version 1 must keep its existing meaning; changed statistics require a new version and compatible retained readers.
|
|
|
|
### Operator workflow and deployment prerequisite
|
|
|
|
Use the R01 offline packaging/seeding workflow for repository built-ins, review a retained version in the web catalog, save a backtest, then open Settings → Configure canonical research. An explicitly prepared v2 dataset can be retained with:
|
|
|
|
```sh
|
|
RESEARCH_DATASET_DATABASE_URL=<database> bun run scripts/import-research-dataset.ts --file <v2-dataset.json>
|
|
```
|
|
|
|
The importer validates content/hash before connecting, never infers calendars/actions, does not migrate tables and never overwrites retained bytes. Normal startup migrations own the schema. The canonical picker validates retained content and shows unsupported entries as unavailable. All capital, cost, risk and statistical settings are explicit; legacy settings are not silently translated. Initial capital must fit the existing USD-cent template column, while engine quantities/notionals retain checked eight-place decimals.
|
|
|
|
Deploy the existing **native research runner (`useRustEngine: true`)**, bundled `orchestrator/dist/native-worker.js`, engine wrapper/addon and lockfile from the same build. Keep executable files immutable while jobs launch/run. Eligibility is an input/artifact preflight, not a worker health check. Accepted runs fail closed after an incompatible deployment; retaining/restoring historical executable builds and an exact reproduction workflow remain R12. No production database was seeded or migrated by this development wave.
|
|
|
|
### Remaining work and release gates
|
|
|
|
- Add explicit provider/source preparation only when it can supply v2 availability, calendar, action coverage and universe evidence; do not relabel v1 data eligible or infer missing facts. Freeze the immutable preparation request and bind the first verified dataset atomically before decisions.
|
|
- Preserve the current single-asset restriction until the simultaneous-mark policy is resolved. Candidate execution still requires A02 isolation; paper/live operation and default simulator retirement remain separately gated.
|
|
- R03 research projects/hypotheses/findings is independently ready and can deliver useful product work without opening these execution gates. R06 remains dependent on completed R05 scope; do not mark it ready from this partial milestone alone.
|
|
- No profiling, performance optimization, benchmark runs, DSL, second job engine, simulator or deployment framework was added.
|
|
|
|
Final validation and source identity are recorded in `manifest.json` → `twenty_third_wave_validation` and the roadmap handoff.
|
|
|
|
## Authorized source-export preparation slice — 2026-10-24
|
|
|
|
Implement explicit web upload of complete `HistoricalDatasetInputV2` source metadata/bars, read-only normalized preview and exact-hash retention into the existing immutable dataset store. Reuse `createDatasetV2`, importer custody and current canonical eligibility. Show source/calendar/action/universe declarations and availability assumptions without claiming independent provider certification. Preview writes nothing; retain does not save a template or start a run. Identical retry/concurrent requests converge on one content-addressed row. Unknown/ineligible or unsupported multiasset datasets remain unavailable for canonical execution.
|
|
|
|
Acceptance: malformed/missing metadata and invalid bars reject; preview hash drift rejects before persistence; corrupt retained rows fail without overwrite; API authorization/CSRF/no-store preserved; file/input/request changes fence stale UI state; exact retention can retry after lost responses; other setup edits survive. A real browser uploads source JSON, previews without writes, retains, selects, saves and runs the unchanged Rust next-open oracle, then reopens identical provenance. Existing importer CLI and v1 datasets remain intact.
|
|
|
|
This slice excludes v1 conversion, external provider access, inferred evidence, new migrations/schedulers, financial semantics and any default/multiasset/paper/live/AI activation. Full R05 remains partial for durable provider-query preparation and cutover. No performance measurements.
|
|
|
|
## Validated source-export handoff — 2026-10-24
|
|
|
|
The above slice is independently reviewed and `partial_validated_uncommitted` on `06039d1`. The web now previews and retains complete explicit source exports using the same normalizer/custody as existing research, then selects through canonical setup. Existing offline importer behavior and historical datasets remain intact; no SQL or engine source changed. Definitive rejection repair, exact uncertain retries, content corruption/concurrency, parent/late UI state and actual native economics pass. The web transport accepts source requests beyond its former 1 MiB cap; this is a functional correction, not a throughput measurement.
|
|
|
|
Final gates: repository check 1077 integration /150 Rust plus93 tooling/43 utility/44 calculation tests; PostgreSQL240/2157; Chromium16/590; strict affected-test types, all16-file lint/format/hash/DAG/diff checks. Independent agent overlays and root browser/transport changes are accepted. Four prior manual Rust cases remain ignored. Logs/hashes/limits are in `manifest.json` → `thirty_fifth_wave_validation` and the [roadmap handoff](../../ROADMAP.md#thirty-fifth-wave-handoff--2026-10-24). Both disposable containers were removed.
|
|
|
|
Full R05 stays `in_progress`: automatic provider-query preparation/first binding and default cutover are not delivered. No performance work or candidate/multiasset/paper/live/AI activation occurred. Changes await the next authorized commit.
|