159 lines
6.5 KiB
TypeScript
159 lines
6.5 KiB
TypeScript
import { randomUUID } from 'node:crypto';
|
|
import { beforeAll, expect, test } from 'bun:test';
|
|
import {
|
|
canonicalRunRequestSchema,
|
|
type CanonicalRunResult,
|
|
} from '@stock-bot/stock-config/canonical-research';
|
|
import { parseFinancialDecimal } from '@stock-bot/types';
|
|
import { buildCanonicalBacktestReport } from '../../apps/stock/orchestrator/src/backtest/canonical-result';
|
|
import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
|
import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
|
|
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
|
|
import { canonicalReproductionHash } from '../../apps/stock/web-api/src/services/reproduction-comparison';
|
|
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
|
|
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
|
|
|
let original: CanonicalRunResult;
|
|
let reproduced: CanonicalRunResult;
|
|
beforeAll(async () => {
|
|
const pkg = (await packageBuiltinStrategies())[0]!;
|
|
const versionId = randomUUID();
|
|
const fixture = canonicalSmaFixture([`strategy:${versionId}`]);
|
|
const runId = randomUUID();
|
|
fixture.config.matching.risk.ledger.sessionId = runId;
|
|
fixture.config.matching.risk.ledger.accountId = `research:${runId}`;
|
|
const request = canonicalRunRequestSchema.parse({
|
|
kind: 'canonical-research/v1',
|
|
runId,
|
|
backtestId: randomUUID(),
|
|
name: 'Comparison fixture',
|
|
strategy: {
|
|
familyId: randomUUID(),
|
|
versionId,
|
|
origin: 'builtin',
|
|
reviewId: randomUUID(),
|
|
package: pkg,
|
|
selection: fixture.selections[0],
|
|
},
|
|
datasetHash: fixture.dataset.manifest.hash,
|
|
policy: fixture.config,
|
|
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
|
|
// Projection fixtures; admission/build verification is covered by PostgreSQL native tests.
|
|
build: {
|
|
version: 1,
|
|
workerSha256: 'a'.repeat(64),
|
|
engineWrapperSha256: 'b'.repeat(64),
|
|
engineBinarySha256: 'c'.repeat(64),
|
|
dependencyLockSha256: 'd'.repeat(64),
|
|
runtime: 'bun',
|
|
runtimeVersion: 'fixture',
|
|
platform: 'fixture',
|
|
arch: 'fixture',
|
|
},
|
|
modelArtifacts: [],
|
|
});
|
|
const execute = (input: typeof request): CanonicalRunResult => {
|
|
const financial = runStrategyReplay(
|
|
prepareReplayLoad(fixture.dataset, input.policy),
|
|
[createBuiltinStrategy(input.strategy.selection)],
|
|
{ resultFormat: 'report' }
|
|
).result;
|
|
const report = buildCanonicalBacktestReport(financial, input.analyticsPolicy);
|
|
return {
|
|
kind: 'canonical-result/v1',
|
|
runId: input.runId,
|
|
backtestId: input.backtestId,
|
|
status: 'completed',
|
|
completedAt: new Date().toISOString(),
|
|
executionTime: 1,
|
|
financialEngine: 'rust',
|
|
strategyExecution: 'typescript-retained-builtin/v1',
|
|
request: input,
|
|
...report,
|
|
};
|
|
};
|
|
original = execute(request);
|
|
const next = structuredClone(request);
|
|
next.runId = randomUUID();
|
|
next.policy.matching.risk.ledger.sessionId = next.runId;
|
|
next.policy.matching.risk.ledger.accountId = `research:${next.runId}`;
|
|
next.strategy.reviewId = randomUUID();
|
|
reproduced = execute(next);
|
|
});
|
|
|
|
test('economic_hash_parity: two actual replays ignore only admission identities and wall-clock metadata', () => {
|
|
expect(original.runId).not.toBe(reproduced.runId);
|
|
expect(original.request.strategy.reviewId).not.toBe(reproduced.request.strategy.reviewId);
|
|
expect(original.financial.projection.fills).toHaveLength(2);
|
|
expect(original.financial.projection.fills).toEqual(reproduced.financial.projection.fills);
|
|
const before = JSON.stringify([original, reproduced]);
|
|
expect(canonicalReproductionHash(original)).toMatch(/^[a-f0-9]{64}$/);
|
|
expect(canonicalReproductionHash(original)).toBe(canonicalReproductionHash(reproduced));
|
|
expect(JSON.stringify([original, reproduced])).toBe(before);
|
|
});
|
|
|
|
test('economic hash retains fees, ordered fills, decision ownership, risk, nulls and statistical facts', () => {
|
|
const changes: ((value: CanonicalRunResult) => void)[] = [
|
|
value => {
|
|
value.financial.projection.valuation.fees = parseFinancialDecimal('9');
|
|
},
|
|
value => {
|
|
value.financial.projection.fills[0]!.fee.amount = parseFinancialDecimal('0.51');
|
|
},
|
|
value => {
|
|
value.financial.projection.fills[0]!.price = parseFinancialDecimal('5.1');
|
|
},
|
|
value => {
|
|
value.financial.projection.fills.reverse();
|
|
},
|
|
value => {
|
|
value.financial.projection.fills[0]!.orderId = 'different-order';
|
|
},
|
|
value => {
|
|
value.financial.projection.fills[0]!.ownerId = 'different-owner';
|
|
value.financial.projection.fills[0]!.decision.ownerId = 'different-owner';
|
|
},
|
|
value => {
|
|
value.financial.view.risk.dailyHalted = !value.financial.view.risk.dailyHalted;
|
|
},
|
|
value => {
|
|
value.analytics.metrics.sharpeRatio = 0;
|
|
},
|
|
value => {
|
|
value.analytics.metrics.totalReturn = 0;
|
|
},
|
|
value => {
|
|
value.financial.modelLimitations.push('Additional model limitation');
|
|
},
|
|
value => {
|
|
value.request.strategy.selection.seed++;
|
|
},
|
|
];
|
|
for (const change of changes) {
|
|
const changed = structuredClone(original);
|
|
change(changed);
|
|
expect(canonicalReproductionHash(changed)).not.toBe(canonicalReproductionHash(original));
|
|
}
|
|
});
|
|
|
|
test('economic hash preserves actual market-session identities and execution policy', () => {
|
|
const changed = structuredClone(original);
|
|
changed.financial.view.risk.riskSession.sessionId = 'different-market-session';
|
|
expect(canonicalReproductionHash(changed)).not.toBe(canonicalReproductionHash(original));
|
|
const policy = structuredClone(original);
|
|
policy.request.policy.matching.risk.feeRate = parseFinancialDecimal('0.02');
|
|
policy.financial.policy.matching.risk.feeRate = parseFinancialDecimal('0.02');
|
|
expect(canonicalReproductionHash(policy)).not.toBe(canonicalReproductionHash(original));
|
|
});
|
|
|
|
test('economic hash rejects mixed result/request/session identities rather than hiding them', () => {
|
|
const wrongRun = structuredClone(original);
|
|
wrongRun.runId = randomUUID();
|
|
expect(() => canonicalReproductionHash(wrongRun)).toThrow('identity');
|
|
const wrongSession = structuredClone(original);
|
|
wrongSession.financial.identity.sessionId = randomUUID();
|
|
expect(() => canonicalReproductionHash(wrongSession)).toThrow();
|
|
const wrongAccount = structuredClone(original);
|
|
wrongAccount.financial.view.portfolio.accountId = 'foreign-account';
|
|
expect(() => canonicalReproductionHash(wrongAccount)).toThrow();
|
|
});
|