docs: explain strategy replay and durable execution code

This commit is contained in:
Boki 2026-10-25 11:31:23 -04:00
parent 8587c71cf3
commit dd7ac53c51
19 changed files with 494 additions and 41 deletions

View file

@ -5,7 +5,8 @@ with a Rust native trading engine. `apps/wcag-ada` is an independent project and
the root workspace checks.
**New to the codebase? Start with [Understanding Stock Bot](docs/guide/README.md):** a
system map, a complete backtest walkthrough, and a guide to TypeScript strategies.
system map, a complete backtest walkthrough, TypeScript strategy authoring, and a
[function-by-function code tour](docs/guide/code-reading.md).
## Current research workflow

View file

@ -1,11 +1,14 @@
//! Additive, cash-funded long-only economic kernel. Not wired to a legacy
//! simulator, NAPI, paper persistence, order matching or portfolio risk.
//! Cash-funded, long-only accounting beneath the matcher and risk gate.
//!
//! One account shares cash, while each instrument holds separate owner books.
//! Fills change quantity/cost/cash; marks change valuation; fees are explicit
//! postings. No order eligibility, strategy sizing or exposure policy lives here.
//!
//! apply() stages only the affected book/owner/instrument scalars before its
//! infallible commit. Marks touch owners of that instrument, not other books.
//! Checkpoint copying and history replay occur only at explicit boundaries.
//! Invalid internal commands return errors without receipts or state changes;
//! future F04 risk rejections are different, accepted/recorded outcomes.
//! risk-policy rejections are different, accepted/recorded outcomes upstream.
use super::{
contract::*,
scalar::{Posting, ScalarError},
@ -284,6 +287,10 @@ impl Ledger {
})
}
/// Post a scoped command once. Reused command/fill IDs must retain their
/// original economic payload; exact retries return the original effects.
/// Fallible arithmetic and ownership/funding checks finish before mutation,
/// so an error leaves cash, books, revisions and receipts unchanged.
pub fn apply(&mut self, command: &EngineFinancialCommand) -> Result<ApplyOutcome, LedgerError> {
if command.session_id != self.config.session_id
|| command.account_id != self.config.account_id
@ -333,7 +340,7 @@ impl Ledger {
{
return Err(LedgerError::InvalidRiskSession);
}
// Identity only. F04 owns baseline/peak/halt policies.
// Identity only. RiskAccount owns baseline/peak/halt policies.
if self.risk_session == *risk_session {
Vec::new()
} else {
@ -370,6 +377,10 @@ impl Ledger {
});
}
/// Stage a fill in its owner's book and update account aggregates together.
/// Sells release proportional cost basis and cannot use another owner's
/// inventory. Fees reduce shared cash separately from gross realized P&L;
/// all calculations use checked fixed-decimal postings.
fn apply_fill(
&mut self,
command: &EngineFinancialCommand,
@ -671,6 +682,10 @@ impl Ledger {
}
}
/// Value actual holdings without synthesizing a liquidation trade.
/// Owner contributions plus reserve capital reconcile to account equity;
/// contributions are attribution, not separate spendable cash balances.
/// Any unmarked open holding makes valuation an error rather than zero.
pub fn valuation(&self) -> Result<LedgerValuation, LedgerError> {
if self.totals.unmarked != 0 {
return Err(LedgerError::MissingMark);
@ -715,6 +730,9 @@ impl Ledger {
}
}
/// Replay accepted receipts from genesis and compare the resulting snapshot.
/// This reconstructs indexes and validates consistency, not authenticity;
/// the durable host must retain and authenticate the checkpoint's provenance.
pub fn restore(checkpoint: LedgerCheckpoint) -> Result<Self, LedgerError> {
let mut ledger =
Self::new(checkpoint.config.clone()).map_err(|_| LedgerError::InvalidCheckpoint)?;

View file

@ -1,6 +1,9 @@
//! Additive F05 order coordinator; not connected to legacy execution.
//! F06 supplies ordered events, prior-available capacity and venue calendars.
//! No OHLC path, scheduler, strategy callback, or mutable financial escape hatch.
//! Order lifecycle shared by historical replay and quote-driven paper execution.
//!
//! The host supplies ordered events, liquidity capacity and venue sessions.
//! This module reconciles strategy intent, applies latency/price/TIF rules and
//! sends candidate fills through [`RiskAccount`]. It never calls strategies or
//! invents an intrabar OHLC path. The nested ledger is exposed read-only.
use super::{
contract::*,
ledger::Ledger,
@ -315,7 +318,8 @@ fn internal_id(value: impl Serialize) -> Id {
.expect("valid generated identity")
}
/// Pure timing predicate. F06 must separately guarantee prefix availability.
/// Pure timing predicate. The replay/paper host separately guarantees that
/// the decision used only observations available before this execution event.
pub fn eligible(submitted: &EventKey, ready_at: EventTime, event: &EventKey) -> bool {
event.phase == EventPhase::Execution && event > submitted && event.at.get() >= ready_at.get()
}
@ -474,6 +478,10 @@ impl MatchingAccount {
&self.receipts
}
/// Process one host event, checking identity, chronology and ownership first.
/// Exact retries return their original receipt with `replayed = true`;
/// callers must not publish those effects twice. An unexpected processing
/// error can terminally fail the attempt: inspect the returned status too.
pub fn apply(&mut self, command: &MatchingCommand) -> Result<MatchingOutcome, MatchingError> {
self.apply_input(&MatchingInput::Engine(command.clone()), None)
}
@ -1008,6 +1016,10 @@ impl MatchingAccount {
});
ids
}
/// Admit owners in stable lexical order against shared account resources.
/// Targets are total owner holdings, not buy/sell deltas: pending orders
/// count toward the projected holding, so repeating a target preserves an
/// already correct working order. Omitted instruments receive no update.
fn submit(
&mut self,
input: &MatchingInput,
@ -1135,6 +1147,10 @@ impl MatchingAccount {
Ok(())
}
/// Match only eligible active orders against this event's finite capacity.
/// Open events share capacity across both sides; quotes have bid/ask sizes.
/// Risk rechecks the proposed quantity and actual price before the order or
/// capacity is advanced, so an admitted order can still be rejected here.
fn execute(
&mut self,
input: &MatchingInput,
@ -1323,6 +1339,8 @@ impl MatchingAccount {
self.sessions.remove(&command.key.instrument_id);
}
MatchingCommandBody::Finish => {
// End of research cancels working orders, not holdings. Terminal
// equity therefore marks inventory without a fabricated sale/fee.
let instruments: Vec<_> = self.active.keys().cloned().collect();
for instrument in instruments {
for id in self.active_ids(&instrument) {

View file

@ -1,7 +1,17 @@
//! Canonical financial contracts, not yet connected to either legacy simulator.
//! Authoritative financial core shared by canonical research and paper execution.
//!
//! F01 defines transport and checked posting primitives. F02 owns ledger
//! transitions/idempotency; F04 owns risk; F06/F07 own replay/session state.
//! Follow one historical decision through these modules:
//! - [`replay`] publishes available bars and pauses at a strategy decision barrier.
//! - [`matching`] turns the submitted intent into orders and selects eligible fills.
//! - [`risk`] reserves cash/inventory and checks constraints again before a fill.
//! - [`ledger`] posts the accepted fill and fee to owned positions and shared cash.
//!
//! [`scalar`] supplies checked decimal arithmetic; [`contract`] defines commands
//! and effects. [`result`] and [`reporting`] read committed facts for output.
//! The native adapters in `api/replay.rs` and `api/paper.rs` expose this core to
//! TypeScript. Strategies, SQL custody and worker supervision stay outside it.
//! Historical replay supplies bar-open events; paper supplies quote events to
//! the same matcher/risk/ledger rather than a second accounting implementation.
pub mod contract;
pub mod ledger;
pub mod matching;

View file

@ -1,8 +1,8 @@
//! Internal F06 bar replay, not a public/native session or a legacy cutover.
//! Deterministic historical clock driving the canonical financial account.
//!
//! F07 must verify the frozen D01 snapshot, retain its eligibility/limitations,
//! and adapt prices to canonical decimals before calling this trusted host API.
//! This module does not authenticate provenance or repeat D01 normalization.
//! The TypeScript dataset loader verifies the retained snapshot and converts it
//! to prepared bars; `api/replay.rs` exposes this module through the native addon.
//! This module validates prepared input but does not authenticate its provenance.
//! Exact canonical prepared input/config bytes bind checkpoints independently
//! of the caller's dataset label. They are not a replacement dataset hash.
//!
@ -200,7 +200,10 @@ fn invalid(reason: &'static str) -> ReplayError {
ReplayError::InvalidInput(reason)
}
/// No mutable matcher/ledger accessor or strategy-facing future-data accessor.
/// A replay owns the event cursor, published-observation prefix and account.
/// `advance` pauses at a barrier; `submit` accepts exactly its due owners before
/// any later event can run. No mutable matcher/ledger accessor or strategy-facing
/// future-data accessor is exposed.
#[derive(Debug)]
pub struct Replay {
input: PreparedReplay,
@ -219,6 +222,8 @@ pub struct Replay {
}
impl Replay {
/// Canonicalize identity/order, validate the prepared input and build the
/// event schedule once. Construction does not publish bars or execute trades.
pub fn new(mut input: PreparedReplay, mut config: ReplayConfig) -> Result<Self, ReplayError> {
Self::canonicalize(&mut input, &mut config);
Self::validate(&input, &config)?;
@ -453,6 +458,10 @@ impl Replay {
}
Ok(())
}
/// Keep observation availability separate from physical execution time.
/// At one timestamp, observations precede the shared decision barrier,
/// then eligible opens execute, then sessions close. Stable tie-breaking
/// is economic policy: changing it can change marks, risk latches and fills.
fn events(input: &PreparedReplay, config: &ReplayConfig) -> Result<Vec<Event>, ReplayError> {
let mut events = Vec::with_capacity(input.bars.len().saturating_mul(2));
let first = config
@ -761,6 +770,8 @@ impl Replay {
}
EventBody::Open(bar_index) => {
let bar = &self.input.bars[bar_index];
// Current-bar volume is future information at its open. Use the
// latest published completed bar; no known volume means no fills.
let volume = self
.latest_observation(&bar.series_id)
.map(|b| b.volume)
@ -789,6 +800,9 @@ impl Replay {
}
Ok(())
}
/// Process at most `budget` events, yielding earlier for a decision or end.
/// An unanswered barrier is returned again without advancing. The budget
/// changes host scheduling granularity, not event order or financial policy.
pub fn advance(&mut self, budget: usize) -> Result<ReplayStep, ReplayError> {
if budget == 0 {
return Err(ReplayError::InvalidBudget);
@ -830,6 +844,9 @@ impl Replay {
},
})
}
/// Require exactly the pending owners and their shared admission revision.
/// Input validation happens before matcher mutation. A valid batch can still
/// contain risk-rejected orders; admission is not a promise of future fills.
pub fn submit(
&mut self,
mut submission: DecisionSubmission,
@ -887,8 +904,9 @@ impl Replay {
matching: self.matching.checkpoint(),
}
}
/// Deterministic fixed-decision-trace recovery. Strategy state/RNG and
/// strategy recomputation are separately owned by F07/S01.
/// Rebuild from identical prepared inputs and the recorded decision trace,
/// then compare the complete checkpoint. This recovers Rust replay state,
/// not TypeScript callback state or RNG; it does not rerun strategy logic.
pub fn restore(
input: PreparedReplay,
config: ReplayConfig,

View file

@ -1,7 +1,11 @@
//! Additive authoritative cash/risk gate. Not connected to legacy execution.
//! F05 supplies normalized orders/matching; F06 supplies the engine clock.
//! Limit crossing, TIF and execution-event eligibility are not certified here.
//! This host API is not a sandbox for arbitrary in-process Rust code.
//! Financial admission and fill-time gate between matching and the ledger.
//!
//! Orders reserve fee-inclusive cash or owner inventory before execution.
//! Actual fills recheck funding and portfolio constraints; a reservation is not
//! permission to borrow after a price gap. Marks update loss/drawdown latches.
//! The matcher owns price crossing, time-in-force and event eligibility; the
//! host owns the clock and authenticates operator actions. These Rust interfaces
//! separate responsibilities but are not an untrusted-code sandbox.
use super::{
contract::*,
ledger::*,
@ -30,7 +34,7 @@ pub enum OrderOrigin {
Target,
}
/// Already normalized by the future order coordinator. Origin is provenance,
/// Already normalized by the order coordinator. Origin is provenance,
/// never an alternate risk path. No target expansion, TIF or matching here.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
@ -196,7 +200,7 @@ pub struct RiskReceipt {
/// Journal replay validates consistency, not authenticity of genesis/history.
/// Durable provenance and operator authentication belong to the host. This is
/// risk+ledger recovery only, not F07 replay/strategy/RNG recovery.
/// risk+ledger recovery only, not replay/strategy/RNG recovery.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RiskCheckpoint {
@ -321,6 +325,10 @@ impl RiskAccount {
.checked_sub(self.reserved_cash)
.expect("cash reservations are funded")
}
/// Apply an engine command under the account's clock and identity rules.
/// A policy rejection is a recorded `RiskDisposition::Rejected`, not an
/// infrastructure error. Exact retries return their original receipt and do
/// not charge another fee, reserve more cash or move the clock.
pub fn apply(&mut self, command: &RiskCommand) -> Result<RiskOutcome, RiskError> {
self.apply_input(&RiskInput::Engine(command.clone()))
}
@ -498,6 +506,10 @@ impl RiskAccount {
Ok(None)
}
/// Buys reserve notional plus fees using fresh marks and any higher limit;
/// pending buys also consume exposure. Sells reserve only this owner's
/// uncommitted inventory, allowing reductions without passing buy-only
/// freshness and loss-halt checks. Both still obey maximum order quantity.
fn reservation(
&self,
order: &RiskOrder,
@ -558,6 +570,8 @@ impl RiskAccount {
Ok(Ok(reservation))
}
/// Loss breaches latch until an explicit reset or applicable risk-session
/// boundary; a subsequent price recovery does not itself lift the halt.
/// All operands are nonnegative representable ledger equity values, so
/// their ordered differences cannot overflow. No fallible state arithmetic
/// occurs after a ledger commit.
@ -762,6 +776,9 @@ impl RiskAccount {
let mut next = None;
let mut rejected = None;
if reservation.order.side == Side::Buy {
// Fund this fill AND the still-working remainder without
// spending other orders' reservations. A price gap may
// reject the fill and release the rest of this order.
let mark = match self
.fresh(&reservation.order.instrument_id, command.event_time)
{

View file

@ -1,3 +1,9 @@
/**
* Supervises one durable research attempt: SQL claim -> engine replay -> SQL result.
* The engine owns financial execution; this class owns attempt lifetime and reporting.
* ResearchBacktestPool supplies a separate runner/engine per concurrent trial, so these
* mutable fields never represent a shared paper account or several simultaneous runs.
*/
import { EventEmitter } from 'node:events';
import type { Logger } from '@stock-bot/services';
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
@ -32,7 +38,12 @@ function parseDurableRequest(input: unknown): DurableRequest {
: parseBacktestRequest(input);
}
/** One canonical workflow for durably admitted research jobs. */
/**
* Executes only requests already admitted to the durable run store. A run ID identifies
* the experiment trial; its attempt ID identifies the worker currently allowed to write.
* A recovered attempt replays the original inputs from the beginning. Creating a new
* reproduction run is an API operation, outside this supervisor.
*/
export class BacktestRunner extends EventEmitter {
private busy = false;
private active: CanonicalRunClaim | undefined;
@ -62,6 +73,7 @@ export class BacktestRunner extends EventEmitter {
throw new BacktestConflictError(LEGACY_EXECUTION_RETIRED);
}
/** Reserve this in-process slot before execute() reaches its first database await. */
private begin(config: CanonicalRunRequest): Promise<CanonicalRunResult> {
if (this.closing) {
throw new BacktestConflictError('Backtest runner is shutting down');
@ -77,7 +89,11 @@ export class BacktestRunner extends EventEmitter {
return this.execution;
}
/** Queue redelivery is an acknowledgement for terminal runs, never a second execution. */
/**
* Resolve queue identity into the saved request; a message never supplies executable
* configuration. Terminal redelivery only acknowledges status. The repository claim,
* not this preliminary read, arbitrates competing workers for a pending run.
*/
async runQueued(runId: string) {
const run = await this.dependencies.repository.load(runId);
if (!run) {
@ -108,6 +124,11 @@ export class BacktestRunner extends EventEmitter {
return { runId, status: result.status };
}
/**
* Keep a lease while preparing/executing/persisting, and finish only under that lease.
* Any uncertainty about renewal stops execution without writing a terminal state;
* the dispatcher later recovers expired attempts under its retry/deadline policy.
*/
private async execute(config: CanonicalRunRequest): Promise<CanonicalRunResult> {
const started = performance.now();
this.progressWrites = Promise.resolve();
@ -116,6 +137,7 @@ export class BacktestRunner extends EventEmitter {
let executionDeadline: ReturnType<typeof setTimeout> | undefined;
let deadlineFailure: Error | undefined;
let deadlineStop: Promise<void> | undefined;
// This wall-clock budget limits research work; it is not the historical replay clock.
const checkDeadline = () => {
const deadline = this.active?.executionDeadlineAt;
if (deadline !== undefined && Date.now() >= deadline) {
@ -182,6 +204,8 @@ export class BacktestRunner extends EventEmitter {
Number.isFinite(Date.parse(data.currentDate))
? data.currentDate
: undefined;
// Serialize event-driven writes and capture this attempt's identity. Completion
// drains the chain so a delayed progress write cannot follow the terminal commit.
this.progressWrites = this.progressWrites
.then(() =>
this.dependencies.repository.updateProgress(
@ -228,6 +252,7 @@ export class BacktestRunner extends EventEmitter {
);
executionDeadline.unref();
}
// Execute the repository's claimed snapshot, never a newly edited template.
const executionConfig = canonicalRunRequestSchema.parse(this.active.config);
if (
executionConfig.runId !== this.active.runId ||
@ -235,6 +260,8 @@ export class BacktestRunner extends EventEmitter {
) {
throw new Error('Canonical claim identity mismatch');
}
// Do not pile up periodic renewals when SQL is slow. Keep the pending renewal
// available to finally so it cannot leak into this runner's next attempt.
heartbeatTimer = setInterval(() => {
if (!heartbeatWork) {
heartbeatWork = heartbeat().finally(() => {
@ -261,6 +288,8 @@ export class BacktestRunner extends EventEmitter {
throw new Error('Canonical execution capabilities are unavailable');
}
const claim = this.active;
// Resolve retained data through the owning attempt. The adapter supplies its
// abort signal; neither this callback nor the worker fetches fresh provider bars.
const report = await engine.runCanonical(
executionConfig,
signal =>
@ -307,6 +336,8 @@ export class BacktestRunner extends EventEmitter {
} catch (error) {
await this.progressWrites;
let failure = this.leaseFailure ?? deadlineFailure ?? error;
// After lease loss, another worker may own the run. Even a failure/cancellation
// write would be an unauthorized state change, so leave recovery to the store.
if (this.active && !(failure instanceof BacktestLeaseLostError)) {
try {
if (failure instanceof BacktestCancelledError) {
@ -351,6 +382,7 @@ export class BacktestRunner extends EventEmitter {
}
}
/** Observer failures are diagnostics; they must not alter the execution outcome. */
private publish(event: string, value: unknown) {
try {
this.emit(event, value);
@ -365,6 +397,11 @@ export class BacktestRunner extends EventEmitter {
}
return this.active;
}
/**
* Stop the locally owned attempt and wait for its cancellation write. Remote API
* cancellation is observed separately through heartbeat's SQL cancel_requested flag.
* Once persistence starts, local stop refuses rather than racing a completed result.
*/
async stopBacktest(runId?: string) {
this.requireActive(runId);
if (this.phase === 'persisting') {
@ -389,6 +426,10 @@ export class BacktestRunner extends EventEmitter {
}
}
/**
* Refuse new work, cancel unfinished execution, and let an in-progress result commit
* finish before closing the engine. Call while the run repository is still available.
*/
async shutdown(): Promise<void> {
this.closing = true;
const execution = this.busy ? this.execution : undefined;
@ -409,6 +450,7 @@ export class BacktestRunner extends EventEmitter {
await this.dependencies.engine.shutdown();
}
}
/** Compatibility control; the engine must accept it before SQL records a pause. */
async pauseBacktest(runId?: string) {
const active = this.requireActive(runId);
await this.dependencies.engine.pauseBacktest();
@ -439,6 +481,7 @@ export class BacktestRunner extends EventEmitter {
active.attemptId
);
}
/** Local worker projection; persisted run status remains authoritative after restart. */
getStatus() {
return {
...this.dependencies.engine.getStatus(),

View file

@ -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(

View file

@ -1,4 +1,9 @@
/** Additive trusted-host F07 boundary, not an active runner or S01 strategy runtime. */
/**
* Active TypeScript-to-Rust replay boundary used by strategy-runtime and the
* isolated candidate host. This module validates native messages and drives a
* pull loop; Rust owns the clock, order matching, risk and financial state.
* Controllers receive published observations and decision views, never the handle.
*/
import { FinancialReplaySession } from '@stock-bot/engine';
import {
parseFinancialDecimal,
@ -68,7 +73,12 @@ export function marketDecimal(value: number): string {
return parseFinancialDecimal(`${negative ? '-' : ''}${plain}`);
}
/** Verify the actual payload in the worker, not an upstream supplied hash label. */
/**
* Verify the retained payload, bind execution series and translate domain names
* into the native wire format. Prices become checked decimal strings; timestamp
* and availability declarations are preserved rather than inferred here.
* The worker verifies actual content instead of trusting an upstream hash label.
*/
export function prepareReplayLoad(datasetInput: unknown, configInput: ReplayConfig) {
const dataset = validateDatasetV2(datasetInput),
manifest = dataset.manifest;
@ -145,7 +155,13 @@ function freeze<T>(value: T): T {
}
return value;
}
/** JSON transport is intentionally explicit and measured. No history/checkpoint API. */
/**
* Checked JSON facade over the NAPI FinancialReplaySession owned by this process.
* Every response is schema/identity checked. The supported StrategyContext does
* not expose this handle; trusted in-process code is not a security sandbox.
* Byte/timing counters measure boundary overhead, not financial performance.
* This research facade exposes no financial checkpoint restore operation.
*/
export class NativeReplaySession {
readonly identity: ReplayIdentity;
private readonly native: FinancialReplaySession;
@ -160,6 +176,7 @@ export class NativeReplaySession {
this.identity = freeze({ ...load.identity });
this.native = new FinancialReplaySession(JSON.stringify(load));
}
/** Advance at most this many replay events, stopping earlier for a decision or completion. */
advance(eventBudget: number): ReplayStep {
const raw = this.native.advance(JSON.stringify({ identity: this.identity, eventBudget }));
this.transport.advanceResponseBytes += Buffer.byteLength(raw);
@ -174,6 +191,7 @@ export class NativeReplaySession {
}
return freeze(result);
}
/** Submit the complete due-owner batch; admission feedback is not later fill feedback. */
submit(barrierId: string, decisions: FinancialStrategyDecision[]) {
const request = JSON.stringify({
identity: this.identity,
@ -357,6 +375,7 @@ export function runReplaySession(
}
}
/** The isolated candidate controller may await IPC; it shares the synchronous driver's loop. */
export async function runReplaySessionAsync(
session: NativeReplaySession,
controller: AsyncReplayController,
@ -387,6 +406,12 @@ type ReplayAction =
}
| { kind: 'committed'; outcome: ReplaySubmissionOutcome };
/**
* One ordered loop serves both trusted synchronous and isolated async decisions.
* Observations accumulate across progress steps until a barrier; stage produces
* all due intents, Rust admits them together, then committed confirms host state.
* Generator cleanup disposes the native session even if a callback/IPC fails.
*/
function* replaySteps(
session: NativeReplaySession,
options: ReplayOptions

View file

@ -32,6 +32,7 @@ type StrategyRun<Result extends ReplayOutput> = {
diagnostics: DeepReadonly<StrategyDiagnosticSnapshot>;
};
/** Replay failure plus the last confirmed callback diagnostics for investigation. */
export class StrategyReplayError extends Error {
constructor(
cause: unknown,
@ -43,6 +44,16 @@ export class StrategyReplayError extends Error {
}
/* eslint-disable no-redeclare -- Keep selected native result formats precise. */
/**
* Run trusted synchronous programs against a newly constructed Rust session.
* The shared replay driver advances to a barrier, asks StrategyController for
* decisions, submits them together, then confirms callback state on admission.
*
* Prepared market input is copied into Rust before callbacks can run. Result
* format selects trace, projection or report output, not different economics.
* Replay failures carry confirmed diagnostics; retries start from original inputs
* and initial program state, not from those diagnostic snapshots.
*/
export function runStrategyReplay(
load: ReturnType<typeof prepareReplayLoad>,
programs: readonly StrategyProgram[],

View file

@ -1,4 +1,8 @@
/** Trusted synchronous strategy author contract. No execution or native capabilities. */
/**
* Strategy-facing types for synchronous decisions on the canonical engine.
* StrategyController supplies these values; the native replay host owns time,
* order admission and accounting. Implementations return intent, not broker calls.
*/
import type { DecisionIdentity, FinancialStrategyIntent } from '@stock-bot/types';
import type {
DecisionContext,
@ -13,7 +17,11 @@ export type DeepReadonly<T> = T extends string | number | boolean | null | undef
? { readonly [Key in keyof T]: DeepReadonly<T[Key]> }
: T;
/** Copied native admission outcomes, not a later fill-event stream. */
/**
* Order outcomes copied when the previous decision batch was admitted.
* These are not later fill notifications: inspect current positions and the
* account view to learn what has executed since that decision.
*/
export interface StrategyAdmissionFeedback {
decision: DecisionIdentity;
revision: number;
@ -25,23 +33,35 @@ export interface StrategyAdmissionFeedback {
}[];
}
/** Read-only input to one owner at an engine-defined decision barrier. */
export interface StrategyContext<State = unknown> {
readonly ownerId: string;
readonly strategyId: string;
readonly strategyVersion: string;
/** Monotonic per-owner identity; advances after confirmed batch admission. */
readonly decisionSequence: number;
/** Engine availability time in milliseconds, never the host's wall clock. */
readonly now: number;
/** Due owners, account revision and freshness of the required input series. */
readonly barrier: DeepReadonly<DecisionContext['barrier']>;
/** The exact same read-only account view is shared by all due callbacks. */
readonly portfolio: DeepReadonly<DecisionContext['view']>;
/** Already filtered to this owner; portfolio contains the account-wide view. */
readonly positions: DeepReadonly<DecisionContext['view']['portfolio']['positions']>;
/** Published since this owner's last callback, buffered across slower cadences. */
readonly observations: readonly DeepReadonly<PublishedObservation>[];
readonly previousAdmission: DeepReadonly<StrategyAdmissionFeedback> | null;
/** Last confirmed JSON state, or initialState before the first decision. */
readonly state: DeepReadonly<State>;
/** Valid only during this synchronous callback; never use Math.random for decisions. */
readonly random: () => number;
}
/**
* One strategy instance bound to one configured financial owner and intent mode.
* Keep decision history in explicit state so a fresh attempt can recompute it.
* Native risk rules still apply to every returned intent.
*/
export interface StrategyProgram<State = unknown> {
readonly ownerId: string;
readonly strategyId: string;
@ -50,12 +70,19 @@ export interface StrategyProgram<State = unknown> {
readonly seed: number;
/** Finite plain JSON, checked and detached before the native attempt starts. */
readonly initialState: State;
/**
* Propose the next JSON state and target holdings or explicit order actions.
* A target quantity is this owner's desired total, not an incremental buy.
* Return synchronously: state and seeded RNG advances become confirmed only
* after Rust acknowledges the whole decision batch, including any rejections.
*/
decide(context: StrategyContext<State>): {
nextState: State;
intent: FinancialStrategyIntent;
};
}
/** Confirmed callback state for inspection; it does not contain the native ledger. */
export interface StrategyDiagnostic {
ownerId: string;
strategyId: string;

View file

@ -29,6 +29,12 @@ interface Slot {
diagnostic: DeepReadonly<StrategyDiagnostic>;
pendingObservations: PublishedObservation[];
}
/**
* Coordinates a two-step callback transition: stage all due owners against the
* same financial view, then confirm their state after native batch admission.
* This owns strategy state and RNG diagnostics, never cash or order matching.
* A failed attempt discards the controller; snapshots are not restart tokens.
*/
export class StrategyController {
private slots: Map<string, Slot>;
private committedBarriers = 0;
@ -44,6 +50,7 @@ export class StrategyController {
}[];
} | null = null;
/** Bind each configured owner exactly once and detach its initial JSON state. */
constructor(
private readonly identity: ReplayIdentity,
programs: readonly StrategyProgram[],
@ -80,6 +87,7 @@ export class StrategyController {
}
}
/** Expose confirmed transitions in stable owner order, excluding staged work. */
snapshot(): DeepReadonly<StrategyDiagnosticSnapshot> {
return freeze({
version: 1,
@ -94,10 +102,18 @@ export class StrategyController {
});
}
/**
* Buffer the replay driver's newly published observations for every owner,
* then evaluate only owners due at this barrier. Return one complete batch
* for native submission; callback state and RNG changes remain proposals.
* Any error aborts the attempt rather than retrying this mutated controller.
*/
stage(context: DecisionContext, observations: readonly PublishedObservation[]) {
if (this.staged) {
throw new Error('Previous strategy barrier has not committed');
}
// The cumulative count detects dropped/repeated input at the host boundary;
// available_at prevents exposing observations ahead of this engine barrier.
this.observed = increment(this.observed, observations.length);
const due = new Set(context.barrier.owner_ids);
if (
@ -135,6 +151,11 @@ export class StrategyController {
return staged.owners.map(owner => owner.decision);
}
/**
* Confirm the staged callback transitions only for the expected native revision.
* Order rejection is valid feedback; acknowledgement does not imply a fill.
* An unexpected or replayed acknowledgement leaves confirmed state unchanged.
*/
committed(outcome: ReplaySubmissionOutcome): void {
const staged = this.staged;
if (

View file

@ -1,6 +1,11 @@
import type { Logger, PostgresClient, Queue } from '@stock-bot/services';
/** PostgreSQL is the source of truth; Redis jobs are repeatable delivery notifications. */
/**
* Bridges committed backtest_dispatch rows to BullMQ and recovers expired leases.
* PostgreSQL is the source of truth; Redis jobs are repeatable notifications.
* Duplicate delivery is safe because BacktestRunner must claim the SQL run before
* executing it. Queue retries and durable attempt limits are separate mechanisms.
*/
export class BacktestDispatcher {
private timer?: ReturnType<typeof setInterval>;
private inFlight?: Promise<void>;
@ -27,6 +32,7 @@ export class BacktestDispatcher {
);
}
/** Timer/manual ticks share one in-flight pass; a slow publish cannot overlap itself. */
tick(): Promise<void> {
if (this.closing) {
return Promise.resolve();
@ -44,6 +50,11 @@ export class BacktestDispatcher {
await this.inFlight;
}
/**
* Recover SQL ownership first, reserve due notifications second, publish last.
* next_publish_at is a retry delay, not a delivery acknowledgement: a crash
* after reservation leaves a durable intent that becomes due again.
*/
private async dispatch() {
// Recovery is independent of Redis availability. Every terminal write fences the old owner.
await this.postgres.transaction(async client => {

View file

@ -158,6 +158,12 @@ export class BacktestRetentionError extends Error {
}
}
/**
* Application service for editable templates and immutable run inputs/results.
* Submission writes a PostgreSQL outbox row for BacktestDispatcher; execution
* belongs to the orchestrator. Historical result readers remain available even
* though new submissions require the canonical Rust research path.
*/
export class BacktestServiceV2 {
private container: IServiceContainer & { postgres: NonNullable<IServiceContainer['postgres']> };
private wsHandler: WebSocketHandler | null = null;
@ -394,7 +400,12 @@ export class BacktestServiceV2 {
});
}
// Run operations
/**
* Admit one logical run, saving its request and dispatch intent atomically.
* A principal/key identifies the submission, not the template's current contents:
* the same retry returns the original run even after a template edit. Conflicting
* reuse fails. No queue operation occurs inside this transaction.
*/
async createRun(request: RunRequest, submission?: RunSubmission): Promise<Run> {
const runId = uuidv4();
const multiplier = request.speedMultiplier ?? null;
@ -561,6 +572,11 @@ export class BacktestServiceV2 {
});
}
/**
* Create a new run from original retained inputs, not today's editable template.
* Current review and retained-build checks still apply. Only execution/account
* identity and the current review reference are rebound; economics stay pinned.
*/
async reproduceRun(originalRunId: string, submission: RunSubmission): Promise<Run> {
if (
!submission ||
@ -819,7 +835,12 @@ export class BacktestServiceV2 {
// The runner, not the API client, commits acknowledged state changes.
}
// Get run results
/**
* Read saved results and verify canonical provenance and derived analytics
* against the frozen request. Recomputing statistics checks integrity; it does
* not simulate fills again. Missing canonical data must not fall back to a
* legacy result projection, which has different financial semantics.
*/
async getRunResults(
runId: string,
database: BacktestResultQuery = this.container.postgres
@ -883,6 +904,7 @@ export class BacktestServiceV2 {
return mapStoredBacktestResult(row);
}
/** Preview admission for the UI without saving a run; submission must recheck it. */
async canonicalCapability(id: string): Promise<CanonicalRunCapability> {
try {
const execution = await this.container.postgres.transaction(async client => {

View file

@ -1,3 +1,10 @@
/**
* Converts editable workbench choices into a fully bound canonical request.
* Admission validates retained data/code and freezes financial policies/build
* identity; it neither runs a strategy nor writes the run/dispatch rows.
* Submission services own persistence; previews can discard the returned request.
* The worker verifies inputs again before execution.
*/
import { randomUUID } from 'node:crypto';
import type { PoolClient } from 'pg';
import type { IServiceContainer } from '@stock-bot/services';
@ -57,6 +64,10 @@ export function canonicalDatasetUnavailableReason(dataset: HistoricalDatasetV2):
return null;
}
/**
* Revalidate the stored payload and hash before trusting a catalog selection.
* A syntactically valid hash or manifest alone is not execution eligibility.
*/
export async function readCanonicalDataset(
database: DatasetCatalogQuery,
hash: unknown
@ -112,7 +123,11 @@ export async function canonicalDatasetEntry(
}
}
/** Separate v2 boundary: never round exchange-session times through the v1 daily parser. */
/**
* Require template symbols, interval and trading bounds to match retained input
* exactly. Warmup remains part of that dataset rather than an implicit new fetch.
* This v2 boundary avoids rounding session timestamps through the v1 daily parser.
*/
export async function validateCanonicalSetup(
database: DatasetCatalogQuery,
template: CanonicalTemplate
@ -157,7 +172,17 @@ export async function validateCanonicalSetup(
return { settings, dataset, execution, series, initial };
}
/** Called under the backtest lock; this also serializes with family review/archive. */
/**
* Build the immutable request while the caller holds the backtest row lock.
* Family locks also serialize admission with review/archive changes. Candidate
* overrides validate both the granted baseline and the replacement; catalog
* approval never turns candidate code into trusted research callbacks.
*
* The returned request pins a retained package, dataset hash, execution profile,
* Rust/worker build and policies. Account identity derives from runId; preview
* callers may use a placeholder and discard the request. Execution callers must
* persist the request and dispatch intent together, using a new research run ID.
*/
export async function admitCanonicalRequest(
client: PoolClient,
container: IServiceContainer,

View file

@ -1,3 +1,8 @@
/**
* Browser state for an editable backtest template and one selected durable run.
* The API owns execution status/results; this hook owns request lifetimes and
* ignores responses belonging to a previous page or run selection.
*/
import { useCallback, useEffect, useRef, useState } from 'react';
import type { CanonicalRunCapability } from '@stock-bot/stock-config/canonical-research';
import { catalogExecutionReason } from '@/features/strategies/components/StrategySelection';
@ -9,6 +14,7 @@ import type {
Run,
} from '../services/backtestApiV2';
/** Object identity is the ownership token for one status/result request chain. */
interface RunSelection {
id: string;
backtestId: string | null;
@ -23,6 +29,11 @@ const isActive = (run: Run) => ['pending', 'running', 'paused'].includes(run.sta
const messageOf = (error: unknown, fallback: string) =>
error instanceof Error ? error.message : fallback;
/**
* Connects BacktestDetailPageV2 to backtestApiV2. Template loading, run monitoring
* and submission have separate state because each can fail independently.
* WebSocket notifications call refreshRun; they never replace the saved result.
*/
export function useBacktestV2() {
const [backtest, setBacktest] = useState<Backtest | null>(null);
const [runs, setRuns] = useState<Run[]>([]);
@ -35,6 +46,9 @@ export function useBacktestV2() {
const [submissionError, setSubmissionError] = useState<string | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const [cancelRequested, setCancelRequested] = useState(false);
// Generations reject late responses even when an earlier request cannot be
// aborted. The selection generation also prevents submission from taking the
// user away from a different run they selected while admission was pending.
const mounted = useRef(true);
const backtestGeneration = useRef(0);
const loadedBacktestId = useRef<string | null>(null);
@ -92,6 +106,8 @@ export function useBacktestV2() {
});
return () => controller.abort();
}, [backtest, catalog, capabilityRetry]);
// Eligibility belongs to this exact loaded definition, not just its ID: an
// edit must invalidate an earlier successful capability check.
const currentCapability =
capabilityState?.definition === backtest && capabilityState?.retry === capabilityRetry
? capabilityState
@ -111,6 +127,7 @@ export function useBacktestV2() {
[]
);
/** Stop browser observation only; cancelling server execution is cancelRun's job. */
const stopMonitoring = useCallback(() => {
selectionGeneration.current++;
const selected = selection.current;
@ -228,6 +245,7 @@ export function useBacktestV2() {
[refreshSelection]
);
/** Reopening a run reads its recorded state; it never submits another backtest. */
const selectRun = useCallback(
(runId: string | undefined) => {
if (
@ -419,6 +437,12 @@ export function useBacktestV2() {
}
}, []);
/**
* Retain the same key/body after an ambiguous response so Retry can recover
* the accepted run. This receipt is in memory for this mounted hook; it is not
* a persistent browser recovery journal. New admissions recheck eligibility;
* receipt retries recover the original run before current eligibility checks.
*/
const createRun = useCallback(
async (_speedMultiplier: number | null = null) => {
if (!backtest || backtest.id !== loadedBacktestId.current || submission.current?.pending) {
@ -481,6 +505,7 @@ export function useBacktestV2() {
[backtest, catalog, canonicalCapability, capabilityError]
);
/** Record a cancellation request, then monitor until the server reports a terminal state. */
const cancelRun = useCallback(async () => {
const selected = selection.current;
if (

View file

@ -17,9 +17,12 @@ In this repository, **canonical** means the supported, authoritative Rust financ
| 1. [System map](system-map.md) | What are the applications, libraries and databases, and how are they connected? |
| 2. [Follow one backtest](backtest-walkthrough.md) | What happens between clicking Run and seeing a trade, result or failure? |
| 3. [Understand and write a strategy](strategy-development.md) | Where does my trading logic go, what can it access, and what does it return? |
| 4. [Read the implementation](code-reading.md) | Which functions call each other, who owns each piece of state, and why are the checks there? |
Read the diagrams and examples first. Follow the source links when a component becomes relevant; you do not need to understand every library before writing a strategy.
For code-level detail, the fourth guide links the documented callback contracts, replay loop, Rust financial methods, durable runner/repository and browser state hook. Their source comments explain invariants and failure behavior beside the implementation.
## A first tour through the product
When your local application is configured and running:

103
docs/guide/code-reading.md Normal file
View file

@ -0,0 +1,103 @@
# Reading the implementation
[Guide home](README.md) · [System map](system-map.md) · [Backtest walkthrough](backtest-walkthrough.md) · [Strategy authoring](strategy-development.md)
This guide follows **functions and state**, rather than application boxes. The linked TypeScript files now have explanatory TSDoc comments, and the Rust financial modules have module and method documentation. Read these beside the implementation; you can hover documented symbols in your editor.
## 1. Begin with the decision contract
Open [canonical-strategy.ts](../../apps/stock/orchestrator/src/contracts/canonical-strategy.ts). `StrategyProgram` describes the object a strategy factory returns. Its `decide(context)` callback returns two things:
- `nextState`: what the strategy wants to remember for its next decision.
- `intent`: what exposure or orders it wants the financial engine to consider.
Neither is a database write or a completed trade. `StrategyContext` is a read-only view. `positions` contains this owner's holdings; `portfolio.portfolio.positions` contains holdings across the account. `observations` contains the published input accumulated since this owner last ran. Keep any longer feature history in explicit state.
Then read [canonical-sma.ts](../../apps/stock/orchestrator/src/strategies/canonical-sma.ts). Follow `createSmaStrategy()` into `decide()`: validate/restore state → consume fresh observations → calculate crossover → return a target. The resulting quantity is a total desired holding. Rust decides the difference between that target, current holdings and working orders.
**A useful distinction:** a rejected order can still be a successfully processed strategy decision. The callback's state and random cursor advance when the native admission response is confirmed, even if risk rejected the requested order. Waiting for a fill before committing all strategy state would have different semantics.
## 2. Follow one callback into Rust
Read these symbols in order:
| Symbol | What to trace in its body |
| --- | --- |
| [`prepareReplayLoad()`](../../apps/stock/orchestrator/src/backtest/native-replay.ts) | Revalidates dataset bytes, matches execution series, and converts prices and names into the native wire format. It does not calculate strategy features. |
| [`runStrategyReplay()`](../../apps/stock/orchestrator/src/backtest/strategy-runtime.ts) | Creates the controller and native session for a fresh attempt. Success includes diagnostics; failure retains the last confirmed diagnostics. |
| [`NativeReplaySession.advance()`](../../apps/stock/orchestrator/src/backtest/native-replay.ts) | Calls the NAPI addon and validates the returned identity and schema. `eventBudget` limits work per call, not the number of bars in the experiment. |
| [`replaySteps()`](../../apps/stock/orchestrator/src/backtest/native-replay.ts) | Accumulates observations until Rust requests a decision. Its generator alternates between staging decisions and confirming admission; both synchronous and isolated async drivers use it. |
| [`StrategyController.stage()`](../../apps/stock/orchestrator/src/strategies/strategy-controller.ts) | Buffers inputs per owner and calls only owners due at the barrier, all against the same financial view. The next callback states are still proposals. |
| [`stageStrategyDecision()`](../../apps/stock/orchestrator/src/strategies/strategy-decision.ts) | Constructs the owner-specific context, provides the seeded RNG, rejects async/lossy state, and stamps the decision identity. |
| [`NativeReplaySession.submit()`](../../apps/stock/orchestrator/src/backtest/native-replay.ts) | Sends the complete batch to Rust and reads admission feedback. Later eligible market events determine actual fills. |
| [`StrategyController.committed()`](../../apps/stock/orchestrator/src/strategies/strategy-controller.ts) | Checks revision and feedback for every staged owner before replacing confirmed state. Clears consumed input for owners that ran. |
A **barrier** is a point where Rust pauses historical advancement so all due strategies can decide from one account view. A faster callback must not get a newer view just because another callback already returned. A **revision** identifies which account/admission state a message belongs to; it helps reject stale or mismatched responses.
The research diagnostic snapshot is deliberately not a resume token. It lacks the complete financial state. An interrupted durable research attempt starts from the retained original inputs with a fresh native session. Paper recovery has its own durable account/checkpoint protocol.
## 3. Read the financial modules as a chain of responsibilities
Start at [financial/mod.rs](../../apps/stock/engine/src/financial/mod.rs), then:
| Module and symbols | What they own |
| --- | --- |
| [`Replay::events`, `advance`, `submit`](../../apps/stock/engine/src/financial/replay.rs) | Schedule available observations and physical execution events, stop for decisions, and require exactly the pending owners. Look at event phases and tie-breaking before changing timing. |
| [`MatchingAccount::apply`, `submit`, `execute`](../../apps/stock/engine/src/financial/matching.rs) | Reconcile targets/orders, preserve correctly sized pending orders, apply execution eligibility and distribute finite fill capacity. |
| [`RiskAccount::apply`, `reservation`](../../apps/stock/engine/src/financial/risk.rs) | Reserve cash or owner inventory and enforce financial constraints. An affordable order at submission can become unaffordable at a later gap price. |
| [`Ledger::apply`, `apply_fill`, `valuation`](../../apps/stock/engine/src/financial/ledger.rs) | Post actual fills/fees, maintain owner cost basis and shared cash, and value remaining inventory. Checked decimal arithmetic lives in [scalar.rs](../../apps/stock/engine/src/financial/scalar.rs). |
Two details explain otherwise surprising results:
- At a bar's open, that bar's completed volume is still future information. Replay uses the latest published completed bar's volume for capacity. No known volume means no fill capacity.
- Ending a replay cancels working orders and values existing holdings. It does not invent a liquidation trade or a closing fee. Inspect positions as well as closed trades.
The financial interfaces have command identities and receipts for retry handling. An exact retry may return old effects marked as replayed; callers must not publish them twice. A receipt is not the same thing as a strategy decision, a durable run or a worker attempt.
## 4. Understand how execution survives outside one process
The native session above is disposable. The durable workflow around it uses SQL state:
1. [`BacktestServiceV2.createRun()`](../../apps/stock/web-api/src/services/backtest-v2.service.ts) locks the saved template, admits its inputs and inserts both the frozen run request and `backtest_dispatch` row. A submission key recovers the same run after an uncertain HTTP response.
2. [`admitCanonicalRequest()`](../../apps/stock/web-api/src/services/canonical-research.service.ts) resolves the retained version/dataset/build and constructs policies and a research account identity. It returns a request; it does not enqueue or simulate it. `canonicalCapability()` uses admission as a preview; new submissions check again, while receipt retries recover their already admitted run.
3. [`BacktestDispatcher.dispatch()`](../../apps/stock/web-api/src/services/BacktestDispatcher.ts) first recovers expired leases, then reserves due outbox rows in SQL, then publishes run IDs to Redis outside the transaction. A failed publish delays delivery without deleting the saved intent.
4. [`BacktestRunner.runQueued()` and `execute()`](../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts) load the saved request and claim an attempt. `execute()` coordinates heartbeats, progress, cancellation, worker execution and completion. It never edits a paper account.
5. [`PostgresBacktestRunRepository.startCanonical()`](../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts) gives the worker a fresh attempt ID and lease. `loadCanonicalDataset()` checks the bound bytes under that ownership. `completeCanonical()` commits the validated result and completed status together.
The worker's **attempt ID is a fencing token**: SQL compares it with the current owner before allowing a write. A stopped worker that wakes up late cannot overwrite a replacement's result. The lease also has to be unexpired according to database time. A local Boolean such as `busy` only protects one runner instance; it cannot replace those database checks.
`BacktestRunner.execute()` has three phases: preparing, executing and persisting. Read its `try/catch/finally` as carefully as its success path. Lease uncertainty stops the attempt; it does not authorize the old worker to mark the run failed. Progress writes are drained before completion, and cleanup waits for heartbeat work before reusing the runner.
The adapter/process boundary is [RustBacktestAdapter.runCanonical()](../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts) → [NativeBacktestWorker.execute()](../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts) → [native-worker.ts](../../apps/stock/orchestrator/src/backtest/native-worker.ts). The parent can terminate a child that is stuck in native computation. The child still uses the same Rust engine; spawning a process does not introduce another simulator.
## 5. Trace the browser state separately
Open [useBacktestV2.ts](../../apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts), then its caller [BacktestDetailPageV2.tsx](../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx).
- `loadBacktest()` loads the editable definition and run list. Generation counters discard late replies after navigation.
- `selectRun()` and `refreshSelection()` own one status → result request chain. Polls and WebSocket refresh notifications converge on that chain.
- `stopMonitoring()` aborts browser reads. `cancelRun()` requests server cancellation. Leaving the page is not cancelling the experiment.
- `createRun()` keeps an in-memory submission key/body after an uncertain response. A repeated click can recover the same accepted run; this is not a persistent browser journal.
- `runResults` comes from the saved result API. Charts render those facts; they do not reconstruct cash or fills from a second model.
The state names reflect different lifetimes: **template**, **selected run**, **submission**, and **result**. Combining them into one loading/error flag would make navigation and retry behavior harder to represent correctly.
## 6. Where a change belongs
| You want to change… | Start here |
| --- | --- |
| A signal, regime filter or entry/exit decision | Canonical strategy and its parameter/state contracts; see the [strategy guide](strategy-development.md). |
| An indicator used in several places | [libs/calculations](../../libs/calculations/README.md), with its warmup/alignment semantics and fixtures. |
| Which retained inputs can run | `validateCanonicalSetup()` / `admitCanonicalRequest()` and shared [canonical-research contracts](../../apps/stock/config/src/contracts/canonical-research.ts). |
| Fill timing, fees, funding or position accounting | The corresponding Rust financial module and its existing regression tests. |
| Worker retry, cancellation or result persistence | Dispatcher, runner and repository; keep attempt ownership checks intact. |
| A run display, selection or loading/error state | Backtest feature components, hook and typed API client. |
Read tests as concrete examples of the contracts:
- [strategy-runtime.test.ts](../../test/integration/strategy-runtime.test.ts): owner isolation, buffered cadence, rejected intents, unconfirmed state and future-data boundaries.
- [canonical-sma.test.ts](../../test/integration/canonical-sma.test.ts): hand-checkable signals, next-open fills and money.
- [canonical-durable-runner.test.ts](../../test/integration/canonical-durable-runner.test.ts): cancellation, lease loss and retired execution paths.
- Rust [replay](../../apps/stock/engine/src/financial/replay_tests.rs), [matching](../../apps/stock/engine/src/financial/matching_tests.rs), [risk](../../apps/stock/engine/src/financial/risk_tests.rs) and [ledger](../../apps/stock/engine/src/financial/ledger_tests.rs) tests: the economic invariants behind each layer.
For a first reading exercise, follow a request for ten shares through `stage()` → `submit()` → a later `execute()` → `apply_fill()`. At each step ask: **is this proposed state, accepted state, or persisted state?** Those boundaries explain most of the checks in this execution path.

View file

@ -23,7 +23,7 @@ Start with these canonical files; older classes under `strategies/builtin/` belo
| --- | --- |
| `now`, `barrier` | Engine time and a synchronized decision point; each required input has an availability status. |
| `observations` | Observations published since this owner last ran, including buffered input for slower decision cadences. `event_time` describes the market event; `available_at` says when the strategy may know it. This is not the entire historical dataset. |
| `positions` | Positions across owners. Filter by **both** `ownerId` and `instrumentId` when reading your strategy's holding. |
| `positions` | Positions already filtered to this strategy's `ownerId`. Select the relevant `instrumentId` when reading a holding. Account-wide positions are in `portfolio.portfolio.positions`. |
| `portfolio` | Read-only native account view. A strategy cannot alter cash by changing this object. |
| `state` | Your previously confirmed plain JSON state. Return a replacement in `nextState`. |
| `previousAdmission` | The previous decision's admission outcome, not a stream of subsequent fills. Read current positions for current holdings. |