stock-bot/apps/stock/orchestrator/src/strategies/strategy-controller.ts
Boki 4cd6038063 refactor: pre-M0 cleanup, core library hardening, and isolated dev/QA Docker stack
- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched)
- Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations()
- Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation
- Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims
- Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution
- Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
2026-11-27 00:11:50 -05:00

193 lines
7 KiB
TypeScript

/** Pure decision staging shared by trusted and OS-isolated strategy hosts.
* This module never imports a native engine, dataset loader or service container. */
import type { FinancialStrategyDecision } from '@stock-bot/types';
import type {
DeepReadonly,
StrategyDiagnostic,
StrategyDiagnosticSnapshot,
StrategyProgram,
} from '@stock-bot/research/strategy-api';
import {
nativeAdmissionOrders,
type DecisionContext,
type PublishedObservation,
type ReplayIdentity,
type ReplaySubmissionOutcome,
} from '@stock-bot/stock-config/canonical-replay';
import {
freeze,
increment,
initialStrategyDiagnostic,
metadataSchema,
ownerAdmissionFeedback,
stageStrategyDecision,
type Metadata,
} from '../strategies/strategy-decision';
interface Slot {
program: Metadata & { decide: StrategyProgram['decide'] };
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;
private lastBarrierId: string | null = null;
private observed = 0;
private staged: {
barrierId: string;
expectedRevision: number;
owners: {
ownerId: string;
diagnostic: StrategyDiagnostic;
decision: FinancialStrategyDecision;
}[];
} | null = null;
/** Bind each configured owner exactly once and detach its initial JSON state. */
constructor(
private readonly identity: ReplayIdentity,
programs: readonly StrategyProgram[],
config: { matching: { owners: { ownerId: string; mode: 'Target' | 'Orders' }[] } }
) {
this.slots = new Map(
programs.map(program => {
const { ownerId, strategyId, strategyVersion, mode, seed } = program;
const metadata = metadataSchema.parse({ ownerId, strategyId, strategyVersion, mode, seed });
const decide = program.decide;
if (typeof decide !== 'function') {
throw new Error('Strategy decide must be synchronous callable code');
}
const diagnostic = freeze(initialStrategyDiagnostic(metadata, program.initialState));
return [ownerId, { program: { ...metadata, decide }, diagnostic, pendingObservations: [] }];
})
);
const owners = config.matching.owners;
if (
this.slots.size !== programs.length ||
this.slots.size !== owners.length ||
owners.some(owner => this.slots.get(owner.ownerId)?.program.mode !== owner.mode.toLowerCase())
) {
throw new Error('Programs must exactly match configured owners and modes');
}
}
/** Expose confirmed transitions in stable owner order, excluding staged work. */
snapshot(): DeepReadonly<StrategyDiagnosticSnapshot> {
return freeze({
version: 1,
identity: this.identity,
committedBarriers: this.committedBarriers,
lastBarrierId: this.lastBarrierId,
strategies: [...this.slots.values()]
.sort((a, b) =>
a.program.ownerId < b.program.ownerId ? -1 : a.program.ownerId > b.program.ownerId ? 1 : 0
)
.map(slot => slot.diagnostic),
});
}
/**
* 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 (
this.observed !== context.barrier.observation_count ||
due.size !== context.barrier.owner_ids.length ||
[...due].some(owner => !this.slots.has(owner)) ||
observations.some(observation => observation.available_at > context.barrier.at)
) {
throw new Error('Strategy barrier observation or owner mismatch');
}
const staged: NonNullable<StrategyController['staged']> = {
barrierId: context.barrier.barrier_id,
expectedRevision: increment(context.barrier.revision),
owners: [],
};
for (const slot of this.slots.values()) {
// Other owners may have slower cadence. Do not discard their warmup/prefix.
for (const observation of observations) {
slot.pendingObservations.push(observation);
}
if (!due.has(slot.program.ownerId)) {
continue;
}
staged.owners.push(
stageStrategyDecision(
this.identity.sessionId,
slot.program,
slot.diagnostic,
slot.pendingObservations,
context
)
);
}
this.staged = staged;
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 (
!staged ||
outcome.replayed ||
outcome.status !== 'Running' ||
outcome.revision !== staged.expectedRevision
) {
throw new Error('Unexpected strategy admission acknowledgement');
}
const orders = nativeAdmissionOrders(outcome.effects);
if (
orders.some(
order => !staged.owners.some(owner => owner.ownerId === order.order.decision.ownerId)
)
) {
throw new Error('Admission feedback belongs to an owner outside the barrier');
}
const nextCount = increment(this.committedBarriers);
const next = new Map(this.slots);
// Parse/detach ALL feedback before swapping any committed slot. Even an
// ambiguous/malformed acknowledgement leaves diagnostics at the old barrier.
for (const owner of staged.owners) {
const slot = this.slots.get(owner.ownerId);
if (!slot) {
throw new Error('Staged strategy owner is missing');
}
const previousAdmission = ownerAdmissionFeedback(
owner.decision.decision,
outcome.revision,
orders
);
next.set(owner.ownerId, {
program: slot.program,
diagnostic: freeze({ ...owner.diagnostic, previousAdmission }),
pendingObservations: [],
});
}
this.slots = next;
this.committedBarriers = nextCount;
this.lastBarrierId = staged.barrierId;
this.staged = null;
}
}