feat(research): cut over canonical runtime and enforce agent budgets
This commit is contained in:
parent
ab08db82fd
commit
bbf0dd4453
103 changed files with 6138 additions and 3112 deletions
|
|
@ -1,39 +1,24 @@
|
|||
/** Trusted synchronous programs on the canonical financial engine. Fresh
|
||||
* attempts recompute from original inputs; diagnostics are not resume tokens. */
|
||||
import type { FinancialStrategyDecision } from '@stock-bot/types';
|
||||
import type {
|
||||
DeepReadonly,
|
||||
StrategyAdmissionFeedback,
|
||||
StrategyDiagnostic,
|
||||
StrategyDiagnosticSnapshot,
|
||||
StrategyProgram,
|
||||
} from '../contracts/canonical-strategy';
|
||||
import {
|
||||
nativeAdmissionOrders,
|
||||
replayConfigSchema,
|
||||
replayIdentitySchema,
|
||||
type DecisionContext,
|
||||
type PublishedObservation,
|
||||
type ReplayIdentity,
|
||||
type ReplayOutput,
|
||||
type ReplayProjectionResult,
|
||||
type ReplayReportResult,
|
||||
type ReplayResult,
|
||||
type ReplaySubmissionOutcome,
|
||||
} from '../contracts/native-replay';
|
||||
import {
|
||||
freeze,
|
||||
increment,
|
||||
metadataSchema,
|
||||
stageStrategyDecision,
|
||||
stateCopy,
|
||||
type Metadata,
|
||||
} from '../strategies/strategy-decision';
|
||||
import { StrategyController } from '../strategies/strategy-controller';
|
||||
import { freeze } from '../strategies/strategy-decision';
|
||||
import {
|
||||
NativeReplaySession,
|
||||
runReplaySession,
|
||||
type prepareReplayLoad,
|
||||
type ReplayController,
|
||||
type ReplayMetrics,
|
||||
type ReplayOptions,
|
||||
} from './native-replay';
|
||||
|
|
@ -57,169 +42,6 @@ export class StrategyReplayError extends Error {
|
|||
}
|
||||
}
|
||||
|
||||
interface Slot {
|
||||
program: Metadata & { decide: StrategyProgram['decide'] };
|
||||
diagnostic: DeepReadonly<StrategyDiagnostic>;
|
||||
pendingObservations: PublishedObservation[];
|
||||
}
|
||||
class StrategyController implements ReplayController {
|
||||
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;
|
||||
|
||||
constructor(
|
||||
private readonly identity: ReplayIdentity,
|
||||
programs: readonly StrategyProgram[],
|
||||
config: ReturnType<typeof replayConfigSchema.parse>
|
||||
) {
|
||||
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({
|
||||
ownerId,
|
||||
strategyId,
|
||||
strategyVersion,
|
||||
nextDecisionSequence: 0,
|
||||
state: stateCopy(program.initialState),
|
||||
rng: { algorithm: 'lcg32-v1' as const, seed, state: seed, draws: 0 },
|
||||
observationCount: 0,
|
||||
previousAdmission: null,
|
||||
});
|
||||
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');
|
||||
}
|
||||
}
|
||||
|
||||
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),
|
||||
});
|
||||
}
|
||||
|
||||
stage(context: DecisionContext, observations: readonly PublishedObservation[]) {
|
||||
if (this.staged) {
|
||||
throw new Error('Previous strategy barrier has not committed');
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
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: StrategyAdmissionFeedback = {
|
||||
decision: owner.decision.decision,
|
||||
revision: outcome.revision,
|
||||
orders: orders
|
||||
.filter(order => order.order.decision.ownerId === owner.ownerId)
|
||||
.map(order => ({
|
||||
orderId: order.order.orderId,
|
||||
instrumentId: order.order.instrumentId,
|
||||
decision: order.order.decision,
|
||||
status: order.status,
|
||||
})),
|
||||
};
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/* eslint-disable no-redeclare -- Keep selected native result formats precise. */
|
||||
export function runStrategyReplay(
|
||||
load: ReturnType<typeof prepareReplayLoad>,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue