docs: explain strategy replay and durable execution code
This commit is contained in:
parent
8587c71cf3
commit
dd7ac53c51
19 changed files with 494 additions and 41 deletions
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* PostgreSQL persistence boundary for research run ownership, retained inputs and results.
|
||||
* It validates identities and commits worker output; it does not calculate trades, cash
|
||||
* or equity. These transactions concern research tables, not paper-account execution.
|
||||
*/
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import type { PoolClient } from 'pg';
|
||||
import type { TransactionCallback } from '@stock-bot/postgres';
|
||||
|
|
@ -27,7 +32,12 @@ import {
|
|||
type RunClaim,
|
||||
} from './run-repository';
|
||||
|
||||
/** The attempt UUID is a fencing token. PostgreSQL time, not worker clocks, defines ownership. */
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
||||
constructor(
|
||||
private readonly postgres: Pick<PostgresClient, 'transaction'>,
|
||||
|
|
@ -38,6 +48,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
}
|
||||
}
|
||||
|
||||
/** Read admission state without claiming it; startCanonical must still arbitrate ownership. */
|
||||
async load(runId: string) {
|
||||
return this.postgres.transaction(async client => {
|
||||
const result = await client.query('SELECT status, request_snapshot FROM runs WHERE id = $1', [
|
||||
|
|
@ -48,6 +59,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
/** Legacy claim/create path. Current queued research uses startCanonical instead. */
|
||||
async start(config: BacktestConfig): Promise<RunClaim> {
|
||||
rejectCatalogVersionReferences(config);
|
||||
const attemptId = randomUUID();
|
||||
|
|
@ -133,6 +145,12 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* back the claim. Recovery must first return an expired run to pending; this method
|
||||
* neither steals active leases nor creates a new run or dataset.
|
||||
*/
|
||||
async startCanonical(input: CanonicalRunRequest): Promise<CanonicalRunClaim> {
|
||||
const request = canonicalRunRequestSchema.parse(input);
|
||||
const attemptId = randomUUID();
|
||||
|
|
@ -171,6 +189,11 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Load only the v2 bytes bound by admission. Check the request, run pointer and content
|
||||
* hash together; no missing-data provider fallback is allowed. The final lease check
|
||||
* prevents slow validation from authorizing execution after ownership has expired.
|
||||
*/
|
||||
async loadCanonicalDataset(
|
||||
runId: string,
|
||||
attemptId: string,
|
||||
|
|
@ -219,6 +242,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
/** Reject malformed/retired queued input only while unclaimed; never overwrite an owner. */
|
||||
async rejectPending(runId: string, error: string) {
|
||||
await this.postgres.transaction(async client => {
|
||||
await client.query(
|
||||
|
|
@ -229,6 +253,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
/** Legacy v1 lookup/pinning; canonical admission already binds a retained v2 dataset. */
|
||||
async loadDataset(
|
||||
runId: string,
|
||||
attemptId: string,
|
||||
|
|
@ -268,6 +293,11 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,
|
||||
|
|
@ -329,8 +359,11 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
return dataset;
|
||||
}
|
||||
|
||||
/** Lock first, then evaluate the lease against real DB time. UPDATE can evaluate its
|
||||
* predicate before waiting on a row lock, even when the predicate uses clock_timestamp(). */
|
||||
/**
|
||||
* 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<T>(runId: string, work: TransactionCallback<T>): Promise<T> {
|
||||
return this.postgres.transaction(async client => {
|
||||
await client.query('SELECT id FROM runs WHERE id = $1 FOR UPDATE', [runId]);
|
||||
|
|
@ -338,6 +371,11 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Renew a still-valid owner and return its cancellation flag in the same statement.
|
||||
* A cancellation request does not immediately revoke ownership: the worker needs its
|
||||
* lease to stop execution and commit cancellation. An expired lease cannot be renewed.
|
||||
*/
|
||||
async heartbeat(runId: string, attemptId: string) {
|
||||
return this.ownedTransaction(runId, async client => {
|
||||
const result = await client.query(
|
||||
|
|
@ -353,6 +391,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
/** Legacy result shape; canonical reports are persisted by completeCanonical. */
|
||||
async complete(result: BacktestRunResult, attemptId: string): Promise<void> {
|
||||
await this.ownedTransaction(result.runId, async client => {
|
||||
const updated = await this.markComplete(client, result, attemptId);
|
||||
|
|
@ -380,6 +419,11 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(
|
||||
client: PoolClient,
|
||||
result: Pick<BacktestRunResult, 'runId' | 'backtestId' | 'status' | 'completedAt'>,
|
||||
|
|
@ -407,6 +451,11 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
return updated.rows[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the Rust report envelope and its admitted inputs, then atomically commit
|
||||
* terminal status plus the full canonical result. Legacy financial columns stay null
|
||||
* so readers do not mistake a second projection for an independent account record.
|
||||
*/
|
||||
async completeCanonical(result: CanonicalRunResult, attemptId: string): Promise<void> {
|
||||
const request = canonicalRunRequestSchema.parse(result.request);
|
||||
if (
|
||||
|
|
@ -443,6 +492,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
/** Monotonic progress within an attempt; starting a recovered attempt resets it to zero. */
|
||||
async updateProgress(
|
||||
runId: string,
|
||||
progress: number,
|
||||
|
|
@ -489,6 +539,10 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
async fail(runId: string, error: string, attemptId: string) {
|
||||
await this.ownedTransaction(runId, async client => {
|
||||
await client.query(
|
||||
|
|
@ -501,6 +555,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
/** Confirm stopped execution under the current lease; failure to write is not success. */
|
||||
async cancel(runId: string, attemptId: string) {
|
||||
await this.ownedTransaction(runId, async client => {
|
||||
const result = await client.query(
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue