diff --git a/apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts b/apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts index f4374703..76c353b4 100644 --- a/apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts +++ b/apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts @@ -7,10 +7,6 @@ import { randomUUID } from 'node:crypto'; import type { PoolClient } from 'pg'; import type { TransactionCallback } from '@stock-bot/postgres'; import type { PostgresClient } from '@stock-bot/services'; -import { - parseBacktestRequest, - rejectCatalogVersionReferences, -} from '@stock-bot/stock-config/backtest'; import { canonicalRunRequestSchema, canonicalStrategyExecution, @@ -19,29 +15,26 @@ import { type CanonicalRunResult, } from '@stock-bot/stock-config/canonical-research'; import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; -import type { BacktestRunResult, HistoricalDataset, HistoricalDatasetV2 } from '@stock-bot/types'; -import { prepareDataset } from '../data/historical-dataset'; +import type { HistoricalDatasetV2 } from '@stock-bot/types'; import { assertDatasetV2Executable } from '../data/historical-dataset-v2'; -import type { BacktestConfig } from '../types'; import { BacktestCancelledError } from './execution-engine'; import { BacktestConflictError, BacktestLeaseLostError, type BacktestRunRepository, type CanonicalRunClaim, - type RunClaim, } from './run-repository'; /** * An attempt UUID is a fencing token: a delayed worker cannot write after replacement. * Ownership also requires an active status and an unexpired lease measured by PostgreSQL - * time. Canonical methods consume pre-admitted requests; legacy methods remain for older - * contracts and fixtures and do not enable legacy execution through BacktestRunner. + * time. This concrete repository exposes only the current, pre-admitted execution path. + * Historical writers use a separate compatibility adapter with the same fencing helpers. */ export class PostgresBacktestRunRepository implements BacktestRunRepository { constructor( - private readonly postgres: Pick, - private readonly leaseMs = 30_000 + protected readonly postgres: Pick, + protected readonly leaseMs = 30_000 ) { if (!Number.isInteger(leaseMs) || leaseMs < 100) { throw new Error('Invalid execution lease duration'); @@ -59,92 +52,6 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository { }); } - /** Legacy claim/create path. Current queued research uses startCanonical instead. */ - async start(config: BacktestConfig): Promise { - rejectCatalogVersionReferences(config); - const attemptId = randomUUID(); - return this.postgres.transaction(async client => { - if (config.runId) { - await client.query('SELECT id FROM runs WHERE id = $1 FOR UPDATE', [config.runId]); - const claimed = await client.query( - `UPDATE runs SET status = 'running', progress = 0, error = NULL, - started_at = NOW(), completed_at = NULL, paused_at = NULL, updated_at = NOW(), - attempt_id = $3, attempt_number = attempt_number + 1, - lease_expires_at = clock_timestamp() + $4::interval - WHERE id = $1 AND status = 'pending' AND NOT cancel_requested - AND request_snapshot IS NOT NULL - AND ($2::uuid IS NULL OR backtest_id = $2::uuid) - RETURNING id, backtest_id, request_snapshot`, - [config.runId, config.backtestId ?? null, attemptId, `${this.leaseMs} milliseconds`] - ); - const run = claimed.rows[0]; - if (!run) { - throw new BacktestConflictError('Run is missing, already claimed, or terminal'); - } - const snapshot = parseBacktestRequest(run.request_snapshot); - return { - runId: String(run.id), - backtestId: String(run.backtest_id), - attemptId, - config: snapshot, - }; - } - - const backtestId = config.backtestId ?? randomUUID(); - if (!config.backtestId) { - await client.query( - `INSERT INTO backtests - (id, name, strategy, symbols, start_date, end_date, initial_capital, config) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, - [ - backtestId, - config.name ?? 'Backtest', - config.strategy, - JSON.stringify(config.symbols), - config.startDate, - config.endDate, - config.initialCapital, - JSON.stringify({ - ...config.config, - dataFrequency: config.dataFrequency, - commission: config.commission, - slippage: config.slippage, - }), - ] - ); - } - const parent = await client.query('SELECT id FROM backtests WHERE id = $1 FOR UPDATE', [ - backtestId, - ]); - if (!parent.rows.length) { - throw new Error('Backtest definition not found'); - } - const runId = randomUUID(); - const snapshot = { ...config, runId, backtestId }; - await client.query( - `INSERT INTO runs (id, backtest_id, run_number, status, started_at, speed_multiplier, - request_snapshot, attempt_id, attempt_number, lease_expires_at) - SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, 'running'::run_status, NOW(), $3, - $4::jsonb, $5::uuid, 1, clock_timestamp() + $6::interval - FROM runs WHERE backtest_id = $2`, - [ - runId, - backtestId, - config.speed === 'max' - ? null - : config.speed === 'realtime' - ? 1 - : Number.parseFloat(config.speed), - JSON.stringify(snapshot), - attemptId, - `${this.leaseMs} milliseconds`, - ] - ); - await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [runId]); - return { runId, backtestId, attemptId, config: snapshot }; - }); - } - /** * Claim an existing pending run and verify the caller supplied its exact frozen inputs. * The status/attempt update and snapshot checks share a transaction, so mismatches roll @@ -253,118 +160,12 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository { }); } - /** Legacy v1 lookup/pinning; canonical admission already binds a retained v2 dataset. */ - async loadDataset( - runId: string, - attemptId: string, - requestedHash?: string, - signal?: AbortSignal - ): Promise { - signal?.throwIfAborted(); - return this.ownedTransaction(runId, async client => { - const owned = await client.query( - `SELECT dataset_hash FROM runs WHERE id = $1 AND attempt_id = $2 - AND lease_expires_at > clock_timestamp() AND status IN ('running', 'paused') AND NOT cancel_requested`, - [runId, attemptId] - ); - if (!owned.rows[0]) { - throw new BacktestLeaseLostError('Execution lease lost'); - } - const hash = owned.rows[0].dataset_hash ?? requestedHash; - if (!hash) { - return null; - } - if (requestedHash && requestedHash !== hash) { - throw new BacktestConflictError('Run dataset is already frozen'); - } - const dataset = await this.readDataset(client, String(hash), signal); - signal?.throwIfAborted(); - const pinned = await client.query( - `UPDATE runs SET dataset_hash = $2 WHERE id = $1 - AND attempt_id = $3 AND lease_expires_at > clock_timestamp() - AND status IN ('running', 'paused') AND NOT cancel_requested RETURNING id`, - [runId, hash, attemptId] - ); - if (!pinned.rows.length) { - throw new BacktestLeaseLostError('Execution lease lost while pinning dataset'); - } - signal?.throwIfAborted(); - return dataset; - }); - } - - /** - * Legacy v1 retention: save validated bytes and pin the run atomically. Reusing an - * existing hash still validates its stored payload; insertion success alone is no proof - * that old content is intact. Any late cancellation/lease failure rolls back the pin. - */ - async freezeDataset( - runId: string, - attemptId: string, - input: HistoricalDataset, - signal?: AbortSignal - ): Promise { - const dataset = await prepareDataset(input, undefined, signal); - return this.ownedTransaction(runId, async client => { - const owned = await client.query( - `SELECT dataset_hash FROM runs WHERE id = $1 AND attempt_id = $2 - AND lease_expires_at > clock_timestamp() AND status IN ('running', 'paused') AND NOT cancel_requested`, - [runId, attemptId] - ); - if (!owned.rows[0]) { - throw new BacktestLeaseLostError('Execution lease lost'); - } - const hash = dataset.manifest.hash; - if (owned.rows[0].dataset_hash && owned.rows[0].dataset_hash !== hash) { - throw new BacktestConflictError('Run dataset is already frozen'); - } - signal?.throwIfAborted(); - await client.query( - 'INSERT INTO backtest_datasets (hash, payload) VALUES ($1, $2::jsonb) ON CONFLICT (hash) DO NOTHING', - [hash, JSON.stringify(dataset)] - ); - const frozen = await this.readDataset(client, hash, signal); - signal?.throwIfAborted(); - const pinned = await client.query( - `UPDATE runs SET dataset_hash = $2 WHERE id = $1 - AND attempt_id = $3 AND lease_expires_at > clock_timestamp() - AND status IN ('running', 'paused') AND NOT cancel_requested RETURNING id`, - [runId, hash, attemptId] - ); - if (!pinned.rows.length) { - throw new BacktestLeaseLostError('Execution lease lost while pinning dataset'); - } - signal?.throwIfAborted(); - return frozen; - }); - } - - private async readDataset( - client: PoolClient, - hash: string, - signal?: AbortSignal - ): Promise { - signal?.throwIfAborted(); - const saved = await client.query('SELECT payload FROM backtest_datasets WHERE hash = $1', [ - hash, - ]); - const row = saved.rows[0]; - if (!row) { - throw new Error('Frozen dataset not found'); - } - const dataset = await prepareDataset(row.payload, undefined, signal); - if (dataset.manifest.hash !== hash) { - throw new Error('Stored dataset identity mismatch'); - } - return dataset; - } - /** * Lock first, then evaluate leases against actual DB time: an UPDATE predicate can be * evaluated before waiting on a row lock, even with clock_timestamp(). This helper only * acquires the lock; each callback must still check attempt, lease and allowed status. */ - private ownedTransaction(runId: string, work: TransactionCallback): Promise { + protected ownedTransaction(runId: string, work: TransactionCallback): Promise { return this.postgres.transaction(async client => { await client.query('SELECT id FROM runs WHERE id = $1 FOR UPDATE', [runId]); return work(client); @@ -391,42 +192,19 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository { }); } - /** Legacy result shape; canonical reports are persisted by completeCanonical. */ - async complete(result: BacktestRunResult, attemptId: string): Promise { - await this.ownedTransaction(result.runId, async client => { - const updated = await this.markComplete(client, result, attemptId); - if (!result.config.dataset || result.config.dataset.hash !== updated.dataset_hash) { - throw new BacktestConflictError('Result does not reference the run frozen dataset'); - } - await client.query( - `INSERT INTO backtest_results - (run_id, completed_at, metrics, equity_curve, ohlc_data, trades, positions, analytics, execution_time, configuration, engine) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`, - [ - result.runId, - result.completedAt, - JSON.stringify(result.metrics), - JSON.stringify(result.equity), - JSON.stringify(result.ohlcData), - JSON.stringify(result.trades), - JSON.stringify(result.positions), - JSON.stringify(result.analytics), - result.executionTime, - JSON.stringify(result.config), - result.engine, - ] - ); - }); - } - /** * Final ownership/cancellation gate inside the surrounding result transaction. A pending * cancel wins over completion; loss of ownership is a different error. If later result * validation or insertion fails, the caller's transaction rolls this status update back. */ - private async markComplete( + protected async markComplete( client: PoolClient, - result: Pick, + result: { + runId: string; + backtestId: string; + status: 'completed' | 'cancelled'; + completedAt: string; + }, attemptId: string ) { const updated = await client.query( @@ -513,32 +291,6 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository { }); } - async updateControl( - runId: string, - update: { status?: 'running' | 'paused'; speedMultiplier?: number | null }, - attemptId: string - ) { - await this.ownedTransaction(runId, async client => { - const result = await client.query( - `UPDATE runs SET status = COALESCE($2::run_status, status), - paused_at = CASE WHEN $2 = 'paused' THEN NOW() ELSE paused_at END, - speed_multiplier = CASE WHEN $3 THEN $4 ELSE speed_multiplier END, updated_at = NOW() - WHERE id = $1 AND attempt_id = $5 AND lease_expires_at > clock_timestamp() - AND status IN ('running', 'paused') AND NOT cancel_requested RETURNING id`, - [ - runId, - update.status ?? null, - update.speedMultiplier !== undefined, - update.speedMultiplier ?? null, - attemptId, - ] - ); - if (!result.rows.length) { - throw new BacktestLeaseLostError('No matching owned active run'); - } - }); - } - /** * Best-effort terminal write for a still-owned attempt. A recorded cancel takes priority; * a stale owner changes no rows. Unlike cancel(), this does not assert an acknowledgement. diff --git a/apps/stock/orchestrator/src/backtest/compatibility/LegacyBacktestRunWriter.ts b/apps/stock/orchestrator/src/backtest/compatibility/LegacyBacktestRunWriter.ts new file mode 100644 index 00000000..79e5145e --- /dev/null +++ b/apps/stock/orchestrator/src/backtest/compatibility/LegacyBacktestRunWriter.ts @@ -0,0 +1,266 @@ +/** Historical-data fixtures and migration compatibility only. Production composition + * uses PostgresBacktestRunRepository, whose public surface has no legacy writer methods. + * Shared ownership/completion helpers keep both paths under the same transaction fences. */ +import { randomUUID } from 'node:crypto'; +import type { PoolClient } from 'pg'; +import { + parseBacktestRequest, + rejectCatalogVersionReferences, +} from '@stock-bot/stock-config/backtest'; +import type { BacktestRunResult, HistoricalDataset } from '@stock-bot/types'; +import { prepareDataset } from '../../data/historical-dataset'; +import type { BacktestConfig } from '../../types'; +import { PostgresBacktestRunRepository } from '../PostgresBacktestRunRepository'; +import { BacktestConflictError, BacktestLeaseLostError, type RunIdentity } from '../run-repository'; + +interface LegacyRunClaim extends RunIdentity { + attemptId: string; + config: BacktestConfig; +} +export class LegacyBacktestRunWriter extends PostgresBacktestRunRepository { + /** Legacy claim/create path. Current queued research uses startCanonical instead. */ + async start(config: BacktestConfig): Promise { + rejectCatalogVersionReferences(config); + const attemptId = randomUUID(); + return this.postgres.transaction(async client => { + if (config.runId) { + await client.query('SELECT id FROM runs WHERE id = $1 FOR UPDATE', [config.runId]); + const claimed = await client.query( + `UPDATE runs SET status = 'running', progress = 0, error = NULL, + started_at = NOW(), completed_at = NULL, paused_at = NULL, updated_at = NOW(), + attempt_id = $3, attempt_number = attempt_number + 1, + lease_expires_at = clock_timestamp() + $4::interval + WHERE id = $1 AND status = 'pending' AND NOT cancel_requested + AND request_snapshot IS NOT NULL + AND ($2::uuid IS NULL OR backtest_id = $2::uuid) + RETURNING id, backtest_id, request_snapshot`, + [config.runId, config.backtestId ?? null, attemptId, `${this.leaseMs} milliseconds`] + ); + const run = claimed.rows[0]; + if (!run) { + throw new BacktestConflictError('Run is missing, already claimed, or terminal'); + } + const snapshot = parseBacktestRequest(run.request_snapshot); + return { + runId: String(run.id), + backtestId: String(run.backtest_id), + attemptId, + config: snapshot, + }; + } + + const backtestId = config.backtestId ?? randomUUID(); + if (!config.backtestId) { + await client.query( + `INSERT INTO backtests + (id, name, strategy, symbols, start_date, end_date, initial_capital, config) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, + [ + backtestId, + config.name ?? 'Backtest', + config.strategy, + JSON.stringify(config.symbols), + config.startDate, + config.endDate, + config.initialCapital, + JSON.stringify({ + ...config.config, + dataFrequency: config.dataFrequency, + commission: config.commission, + slippage: config.slippage, + }), + ] + ); + } + const parent = await client.query('SELECT id FROM backtests WHERE id = $1 FOR UPDATE', [ + backtestId, + ]); + if (!parent.rows.length) { + throw new Error('Backtest definition not found'); + } + const runId = randomUUID(); + const snapshot = { ...config, runId, backtestId }; + await client.query( + `INSERT INTO runs (id, backtest_id, run_number, status, started_at, speed_multiplier, + request_snapshot, attempt_id, attempt_number, lease_expires_at) + SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, 'running'::run_status, NOW(), $3, + $4::jsonb, $5::uuid, 1, clock_timestamp() + $6::interval + FROM runs WHERE backtest_id = $2`, + [ + runId, + backtestId, + config.speed === 'max' + ? null + : config.speed === 'realtime' + ? 1 + : Number.parseFloat(config.speed), + JSON.stringify(snapshot), + attemptId, + `${this.leaseMs} milliseconds`, + ] + ); + await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [runId]); + return { runId, backtestId, attemptId, config: snapshot }; + }); + } + + /** Legacy v1 lookup/pinning; canonical admission already binds a retained v2 dataset. */ + async loadDataset( + runId: string, + attemptId: string, + requestedHash?: string, + signal?: AbortSignal + ): Promise { + signal?.throwIfAborted(); + return this.ownedTransaction(runId, async client => { + const owned = await client.query( + `SELECT dataset_hash FROM runs WHERE id = $1 AND attempt_id = $2 + AND lease_expires_at > clock_timestamp() AND status IN ('running', 'paused') AND NOT cancel_requested`, + [runId, attemptId] + ); + if (!owned.rows[0]) { + throw new BacktestLeaseLostError('Execution lease lost'); + } + const hash = owned.rows[0].dataset_hash ?? requestedHash; + if (!hash) { + return null; + } + if (requestedHash && requestedHash !== hash) { + throw new BacktestConflictError('Run dataset is already frozen'); + } + const dataset = await this.readDataset(client, String(hash), signal); + signal?.throwIfAborted(); + const pinned = await client.query( + `UPDATE runs SET dataset_hash = $2 WHERE id = $1 + AND attempt_id = $3 AND lease_expires_at > clock_timestamp() + AND status IN ('running', 'paused') AND NOT cancel_requested RETURNING id`, + [runId, hash, attemptId] + ); + if (!pinned.rows.length) { + throw new BacktestLeaseLostError('Execution lease lost while pinning dataset'); + } + signal?.throwIfAborted(); + return dataset; + }); + } + + /** + * Legacy v1 retention: save validated bytes and pin the run atomically. Reusing an + * existing hash still validates its stored payload; insertion success alone is no proof + * that old content is intact. Any late cancellation/lease failure rolls back the pin. + */ + async freezeDataset( + runId: string, + attemptId: string, + input: HistoricalDataset, + signal?: AbortSignal + ): Promise { + const dataset = await prepareDataset(input, undefined, signal); + return this.ownedTransaction(runId, async client => { + const owned = await client.query( + `SELECT dataset_hash FROM runs WHERE id = $1 AND attempt_id = $2 + AND lease_expires_at > clock_timestamp() AND status IN ('running', 'paused') AND NOT cancel_requested`, + [runId, attemptId] + ); + if (!owned.rows[0]) { + throw new BacktestLeaseLostError('Execution lease lost'); + } + const hash = dataset.manifest.hash; + if (owned.rows[0].dataset_hash && owned.rows[0].dataset_hash !== hash) { + throw new BacktestConflictError('Run dataset is already frozen'); + } + signal?.throwIfAborted(); + await client.query( + 'INSERT INTO backtest_datasets (hash, payload) VALUES ($1, $2::jsonb) ON CONFLICT (hash) DO NOTHING', + [hash, JSON.stringify(dataset)] + ); + const frozen = await this.readDataset(client, hash, signal); + signal?.throwIfAborted(); + const pinned = await client.query( + `UPDATE runs SET dataset_hash = $2 WHERE id = $1 + AND attempt_id = $3 AND lease_expires_at > clock_timestamp() + AND status IN ('running', 'paused') AND NOT cancel_requested RETURNING id`, + [runId, hash, attemptId] + ); + if (!pinned.rows.length) { + throw new BacktestLeaseLostError('Execution lease lost while pinning dataset'); + } + signal?.throwIfAborted(); + return frozen; + }); + } + + private async readDataset( + client: PoolClient, + hash: string, + signal?: AbortSignal + ): Promise { + signal?.throwIfAborted(); + const saved = await client.query('SELECT payload FROM backtest_datasets WHERE hash = $1', [ + hash, + ]); + const row = saved.rows[0]; + if (!row) { + throw new Error('Frozen dataset not found'); + } + const dataset = await prepareDataset(row.payload, undefined, signal); + if (dataset.manifest.hash !== hash) { + throw new Error('Stored dataset identity mismatch'); + } + return dataset; + } + + /** Legacy result shape; canonical reports are persisted by completeCanonical. */ + async complete(result: BacktestRunResult, attemptId: string): Promise { + await this.ownedTransaction(result.runId, async client => { + const updated = await this.markComplete(client, result, attemptId); + if (!result.config.dataset || result.config.dataset.hash !== updated.dataset_hash) { + throw new BacktestConflictError('Result does not reference the run frozen dataset'); + } + await client.query( + `INSERT INTO backtest_results + (run_id, completed_at, metrics, equity_curve, ohlc_data, trades, positions, analytics, execution_time, configuration, engine) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`, + [ + result.runId, + result.completedAt, + JSON.stringify(result.metrics), + JSON.stringify(result.equity), + JSON.stringify(result.ohlcData), + JSON.stringify(result.trades), + JSON.stringify(result.positions), + JSON.stringify(result.analytics), + result.executionTime, + JSON.stringify(result.config), + result.engine, + ] + ); + }); + } + + async updateControl( + runId: string, + update: { status?: 'running' | 'paused'; speedMultiplier?: number | null }, + attemptId: string + ) { + await this.ownedTransaction(runId, async client => { + const result = await client.query( + `UPDATE runs SET status = COALESCE($2::run_status, status), + paused_at = CASE WHEN $2 = 'paused' THEN NOW() ELSE paused_at END, + speed_multiplier = CASE WHEN $3 THEN $4 ELSE speed_multiplier END, updated_at = NOW() + WHERE id = $1 AND attempt_id = $5 AND lease_expires_at > clock_timestamp() + AND status IN ('running', 'paused') AND NOT cancel_requested RETURNING id`, + [ + runId, + update.status ?? null, + update.speedMultiplier !== undefined, + update.speedMultiplier ?? null, + attemptId, + ] + ); + if (!result.rows.length) { + throw new BacktestLeaseLostError('No matching owned active run'); + } + }); + } +} diff --git a/apps/stock/orchestrator/src/backtest/run-repository.ts b/apps/stock/orchestrator/src/backtest/run-repository.ts index fc86a604..48437143 100644 --- a/apps/stock/orchestrator/src/backtest/run-repository.ts +++ b/apps/stock/orchestrator/src/backtest/run-repository.ts @@ -2,18 +2,12 @@ import type { CanonicalRunRequest, CanonicalRunResult, } from '@stock-bot/stock-config/canonical-research'; -import type { BacktestRunResult, HistoricalDataset, HistoricalDatasetV2 } from '@stock-bot/types'; -import type { BacktestConfig } from '../types'; +import type { HistoricalDatasetV2 } from '@stock-bot/types'; export interface RunIdentity { runId: string; backtestId: string; } -export interface RunClaim extends RunIdentity { - attemptId: string; - config: BacktestConfig; -} - export interface CanonicalRunClaim extends RunIdentity { /** Authoritative per-attempt research budget deadline; outside financial semantics. */ executionDeadlineAt?: number; @@ -22,7 +16,7 @@ export interface CanonicalRunClaim extends RunIdentity { } /** Canonical execution only; every write proves ownership of an unexpired attempt. - * Concrete compatibility methods for older saved runs are outside this contract. */ + * Historical writer adapters are outside this production contract. */ export interface BacktestRunRepository { /** Only already admitted canonical rows may be claimed; no implicit creation. */ startCanonical(request: CanonicalRunRequest): Promise; @@ -62,10 +56,6 @@ export class UnavailableBacktestRunRepository implements BacktestRunRepository { async completeCanonical(_result: CanonicalRunResult, _attemptId: string): Promise { this.unavailable(); } - /** Compatibility diagnostics for callers of the retired repository surface. */ - async start(_config: BacktestConfig): Promise { - return this.unavailable(); - } async load(_runId: string): Promise { return this.unavailable(); } @@ -75,21 +65,9 @@ export class UnavailableBacktestRunRepository implements BacktestRunRepository { async heartbeat(_runId: string, _attemptId: string): Promise<{ cancelRequested: boolean }> { return this.unavailable(); } - async loadDataset(): Promise { - return this.unavailable(); - } - async freezeDataset(): Promise { - return this.unavailable(); - } - async complete(_result: BacktestRunResult, _attemptId: string): Promise { - this.unavailable(); - } async updateProgress(): Promise { this.unavailable(); } - async updateControl(): Promise { - this.unavailable(); - } async fail(_runId: string, _error: string, _attemptId: string): Promise { this.unavailable(); } diff --git a/docs/development/architecture-cleanup-execution.md b/docs/development/architecture-cleanup-execution.md index 27ff6fd5..97ecdaf8 100644 --- a/docs/development/architecture-cleanup-execution.md +++ b/docs/development/architecture-cleanup-execution.md @@ -31,3 +31,5 @@ Agents use root-reserved disjoint files in the integration worktree. Root alone - **CL31:** Independent public-author/runtime suite:25 passed,363 assertions; standalone compilation uses no repository aliases or orchestrator/native implementation types. Source and packaged strategies produce identical native traces/checkpoints; contract compilation and scoped lint/format passed. Old contract path is a type-only compatibility export. - **CL28:** One application composition graph with narrow collaborators and caller-owned transactions; independent review no blockers. Focused API45 passed547 assertions; root combined composition/capability5 passed1091 assertions. Disposable PG research/validation/walk-forward/paper/durable gates69 passed602 assertions plus catalog/durable-validation17 passed186 assertions. Scoped lint/format passed. + +- **CL33:** Canonical concrete/unavailable repositories expose supported writes only; legacy adapter reuses exact fencing helpers and unchanged method bodies. Root capability/composition5 passed1091 assertions. Disposable PG durable/canonical/retention/catalog tests passed in69+17-test gates; source and contract typechecks pass. Historical readers and supported runtime behavior preserved. diff --git a/docs/development/backlog/README.md b/docs/development/backlog/README.md index 88e54011..fe19a7c9 100644 --- a/docs/development/backlog/README.md +++ b/docs/development/backlog/README.md @@ -1,6 +1,6 @@ # Canonical development backlog -**Active: E13 architecture cleanup, CL22–CL35 (12/14 complete).** Owner authorized all October 28 audit recommendations and a commit per validated task. Earlier completion counts below are historical. [Execution record](../architecture-cleanup-execution.md). +**Active: E13 architecture cleanup, CL22–CL35 (13/14 complete).** Owner authorized all October 28 audit recommendations and a commit per validated task. Earlier completion counts below are historical. [Execution record](../architecture-cleanup-execution.md). **Current scheduled backlog: 99/99 complete.** The owner resumed performance and authorized review of all seven conditions. P08 and O02 are implemented; five optional extensions remain deliberately deferred, and four merged IDs are redirects. This is not a claim that all 108 retained IDs were implemented. [Decisions, measurements and validation](../conditional-review.md). diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index a54bf225..67371655 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -3877,7 +3877,7 @@ "complexity": "M", "assignment": null, "write_locks": ["CL28"], - "completed_commit": null, + "completed_commit": "24487d35daef7bd09af09905a7dfca3955aec5a7", "blocker": null, "release_gates": [], "completion_evidence": "architecture-cleanup-execution.md", @@ -3968,7 +3968,7 @@ "epic": "E13", "priority": "P2", "severity": "Medium", - "status": "ready", + "status": "done", "dependencies": [], "decision_dependencies": [], "task_file": "backlog/tasks/CL33.md", @@ -3978,7 +3978,9 @@ "completed_commit": null, "blocker": null, "release_gates": [], - "completion_evidence": "architecture-cleanup-execution.md" + "completion_evidence": "architecture-cleanup-execution.md", + "integration_state": "accepted", + "validation": "Canonical concrete/unavailable repositories expose supported writes only; legacy adapter reuses exact fencing helpers and unchanged method bodies. Root capability/composition5 passed1091 assertions. Disposable PG durable/canonical/retention/catalog tests passed in69+17-test gates; source and contract typechecks pass. Historical readers and supported runtime behavior preserved." }, { "id": "CL34", @@ -10405,7 +10407,7 @@ ], "work_policy": "Root integrates/commits reviewed tasks; agents own disjoint explicit files in the root integration worktree. Only root builds shared outputs and runs combined gates. No isolated native agent build claim.", "first_wave": ["CL22", "CL23", "CL24"], - "completed": 12, - "last_verification": "One application composition graph with narrow collaborators and caller-owned transactions; independent review no blockers. Focused API45 passed547 assertions; root combined composition/capability5 passed1091 assertions. Disposable PG research/validation/walk-forward/paper/durable gates69 passed602 assertions plus catalog/durable-validation17 passed186 assertions. Scoped lint/format passed." + "completed": 13, + "last_verification": "Canonical concrete/unavailable repositories expose supported writes only; legacy adapter reuses exact fencing helpers and unchanged method bodies. Root capability/composition5 passed1091 assertions. Disposable PG durable/canonical/retention/catalog tests passed in69+17-test gates; source and contract typechecks pass. Historical readers and supported runtime behavior preserved." } } diff --git a/docs/development/backlog/tasks/CL33.md b/docs/development/backlog/tasks/CL33.md index 79645525..b0d418f4 100644 --- a/docs/development/backlog/tasks/CL33.md +++ b/docs/development/backlog/tasks/CL33.md @@ -18,3 +18,7 @@ Canonical/legacy PostgreSQL durable/recovery tests; production import checks. Fo No new service/framework, financial simulator, real trading activation, external research execution, push/PR or .env changes. D04/P03/P05/P06/CL21 remain deferred. Root owns shared outputs, task state and commits; agents own disjoint files in the integration worktree. + +## Accepted verification + +Canonical concrete/unavailable repositories expose supported writes only; legacy adapter reuses exact fencing helpers and unchanged method bodies. Root capability/composition5 passed1091 assertions. Disposable PG durable/canonical/retention/catalog tests passed in69+17-test gates; source and contract typechecks pass. Historical readers and supported runtime behavior preserved. diff --git a/test/contracts/canonical-runner.type-test.ts b/test/contracts/canonical-runner.type-test.ts index f25548d3..14054a7a 100644 --- a/test/contracts/canonical-runner.type-test.ts +++ b/test/contracts/canonical-runner.type-test.ts @@ -3,7 +3,11 @@ import type { BacktestExecutionEngine, LegacyBacktestExecutionEngine, } from '../../apps/stock/orchestrator/src/backtest/execution-engine'; -import type { BacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/run-repository'; +import type { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository'; +import type { + BacktestRunRepository, + UnavailableBacktestRunRepository, +} from '../../apps/stock/orchestrator/src/backtest/run-repository'; import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter'; function canonicalDependencies( @@ -34,3 +38,27 @@ function canonicalDependencies( } void canonicalDependencies; + +function canonicalRepositorySurface( + repository: PostgresBacktestRunRepository, + unavailable: UnavailableBacktestRunRepository +) { + // @ts-expect-error Legacy claim/create is an explicit compatibility-only capability. + repository.start; + // @ts-expect-error Production cannot perform legacy provider lookup/pinning. + repository.loadDataset; + // @ts-expect-error Admission already binds canonical datasets. + repository.freezeDataset; + // @ts-expect-error Production cannot persist an independent legacy financial result. + repository.complete; + // @ts-expect-error Playback controls are retained only by the compatibility writer. + repository.updateControl; + // @ts-expect-error Shared completion fences are not public writer capabilities. + repository.markComplete; + // @ts-expect-error Shared transaction locks are protected, not public. + repository.ownedTransaction; + // @ts-expect-error The unavailable production implementation has the same canonical surface. + unavailable.start; +} + +void canonicalRepositorySurface; diff --git a/test/integration/catalog-backtest-contract.test.ts b/test/integration/catalog-backtest-contract.test.ts index 97b10a2f..f08361d9 100644 --- a/test/integration/catalog-backtest-contract.test.ts +++ b/test/integration/catalog-backtest-contract.test.ts @@ -12,7 +12,7 @@ import { parseStrategyVersionPackage, validateStrategyParameters, } from '@stock-bot/stock-config/strategy'; -import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository'; +import { LegacyBacktestRunWriter } from '../../apps/stock/orchestrator/src/backtest/compatibility/LegacyBacktestRunWriter'; import { BacktestService } from '../../apps/stock/web-api/src/services/backtest.service'; const definition = { @@ -69,7 +69,7 @@ describe('catalog draft and execution contracts', () => { throw new Error('Unexpected write'); }), }; - const repository = new PostgresBacktestRunRepository(database); + const repository = new LegacyBacktestRunWriter(database); for (const marker of [ { strategy: 'catalog' }, { strategyVersionId: null }, diff --git a/test/integration/run-repository-capabilities.test.ts b/test/integration/run-repository-capabilities.test.ts new file mode 100644 index 00000000..edc66561 --- /dev/null +++ b/test/integration/run-repository-capabilities.test.ts @@ -0,0 +1,63 @@ +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { expect, mock, test } from 'bun:test'; +import { LegacyBacktestRunWriter } from '../../apps/stock/orchestrator/src/backtest/compatibility/LegacyBacktestRunWriter'; +import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository'; +import { UnavailableBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/run-repository'; +import { runtimeImports } from '../../scripts/runtime-imports'; + +const legacyMethods = [ + 'start', + 'loadDataset', + 'freezeDataset', + 'complete', + 'updateControl', +] as const; + +test('canonical concrete repositories cannot expose retired write capabilities', () => { + const database = { + transaction: mock(async () => { + throw new Error('Unexpected database access'); + }), + }; + const canonical = new PostgresBacktestRunRepository(database); + const unavailable = new UnavailableBacktestRunRepository(); + const historical = new LegacyBacktestRunWriter(database); + for (const method of legacyMethods) { + expect(method in canonical).toBe(false); + expect(method in unavailable).toBe(false); + expect(typeof historical[method]).toBe('function'); + } + // Compatibility does not copy or replace supported ownership/failure transitions. + for (const method of [ + 'startCanonical', + 'loadCanonicalDataset', + 'completeCanonical', + 'heartbeat', + 'updateProgress', + 'cancel', + 'fail', + ] as const) { + expect(historical[method]).toBe(canonical[method]); + } + expect(database.transaction).not.toHaveBeenCalled(); +}); + +test('production modules do not import or re-export the compatibility writer', () => { + const root = fileURLToPath(new URL('../../', import.meta.url)); + const compatibility = resolve( + root, + 'apps/stock/orchestrator/src/backtest/compatibility/LegacyBacktestRunWriter' + ); + const files = new Bun.Glob('{apps,libs}/**/src/**/*.{ts,tsx}').scanSync({ cwd: root }); + for (const file of files) { + const absolute = resolve(root, file); + for (const specifier of runtimeImports(absolute)) { + if (specifier.startsWith('.')) { + expect(resolve(dirname(absolute), specifier).replace(/\.[cm]?[jt]sx?$/, '')).not.toBe( + compatibility + ); + } + } + } +}); diff --git a/test/postgres/canonical-durable-backtest.test.ts b/test/postgres/canonical-durable-backtest.test.ts index 0423c3dc..e883ca74 100644 --- a/test/postgres/canonical-durable-backtest.test.ts +++ b/test/postgres/canonical-durable-backtest.test.ts @@ -12,6 +12,7 @@ import { } from '@stock-bot/stock-config/canonical-research'; import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner'; import { readCanonicalBuildIdentity } from '../../apps/stock/orchestrator/src/backtest/canonical-build'; +import { LegacyBacktestRunWriter } from '../../apps/stock/orchestrator/src/backtest/compatibility/LegacyBacktestRunWriter'; import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine'; import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository'; import { BacktestLeaseLostError } from '../../apps/stock/orchestrator/src/backtest/run-repository'; @@ -183,6 +184,7 @@ async function fixture(options: { corruptDataset?: boolean; buildMismatch?: bool return { pool, repository, + legacyWriter: new LegacyBacktestRunWriter(postgres, 5000), engine, runner, dispatcher, @@ -211,7 +213,7 @@ async function fixture(options: { corruptDataset?: boolean; buildMismatch?: bool }), kind: 'canonical-research/v999', }; - await expect(f.repository.start(raw)).rejects.toThrow('Retained strategy versions'); + await expect(f.legacyWriter.start(raw)).rejects.toThrow('Retained strategy versions'); expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0); await f.admit(); await expect(f.repository.startCanonical({ ...f.request, name: 'different' })).rejects.toThrow( diff --git a/test/postgres/catalog-backtest-drafts.test.ts b/test/postgres/catalog-backtest-drafts.test.ts index 3e0d0777..95a7bb91 100644 --- a/test/postgres/catalog-backtest-drafts.test.ts +++ b/test/postgres/catalog-backtest-drafts.test.ts @@ -7,7 +7,7 @@ import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { PostgreSQLClient } from '@stock-bot/postgres'; import { parseBacktestRequest } from '@stock-bot/stock-config/backtest'; import type { StrategyVersionPackage } from '@stock-bot/types'; -import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository'; +import { LegacyBacktestRunWriter } from '../../apps/stock/orchestrator/src/backtest/compatibility/LegacyBacktestRunWriter'; import { createBacktestRoutes } from '../../apps/stock/web-api/src/routes/backtest.routes'; import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes'; import { @@ -304,7 +304,7 @@ describe.skipIf(!url)('saved catalog backtest drafts on PostgreSQL', () => { await expect(f.api.createRun({ backtestId: saved.id })).rejects.toMatchObject({ code: 'catalog_execution_unavailable', }); - const repository = new PostgresBacktestRunRepository(f.postgres); + const repository = new LegacyBacktestRunWriter(f.postgres); const legacyConfig = parseBacktestRequest({ ...common, mode: 'backtest', diff --git a/test/postgres/durable-backtest.test.ts b/test/postgres/durable-backtest.test.ts index 9c8fd773..8f49ce90 100644 --- a/test/postgres/durable-backtest.test.ts +++ b/test/postgres/durable-backtest.test.ts @@ -17,6 +17,7 @@ import { type CanonicalRunResult, } from '@stock-bot/stock-config/canonical-research'; import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner'; +import { LegacyBacktestRunWriter } from '../../apps/stock/orchestrator/src/backtest/compatibility/LegacyBacktestRunWriter'; import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine'; import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository'; import { BacktestLeaseLostError } from '../../apps/stock/orchestrator/src/backtest/run-repository'; @@ -181,6 +182,7 @@ async function fixture(historical = false) { return { id: runId }; }; const repository = new PostgresBacktestRunRepository(postgres, 2_000); + const legacyWriter = new LegacyBacktestRunWriter(postgres, 2_000); const history = { reads: 0, unavailable: false }; const storage = { async getHistoricalBars() { @@ -268,6 +270,7 @@ async function fixture(historical = false) { definition, definitionInput, repository, + legacyWriter, runner, engine, queue, @@ -517,7 +520,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red .query(`CREATE FUNCTION delay_snapshot() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN PERFORM pg_sleep(0.35); RETURN NEW; END $$; CREATE TRIGGER delay_snapshot BEFORE INSERT ON backtest_datasets FOR EACH ROW EXECUTE FUNCTION delay_snapshot()`); - const short = new PostgresBacktestRunRepository(f.postgres, 250); + const short = new LegacyBacktestRunWriter(f.postgres, 250); const claim = await short.start(config); await expect(short.freezeDataset(run.id, claim.attemptId, dataset)).rejects.toBeInstanceOf( BacktestLeaseLostError @@ -562,13 +565,13 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red const f = await fixture(true); const run = await f.historicalRun({ backtestId: f.definition.id }); const config = await f.legacySnapshot(run.id); - const claim = await f.repository.start(config); + const claim = await f.legacyWriter.start(config); const dataset = await loadDataset(f.storage, config); await f.pool .query(`CREATE FUNCTION reject_dataset_pointer() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.dataset_hash IS NOT NULL THEN RAISE EXCEPTION 'injected snapshot pointer failure'; END IF; RETURN NEW; END $$; CREATE TRIGGER reject_dataset_pointer BEFORE UPDATE ON runs FOR EACH ROW EXECUTE FUNCTION reject_dataset_pointer()`); - await expect(f.repository.freezeDataset(run.id, claim.attemptId, dataset)).rejects.toThrow( + await expect(f.legacyWriter.freezeDataset(run.id, claim.attemptId, dataset)).rejects.toThrow( 'injected' ); expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(0); @@ -577,16 +580,16 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red .dataset_hash ).toBeNull(); await f.pool.query('DROP TRIGGER reject_dataset_pointer ON runs'); - await f.repository.freezeDataset(run.id, claim.attemptId, dataset); + await f.legacyWriter.freezeDataset(run.id, claim.attemptId, dataset); const different = await loadDataset(f.storage, { ...config, dataPolicy: { adjustment: 'raw', timestamp: 'utc-session-date' }, endDate: '2024-03-16T00:00:00.000Z', }); - await expect(f.repository.freezeDataset(run.id, claim.attemptId, different)).rejects.toThrow( + await expect(f.legacyWriter.freezeDataset(run.id, claim.attemptId, different)).rejects.toThrow( 'already frozen' ); - expect((await f.repository.loadDataset(run.id, claim.attemptId))?.manifest.hash).toBe( + expect((await f.legacyWriter.loadDataset(run.id, claim.attemptId))?.manifest.hash).toBe( dataset.manifest.hash ); }); @@ -595,11 +598,11 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red const f = await fixture(true); const run = await f.historicalRun({ backtestId: f.definition.id }); const config = await f.legacySnapshot(run.id); - const claim = await f.repository.start(config); + const claim = await f.legacyWriter.start(config); const dataset = await loadDataset(f.storage, config); const controller = new AbortController(); const reason = new BacktestCancelledError(); - const repository = new PostgresBacktestRunRepository({ + const repository = new LegacyBacktestRunWriter({ transaction: work => f.postgres.transaction(client => work( @@ -637,7 +640,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red const f = await fixture(true); const run = await f.historicalRun({ backtestId: f.definition.id }); const config = await f.legacySnapshot(run.id); - const claim = await f.repository.start(config); + const claim = await f.legacyWriter.start(config); const dataset = await loadDataset(f.storage, config); // Model corrupt historical storage at initial insertion; retained evidence cannot be edited. const corrupt = structuredClone(dataset); @@ -652,7 +655,9 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red ]); const reads = f.history.reads; f.history.unavailable = true; - await expect(f.repository.loadDataset(run.id, claim.attemptId)).rejects.toThrow('hash/content'); + await expect(f.legacyWriter.loadDataset(run.id, claim.attemptId)).rejects.toThrow( + 'hash/content' + ); await f.expire(run.id); await f.dispatcher.tick(); expect((await f.runner.runQueued(run.id)).status).toBe('failed'); @@ -797,7 +802,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red f.repository.updateProgress(run.id, 99, undefined, old.attemptId) ).rejects.toBeInstanceOf(BacktestLeaseLostError); await expect( - f.repository.updateControl(run.id, { status: 'paused' }, old.attemptId) + f.legacyWriter.updateControl(run.id, { status: 'paused' }, old.attemptId) ).rejects.toBeInstanceOf(BacktestLeaseLostError); await expect(f.repository.cancel(run.id, old.attemptId)).rejects.toBeInstanceOf( BacktestLeaseLostError @@ -996,7 +1001,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red ]); const active = await f.historicalRun({ backtestId: f.definition.id }); const oldActive = await f.historicalRun({ backtestId: f.definition.id }); - const claim = await f.repository.start(await f.legacySnapshot(active.id)); + const claim = await f.legacyWriter.start(await f.legacySnapshot(active.id)); await f.pool.query("UPDATE runs SET status = 'running' WHERE id = $1", [oldActive.id]); const migration = readFileSync( new URL('../../database/postgres/init/10-durable-backtest-dispatch.sql', import.meta.url), diff --git a/test/postgres/research-retention.test.ts b/test/postgres/research-retention.test.ts index c81f5967..6d838358 100644 --- a/test/postgres/research-retention.test.ts +++ b/test/postgres/research-retention.test.ts @@ -7,7 +7,7 @@ import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { PostgreSQLClient } from '@stock-bot/postgres'; import { parseBacktestRequest } from '@stock-bot/stock-config/backtest'; import type { BacktestRunResult, HistoricalDataset } from '@stock-bot/types'; -import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository'; +import { LegacyBacktestRunWriter } from '../../apps/stock/orchestrator/src/backtest/compatibility/LegacyBacktestRunWriter'; import { loadDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset'; import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes'; import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service'; @@ -89,7 +89,7 @@ async function fixture() { const api = new BacktestServiceV2({ postgres, logger }, async () => { throw new Error('No remote execution in retention tests'); }); - const repository = new PostgresBacktestRunRepository(postgres); + const repository = new LegacyBacktestRunWriter(postgres); const definition = await api.createBacktest(request, { autoStart: false }); const snapshot = async (runId: string) => parseBacktestRequest(