378 lines
14 KiB
TypeScript
378 lines
14 KiB
TypeScript
/** 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';
|
||
|
||
type SessionWorkload = { totalBars: number; assets: number; owners: number; eventBudget: number };
|
||
const hash = (value: string) => createHash('sha256').update(value).digest('hex');
|
||
const capital = '1000000.00000000';
|
||
|
||
function cents(value: bigint): string {
|
||
const magnitude = value < 0n ? -value : value;
|
||
return `${value < 0n ? '-' : ''}${magnitude / 100n}.${String(magnitude % 100n).padStart(2, '0')}000000`;
|
||
}
|
||
|
||
/** 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) {
|
||
if (
|
||
![barsPerAsset, assets, owners].every(Number.isSafeInteger) ||
|
||
barsPerAsset < 3 ||
|
||
assets < 1 ||
|
||
owners < 1
|
||
) {
|
||
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;
|
||
}
|
||
const books = BigInt(assets * owners),
|
||
holding = (barsPerAsset - 1) % 2;
|
||
const lastOpen = BigInt(10 + ((barsPerAsset - 1) % 20) * 2);
|
||
const cash = 100_000_000n + cashDelta * books;
|
||
return {
|
||
cash: cents(cash),
|
||
equity: cents(cash + BigInt(holding) * (lastOpen + 1n) * 100n * books),
|
||
feePerOwner: cents(fee * BigInt(assets)),
|
||
quantity: `${holding}.00000000`,
|
||
remainingCost: cents(BigInt(holding) * lastOpen * 100n),
|
||
fills: (barsPerAsset - 1) * assets * owners,
|
||
decisions: (barsPerAsset - 1) * owners,
|
||
};
|
||
}
|
||
|
||
function assertEconomics(result: ReplayResult, workload: SessionWorkload) {
|
||
const expected = turnoverOracle(
|
||
workload.totalBars / workload.assets,
|
||
workload.assets,
|
||
workload.owners
|
||
);
|
||
const portfolio = result.view.portfolio;
|
||
if (
|
||
portfolio.cash !== expected.cash ||
|
||
result.view.equity !== expected.equity ||
|
||
portfolio.positions.length !== workload.assets * workload.owners ||
|
||
portfolio.positions.some(
|
||
p => p.quantity !== expected.quantity || p.remainingCost !== expected.remainingCost
|
||
) ||
|
||
portfolio.fees.length !== workload.owners ||
|
||
portfolio.fees.some(f => f.amount !== expected.feePerOwner) ||
|
||
result.view.orders.length ||
|
||
result.view.reservations.length
|
||
) {
|
||
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) {
|
||
throw new Error('Unexpected benchmark fill/fee count');
|
||
}
|
||
return { ...expected, fees };
|
||
}
|
||
|
||
export async function sessionChild(workload: SessionWorkload) {
|
||
const entryUptimeMs = process.uptime() * 1000,
|
||
start = performance.now();
|
||
let clock = start;
|
||
const elapsed = () => {
|
||
const now = performance.now(),
|
||
duration = now - clock;
|
||
clock = now;
|
||
return duration;
|
||
};
|
||
const { validateDatasetV2 } = await import(
|
||
'../apps/stock/orchestrator/src/data/historical-dataset-v2'
|
||
);
|
||
const { nativeReplayFixture } = await import('../test/fixtures/native-replay');
|
||
const { parseFinancialDecimal } = await import('@stock-bot/types');
|
||
const applicationImportMs = elapsed();
|
||
await import('@stock-bot/engine');
|
||
const addonImportMs = elapsed();
|
||
const { prepareReplayLoad, NativeReplaySession, runReplayConformance } = await import(
|
||
'../apps/stock/orchestrator/src/backtest/native-replay'
|
||
);
|
||
const adapterImportMs = elapsed();
|
||
const ownerIds = Array.from({ length: workload.owners }, (_, i) => `owner-${i}`);
|
||
const fixture = nativeReplayFixture(
|
||
workload.totalBars / workload.assets,
|
||
workload.assets,
|
||
ownerIds
|
||
);
|
||
fixture.config.matching.risk.ledger.initialCapital = capital;
|
||
const fixtureGenerationMs = elapsed();
|
||
// Detach so the first verification cannot hit D01's immutable-object cache.
|
||
const wireDataset = JSON.stringify(fixture.dataset);
|
||
const detached = JSON.parse(wireDataset);
|
||
const datasetTransportRoundtripMs = elapsed();
|
||
const dataset = validateDatasetV2(detached);
|
||
const frozenDatasetVerificationMs = elapsed();
|
||
const load = prepareReplayLoad(dataset, fixture.config);
|
||
const preparedReuseAndMappingMs = elapsed();
|
||
const createRequestBytes = Buffer.byteLength(JSON.stringify(load));
|
||
const advanceRequestBytes = Buffer.byteLength(
|
||
JSON.stringify({ identity: load.identity, eventBudget: workload.eventBudget })
|
||
);
|
||
const finalizeRequestBytes = Buffer.byteLength(JSON.stringify(load.identity));
|
||
const requestSizingMs = elapsed();
|
||
const trials = [];
|
||
for (let repeat = 0; repeat < 2; repeat++) {
|
||
const trialStart = performance.now();
|
||
const session = new NativeReplaySession(load);
|
||
const nativeCreateMs = performance.now() - trialStart;
|
||
const counts = new Map<string, number>();
|
||
const one = parseFinancialDecimal('1'),
|
||
zero = parseFinancialDecimal('0');
|
||
const runStart = performance.now();
|
||
const { result, metrics } = runReplayConformance(
|
||
session,
|
||
owner => {
|
||
const decision = counts.get(owner) ?? 0;
|
||
counts.set(owner, decision + 1);
|
||
return {
|
||
mode: 'target',
|
||
targets: fixture.instruments.map(instrumentId => ({
|
||
instrumentId,
|
||
quantity: decision % 2 ? zero : one,
|
||
})),
|
||
};
|
||
},
|
||
{ eventBudget: workload.eventBudget, reverseCallbacks: repeat === 1 }
|
||
);
|
||
const runWallMs = performance.now() - runStart;
|
||
const validationStart = performance.now();
|
||
const economic = assertEconomics(result, workload);
|
||
const decisions = [...counts.values()].reduce((a, b) => a + b, 0);
|
||
if (decisions !== economic.decisions) {
|
||
throw new Error('Unexpected benchmark decision count');
|
||
}
|
||
// 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 validationAndHashMs = performance.now() - validationStart;
|
||
const wallMs = performance.now() - trialStart;
|
||
trials.push({
|
||
repeat,
|
||
reverseCallbacks: repeat === 1,
|
||
resultHash,
|
||
economic,
|
||
calls: {
|
||
create: 1,
|
||
advance: metrics.advanceCalls,
|
||
submit: metrics.submitCalls,
|
||
finalize: 1,
|
||
dispose: 1,
|
||
decisions,
|
||
},
|
||
bytes: {
|
||
createRequest: createRequestBytes,
|
||
advanceRequests: advanceRequestBytes * metrics.advanceCalls,
|
||
advanceResponses: metrics.contextBytes,
|
||
submitRequests: metrics.submissionBytes,
|
||
submitResponses: metrics.outcomeBytes,
|
||
finalizeRequest: finalizeRequestBytes,
|
||
finalizeResponse: metrics.resultBytes,
|
||
},
|
||
timingsMs: {
|
||
nativeCreateMs,
|
||
advance: metrics.advanceMs,
|
||
submit: metrics.submitMs,
|
||
decisions: metrics.decisionMs,
|
||
finalize: metrics.finalizeMs,
|
||
runWallMs,
|
||
validationAndHashMs,
|
||
wallMs,
|
||
},
|
||
meanCallMs: {
|
||
advance: metrics.advanceMs / metrics.advanceCalls,
|
||
submit: metrics.submitMs / metrics.submitCalls,
|
||
},
|
||
rates: {
|
||
runBarsPerSecond: workload.totalBars / (runWallMs / 1000),
|
||
wholeTrialBarsPerSecond: workload.totalBars / (wallMs / 1000),
|
||
decisionsPerSecond: decisions / (runWallMs / 1000),
|
||
trialsPerSecond: 1000 / wallMs,
|
||
},
|
||
rssBytes: process.memoryUsage().rss,
|
||
});
|
||
}
|
||
const peakRss =
|
||
process.platform === 'linux'
|
||
? /^VmHWM:\s+(\d+) kB$/m.exec(readFileSync('/proc/self/status', 'utf8'))
|
||
: null;
|
||
return {
|
||
workload,
|
||
datasetHash: dataset.manifest.hash,
|
||
policyHash: hash(
|
||
JSON.stringify({ config: load.config, strategy: 'alternating-unit-target-v1' })
|
||
),
|
||
datasetBytes: Buffer.byteLength(wireDataset),
|
||
policy: load.config,
|
||
phasesMs: {
|
||
entryUptimeMs,
|
||
applicationImportMs,
|
||
addonImportMs,
|
||
adapterImportMs,
|
||
fixtureGenerationMs,
|
||
datasetTransportRoundtripMs,
|
||
frozenDatasetVerificationMs,
|
||
preparedReuseAndMappingMs,
|
||
requestSizingMs,
|
||
childWallMs: performance.now() - start,
|
||
},
|
||
peakRssBytes: peakRss ? Number(peakRss[1]) * 1024 : null,
|
||
peakRssSource: peakRss ? '/proc/self/status VmHWM' : 'unavailable',
|
||
trials,
|
||
};
|
||
}
|
||
|
||
export function verifySessionRepeats(
|
||
samples: { datasetHash: string; policyHash: string; trials: { resultHash: string }[] }[]
|
||
) {
|
||
const first = samples[0],
|
||
expected = first?.trials[0]?.resultHash;
|
||
if (!first || !expected) {
|
||
throw new Error('Missing canonical benchmark samples');
|
||
}
|
||
for (const sample of samples) {
|
||
if (
|
||
sample.datasetHash !== first.datasetHash ||
|
||
sample.policyHash !== first.policyHash ||
|
||
!sample.trials.length ||
|
||
sample.trials.some(trial => trial.resultHash !== expected)
|
||
) {
|
||
throw new Error('Canonical dataset/policy/result mismatch; no timing comparison is valid');
|
||
}
|
||
}
|
||
}
|
||
|
||
export async function sessionBenchmark(
|
||
root: string,
|
||
entry: string,
|
||
metadata: object,
|
||
measured: boolean,
|
||
large: boolean
|
||
) {
|
||
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 measurements = [];
|
||
for (const workload of workloads) {
|
||
const samples = [];
|
||
for (let processRepeat = 0; processRepeat < 2; processRepeat++) {
|
||
const start = performance.now();
|
||
const worker = Bun.spawn(
|
||
[process.execPath, entry, '--session-child', JSON.stringify(workload)],
|
||
{
|
||
cwd: root,
|
||
stdout: 'pipe',
|
||
stderr: 'pipe',
|
||
env: { ...process.env, NODE_ENV: 'production' },
|
||
}
|
||
);
|
||
const [stdout, stderr, exit] = await Promise.all([
|
||
new Response(worker.stdout).text(),
|
||
new Response(worker.stderr).text(),
|
||
worker.exited,
|
||
]);
|
||
const processWallMs = performance.now() - start;
|
||
if (exit !== 0) {
|
||
throw new Error(`Canonical benchmark child failed (${exit}): ${stderr}\n${stdout}`);
|
||
}
|
||
const sample = JSON.parse(stdout) as Awaited<ReturnType<typeof sessionChild>>;
|
||
samples.push({
|
||
...sample,
|
||
processRepeat,
|
||
processWallMs,
|
||
nativeDiagnosticBytes: Buffer.byteLength(stderr),
|
||
processTrialsPerSecond: sample.trials.length / (processWallMs / 1000),
|
||
processBarsPerSecond: (workload.totalBars * sample.trials.length) / (processWallMs / 1000),
|
||
});
|
||
}
|
||
verifySessionRepeats(samples);
|
||
measurements.push({ workload, repeatedResultHashesMatch: true, samples });
|
||
process.stderr.write(
|
||
`Verified canonical ${workload.totalBars} bars / ${workload.assets} assets / ${workload.owners} owners, 2 fresh processes × 2 fresh sessions\n`
|
||
);
|
||
}
|
||
process.stdout.write(
|
||
JSON.stringify(
|
||
{
|
||
schemaVersion: 1,
|
||
path: 'canonical-pull-session',
|
||
mode: measured ? 'measurement' : 'self-test',
|
||
...metadata,
|
||
strategy: {
|
||
definition: 'alternating-unit-target-v1',
|
||
randomness: 'None; controlled deterministic fixture/decision counters',
|
||
},
|
||
unavailable: {
|
||
storage: 'Synthetic fixture; no database I/O.',
|
||
queue: 'Direct child/session calls, not durable dispatch.',
|
||
allocations: 'No allocation counter or native/JS heap attribution.',
|
||
residentDataset: 'Every trial creates and reloads a fresh native session.',
|
||
pureBoundary:
|
||
'Timings include JS encoding/validation, native work and serialization; not empty NAPI crossing cost.',
|
||
sharedIndicators: 'No indicator cache or feature model in this conformance trace.',
|
||
parallelism: 'Sequential trials; no parallel simulation.',
|
||
perCallDistribution:
|
||
'Mean and total latency only; no latency histogram or cancellation wall-time claim.',
|
||
},
|
||
limitations: [
|
||
'Component conformance throughput, not a production strategy or durable research run; no comparison/speedup against legacy economics.',
|
||
'First imports and detached dataset verification are separate from once-per-child prepared-JS-object mapping and repeated fresh-session loads. OS page caches are not flushed.',
|
||
'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.',
|
||
'An event budget bounds event count, not elapsed time. JSON throughput and actual decision costs are measured together with boundary work.',
|
||
],
|
||
measurements,
|
||
},
|
||
null,
|
||
2
|
||
) + '\n'
|
||
);
|
||
}
|