feat(paper): gate canonical execution on durable feed readiness
This commit is contained in:
parent
c01e96e4dd
commit
75abae2cfc
24 changed files with 3720 additions and 66 deletions
|
|
@ -27,6 +27,7 @@ import {
|
|||
type CanonicalExecutionRepository,
|
||||
type CanonicalJournalEntry,
|
||||
type CanonicalOwner,
|
||||
type CanonicalPaperHost,
|
||||
type CanonicalPaperInput,
|
||||
type CanonicalTransaction,
|
||||
} from './canonical-paper';
|
||||
|
|
@ -65,6 +66,8 @@ export class CanonicalPaperExecution {
|
|||
programs: readonly StrategyProgram[];
|
||||
/** Best effort after SQL commit. Recover missed notifications using journal(sequence). */
|
||||
publish?: (entries: readonly CanonicalJournalEntry[]) => void | Promise<void>;
|
||||
/** Only the trusted paper runtime owns this generation and operational gate. */
|
||||
control?: { generation: string; guard(account: CanonicalAccount): boolean };
|
||||
}
|
||||
) {
|
||||
this.programs = new Map();
|
||||
|
|
@ -95,12 +98,14 @@ export class CanonicalPaperExecution {
|
|||
pendingObservations: [],
|
||||
};
|
||||
})
|
||||
.sort((a, b) => (a.definition.ownerId < b.definition.ownerId ? -1 : 1));
|
||||
.sort((a, b) =>
|
||||
Buffer.compare(Buffer.from(a.definition.ownerId), Buffer.from(b.definition.ownerId))
|
||||
);
|
||||
// Program closures are trusted code. Metadata and state are detached now, before any await.
|
||||
freeze(this.initialOwners);
|
||||
}
|
||||
|
||||
initialize(configuration: CanonicalMatchingConfig): Promise<void> {
|
||||
initialize(configuration: CanonicalMatchingConfig, host?: CanonicalPaperHost): Promise<void> {
|
||||
outsideCallback();
|
||||
const config = canonicalMatchingConfigSchema.parse(configuration);
|
||||
const identity = {
|
||||
|
|
@ -131,6 +136,7 @@ export class CanonicalPaperExecution {
|
|||
observed: 0,
|
||||
pendingDecisionSequence: null,
|
||||
latestObservations: [],
|
||||
...(host ? { host } : {}),
|
||||
};
|
||||
return this.options.repository.initialize(initial, this.initialOwners).then(() => {
|
||||
this.identity = identity;
|
||||
|
|
@ -149,6 +155,49 @@ export class CanonicalPaperExecution {
|
|||
enqueue(value: CanonicalPaperInput): Promise<boolean> {
|
||||
outsideCallback();
|
||||
const id = this.accountId();
|
||||
return this.options.repository.transact(id, async tx => {
|
||||
if (tx.account.host) {
|
||||
throw new ExecutionConflictError(
|
||||
'Controlled paper accounts accept only atomic producer frames'
|
||||
);
|
||||
}
|
||||
return this.enqueueInput(tx, value);
|
||||
});
|
||||
}
|
||||
|
||||
/** The runtime calls this while holding the account lock for the whole frame. */
|
||||
async enqueueFrame(
|
||||
tx: CanonicalTransaction,
|
||||
inputs: readonly CanonicalPaperInput[]
|
||||
): Promise<void> {
|
||||
outsideCallback();
|
||||
if (
|
||||
tx.account.identity.accountId !== this.accountId() ||
|
||||
!tx.account.host ||
|
||||
!this.allowed(tx.account)
|
||||
) {
|
||||
throw new ExecutionConflictError('Paper frame admission requires an active owned runtime');
|
||||
}
|
||||
for (const input of inputs) {
|
||||
await this.enqueueInput(tx, input);
|
||||
}
|
||||
}
|
||||
|
||||
private allowed(account: CanonicalAccount): boolean {
|
||||
if (!account.host) {
|
||||
return true;
|
||||
}
|
||||
const control = this.options.control;
|
||||
if (!control || account.host.generation !== control.generation) {
|
||||
throw new ExecutionConflictError('Canonical paper runtime generation is obsolete');
|
||||
}
|
||||
return control.guard(account) && account.host.active && !account.host.operatorHalted;
|
||||
}
|
||||
|
||||
private async enqueueInput(
|
||||
tx: CanonicalTransaction,
|
||||
value: CanonicalPaperInput
|
||||
): Promise<boolean> {
|
||||
const input = canonicalPaperInputSchema.parse(value);
|
||||
if (input.command.body.kind === 'submit') {
|
||||
throw new Error('Strategy submissions require a durable all-owner decision batch');
|
||||
|
|
@ -182,30 +231,28 @@ export class CanonicalPaperExecution {
|
|||
throw new Error('Observation is unavailable at its admitted input time');
|
||||
}
|
||||
const fingerprint = createHash('sha256').update(canonicalJson(input)).digest('hex');
|
||||
return this.options.repository.transact(id, async tx => {
|
||||
const old = await tx.getInput(input.command.commandId);
|
||||
if (old) {
|
||||
if (old.fingerprint !== fingerprint) {
|
||||
throw new ExecutionConflictError('Conflicting canonical market input identity');
|
||||
}
|
||||
return false;
|
||||
const old = await tx.getInput(input.command.commandId);
|
||||
if (old) {
|
||||
if (old.fingerprint !== fingerprint) {
|
||||
throw new ExecutionConflictError('Conflicting canonical market input identity');
|
||||
}
|
||||
if (tx.account.checkpoint.status !== 'Running') {
|
||||
throw new Error(
|
||||
`Canonical account is terminal: ${diagnosticFailure(tx.account) ?? tx.account.checkpoint.status}`
|
||||
);
|
||||
}
|
||||
tx.account.inputSequence = increment(tx.account.inputSequence);
|
||||
await tx.putInput({
|
||||
version: 1,
|
||||
id: input.command.commandId,
|
||||
sequence: tx.account.inputSequence,
|
||||
fingerprint,
|
||||
status: 'pending',
|
||||
input,
|
||||
});
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
if (tx.account.checkpoint.status !== 'Running') {
|
||||
throw new Error(
|
||||
`Canonical account is terminal: ${diagnosticFailure(tx.account) ?? tx.account.checkpoint.status}`
|
||||
);
|
||||
}
|
||||
tx.account.inputSequence = increment(tx.account.inputSequence);
|
||||
await tx.putInput({
|
||||
version: 1,
|
||||
id: input.command.commandId,
|
||||
sequence: tx.account.inputSequence,
|
||||
fingerprint,
|
||||
status: 'pending',
|
||||
input,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
private async persist(
|
||||
|
|
@ -357,7 +404,8 @@ export class CanonicalPaperExecution {
|
|||
tx: CanonicalTransaction,
|
||||
input: NonNullable<CanonicalPaperInput['decision']>
|
||||
): DecisionContext {
|
||||
const series = tx.account.checkpoint.config.series;
|
||||
const series =
|
||||
tx.account.host?.configuration.policy.observations ?? tx.account.checkpoint.config.series;
|
||||
if (
|
||||
input.inputs.length !== series.length ||
|
||||
new Set(input.inputs.map(item => item.series_id)).size !== series.length ||
|
||||
|
|
@ -372,7 +420,10 @@ export class CanonicalPaperExecution {
|
|||
const expected = !latest
|
||||
? 'Missing'
|
||||
: {
|
||||
[input.key.at - latest.event_time > tx.account.checkpoint.config.risk.maxMarkAgeMs
|
||||
[input.key.at - latest.event_time >
|
||||
(tx.account.host?.configuration.policy.observations.find(
|
||||
series => series.seriesId === item.series_id
|
||||
)?.staleAfterMs ?? tx.account.checkpoint.config.risk.maxMarkAgeMs)
|
||||
? 'Stale'
|
||||
: 'Fresh']: { event_time: latest.event_time, available_at: latest.available_at },
|
||||
};
|
||||
|
|
@ -389,7 +440,9 @@ export class CanonicalPaperExecution {
|
|||
barrier_id: input.barrierId,
|
||||
at: input.key.at,
|
||||
revision: tx.account.view.admissionRevision,
|
||||
owner_ids: [...input.ownerIds].sort(),
|
||||
owner_ids: [...input.ownerIds].sort((a, b) =>
|
||||
Buffer.compare(Buffer.from(a), Buffer.from(b))
|
||||
),
|
||||
observation_count: tx.account.observed,
|
||||
inputs: input.inputs,
|
||||
},
|
||||
|
|
@ -410,7 +463,10 @@ export class CanonicalPaperExecution {
|
|||
const observations = input.input.observations;
|
||||
for (const observation of observations) {
|
||||
if (
|
||||
!tx.account.checkpoint.config.series.some(
|
||||
!(
|
||||
tx.account.host?.configuration.policy.observations ??
|
||||
tx.account.checkpoint.config.series
|
||||
).some(
|
||||
series =>
|
||||
series.seriesId === observation.series_id &&
|
||||
series.instrumentId === observation.instrument_id
|
||||
|
|
@ -461,6 +517,9 @@ export class CanonicalPaperExecution {
|
|||
return (async () => {
|
||||
for (;;) {
|
||||
const step = await this.options.repository.transact(id, async tx => {
|
||||
if (!this.allowed(tx.account)) {
|
||||
return { worked: false, entries: [], failure: undefined };
|
||||
}
|
||||
const failure = diagnosticFailure(tx.account);
|
||||
if (failure) {
|
||||
return { worked: false, entries: [], failure };
|
||||
|
|
|
|||
|
|
@ -35,6 +35,44 @@ function accountState(raw: unknown): CanonicalAccount {
|
|||
) {
|
||||
throw new ExecutionConflictError('Canonical envelope identity or revision mismatch');
|
||||
}
|
||||
if (
|
||||
account.host &&
|
||||
canonicalJson(account.host.configuration.matching) !== canonicalJson(account.checkpoint.config)
|
||||
) {
|
||||
throw new ExecutionConflictError(
|
||||
'Canonical host configuration differs from financial configuration'
|
||||
);
|
||||
}
|
||||
if (account.host) {
|
||||
const { configuration, connection, quotes, quoteHighWater } = account.host;
|
||||
if (
|
||||
configuration.strategies.length !== account.definitions.length ||
|
||||
configuration.strategies.some(
|
||||
selection =>
|
||||
!account.definitions.some(
|
||||
definition =>
|
||||
definition.ownerId === selection.ownerId &&
|
||||
definition.strategyId === selection.strategyId &&
|
||||
definition.strategyVersion === selection.strategyVersion &&
|
||||
definition.seed === selection.seed &&
|
||||
definition.mode === 'target'
|
||||
)
|
||||
) ||
|
||||
(connection && connection.sourceId !== configuration.policy.sourceId) ||
|
||||
[quotes, quoteHighWater].some(
|
||||
clocks =>
|
||||
new Set(clocks.map(quote => quote.instrumentId)).size !== clocks.length ||
|
||||
clocks.some(
|
||||
quote =>
|
||||
!configuration.matching.series.some(
|
||||
series => series.instrumentId === quote.instrumentId
|
||||
)
|
||||
)
|
||||
)
|
||||
) {
|
||||
throw new ExecutionConflictError('Canonical host strategy or feed binding mismatch');
|
||||
}
|
||||
}
|
||||
return account;
|
||||
}
|
||||
|
||||
|
|
@ -59,11 +97,13 @@ export class PostgresCanonicalExecutionRepository implements CanonicalExecutionR
|
|||
identity: account.identity,
|
||||
config: account.checkpoint.config,
|
||||
definitions: account.definitions,
|
||||
hostConfiguration: account.host?.configuration ?? null,
|
||||
}) !==
|
||||
canonicalJson({
|
||||
identity: expected.identity,
|
||||
config: expected.checkpoint.config,
|
||||
definitions: expected.definitions,
|
||||
hostConfiguration: expected.host?.configuration ?? null,
|
||||
})
|
||||
) {
|
||||
throw new ExecutionConflictError(
|
||||
|
|
|
|||
|
|
@ -12,13 +12,44 @@ import {
|
|||
nativeManagedOrderSchema,
|
||||
stepSchema,
|
||||
} from '../contracts/native-replay';
|
||||
import { paperConfigurationSchema, paperConnectionSchema } from '../contracts/paper-runtime';
|
||||
import { metadataSchema, stateCopy } from '../strategies/strategy-decision';
|
||||
|
||||
const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
const time = matchingCommandSchema.shape.key.shape.at;
|
||||
const json = z.unknown().transform(value => stateCopy(value));
|
||||
const observation = stepSchema.shape.observations.element;
|
||||
const barrier = stepSchema.shape.step.options[1].shape.barrier;
|
||||
const definition = metadataSchema.extend({ initialState: json }).strict();
|
||||
const quoteClock = z
|
||||
.object({ instrumentId: z.string(), observedAt: time, sourceSequence: counter })
|
||||
.strict();
|
||||
/** Host controls are deliberately outside the native financial checkpoint. */
|
||||
export const canonicalPaperHostSchema = z
|
||||
.object({
|
||||
version: z.literal(1),
|
||||
configuration: paperConfigurationSchema,
|
||||
generation: z.string().min(1),
|
||||
active: z.boolean(),
|
||||
operatorHalted: z.boolean(),
|
||||
haltReason: z.string().nullable(),
|
||||
diagnostic: z.string().nullable(),
|
||||
connection: paperConnectionSchema.nullable(),
|
||||
lastReceivedAt: time.nullable(),
|
||||
lastAvailableAt: time.nullable(),
|
||||
lastSequence: counter.nullable(),
|
||||
quotes: z.array(quoteClock),
|
||||
quoteHighWater: z.array(quoteClock),
|
||||
frames: z.record(
|
||||
z
|
||||
.object({ fingerprint: z.string(), disposition: z.enum(['health-only', 'admitted']) })
|
||||
.strict()
|
||||
),
|
||||
observations: z.record(z.string()),
|
||||
physicalQuotes: z.record(z.string()),
|
||||
})
|
||||
.strict();
|
||||
export type CanonicalPaperHost = z.infer<typeof canonicalPaperHostSchema>;
|
||||
const feedback = z
|
||||
.object({
|
||||
decision: nativeManagedOrderSchema.shape.order.shape.decision,
|
||||
|
|
@ -76,6 +107,7 @@ export const canonicalAccountSchema = z
|
|||
observed: counter,
|
||||
pendingDecisionSequence: counter.nullable(),
|
||||
latestObservations: z.array(observation),
|
||||
host: canonicalPaperHostSchema.optional(),
|
||||
})
|
||||
.strict();
|
||||
export const canonicalPaperInputSchema = z
|
||||
|
|
@ -170,7 +202,7 @@ export function compareEventKeys(
|
|||
return (
|
||||
a.at - b.at ||
|
||||
phases[a.phase] - phases[b.phase] ||
|
||||
(a.instrumentId < b.instrumentId ? -1 : a.instrumentId > b.instrumentId ? 1 : 0) ||
|
||||
Buffer.compare(Buffer.from(a.instrumentId), Buffer.from(b.instrumentId)) ||
|
||||
a.sourceSequence - b.sourceSequence
|
||||
);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue