perf(research): add compact replay projections and representative profiling
This commit is contained in:
parent
19e9dad68b
commit
e3bd722e31
21 changed files with 2830 additions and 130 deletions
|
|
@ -1,11 +1,35 @@
|
|||
/** F07 extension of P01, invoked only through benchmark-research.ts --session. */
|
||||
import { createHash } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import type { ReplayResult } from '../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
import type { FinancialEffects } from '@stock-bot/types';
|
||||
import type {
|
||||
ReplayOutput,
|
||||
ReplayProjectionResult,
|
||||
ReplayResultFormat,
|
||||
} from '../apps/stock/orchestrator/src/contracts/native-replay';
|
||||
|
||||
type SessionWorkload = { totalBars: number; assets: number; owners: number; eventBudget: number };
|
||||
export const replayProfiles = ['none', 'sparse', 'turnover'] as const;
|
||||
export type ReplayProfile = (typeof replayProfiles)[number];
|
||||
export type SessionOptions = {
|
||||
profiles: ReplayProfile[];
|
||||
resultFormat: ReplayResultFormat | 'both';
|
||||
totalBars?: number;
|
||||
};
|
||||
type SessionWorkload = {
|
||||
totalBars: number;
|
||||
assets: number;
|
||||
owners: number;
|
||||
eventBudget: number;
|
||||
profile: ReplayProfile;
|
||||
resultFormat: ReplayResultFormat;
|
||||
};
|
||||
const hash = (value: string) => createHash('sha256').update(value).digest('hex');
|
||||
const capital = '1000000.00000000';
|
||||
const profileDefinitions: Record<ReplayProfile, string> = {
|
||||
none: 'no-targets-v1',
|
||||
sparse: 'first-last-unit-target-v1',
|
||||
turnover: 'alternating-unit-target-v1',
|
||||
};
|
||||
|
||||
function cents(value: bigint): string {
|
||||
const magnitude = value < 0n ? -value : value;
|
||||
|
|
@ -15,7 +39,12 @@ function cents(value: bigint): string {
|
|||
/** Independent integer-cent oracle for this fixture only, not a second simulator.
|
||||
* One unit per owner/asset alternates buy/sell at opens 1..N-1, with a 1% fee.
|
||||
* Final position is marked at last close (open+1); no invented liquidation. */
|
||||
export function turnoverOracle(barsPerAsset: number, assets: number, owners: number) {
|
||||
export function profileOracle(
|
||||
profile: ReplayProfile,
|
||||
barsPerAsset: number,
|
||||
assets: number,
|
||||
owners: number
|
||||
) {
|
||||
if (
|
||||
![barsPerAsset, assets, owners].every(Number.isSafeInteger) ||
|
||||
barsPerAsset < 3 ||
|
||||
|
|
@ -25,15 +54,26 @@ export function turnoverOracle(barsPerAsset: number, assets: number, owners: num
|
|||
throw new Error('Expected at least three bars and positive asset/owner counts');
|
||||
}
|
||||
let cashDelta = 0n,
|
||||
fee = 0n;
|
||||
for (let step = 1; step < barsPerAsset; step++) {
|
||||
const price = BigInt(10 + (step % 20) * 2);
|
||||
cashDelta += (step % 2 ? -price : price) * 100n - price;
|
||||
fee += price;
|
||||
fee = 0n,
|
||||
fillsPerBook = 0;
|
||||
const lastOpen = BigInt(10 + ((barsPerAsset - 1) % 20) * 2);
|
||||
if (profile === 'turnover') {
|
||||
for (let step = 1; step < barsPerAsset; step++) {
|
||||
const price = BigInt(10 + (step % 20) * 2);
|
||||
cashDelta += (step % 2 ? -price : price) * 100n - price;
|
||||
fee += price;
|
||||
}
|
||||
fillsPerBook = barsPerAsset - 1;
|
||||
} else if (profile === 'sparse') {
|
||||
// Exactly one unit bought at first eligible open12 and sold at last open.
|
||||
cashDelta = (lastOpen - 12n) * 100n - 12n - lastOpen;
|
||||
fee = 12n + lastOpen;
|
||||
fillsPerBook = 2;
|
||||
} else if (profile !== 'none') {
|
||||
throw new Error('Unknown replay profile');
|
||||
}
|
||||
const books = BigInt(assets * owners),
|
||||
holding = (barsPerAsset - 1) % 2;
|
||||
const lastOpen = BigInt(10 + ((barsPerAsset - 1) % 20) * 2);
|
||||
holding = profile === 'turnover' ? (barsPerAsset - 1) % 2 : 0;
|
||||
const cash = 100_000_000n + cashDelta * books;
|
||||
return {
|
||||
cash: cents(cash),
|
||||
|
|
@ -41,13 +81,154 @@ export function turnoverOracle(barsPerAsset: number, assets: number, owners: num
|
|||
feePerOwner: cents(fee * BigInt(assets)),
|
||||
quantity: `${holding}.00000000`,
|
||||
remainingCost: cents(BigInt(holding) * lastOpen * 100n),
|
||||
fills: (barsPerAsset - 1) * assets * owners,
|
||||
fills: fillsPerBook * assets * owners,
|
||||
decisions: (barsPerAsset - 1) * owners,
|
||||
};
|
||||
}
|
||||
|
||||
function assertEconomics(result: ReplayResult, workload: SessionWorkload) {
|
||||
const expected = turnoverOracle(
|
||||
export function turnoverOracle(barsPerAsset: number, assets: number, owners: number) {
|
||||
return profileOracle('turnover', barsPerAsset, assets, owners);
|
||||
}
|
||||
|
||||
/** A desired unit target only, not an accounting/fill model. null means hold. */
|
||||
export function profileTarget(
|
||||
profile: ReplayProfile,
|
||||
decision: number,
|
||||
barsPerAsset: number
|
||||
): 0 | 1 | null {
|
||||
if (profile === 'none') {
|
||||
return null;
|
||||
}
|
||||
if (profile === 'turnover') {
|
||||
return decision % 2 ? 0 : 1;
|
||||
}
|
||||
if (decision === 0) {
|
||||
return 1;
|
||||
}
|
||||
return decision === barsPerAsset - 2 ? 0 : null;
|
||||
}
|
||||
|
||||
type SharedFill = Pick<
|
||||
ReplayProjectionResult['projection']['fills'][number],
|
||||
| 'commandId'
|
||||
| 'eventTime'
|
||||
| 'ownerId'
|
||||
| 'orderId'
|
||||
| 'fillId'
|
||||
| 'instrumentId'
|
||||
| 'price'
|
||||
| 'cashDelta'
|
||||
| 'quantityDelta'
|
||||
| 'releasedBasis'
|
||||
| 'realizedGrossPnl'
|
||||
| 'fee'
|
||||
>;
|
||||
|
||||
function sharedFill(fill: SharedFill): SharedFill {
|
||||
return {
|
||||
commandId: fill.commandId,
|
||||
eventTime: fill.eventTime,
|
||||
ownerId: fill.ownerId,
|
||||
orderId: fill.orderId,
|
||||
fillId: fill.fillId,
|
||||
instrumentId: fill.instrumentId,
|
||||
price: fill.price,
|
||||
cashDelta: fill.cashDelta,
|
||||
quantityDelta: fill.quantityDelta,
|
||||
releasedBasis: fill.releasedBasis,
|
||||
realizedGrossPnl: fill.realizedGrossPnl,
|
||||
fee: { feeId: fill.fee.feeId, amount: fill.fee.amount },
|
||||
};
|
||||
}
|
||||
|
||||
/** Benchmark-only copy of shared authoritative fields. No valuation, fee or P&L
|
||||
* arithmetic. The trace has no LedgerValuation; that extra compact projection
|
||||
* remains covered by Rust/independent fixtures, not synthesized in this hash. */
|
||||
export function commonFinancialProjection(result: ReplayOutput) {
|
||||
const fills: SharedFill[] = [];
|
||||
if ('projection' in result) {
|
||||
for (const fill of result.projection.fills) {
|
||||
fills.push(sharedFill(fill));
|
||||
}
|
||||
} else {
|
||||
for (const receipt of result.receipts) {
|
||||
if (receipt.outcome.replayed) {
|
||||
continue;
|
||||
}
|
||||
for (const effect of receipt.outcome.effects) {
|
||||
if (!('Risk' in effect)) {
|
||||
continue;
|
||||
}
|
||||
const risk = effect.Risk as {
|
||||
outcome: {
|
||||
replayed: boolean;
|
||||
disposition: unknown;
|
||||
financial: null | { replayed: boolean; effects: FinancialEffects };
|
||||
};
|
||||
};
|
||||
if (risk.outcome.replayed) {
|
||||
continue;
|
||||
}
|
||||
if (risk.outcome.disposition !== 'Accepted') {
|
||||
throw new Error('Unexpected benchmark risk rejection');
|
||||
}
|
||||
const financial = risk.outcome.financial;
|
||||
if (!financial || financial.replayed) {
|
||||
continue;
|
||||
}
|
||||
const applied = financial.effects.effects.filter(e => e.kind === 'fillApplied');
|
||||
const fees = financial.effects.effects.filter(e => e.kind === 'feeApplied');
|
||||
if (!applied.length && !fees.length) {
|
||||
continue;
|
||||
}
|
||||
const fill = applied[0],
|
||||
fee = fees[0];
|
||||
if (
|
||||
applied.length !== 1 ||
|
||||
fees.length !== 1 ||
|
||||
!fill ||
|
||||
!fee ||
|
||||
fill.ownerId !== fee.ownerId ||
|
||||
fill.fillId !== fee.fillId
|
||||
) {
|
||||
throw new Error('Malformed trace fill/fee pair');
|
||||
}
|
||||
fills.push(
|
||||
sharedFill({
|
||||
...fill,
|
||||
commandId: financial.effects.commandId,
|
||||
eventTime: financial.effects.eventTime,
|
||||
fee: { feeId: fee.feeId, amount: fee.amount },
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
identity: result.identity,
|
||||
status: result.status,
|
||||
manifest: result.manifest,
|
||||
policy: result.policy,
|
||||
view: result.view,
|
||||
limitations: result.limitations,
|
||||
modelLimitations: result.modelLimitations,
|
||||
fills,
|
||||
};
|
||||
}
|
||||
|
||||
export function assertResultFormat(result: ReplayOutput, expected: ReplayResultFormat): void {
|
||||
if (('projection' in result ? 'projection' : 'trace') !== expected) {
|
||||
throw new Error('Benchmark result format mismatch');
|
||||
}
|
||||
}
|
||||
|
||||
function assertEconomics(
|
||||
result: ReplayOutput,
|
||||
workload: SessionWorkload,
|
||||
fills: readonly SharedFill[]
|
||||
) {
|
||||
const expected = profileOracle(
|
||||
workload.profile,
|
||||
workload.totalBars / workload.assets,
|
||||
workload.assets,
|
||||
workload.owners
|
||||
|
|
@ -56,7 +237,8 @@ function assertEconomics(result: ReplayResult, workload: SessionWorkload) {
|
|||
if (
|
||||
portfolio.cash !== expected.cash ||
|
||||
result.view.equity !== expected.equity ||
|
||||
portfolio.positions.length !== workload.assets * workload.owners ||
|
||||
portfolio.positions.length !==
|
||||
(workload.profile === 'none' ? 0 : workload.assets * workload.owners) ||
|
||||
portfolio.positions.some(
|
||||
p => p.quantity !== expected.quantity || p.remainingCost !== expected.remainingCost
|
||||
) ||
|
||||
|
|
@ -67,42 +249,10 @@ function assertEconomics(result: ReplayResult, workload: SessionWorkload) {
|
|||
) {
|
||||
throw new Error('Canonical benchmark failed independent cash/equity/owner/basis/fee oracle');
|
||||
}
|
||||
let fills = 0,
|
||||
fees = 0;
|
||||
for (const receipt of result.receipts) {
|
||||
for (const effect of receipt.outcome.effects) {
|
||||
if (!('Risk' in effect)) {
|
||||
continue;
|
||||
}
|
||||
const risk = effect.Risk as {
|
||||
outcome: {
|
||||
disposition: unknown;
|
||||
financial: null | { replayed: boolean; effects: { effects: { kind: string }[] } };
|
||||
};
|
||||
};
|
||||
if (risk.outcome.disposition !== 'Accepted') {
|
||||
throw new Error('Unexpected benchmark risk rejection');
|
||||
}
|
||||
if (!risk.outcome.financial) {
|
||||
continue;
|
||||
}
|
||||
if (risk.outcome.financial.replayed) {
|
||||
throw new Error('Unexpected benchmark duplicate effect');
|
||||
}
|
||||
for (const financial of risk.outcome.financial.effects.effects) {
|
||||
if (financial.kind === 'fillApplied') {
|
||||
fills++;
|
||||
}
|
||||
if (financial.kind === 'feeApplied') {
|
||||
fees++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (fills !== expected.fills || fees !== fills) {
|
||||
if (fills.length !== expected.fills) {
|
||||
throw new Error('Unexpected benchmark fill/fee count');
|
||||
}
|
||||
return { ...expected, fees };
|
||||
return { ...expected, fees: fills.length };
|
||||
}
|
||||
|
||||
export async function sessionChild(workload: SessionWorkload) {
|
||||
|
|
@ -121,6 +271,10 @@ export async function sessionChild(workload: SessionWorkload) {
|
|||
const { nativeReplayFixture } = await import('../test/fixtures/native-replay');
|
||||
const { parseFinancialDecimal } = await import('@stock-bot/types');
|
||||
const applicationImportMs = elapsed();
|
||||
const nativeSha256 = createHash('sha256')
|
||||
.update(readFileSync(new URL('../apps/stock/engine/dist/engine.node', import.meta.url)))
|
||||
.digest('hex');
|
||||
const artifactIdentityMs = elapsed();
|
||||
await import('@stock-bot/engine');
|
||||
const addonImportMs = elapsed();
|
||||
const { prepareReplayLoad, NativeReplaySession, runReplayConformance } = await import(
|
||||
|
|
@ -163,19 +317,33 @@ export async function sessionChild(workload: SessionWorkload) {
|
|||
owner => {
|
||||
const decision = counts.get(owner) ?? 0;
|
||||
counts.set(owner, decision + 1);
|
||||
const quantity = profileTarget(
|
||||
workload.profile,
|
||||
decision,
|
||||
workload.totalBars / workload.assets
|
||||
);
|
||||
return {
|
||||
mode: 'target',
|
||||
targets: fixture.instruments.map(instrumentId => ({
|
||||
instrumentId,
|
||||
quantity: decision % 2 ? zero : one,
|
||||
})),
|
||||
targets:
|
||||
quantity === null
|
||||
? []
|
||||
: fixture.instruments.map(instrumentId => ({
|
||||
instrumentId,
|
||||
quantity: quantity === 0 ? zero : one,
|
||||
})),
|
||||
};
|
||||
},
|
||||
{ eventBudget: workload.eventBudget, reverseCallbacks: repeat === 1 }
|
||||
{
|
||||
eventBudget: workload.eventBudget,
|
||||
reverseCallbacks: repeat === 1,
|
||||
resultFormat: workload.resultFormat,
|
||||
}
|
||||
);
|
||||
const runWallMs = performance.now() - runStart;
|
||||
const validationStart = performance.now();
|
||||
const economic = assertEconomics(result, workload);
|
||||
assertResultFormat(result, workload.resultFormat);
|
||||
const common = commonFinancialProjection(result);
|
||||
const economic = assertEconomics(result, workload, common.fills);
|
||||
const decisions = [...counts.values()].reduce((a, b) => a + b, 0);
|
||||
if (decisions !== economic.decisions) {
|
||||
throw new Error('Unexpected benchmark decision count');
|
||||
|
|
@ -183,12 +351,14 @@ export async function sessionChild(workload: SessionWorkload) {
|
|||
// Exact complete normalized result bytes include provenance, ordered receipts,
|
||||
// policy and terminal holdings, not just a selectively hashed P&L summary.
|
||||
const resultHash = hash(JSON.stringify(result));
|
||||
const commonFinancialHash = hash(JSON.stringify(common));
|
||||
const validationAndHashMs = performance.now() - validationStart;
|
||||
const wallMs = performance.now() - trialStart;
|
||||
trials.push({
|
||||
repeat,
|
||||
reverseCallbacks: repeat === 1,
|
||||
resultHash,
|
||||
commonFinancialHash,
|
||||
economic,
|
||||
calls: {
|
||||
create: 1,
|
||||
|
|
@ -213,6 +383,18 @@ export async function sessionChild(workload: SessionWorkload) {
|
|||
submit: metrics.submitMs,
|
||||
decisions: metrics.decisionMs,
|
||||
finalize: metrics.finalizeMs,
|
||||
finalizeNative: metrics.finalizeNativeMs,
|
||||
finalizeDecode: metrics.finalizeDecodeMs,
|
||||
finalizeValidation: metrics.finalizeValidationMs,
|
||||
dispose: metrics.disposeMs,
|
||||
// This is measured time outside the named phases, not an inferred GC cost.
|
||||
unattributedLoop:
|
||||
runWallMs -
|
||||
metrics.advanceMs -
|
||||
metrics.submitMs -
|
||||
metrics.decisionMs -
|
||||
metrics.finalizeMs -
|
||||
metrics.disposeMs,
|
||||
runWallMs,
|
||||
validationAndHashMs,
|
||||
wallMs,
|
||||
|
|
@ -236,15 +418,20 @@ export async function sessionChild(workload: SessionWorkload) {
|
|||
: null;
|
||||
return {
|
||||
workload,
|
||||
nativeSha256,
|
||||
profile: workload.profile,
|
||||
resultFormat: workload.resultFormat,
|
||||
strategyHash: hash(profileDefinitions[workload.profile]),
|
||||
datasetHash: dataset.manifest.hash,
|
||||
policyHash: hash(
|
||||
JSON.stringify({ config: load.config, strategy: 'alternating-unit-target-v1' })
|
||||
JSON.stringify({ config: load.config, strategy: profileDefinitions[workload.profile] })
|
||||
),
|
||||
datasetBytes: Buffer.byteLength(wireDataset),
|
||||
policy: load.config,
|
||||
phasesMs: {
|
||||
entryUptimeMs,
|
||||
applicationImportMs,
|
||||
artifactIdentityMs,
|
||||
addonImportMs,
|
||||
adapterImportMs,
|
||||
fixtureGenerationMs,
|
||||
|
|
@ -261,43 +448,121 @@ export async function sessionChild(workload: SessionWorkload) {
|
|||
}
|
||||
|
||||
export function verifySessionRepeats(
|
||||
samples: { datasetHash: string; policyHash: string; trials: { resultHash: string }[] }[]
|
||||
samples: {
|
||||
datasetHash: string;
|
||||
policyHash: string;
|
||||
nativeSha256: string;
|
||||
profile: ReplayProfile;
|
||||
resultFormat: ReplayResultFormat;
|
||||
strategyHash: string;
|
||||
trials: { resultHash: string; commonFinancialHash: string }[];
|
||||
}[],
|
||||
expectedNativeHash?: string
|
||||
) {
|
||||
const first = samples[0],
|
||||
expected = first?.trials[0]?.resultHash;
|
||||
if (!first || !expected) {
|
||||
if (!first || !expected || !first.trials[0]?.commonFinancialHash) {
|
||||
throw new Error('Missing canonical benchmark samples');
|
||||
}
|
||||
for (const sample of samples) {
|
||||
if (
|
||||
sample.datasetHash !== first.datasetHash ||
|
||||
sample.policyHash !== first.policyHash ||
|
||||
sample.nativeSha256 !== first.nativeSha256 ||
|
||||
(expectedNativeHash !== undefined && sample.nativeSha256 !== expectedNativeHash) ||
|
||||
sample.profile !== first.profile ||
|
||||
sample.resultFormat !== first.resultFormat ||
|
||||
sample.strategyHash !== first.strategyHash ||
|
||||
!sample.trials.length ||
|
||||
sample.trials.some(trial => trial.resultHash !== expected)
|
||||
sample.trials.some(
|
||||
trial =>
|
||||
trial.resultHash !== expected ||
|
||||
trial.commonFinancialHash !== first.trials[0]?.commonFinancialHash
|
||||
)
|
||||
) {
|
||||
throw new Error('Canonical dataset/policy/result mismatch; no timing comparison is valid');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type SessionSample = Parameters<typeof verifySessionRepeats>[0][number];
|
||||
export function verifyProjectionParity(
|
||||
trace: SessionSample[],
|
||||
projection: SessionSample[]
|
||||
): string {
|
||||
verifySessionRepeats(trace);
|
||||
verifySessionRepeats(projection);
|
||||
const a = trace[0],
|
||||
b = projection[0],
|
||||
sharedHash = a?.trials[0]?.commonFinancialHash;
|
||||
if (
|
||||
!a ||
|
||||
!b ||
|
||||
!sharedHash ||
|
||||
a.resultFormat !== 'trace' ||
|
||||
b.resultFormat !== 'projection' ||
|
||||
a.datasetHash !== b.datasetHash ||
|
||||
a.policyHash !== b.policyHash ||
|
||||
a.strategyHash !== b.strategyHash ||
|
||||
a.profile !== b.profile ||
|
||||
a.nativeSha256 !== b.nativeSha256 ||
|
||||
sharedHash !== b.trials[0]?.commonFinancialHash
|
||||
) {
|
||||
throw new Error('Compact/trace financial projection or provenance mismatch');
|
||||
}
|
||||
return sharedHash;
|
||||
}
|
||||
|
||||
function median(values: number[]): number {
|
||||
const sorted = [...values].sort((a, b) => a - b),
|
||||
middle = Math.floor(sorted.length / 2),
|
||||
upper = sorted[middle],
|
||||
lower = sorted[Math.max(0, middle - 1)];
|
||||
if (upper === undefined || lower === undefined) {
|
||||
throw new Error('Missing measurement samples');
|
||||
}
|
||||
return sorted.length % 2 ? upper : (lower + upper) / 2;
|
||||
}
|
||||
|
||||
export async function sessionBenchmark(
|
||||
root: string,
|
||||
entry: string,
|
||||
metadata: object,
|
||||
metadata: { native: { sha256: string } },
|
||||
measured: boolean,
|
||||
large: boolean
|
||||
large: boolean,
|
||||
options: SessionOptions = { profiles: ['turnover'], resultFormat: 'trace' }
|
||||
) {
|
||||
const workloads = (measured ? (large ? [1000, 10000, 100000] : [1000, 10000]) : [8]).flatMap(
|
||||
bars => [
|
||||
{ totalBars: bars, assets: 1, owners: 1, eventBudget: 64 },
|
||||
{
|
||||
totalBars: measured ? bars : bars * 2,
|
||||
assets: measured ? 10 : 2,
|
||||
owners: 2,
|
||||
eventBudget: 64,
|
||||
},
|
||||
]
|
||||
);
|
||||
const sizes = options.totalBars
|
||||
? [options.totalBars]
|
||||
: measured
|
||||
? large
|
||||
? [1000, 10000, 100000]
|
||||
: [1000, 10000]
|
||||
: [8];
|
||||
const formats: ReplayResultFormat[] =
|
||||
options.resultFormat === 'both' ? ['trace', 'projection'] : [options.resultFormat];
|
||||
const workloads = options.profiles
|
||||
.flatMap(profile =>
|
||||
sizes.flatMap(bars => [
|
||||
{
|
||||
totalBars: bars,
|
||||
assets: 1,
|
||||
owners: 1,
|
||||
eventBudget: 64,
|
||||
profile,
|
||||
resultFormat: 'trace' as const,
|
||||
},
|
||||
{
|
||||
totalBars: measured ? bars : bars * 2,
|
||||
assets: measured ? 10 : 2,
|
||||
owners: 2,
|
||||
eventBudget: 64,
|
||||
profile,
|
||||
resultFormat: 'trace' as const,
|
||||
},
|
||||
])
|
||||
)
|
||||
.flatMap(workload => formats.map(resultFormat => ({ ...workload, resultFormat })));
|
||||
const measurements = [];
|
||||
for (const workload of workloads) {
|
||||
const samples = [];
|
||||
|
|
@ -331,21 +596,59 @@ export async function sessionBenchmark(
|
|||
processBarsPerSecond: (workload.totalBars * sample.trials.length) / (processWallMs / 1000),
|
||||
});
|
||||
}
|
||||
verifySessionRepeats(samples);
|
||||
measurements.push({ workload, repeatedResultHashesMatch: true, samples });
|
||||
verifySessionRepeats(samples, metadata.native.sha256);
|
||||
const trials = samples.flatMap(sample => sample.trials),
|
||||
firstTrial = trials[0];
|
||||
if (!firstTrial) {
|
||||
throw new Error('Missing measurement trials');
|
||||
}
|
||||
const breakdown = {
|
||||
samples: trials.length,
|
||||
medianMs: Object.fromEntries(
|
||||
Object.keys(firstTrial.timingsMs).map(key => [
|
||||
key,
|
||||
median(trials.map(trial => trial.timingsMs[key as keyof typeof trial.timingsMs])),
|
||||
])
|
||||
),
|
||||
resultBytes: firstTrial.bytes.finalizeResponse,
|
||||
};
|
||||
measurements.push({ workload, repeatedResultHashesMatch: true, breakdown, samples });
|
||||
process.stderr.write(
|
||||
`Verified canonical ${workload.totalBars} bars / ${workload.assets} assets / ${workload.owners} owners, 2 fresh processes × 2 fresh sessions\n`
|
||||
`Verified canonical ${workload.profile}/${workload.resultFormat}: ${workload.totalBars} bars / ${workload.assets} assets / ${workload.owners} owners, 2 fresh processes × 2 fresh sessions\n`
|
||||
);
|
||||
}
|
||||
const comparisons = [];
|
||||
if (options.resultFormat === 'both') {
|
||||
for (let index = 0; index < measurements.length; index += 2) {
|
||||
const trace = measurements[index],
|
||||
projection = measurements[index + 1];
|
||||
if (!trace || !projection) {
|
||||
throw new Error('Missing paired measurements');
|
||||
}
|
||||
const commonFinancialHash = verifyProjectionParity(trace.samples, projection.samples);
|
||||
comparisons.push({
|
||||
profile: trace.workload.profile,
|
||||
totalBars: trace.workload.totalBars,
|
||||
assets: trace.workload.assets,
|
||||
owners: trace.workload.owners,
|
||||
commonFinancialHash,
|
||||
trace: trace.breakdown,
|
||||
projection: projection.breakdown,
|
||||
});
|
||||
}
|
||||
}
|
||||
process.stdout.write(
|
||||
JSON.stringify(
|
||||
{
|
||||
schemaVersion: 1,
|
||||
schemaVersion: 2,
|
||||
path: 'canonical-pull-session',
|
||||
mode: measured ? 'measurement' : 'self-test',
|
||||
...metadata,
|
||||
strategy: {
|
||||
definition: 'alternating-unit-target-v1',
|
||||
profiles: options.profiles.map(profile => ({
|
||||
profile,
|
||||
definition: profileDefinitions[profile],
|
||||
})),
|
||||
randomness: 'None; controlled deterministic fixture/decision counters',
|
||||
},
|
||||
unavailable: {
|
||||
|
|
@ -359,6 +662,8 @@ export async function sessionBenchmark(
|
|||
parallelism: 'Sequential trials; no parallel simulation.',
|
||||
perCallDistribution:
|
||||
'Mean and total latency only; no latency histogram or cancellation wall-time claim.',
|
||||
nativeInternals:
|
||||
'Native-call timers include Rust work/serialization and NAPI; no Rust compute/serialization/allocation split.',
|
||||
},
|
||||
limitations: [
|
||||
'Component conformance throughput, not a production strategy or durable research run; no comparison/speedup against legacy economics.',
|
||||
|
|
@ -366,10 +671,14 @@ export async function sessionBenchmark(
|
|||
'First session and repeat are reported separately; no explicit warmup. Every repeated result, including reversed callback order, must match exactly.',
|
||||
'Advance response bytes include immutable context, observation deltas and protocol envelopes; they are not feature payload bytes alone.',
|
||||
'Financial oracle uses integer cents for this fixed-price/unit/1%-fee fixture only. Multi-asset sequential-mark risk semantics remain unchanged.',
|
||||
'Full retained receipts are finalized and parsed; RSS is process-wide, not native residency. Metadata hashing and parent aggregation are outside child timings.',
|
||||
'Trace returns full retained receipts; projection returns compact authoritative fields. Neither mode compacts internal journals. RSS is process-wide, not native residency.',
|
||||
'Source/parent metadata hashing and aggregation are outside child timings. The child addon hash is measured separately in artifactIdentityMs and included in childWallMs.',
|
||||
'Each format retains its own full normalized result hash. Cross-format comparison hashes shared provenance/view and copied fill/effect/fee fields; projection-only LedgerValuation is not recomputed in TypeScript.',
|
||||
'Whole-trial time includes benchmark oracle and both result/projection hashes. runWallMs excludes that benchmark-only validation and includes separately measured disposal. Unattributed loop time is not labelled native work or GC.',
|
||||
'An event budget bounds event count, not elapsed time. JSON throughput and actual decision costs are measured together with boundary work.',
|
||||
],
|
||||
measurements,
|
||||
comparisons,
|
||||
},
|
||||
null,
|
||||
2
|
||||
|
|
|
|||
|
|
@ -5,6 +5,8 @@
|
|||
* bun run scripts/benchmark-research.ts --measure --large # additionally 100k (quadratic queue)
|
||||
* bun run scripts/benchmark-research.ts --session # canonical pull-session self-test
|
||||
* bun run scripts/benchmark-research.ts --session --measure # 1k/10k bars, actual TS decisions
|
||||
* bun run scripts/benchmark-research.ts --session --measure --profile=sparse --bars=10000
|
||||
* bun run scripts/benchmark-research.ts --session --measure --profile=all --format=both --bars=10000
|
||||
* Build workspace libraries/config and the local engine first. JSON stdout; diagnostics stderr.
|
||||
*/
|
||||
import { createHash } from 'node:crypto';
|
||||
|
|
@ -336,6 +338,77 @@ export function verifyRepeats(
|
|||
}
|
||||
}
|
||||
|
||||
/** Explicit benchmark selections, not application dataset/input limits. */
|
||||
export function parseBenchmarkArguments(args: string[]) {
|
||||
const options = {
|
||||
session: false,
|
||||
measured: false,
|
||||
large: false,
|
||||
selfTest: false,
|
||||
profile: 'turnover' as 'none' | 'sparse' | 'turnover' | 'all',
|
||||
resultFormat: 'trace' as 'trace' | 'projection' | 'both',
|
||||
totalBars: undefined as number | undefined,
|
||||
};
|
||||
const seen = new Set<string>();
|
||||
for (const argument of args) {
|
||||
const [flag, value] = argument.split('=');
|
||||
if (!flag || seen.has(flag)) {
|
||||
throw new Error('Duplicate or invalid benchmark flag');
|
||||
}
|
||||
seen.add(flag);
|
||||
switch (flag) {
|
||||
case '--session':
|
||||
options.session = true;
|
||||
break;
|
||||
case '--measure':
|
||||
options.measured = true;
|
||||
break;
|
||||
case '--large':
|
||||
options.large = true;
|
||||
break;
|
||||
case '--self-test':
|
||||
options.selfTest = true;
|
||||
break;
|
||||
case '--profile':
|
||||
if (!['none', 'sparse', 'turnover', 'all'].includes(value ?? '')) {
|
||||
throw new Error('Unknown benchmark profile');
|
||||
}
|
||||
options.profile = value as typeof options.profile;
|
||||
break;
|
||||
case '--format':
|
||||
if (!['trace', 'projection', 'both'].includes(value ?? '')) {
|
||||
throw new Error('Unknown benchmark result format');
|
||||
}
|
||||
options.resultFormat = value as typeof options.resultFormat;
|
||||
break;
|
||||
case '--bars':
|
||||
if (!['1000', '10000', '100000'].includes(value ?? '')) {
|
||||
throw new Error('Benchmark --bars must be1000,10000 or100000');
|
||||
}
|
||||
options.totalBars = Number(value);
|
||||
break;
|
||||
default:
|
||||
throw new Error('Unknown benchmark flag');
|
||||
}
|
||||
if (!['--profile', '--format', '--bars'].includes(flag) && value !== undefined) {
|
||||
throw new Error('Boolean benchmark flags do not accept values');
|
||||
}
|
||||
if (argument.split('=').length > 2) {
|
||||
throw new Error('Invalid benchmark flag value');
|
||||
}
|
||||
}
|
||||
if ((options.large && !options.measured) || (options.selfTest && options.measured)) {
|
||||
throw new Error('Use no flags/--self-test, --measure, or --measure --large');
|
||||
}
|
||||
if (!options.session && ['--profile', '--format', '--bars'].some(flag => seen.has(flag))) {
|
||||
throw new Error('Profile, format and bar selections require --session');
|
||||
}
|
||||
if (options.totalBars !== undefined && (!options.measured || options.large)) {
|
||||
throw new Error('--bars requires --measure and cannot be combined with --large');
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
async function main(args: string[]) {
|
||||
if (args[0] === '--session-child') {
|
||||
const { sessionChild } = await import('./benchmark-replay');
|
||||
|
|
@ -346,25 +419,23 @@ async function main(args: string[]) {
|
|||
process.stdout.write(JSON.stringify(await child(JSON.parse(args[1] ?? ''))) + '\n');
|
||||
return;
|
||||
}
|
||||
if (
|
||||
args.some(a => !['--self-test', '--measure', '--large', '--session'].includes(a)) ||
|
||||
(args.includes('--large') && !args.includes('--measure')) ||
|
||||
(args.includes('--self-test') && args.includes('--measure'))
|
||||
) {
|
||||
throw new Error(
|
||||
'Use no flags/--self-test, --measure, or --measure --large; optionally --session'
|
||||
);
|
||||
}
|
||||
const selection = parseBenchmarkArguments(args);
|
||||
const metadata = identity(); // Excluded from workload timings.
|
||||
const measured = args.includes('--measure');
|
||||
if (args.includes('--session')) {
|
||||
const measured = selection.measured;
|
||||
if (selection.session) {
|
||||
const { sessionBenchmark } = await import('./benchmark-replay');
|
||||
await sessionBenchmark(
|
||||
root,
|
||||
fileURLToPath(import.meta.url),
|
||||
metadata,
|
||||
measured,
|
||||
args.includes('--large')
|
||||
selection.large,
|
||||
{
|
||||
profiles:
|
||||
selection.profile === 'all' ? ['none', 'sparse', 'turnover'] : [selection.profile],
|
||||
resultFormat: selection.resultFormat,
|
||||
totalBars: selection.totalBars,
|
||||
}
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,100 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { turnoverOracle, verifySessionRepeats } from '../benchmark-replay';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import { executeReplayTrace } from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import { nativeReplayFixture } from '../../test/fixtures/native-replay';
|
||||
import {
|
||||
assertResultFormat,
|
||||
commonFinancialProjection,
|
||||
profileOracle,
|
||||
profileTarget,
|
||||
turnoverOracle,
|
||||
verifyProjectionParity,
|
||||
verifySessionRepeats,
|
||||
} from '../benchmark-replay';
|
||||
import { parseBenchmarkArguments } from '../benchmark-research';
|
||||
|
||||
test('canonical benchmark integer-cent oracle includes fees and terminal marks', () => {
|
||||
test('profile_none invokes the same cadence without orders, fees or position books', () => {
|
||||
expect(profileOracle('none', 602, 2, 2)).toEqual({
|
||||
cash: '1000000.00000000',
|
||||
equity: '1000000.00000000',
|
||||
feePerOwner: '0.00000000',
|
||||
quantity: '0.00000000',
|
||||
remainingCost: '0.00000000',
|
||||
fills: 0,
|
||||
decisions: 1202,
|
||||
});
|
||||
for (let decision = 0; decision < 601; decision++) {
|
||||
expect(profileTarget('none', decision, 602)).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
test('profile_sparse buys first and sells last across retained session gaps', () => {
|
||||
expect(profileOracle('sparse', 602, 2, 2)).toEqual({
|
||||
cash: '999999.04000000',
|
||||
equity: '999999.04000000',
|
||||
feePerOwner: '0.48000000',
|
||||
quantity: '0.00000000',
|
||||
remainingCost: '0.00000000',
|
||||
fills: 8,
|
||||
decisions: 1202,
|
||||
});
|
||||
expect(profileTarget('sparse', 0, 602)).toBe(1);
|
||||
expect(profileTarget('sparse', 600, 602)).toBe(0);
|
||||
for (let decision = 1; decision < 600; decision++) {
|
||||
expect(profileTarget('sparse', decision, 602)).toBeNull();
|
||||
}
|
||||
expect(profileOracle('sparse', 4, 1, 1).cash).toBe('1000003.72000000');
|
||||
});
|
||||
|
||||
test('benchmark_profile_arguments preserves defaults and rejects unsupported combinations', () => {
|
||||
expect(parseBenchmarkArguments([])).toMatchObject({
|
||||
session: false,
|
||||
measured: false,
|
||||
profile: 'turnover',
|
||||
resultFormat: 'trace',
|
||||
});
|
||||
expect(parseBenchmarkArguments(['--session'])).toMatchObject({
|
||||
session: true,
|
||||
profile: 'turnover',
|
||||
});
|
||||
expect(
|
||||
parseBenchmarkArguments([
|
||||
'--session',
|
||||
'--measure',
|
||||
'--profile=all',
|
||||
'--format=trace',
|
||||
'--bars=100000',
|
||||
])
|
||||
).toMatchObject({
|
||||
session: true,
|
||||
measured: true,
|
||||
profile: 'all',
|
||||
resultFormat: 'trace',
|
||||
totalBars: 100000,
|
||||
});
|
||||
for (const resultFormat of ['trace', 'projection', 'both'] as const) {
|
||||
expect(parseBenchmarkArguments(['--session', `--format=${resultFormat}`]).resultFormat).toBe(
|
||||
resultFormat
|
||||
);
|
||||
}
|
||||
for (const args of [
|
||||
['--profile=none'],
|
||||
['--session', '--profile=unknown'],
|
||||
['--session', '--format=unknown'],
|
||||
['--session', '--bars=10000'],
|
||||
['--session', '--measure', '--bars=99'],
|
||||
['--large'],
|
||||
['--session', '--measure', '--large', '--bars=10000'],
|
||||
['--self-test', '--measure'],
|
||||
['--session=yes'],
|
||||
['--session', '--session'],
|
||||
['--session', '--profile=none=extra'],
|
||||
]) {
|
||||
expect(() => parseBenchmarkArguments(args)).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
test('profile_turnover integer-cent oracle includes fees and terminal marks', () => {
|
||||
expect(turnoverOracle(3, 1, 1)).toEqual({
|
||||
cash: '1000001.74000000',
|
||||
equity: '1000001.74000000',
|
||||
|
|
@ -27,18 +120,261 @@ test('canonical benchmark rejects any changed provenance or complete result hash
|
|||
const sample = {
|
||||
datasetHash: 'dataset',
|
||||
policyHash: 'policy',
|
||||
trials: [{ resultHash: 'result' }, { resultHash: 'result' }],
|
||||
nativeSha256: 'native',
|
||||
profile: 'turnover' as const,
|
||||
resultFormat: 'trace' as const,
|
||||
strategyHash: 'strategy',
|
||||
trials: [
|
||||
{ resultHash: 'result', commonFinancialHash: 'common' },
|
||||
{ resultHash: 'result', commonFinancialHash: 'common' },
|
||||
],
|
||||
};
|
||||
expect(() => verifySessionRepeats([sample, structuredClone(sample)])).not.toThrow();
|
||||
for (const changed of [
|
||||
{ ...sample, datasetHash: 'changed' },
|
||||
{ ...sample, policyHash: 'changed' },
|
||||
{ ...sample, trials: [{ resultHash: 'changed' }] },
|
||||
{ ...sample, nativeSha256: 'changed' },
|
||||
{ ...sample, strategyHash: 'changed' },
|
||||
{ ...sample, profile: 'none' as const },
|
||||
{ ...sample, resultFormat: 'projection' as const },
|
||||
{ ...sample, trials: [{ resultHash: 'changed', commonFinancialHash: 'common' }] },
|
||||
{ ...sample, trials: [{ resultHash: 'result', commonFinancialHash: 'changed' }] },
|
||||
{ ...sample, trials: [] },
|
||||
]) {
|
||||
expect(() => verifySessionRepeats([sample, changed])).toThrow('mismatch');
|
||||
}
|
||||
expect(() => verifySessionRepeats([])).toThrow('Missing');
|
||||
expect(() =>
|
||||
verifySessionRepeats([
|
||||
{ ...sample, trials: [{ resultHash: 'result', commonFinancialHash: '' }] },
|
||||
])
|
||||
).toThrow('Missing');
|
||||
expect(() => verifySessionRepeats([sample], 'different-artifact')).toThrow('mismatch');
|
||||
});
|
||||
|
||||
function normalizerFixture() {
|
||||
const fixture = nativeReplayFixture();
|
||||
const input = {
|
||||
type: 'runReplayTrace' as const,
|
||||
version: 1 as const,
|
||||
dataset: fixture.dataset,
|
||||
config: fixture.config,
|
||||
eventBudget: 1,
|
||||
trace: [
|
||||
{
|
||||
at: fixture.start + fixture.minute,
|
||||
ownerId: 'A',
|
||||
intent: {
|
||||
mode: 'target' as const,
|
||||
targets: [{ instrumentId: 'X0.US', quantity: parseFinancialDecimal('2') }],
|
||||
},
|
||||
},
|
||||
{
|
||||
at: fixture.start + 2 * fixture.minute,
|
||||
ownerId: 'A',
|
||||
intent: { mode: 'target' as const, targets: [] },
|
||||
},
|
||||
],
|
||||
};
|
||||
return {
|
||||
trace: executeReplayTrace(input).result,
|
||||
projection: executeReplayTrace({ ...input, resultFormat: 'projection' }).result,
|
||||
};
|
||||
}
|
||||
|
||||
test('common financial projection copies authoritative fill facts without valuing positions', () => {
|
||||
const { trace, projection } = normalizerFixture();
|
||||
const common = commonFinancialProjection(trace);
|
||||
expect(commonFinancialProjection(projection)).toEqual(common);
|
||||
expect(common).not.toHaveProperty('valuation');
|
||||
expect(common.fills).toHaveLength(1);
|
||||
expect(common.fills[0]).toMatchObject({
|
||||
cashDelta: '-24.00000000',
|
||||
fee: { amount: '0.24000000' },
|
||||
});
|
||||
for (const field of [
|
||||
'commandId',
|
||||
'eventTime',
|
||||
'ownerId',
|
||||
'orderId',
|
||||
'fillId',
|
||||
'instrumentId',
|
||||
'price',
|
||||
'cashDelta',
|
||||
'quantityDelta',
|
||||
'releasedBasis',
|
||||
'realizedGrossPnl',
|
||||
] as const) {
|
||||
const changed = structuredClone(projection);
|
||||
const fill = changed.projection.fills[0]!;
|
||||
Object.assign(fill, {
|
||||
[field]: typeof fill[field] === 'number' ? Number(fill[field]) + 1 : 'changed',
|
||||
});
|
||||
expect(commonFinancialProjection(changed)).not.toEqual(common);
|
||||
}
|
||||
for (const field of ['feeId', 'amount'] as const) {
|
||||
const changed = structuredClone(projection);
|
||||
Object.assign(changed.projection.fills[0]!.fee, { [field]: 'changed' });
|
||||
expect(commonFinancialProjection(changed)).not.toEqual(common);
|
||||
}
|
||||
expect(() => assertResultFormat(trace, 'trace')).not.toThrow();
|
||||
expect(() => assertResultFormat(projection, 'projection')).not.toThrow();
|
||||
expect(() => assertResultFormat(trace, 'projection')).toThrow('format mismatch');
|
||||
expect(() => assertResultFormat(projection, 'trace')).toThrow('format mismatch');
|
||||
});
|
||||
|
||||
test('common projection skips matching, risk and financial replay aliases independently', () => {
|
||||
const { trace } = normalizerFixture();
|
||||
const receipt = trace.receipts.find(r =>
|
||||
r.outcome.effects.some((effect: any) =>
|
||||
effect.Risk?.outcome.financial?.effects.effects.some((e: any) => e.kind === 'fillApplied')
|
||||
)
|
||||
)!;
|
||||
expect(receipt).toBeDefined();
|
||||
for (const level of ['matching', 'risk', 'financial']) {
|
||||
const alias = structuredClone(receipt);
|
||||
const risk: any = alias.outcome.effects.find((effect: any) =>
|
||||
effect.Risk?.outcome.financial?.effects.effects.some((e: any) => e.kind === 'fillApplied')
|
||||
)!.Risk;
|
||||
if (level === 'matching') {
|
||||
alias.outcome.replayed = true;
|
||||
} else if (level === 'risk') {
|
||||
risk.outcome.replayed = true;
|
||||
} else {
|
||||
risk.outcome.financial.replayed = true;
|
||||
}
|
||||
expect(commonFinancialProjection({ ...trace, receipts: [receipt, alias] }).fills).toHaveLength(
|
||||
1
|
||||
);
|
||||
expect(commonFinancialProjection({ ...trace, receipts: [alias] }).fills).toHaveLength(0);
|
||||
}
|
||||
});
|
||||
|
||||
test('common projection handles 100k multi-owner turnover without argument spreading', () => {
|
||||
const { projection } = normalizerFixture();
|
||||
projection.projection.fills = Array.from(
|
||||
{ length: 200000 },
|
||||
() => projection.projection.fills[0]!
|
||||
);
|
||||
const common = commonFinancialProjection(projection);
|
||||
expect(common.fills).toHaveLength(200000);
|
||||
expect(common.fills.at(-1)).toEqual(common.fills[0]!);
|
||||
});
|
||||
|
||||
test('common projection rejects missing, duplicate or mismatched financial fee pairs', () => {
|
||||
const { trace } = normalizerFixture();
|
||||
for (const change of ['missing', 'extra', 'owner', 'fill', 'rejection']) {
|
||||
const invalid = structuredClone(trace);
|
||||
const risk: any = invalid.receipts
|
||||
.flatMap(r => r.outcome.effects)
|
||||
.map(effect => effect.Risk)
|
||||
.find((r: any) =>
|
||||
r?.outcome.financial?.effects.effects.some((e: any) => e.kind === 'fillApplied')
|
||||
);
|
||||
const effects = risk.outcome.financial.effects.effects;
|
||||
const fee = effects.find((e: any) => e.kind === 'feeApplied');
|
||||
if (change === 'missing') {
|
||||
effects.splice(effects.indexOf(fee), 1);
|
||||
} else if (change === 'extra') {
|
||||
effects.push(structuredClone(fee));
|
||||
} else if (change === 'owner') {
|
||||
fee.ownerId = 'other';
|
||||
} else if (change === 'fill') {
|
||||
fee.fillId = 'other';
|
||||
} else {
|
||||
risk.outcome.disposition = { Rejected: 'fixture' };
|
||||
}
|
||||
expect(() => commonFinancialProjection(invalid)).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
test('paired comparison requires shared economics and provenance while retaining distinct full hashes', () => {
|
||||
const trace = {
|
||||
datasetHash: 'dataset',
|
||||
policyHash: 'policy',
|
||||
nativeSha256: 'native',
|
||||
profile: 'sparse' as const,
|
||||
resultFormat: 'trace' as const,
|
||||
strategyHash: 'strategy',
|
||||
trials: [{ resultHash: 'full-trace', commonFinancialHash: 'common' }],
|
||||
};
|
||||
const projection = {
|
||||
...trace,
|
||||
resultFormat: 'projection' as const,
|
||||
trials: [{ resultHash: 'compact-projection', commonFinancialHash: 'common' }],
|
||||
};
|
||||
expect(verifyProjectionParity([trace], [projection])).toBe('common');
|
||||
for (const changed of [
|
||||
{ ...projection, datasetHash: 'changed' },
|
||||
{ ...projection, policyHash: 'changed' },
|
||||
{ ...projection, nativeSha256: 'changed' },
|
||||
{ ...projection, strategyHash: 'changed' },
|
||||
{ ...projection, profile: 'none' as const },
|
||||
{ ...projection, resultFormat: 'trace' as const },
|
||||
{
|
||||
...projection,
|
||||
trials: [{ resultHash: 'compact-projection', commonFinancialHash: 'changed' }],
|
||||
},
|
||||
]) {
|
||||
expect(() => verifyProjectionParity([trace], [changed])).toThrow('mismatch');
|
||||
}
|
||||
});
|
||||
|
||||
test('all tiny replay profiles pin financial expectations and distinct strategy identities', async () => {
|
||||
const worker = Bun.spawn(
|
||||
[
|
||||
process.execPath,
|
||||
'scripts/benchmark-research.ts',
|
||||
'--session',
|
||||
'--profile=all',
|
||||
'--format=both',
|
||||
],
|
||||
{
|
||||
cwd: new URL('../..', import.meta.url).pathname,
|
||||
stdout: 'pipe',
|
||||
stderr: 'pipe',
|
||||
}
|
||||
);
|
||||
const [stdout, stderr, exit] = await Promise.all([
|
||||
new Response(worker.stdout).text(),
|
||||
new Response(worker.stderr).text(),
|
||||
worker.exited,
|
||||
]);
|
||||
expect(exit, stderr).toBe(0);
|
||||
const report = JSON.parse(stdout);
|
||||
expect(report.measurements).toHaveLength(12);
|
||||
expect(report.comparisons).toHaveLength(6);
|
||||
for (const comparison of report.comparisons) {
|
||||
expect(comparison.commonFinancialHash).toMatch(/^[a-f0-9]{64}$/);
|
||||
expect(comparison.projection.resultBytes).toBeLessThan(comparison.trace.resultBytes);
|
||||
}
|
||||
expect(new Set(report.measurements.map((m: any) => m.samples[0].strategyHash)).size).toBe(3);
|
||||
for (const measurement of report.measurements) {
|
||||
verifySessionRepeats(measurement.samples, report.native.sha256);
|
||||
const workload = measurement.workload;
|
||||
const expected = profileOracle(
|
||||
workload.profile,
|
||||
workload.totalBars / workload.assets,
|
||||
workload.assets,
|
||||
workload.owners
|
||||
);
|
||||
for (const sample of measurement.samples) {
|
||||
expect(sample.profile).toBe(workload.profile);
|
||||
expect(sample.resultFormat).toBe(workload.resultFormat);
|
||||
for (const trial of sample.trials) {
|
||||
expect(trial.economic).toEqual({ ...expected, fees: expected.fills });
|
||||
for (const value of Object.values(trial.timingsMs) as number[]) {
|
||||
expect(Number.isFinite(value)).toBe(true);
|
||||
expect(value).toBeGreaterThanOrEqual(0);
|
||||
}
|
||||
expect(trial.timingsMs.finalize).toBeGreaterThanOrEqual(
|
||||
trial.timingsMs.finalizeNative +
|
||||
trial.timingsMs.finalizeDecode +
|
||||
trial.timingsMs.finalizeValidation
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('canonical self-test measures real sessions and verifies repeated full-result hashes', async () => {
|
||||
|
|
|
|||
|
|
@ -72,6 +72,7 @@ describe('generated native bindings', () => {
|
|||
expect(binding.TechnicalIndicators).toBe(TechnicalIndicators);
|
||||
expect(binding.IncrementalSMA).toBe(IncrementalSMA);
|
||||
expect(binding.FinancialReplaySession).toBe(FinancialReplaySession);
|
||||
expect(typeof FinancialReplaySession.prototype.project).toBe('function');
|
||||
});
|
||||
|
||||
it('MACD keeps full-length EMA series aligned without out-of-bounds access', () => {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue