300 lines
12 KiB
TypeScript
300 lines
12 KiB
TypeScript
import { increment } from '../strategies/strategy-decision';
|
|
import {
|
|
canonicalAccountSchema,
|
|
canonicalBatchSchema,
|
|
canonicalJournalSchema,
|
|
canonicalOwnerSchema,
|
|
canonicalStoredInputSchema,
|
|
type CanonicalAccount,
|
|
type CanonicalExecutionRepository,
|
|
type CanonicalOwner,
|
|
type CanonicalPostgres,
|
|
type CanonicalTransaction,
|
|
} from './canonical-paper';
|
|
import { ExecutionConflictError } from './repository';
|
|
import { canonicalJson } from './strategy-recovery';
|
|
|
|
function accountState(raw: unknown): CanonicalAccount {
|
|
const result = canonicalAccountSchema.safeParse(raw);
|
|
if (!result.success) {
|
|
throw new ExecutionConflictError(
|
|
'Incompatible execution snapshot; use an explicit migration or a new canonical account ID'
|
|
);
|
|
}
|
|
const account = result.data;
|
|
const ledger = account.checkpoint.config.risk.ledger;
|
|
const portfolio = account.view.portfolio;
|
|
if (
|
|
account.identity.sessionId !== ledger.sessionId ||
|
|
account.identity.accountId !== ledger.accountId ||
|
|
portfolio.sessionId !== ledger.sessionId ||
|
|
portfolio.accountId !== ledger.accountId ||
|
|
portfolio.baseCurrency !== ledger.baseCurrency ||
|
|
portfolio.reserveOwnerId !== ledger.reserveOwnerId ||
|
|
account.view.admissionRevision !== account.checkpoint.revision
|
|
) {
|
|
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;
|
|
}
|
|
|
|
/** Same account row lock as legacy custody; no transaction-local native state escapes. */
|
|
export class PostgresCanonicalExecutionRepository implements CanonicalExecutionRepository {
|
|
constructor(private readonly postgres: CanonicalPostgres) {}
|
|
|
|
async initialize(initial: CanonicalAccount, owners: CanonicalOwner[]) {
|
|
const expected = canonicalAccountSchema.parse(initial);
|
|
await this.postgres.transaction(async client => {
|
|
const inserted = await client.query(
|
|
'INSERT INTO simulation_accounts (id,state) VALUES ($1,$2::jsonb) ON CONFLICT (id) DO NOTHING RETURNING id',
|
|
[expected.identity.accountId, JSON.stringify(expected)]
|
|
);
|
|
const row = await client.query(
|
|
'SELECT state FROM simulation_accounts WHERE id = $1 FOR UPDATE',
|
|
[expected.identity.accountId]
|
|
);
|
|
const account = accountState(row.rows[0].state);
|
|
if (
|
|
canonicalJson({
|
|
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(
|
|
'Canonical account configuration or strategy definition changed; use an explicit migration or a new account ID'
|
|
);
|
|
}
|
|
if (inserted.rows.length) {
|
|
for (const owner of owners) {
|
|
const parsed = canonicalOwnerSchema.parse(owner);
|
|
await client.query(
|
|
'INSERT INTO simulation_strategy_checkpoints (account_id,strategy_id,payload) VALUES ($1,$2,$3::jsonb)',
|
|
[account.identity.accountId, parsed.definition.ownerId, JSON.stringify(parsed)]
|
|
);
|
|
}
|
|
}
|
|
const saved = await client.query(
|
|
'SELECT payload FROM simulation_strategy_checkpoints WHERE account_id = $1',
|
|
[account.identity.accountId]
|
|
);
|
|
this.validateOwners(
|
|
account,
|
|
saved.rows.map(row => canonicalOwnerSchema.parse(row.payload))
|
|
);
|
|
});
|
|
}
|
|
|
|
private validateOwners(account: CanonicalAccount, owners: CanonicalOwner[]) {
|
|
if (
|
|
owners.length !== account.definitions.length ||
|
|
new Set(owners.map(owner => owner.definition.ownerId)).size !== owners.length
|
|
) {
|
|
throw new ExecutionConflictError('Missing or duplicate canonical strategy checkpoints');
|
|
}
|
|
for (const owner of owners) {
|
|
const definition = account.definitions.find(
|
|
item => item.ownerId === owner.definition.ownerId
|
|
);
|
|
const diagnostic = owner.diagnostic;
|
|
if (
|
|
canonicalJson(definition) !== canonicalJson(owner.definition) ||
|
|
diagnostic.ownerId !== owner.definition.ownerId ||
|
|
diagnostic.strategyId !== owner.definition.strategyId ||
|
|
diagnostic.strategyVersion !== owner.definition.strategyVersion ||
|
|
diagnostic.rng.seed !== owner.definition.seed ||
|
|
diagnostic.observationCount + owner.pendingObservations.length !== account.observed ||
|
|
owner.cursor > account.journalSequence
|
|
) {
|
|
throw new ExecutionConflictError(
|
|
'Canonical strategy checkpoint definition or observation cursor mismatch'
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
transact<T>(accountId: string, work: (tx: CanonicalTransaction) => Promise<T>): Promise<T> {
|
|
return this.postgres.transaction(async client => {
|
|
const locked = await client.query(
|
|
'SELECT state FROM simulation_accounts WHERE id = $1 FOR UPDATE',
|
|
[accountId]
|
|
);
|
|
if (!locked.rows[0]) {
|
|
throw new Error('Canonical execution account is not initialized');
|
|
}
|
|
const account = accountState(locked.rows[0].state);
|
|
if (account.identity.accountId !== accountId) {
|
|
throw new ExecutionConflictError('Canonical account identity mismatch');
|
|
}
|
|
const owners = async () => {
|
|
const result = await client.query(
|
|
'SELECT payload FROM simulation_strategy_checkpoints WHERE account_id = $1 ORDER BY strategy_id COLLATE "C"',
|
|
[accountId]
|
|
);
|
|
return result.rows.map(row => canonicalOwnerSchema.parse(row.payload));
|
|
};
|
|
this.validateOwners(account, await owners());
|
|
const readInput = async (id: string) => {
|
|
const result = await client.query(
|
|
'SELECT payload FROM simulation_market_inputs WHERE account_id = $1 AND id = $2',
|
|
[accountId, id]
|
|
);
|
|
return result.rows[0]
|
|
? canonicalStoredInputSchema.parse(result.rows[0].payload)
|
|
: undefined;
|
|
};
|
|
const result = await work({
|
|
account,
|
|
owners,
|
|
async putOwner(value) {
|
|
const owner = canonicalOwnerSchema.parse(value);
|
|
await client.query(
|
|
`INSERT INTO simulation_strategy_checkpoints (account_id,strategy_id,payload) VALUES ($1,$2,$3::jsonb)
|
|
ON CONFLICT (account_id,strategy_id) DO UPDATE SET payload = EXCLUDED.payload`,
|
|
[accountId, owner.definition.ownerId, JSON.stringify(owner)]
|
|
);
|
|
},
|
|
getInput: readInput,
|
|
async nextInput() {
|
|
const result = await client.query(
|
|
"SELECT payload FROM simulation_market_inputs WHERE account_id = $1 AND status = 'pending' ORDER BY sequence LIMIT 1",
|
|
[accountId]
|
|
);
|
|
return result.rows[0]
|
|
? canonicalStoredInputSchema.parse(result.rows[0].payload)
|
|
: undefined;
|
|
},
|
|
async putInput(value) {
|
|
const input = canonicalStoredInputSchema.parse(value);
|
|
const old = await readInput(input.id);
|
|
if (
|
|
old &&
|
|
(old.fingerprint !== input.fingerprint ||
|
|
old.sequence !== input.sequence ||
|
|
canonicalJson(old.input) !== canonicalJson(input.input) ||
|
|
(old.status === 'applied' && input.status !== 'applied'))
|
|
) {
|
|
throw new ExecutionConflictError('Conflicting canonical market input');
|
|
}
|
|
await client.query(
|
|
`INSERT INTO simulation_market_inputs (account_id,id,sequence,status,payload) VALUES ($1,$2,$3,$4,$5::jsonb)
|
|
ON CONFLICT (account_id,id) DO UPDATE SET status = EXCLUDED.status,payload = EXCLUDED.payload`,
|
|
[accountId, input.id, input.sequence, input.status, JSON.stringify(input)]
|
|
);
|
|
},
|
|
async nextBatch() {
|
|
const result = await client.query(
|
|
"SELECT payload FROM simulation_canonical_intents WHERE account_id = $1 AND status = 'pending' ORDER BY sequence LIMIT 1",
|
|
[accountId]
|
|
);
|
|
return result.rows[0] ? canonicalBatchSchema.parse(result.rows[0].payload) : undefined;
|
|
},
|
|
async putBatch(value) {
|
|
const batch = canonicalBatchSchema.parse(value);
|
|
if (batch.command.body.kind !== 'submit' || batch.id !== batch.command.commandId) {
|
|
throw new ExecutionConflictError(
|
|
'Canonical intent must contain one complete submission batch'
|
|
);
|
|
}
|
|
const result = await client.query(
|
|
'SELECT payload FROM simulation_canonical_intents WHERE account_id = $1 AND id = $2',
|
|
[accountId, batch.id]
|
|
);
|
|
const old = result.rows[0]
|
|
? canonicalBatchSchema.parse(result.rows[0].payload)
|
|
: undefined;
|
|
if (
|
|
old &&
|
|
(old.sequence !== batch.sequence ||
|
|
canonicalJson(old.command) !== canonicalJson(batch.command) ||
|
|
(old.status !== 'pending' && old.status !== batch.status))
|
|
) {
|
|
throw new ExecutionConflictError('Conflicting canonical decision batch');
|
|
}
|
|
await client.query(
|
|
`INSERT INTO simulation_canonical_intents (account_id,id,sequence,status,payload) VALUES ($1,$2,$3,$4,$5::jsonb)
|
|
ON CONFLICT (account_id,id) DO UPDATE SET status = EXCLUDED.status,payload = EXCLUDED.payload`,
|
|
[accountId, batch.id, batch.sequence, batch.status, JSON.stringify(batch)]
|
|
);
|
|
},
|
|
async appendJournal(value) {
|
|
const payload = canonicalJournalSchema.parse(value);
|
|
account.journalSequence = increment(account.journalSequence);
|
|
const entry = { sequence: account.journalSequence, payload };
|
|
await client.query(
|
|
'INSERT INTO simulation_strategy_journal (account_id,sequence,payload) VALUES ($1,$2,$3::jsonb)',
|
|
[accountId, entry.sequence, JSON.stringify(payload)]
|
|
);
|
|
return entry;
|
|
},
|
|
async journal(after) {
|
|
if (!Number.isSafeInteger(after) || after < 0) {
|
|
throw new Error('Invalid canonical journal cursor');
|
|
}
|
|
const result = await client.query(
|
|
'SELECT sequence,payload FROM simulation_strategy_journal WHERE account_id = $1 AND sequence > $2 ORDER BY sequence',
|
|
[accountId, after]
|
|
);
|
|
return result.rows.map(row => {
|
|
const sequence = Number(row.sequence);
|
|
if (!Number.isSafeInteger(sequence) || sequence <= 0) {
|
|
throw new Error('Invalid canonical journal sequence');
|
|
}
|
|
return { sequence, payload: canonicalJournalSchema.parse(row.payload) };
|
|
});
|
|
},
|
|
});
|
|
this.validateOwners(account, await owners());
|
|
await client.query(
|
|
'UPDATE simulation_accounts SET state = $2::jsonb,updated_at = NOW() WHERE id = $1',
|
|
[accountId, JSON.stringify(canonicalAccountSchema.parse(account))]
|
|
);
|
|
return result;
|
|
});
|
|
}
|
|
}
|