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
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue