1078 lines
41 KiB
TypeScript
1078 lines
41 KiB
TypeScript
import { createHash } from 'node:crypto';
|
||
import { describe, expect, it } from 'bun:test';
|
||
import {
|
||
deflatedSharpeRatio,
|
||
effectiveIndependentTrials,
|
||
trialMoments,
|
||
} from '@stock-bot/calculations';
|
||
import {
|
||
HORIZON_BUCKETS,
|
||
MAX_TRIAL_BATCH_SIZE,
|
||
TRIAL_STAGES,
|
||
TrialLedgerError,
|
||
UNIVERSE_MARKETS,
|
||
buildTrialRow,
|
||
canonicalExpressionHash,
|
||
clusterDeflatedSharpe,
|
||
loadClusterTrials,
|
||
recordTrials,
|
||
type BuiltTrialRow,
|
||
type CanonicalExpressionInput,
|
||
type TrialLedgerErrorCode,
|
||
type TrialLedgerExecutor,
|
||
type TrialRowInput,
|
||
} from '@stock-bot/research';
|
||
import {
|
||
HORIZON_BUCKETS as subpathHorizonBuckets,
|
||
MAX_TRIAL_BATCH_SIZE as subpathMaxBatchSize,
|
||
TRIAL_STAGES as subpathTrialStages,
|
||
TrialLedgerError as SubpathTrialLedgerError,
|
||
UNIVERSE_MARKETS as subpathUniverseMarkets,
|
||
buildTrialRow as subpathBuildTrialRow,
|
||
canonicalExpressionHash as subpathCanonicalExpressionHash,
|
||
clusterDeflatedSharpe as subpathClusterDeflatedSharpe,
|
||
loadClusterTrials as subpathLoadClusterTrials,
|
||
recordTrials as subpathRecordTrials,
|
||
} from '@stock-bot/research/trial-ledger';
|
||
|
||
const VALID_AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555';
|
||
const VALID_UUID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee';
|
||
const VALID_HASH = 'a'.repeat(64);
|
||
const VAULT_CUTOFF = '2025-05-01';
|
||
|
||
function createSeededRng(seed: number): () => number {
|
||
let state = seed >>> 0;
|
||
return () => {
|
||
state = (state + 0x6d2b79f5) >>> 0;
|
||
let t = Math.imul(state ^ (state >>> 15), 1 | state);
|
||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
|
||
};
|
||
}
|
||
|
||
function createGaussianSampler(seed: number): () => number {
|
||
const next = createSeededRng(seed);
|
||
let spare: number | null = null;
|
||
return () => {
|
||
if (spare !== null) {
|
||
const value = spare;
|
||
spare = null;
|
||
return value;
|
||
}
|
||
let u = 0;
|
||
let v = 0;
|
||
while (u <= 1e-12) {
|
||
u = next();
|
||
}
|
||
v = next();
|
||
const mag = Math.sqrt(-2 * Math.log(u));
|
||
const theta = 2 * Math.PI * v;
|
||
spare = mag * Math.sin(theta);
|
||
return mag * Math.cos(theta);
|
||
};
|
||
}
|
||
|
||
function makeBusinessDates(startDate: string, count: number): string[] {
|
||
const out = new Array<string>(count);
|
||
const current = new Date(`${startDate}T00:00:00.000Z`);
|
||
let written = 0;
|
||
while (written < count) {
|
||
const day = current.getUTCDay();
|
||
if (day !== 0 && day !== 6) {
|
||
out[written] = current.toISOString().slice(0, 10);
|
||
written += 1;
|
||
}
|
||
current.setUTCDate(current.getUTCDate() + 1);
|
||
}
|
||
return out;
|
||
}
|
||
|
||
function makeSampleSeries(seed: number, length: number, mean = 0.0004, std = 0.01): number[] {
|
||
const gauss = createGaussianSampler(seed);
|
||
const out = new Array<number>(length);
|
||
for (let i = 0; i < length; i += 1) {
|
||
out[i] = mean + std * gauss();
|
||
}
|
||
return out;
|
||
}
|
||
|
||
function makeValidInput(overrides: Partial<TrialRowInput> = {}): TrialRowInput {
|
||
return {
|
||
principalId: 'operator',
|
||
campaignId: null,
|
||
hypothesisId: null,
|
||
stage: 'signal_ic',
|
||
universeMarket: 'US_EQ',
|
||
horizonBucket: 'swing_1_10d',
|
||
expressionHash: VALID_HASH,
|
||
sampleStart: '2020-01-02',
|
||
sampleEnd: '2024-12-31',
|
||
vaultCutoffDate: VAULT_CUTOFF,
|
||
dailySeries: [0.002, -0.001, 0.004, 0.0015, -0.0005, 0.003],
|
||
...overrides,
|
||
};
|
||
}
|
||
|
||
function expectLedgerErrorCode(fn: () => unknown, expectedCode: TrialLedgerErrorCode): void {
|
||
try {
|
||
fn();
|
||
} catch (error) {
|
||
expect(error).toBeInstanceOf(TrialLedgerError);
|
||
expect((error as TrialLedgerError).code).toBe(expectedCode);
|
||
return;
|
||
}
|
||
throw new Error(`Expected TrialLedgerError(${expectedCode}), but call succeeded`);
|
||
}
|
||
|
||
async function expectAsyncLedgerErrorCode(
|
||
fn: () => Promise<unknown>,
|
||
expectedCode: TrialLedgerErrorCode
|
||
): Promise<void> {
|
||
try {
|
||
await fn();
|
||
} catch (error) {
|
||
expect(error).toBeInstanceOf(TrialLedgerError);
|
||
expect((error as TrialLedgerError).code).toBe(expectedCode);
|
||
return;
|
||
}
|
||
throw new Error(`Expected async TrialLedgerError(${expectedCode}), but call succeeded`);
|
||
}
|
||
|
||
interface FakeCall {
|
||
readonly text: string;
|
||
readonly params: readonly unknown[] | undefined;
|
||
}
|
||
|
||
function createFakeExecutor(
|
||
handler?: (text: string, params?: readonly unknown[]) => { rows: readonly Record<string, unknown>[] }
|
||
): { executor: TrialLedgerExecutor; calls: FakeCall[] } {
|
||
const calls: FakeCall[] = [];
|
||
const executor: TrialLedgerExecutor = {
|
||
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
|
||
calls.push({ text, params });
|
||
if (handler !== undefined) {
|
||
return handler(text, params) as { rows: readonly Row[] };
|
||
}
|
||
return { rows: [] };
|
||
},
|
||
};
|
||
return { executor, calls };
|
||
}
|
||
|
||
function builtRowToDbRow(
|
||
row: BuiltTrialRow,
|
||
trialId: number,
|
||
createdAt = '2025-04-01T12:00:00.000Z'
|
||
): Record<string, unknown> {
|
||
return {
|
||
trial_id: String(trialId),
|
||
created_at: new Date(createdAt),
|
||
principal_id: row.principalId,
|
||
campaign_id: row.campaignId,
|
||
stage: row.stage,
|
||
universe_market: row.universeMarket,
|
||
horizon_bucket: row.horizonBucket,
|
||
hypothesis_id: row.hypothesisId,
|
||
expression_hash: row.expressionHash,
|
||
sample_start: row.sampleStart,
|
||
sample_end: row.sampleEnd,
|
||
n_obs: row.nObs,
|
||
sharpe_unann: row.sharpeUnann,
|
||
skewness: row.skewness,
|
||
kurtosis: row.kurtosis,
|
||
daily_series: row.dailySeries.map(v => Math.fround(v)),
|
||
};
|
||
}
|
||
|
||
describe('trial-ledger exports', () => {
|
||
it('exposes identical runtime exports from package root and subpath', () => {
|
||
expect(canonicalExpressionHash).toBe(subpathCanonicalExpressionHash);
|
||
expect(buildTrialRow).toBe(subpathBuildTrialRow);
|
||
expect(recordTrials).toBe(subpathRecordTrials);
|
||
expect(loadClusterTrials).toBe(subpathLoadClusterTrials);
|
||
expect(clusterDeflatedSharpe).toBe(subpathClusterDeflatedSharpe);
|
||
expect(TrialLedgerError).toBe(SubpathTrialLedgerError);
|
||
expect(TRIAL_STAGES).toBe(subpathTrialStages);
|
||
expect(UNIVERSE_MARKETS).toBe(subpathUniverseMarkets);
|
||
expect(HORIZON_BUCKETS).toBe(subpathHorizonBuckets);
|
||
expect(MAX_TRIAL_BATCH_SIZE).toBe(subpathMaxBatchSize);
|
||
});
|
||
});
|
||
|
||
describe('canonicalExpressionHash', () => {
|
||
const baseInput: CanonicalExpressionInput = {
|
||
expression: 'rank(ret_20d) - zscore(vol_20d)',
|
||
params: { lookback: 20, winsor: 0.01, nested: { b: 2, a: 1 } },
|
||
universe: { market: 'US_EQ', minAdvUsd: 5_000_000 },
|
||
sampleStart: '2018-01-02',
|
||
sampleEnd: '2024-12-31',
|
||
horizon: '5d',
|
||
};
|
||
|
||
it('is invariant to top-level/nested key ordering, undefined keys, -0, and expression whitespace', () => {
|
||
const h1 = canonicalExpressionHash(baseInput);
|
||
expect(h1).toMatch(/^[0-9a-f]{64}$/);
|
||
|
||
const reordered: CanonicalExpressionInput = {
|
||
horizon: '5d',
|
||
sampleEnd: '2024-12-31',
|
||
sampleStart: '2018-01-02',
|
||
universe: { minAdvUsd: 5_000_000, market: 'US_EQ', ignored: undefined },
|
||
params: { nested: { a: 1, b: 2, omitMe: undefined }, winsor: 0.01, lookback: 20 },
|
||
expression: ' rank(ret_20d)\n\t - zscore(vol_20d) ',
|
||
};
|
||
expect(canonicalExpressionHash(reordered)).toBe(h1);
|
||
|
||
const negZero = canonicalExpressionHash({
|
||
...baseInput,
|
||
params: { zero: -0 },
|
||
});
|
||
const posZero = canonicalExpressionHash({
|
||
...baseInput,
|
||
params: { zero: 0 },
|
||
});
|
||
expect(negZero).toBe(posZero);
|
||
});
|
||
|
||
it('changes when any field or nested value changes', () => {
|
||
const base = canonicalExpressionHash(baseInput);
|
||
expect(canonicalExpressionHash({ ...baseInput, expression: 'rank(ret_10d) - zscore(vol_20d)' })).not.toBe(base);
|
||
expect(
|
||
canonicalExpressionHash({
|
||
...baseInput,
|
||
params: { lookback: 21, winsor: 0.01, nested: { b: 2, a: 1 } },
|
||
})
|
||
).not.toBe(base);
|
||
expect(
|
||
canonicalExpressionHash({
|
||
...baseInput,
|
||
universe: { market: 'CA_EQ', minAdvUsd: 5_000_000 },
|
||
})
|
||
).not.toBe(base);
|
||
expect(canonicalExpressionHash({ ...baseInput, sampleStart: '2018-01-03' })).not.toBe(base);
|
||
expect(canonicalExpressionHash({ ...baseInput, sampleEnd: '2024-12-30' })).not.toBe(base);
|
||
expect(canonicalExpressionHash({ ...baseInput, horizon: '20d' })).not.toBe(base);
|
||
});
|
||
|
||
it('matches node:crypto SHA-256 bit-for-bit across ASCII, UTF-8, and block-boundary lengths', () => {
|
||
const cases: CanonicalExpressionInput[] = [
|
||
baseInput,
|
||
{
|
||
expression: 'α_momentum + 収益率 🚀',
|
||
params: { label: 'café', tags: ['日本語', 'Ελληνικά'] },
|
||
universe: 'US_EQ',
|
||
sampleStart: '2020-01-02',
|
||
sampleEnd: '2020-12-31',
|
||
horizon: '1d',
|
||
},
|
||
// Exercise SHA-256 padding boundaries (55, 56, 63, 64, 65 bytes of payload variation)
|
||
...[1, 8, 15, 16, 17, 63, 64, 65, 128].map(padLen => ({
|
||
expression: 'x'.repeat(padLen),
|
||
params: null,
|
||
universe: 'FX',
|
||
sampleStart: '2021-01-04',
|
||
sampleEnd: '2021-06-30',
|
||
horizon: 5,
|
||
})),
|
||
];
|
||
|
||
for (const input of cases) {
|
||
const canonicalJson = JSON.stringify({
|
||
expression: input.expression.trim().replace(/\s+/g, ' '),
|
||
horizon: input.horizon,
|
||
params:
|
||
input.params !== null && typeof input.params === 'object' && !Array.isArray(input.params)
|
||
? Object.fromEntries(
|
||
Object.entries(input.params as Record<string, unknown>)
|
||
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
||
.map(([k, v]) => [
|
||
k,
|
||
v !== null && typeof v === 'object' && !Array.isArray(v)
|
||
? Object.fromEntries(
|
||
Object.entries(v as Record<string, unknown>).sort(([a], [b]) =>
|
||
a < b ? -1 : a > b ? 1 : 0
|
||
)
|
||
)
|
||
: v,
|
||
])
|
||
)
|
||
: input.params,
|
||
sampleEnd: input.sampleEnd,
|
||
sampleStart: input.sampleStart,
|
||
universe:
|
||
input.universe !== null &&
|
||
typeof input.universe === 'object' &&
|
||
!Array.isArray(input.universe)
|
||
? Object.fromEntries(
|
||
Object.entries(input.universe as Record<string, unknown>).sort(([a], [b]) =>
|
||
a < b ? -1 : a > b ? 1 : 0
|
||
)
|
||
)
|
||
: input.universe,
|
||
});
|
||
|
||
const expected = createHash('sha256').update(canonicalJson, 'utf8').digest('hex');
|
||
expect(canonicalExpressionHash(input)).toBe(expected);
|
||
}
|
||
});
|
||
|
||
it('rejects non-JSON values, cycles, malformed dates, and inverted sample windows', () => {
|
||
expectLedgerErrorCode(
|
||
() => canonicalExpressionHash({ ...baseInput, expression: ' ' }),
|
||
'INVALID_EXPRESSION_INPUT'
|
||
);
|
||
expectLedgerErrorCode(
|
||
() => canonicalExpressionHash({ ...baseInput, params: { bad: Number.NaN } }),
|
||
'INVALID_EXPRESSION_INPUT'
|
||
);
|
||
expectLedgerErrorCode(
|
||
() => canonicalExpressionHash({ ...baseInput, params: { bad: Number.POSITIVE_INFINITY } }),
|
||
'INVALID_EXPRESSION_INPUT'
|
||
);
|
||
expectLedgerErrorCode(
|
||
() => canonicalExpressionHash({ ...baseInput, params: { bad: 1n } }),
|
||
'INVALID_EXPRESSION_INPUT'
|
||
);
|
||
expectLedgerErrorCode(
|
||
() => canonicalExpressionHash({ ...baseInput, params: { bad: () => 1 } }),
|
||
'INVALID_EXPRESSION_INPUT'
|
||
);
|
||
expectLedgerErrorCode(
|
||
() => canonicalExpressionHash({ ...baseInput, params: { bad: Symbol('x') } }),
|
||
'INVALID_EXPRESSION_INPUT'
|
||
);
|
||
expectLedgerErrorCode(
|
||
() => canonicalExpressionHash({ ...baseInput, params: new Map([['a', 1]]) }),
|
||
'INVALID_EXPRESSION_INPUT'
|
||
);
|
||
expectLedgerErrorCode(
|
||
() => canonicalExpressionHash({ ...baseInput, params: [undefined] }),
|
||
'INVALID_EXPRESSION_INPUT'
|
||
);
|
||
|
||
const cyclic: Record<string, unknown> = {};
|
||
cyclic.self = cyclic;
|
||
expectLedgerErrorCode(
|
||
() => canonicalExpressionHash({ ...baseInput, params: cyclic }),
|
||
'INVALID_EXPRESSION_INPUT'
|
||
);
|
||
|
||
expectLedgerErrorCode(
|
||
() => canonicalExpressionHash({ ...baseInput, sampleStart: '2026-02-29' }),
|
||
'INVALID_DATE'
|
||
);
|
||
expectLedgerErrorCode(
|
||
() =>
|
||
canonicalExpressionHash({
|
||
...baseInput,
|
||
sampleStart: '2024-06-02',
|
||
sampleEnd: '2024-06-01',
|
||
}),
|
||
'INVALID_SAMPLE_WINDOW'
|
||
);
|
||
});
|
||
});
|
||
|
||
describe('buildTrialRow', () => {
|
||
it('computes moments identical to trialMoments and accepts operator and agent principals', () => {
|
||
const series = [0.012, -0.004, 0.007, 0.003, -0.009, 0.015, 0.002, -0.001];
|
||
const expected = trialMoments(series);
|
||
expect(expected).not.toBeNull();
|
||
|
||
const row = buildTrialRow(
|
||
makeValidInput({
|
||
principalId: VALID_AGENT_PRINCIPAL,
|
||
campaignId: VALID_UUID.toUpperCase(),
|
||
hypothesisId: VALID_UUID,
|
||
dailySeries: series,
|
||
})
|
||
);
|
||
|
||
expect(row.principalId).toBe(VALID_AGENT_PRINCIPAL);
|
||
expect(row.campaignId).toBe(VALID_UUID);
|
||
expect(row.hypothesisId).toBe(VALID_UUID);
|
||
expect(row.nObs).toBe(expected!.nObs);
|
||
expect(row.sharpeUnann).toBe(expected!.sharpeUnann);
|
||
expect(row.skewness).toBe(expected!.skewness);
|
||
expect(row.kurtosis).toBe(expected!.kurtosis);
|
||
expect(Object.isFrozen(row)).toBe(true);
|
||
expect(Object.isFrozen(row.dailySeries)).toBe(true);
|
||
});
|
||
|
||
it('rejects every invalid field and vault fence violation with the expected typed error code', () => {
|
||
const invalidCases: readonly [Partial<TrialRowInput>, TrialLedgerErrorCode][] = [
|
||
[{ dailySeries: [] }, 'SERIES_TOO_SHORT'],
|
||
[{ dailySeries: [0.01] }, 'SERIES_TOO_SHORT'],
|
||
[{ dailySeries: [0.01, Number.NaN] }, 'INVALID_SERIES_VALUE'],
|
||
[{ dailySeries: [0.01, Number.POSITIVE_INFINITY] }, 'INVALID_SERIES_VALUE'],
|
||
[{ dailySeries: [0.01, Number.NEGATIVE_INFINITY] }, 'INVALID_SERIES_VALUE'],
|
||
[{ dailySeries: [0.01, 1e40] }, 'INVALID_SERIES_VALUE'],
|
||
[{ dailySeries: [0.01, 1e-50] }, 'INVALID_SERIES_VALUE'],
|
||
[{ dailySeries: [0.01, 0.01, 0.01] }, 'ZERO_VARIANCE_SERIES'],
|
||
[{ dailySeries: [1.0, 1.0 + 1e-12, 1.0 + 2e-12] }, 'ZERO_VARIANCE_SERIES'],
|
||
[{ sampleStart: '2024-05-02', sampleEnd: '2024-05-01' }, 'INVALID_SAMPLE_WINDOW'],
|
||
[{ sampleStart: '2026-02-29' }, 'INVALID_DATE'],
|
||
[{ sampleEnd: '2024-12-31T00:00:00Z' }, 'INVALID_DATE'],
|
||
[{ vaultCutoffDate: '2025-02-29' }, 'INVALID_DATE'],
|
||
[{ principalId: 'service' }, 'INVALID_PRINCIPAL'],
|
||
[{ principalId: '' }, 'INVALID_PRINCIPAL'],
|
||
[{ principalId: 'agent:not-a-uuid' }, 'INVALID_PRINCIPAL'],
|
||
[{ principalId: 'agent:00000000-0000-0000-0000-000000000000' }, 'INVALID_PRINCIPAL'],
|
||
[{ principalId: 'agent:11111111-2222-4333-8444-55555555555A' }, 'INVALID_PRINCIPAL'],
|
||
[{ campaignId: 'not-a-uuid' }, 'INVALID_UUID'],
|
||
[{ hypothesisId: '1234' }, 'INVALID_UUID'],
|
||
[{ stage: 'live_trade' as TrialRowInput['stage'] }, 'INVALID_STAGE'],
|
||
[{ universeMarket: 'US' as TrialRowInput['universeMarket'] }, 'INVALID_UNIVERSE_MARKET'],
|
||
[{ horizonBucket: 'weekly' as TrialRowInput['horizonBucket'] }, 'INVALID_HORIZON_BUCKET'],
|
||
[{ expressionHash: 'A'.repeat(64) }, 'INVALID_EXPRESSION_HASH'],
|
||
[{ expressionHash: 'a'.repeat(63) }, 'INVALID_EXPRESSION_HASH'],
|
||
[{ expressionHash: 'g'.repeat(64) }, 'INVALID_EXPRESSION_HASH'],
|
||
[{ sampleEnd: VAULT_CUTOFF }, 'VAULT_FENCE_VIOLATION'],
|
||
[{ sampleEnd: '2025-05-02' }, 'VAULT_FENCE_VIOLATION'],
|
||
[{ sampleStart: VAULT_CUTOFF, sampleEnd: '2025-06-01' }, 'VAULT_FENCE_VIOLATION'],
|
||
];
|
||
|
||
for (const [overrides, expectedCode] of invalidCases) {
|
||
expectLedgerErrorCode(() => buildTrialRow(makeValidInput(overrides)), expectedCode);
|
||
}
|
||
});
|
||
});
|
||
|
||
describe('recordTrials', () => {
|
||
it('returns [] and issues zero SQL for an empty batch', async () => {
|
||
const { executor, calls } = createFakeExecutor();
|
||
const receipts = await recordTrials(executor, []);
|
||
expect(receipts).toEqual([]);
|
||
expect(calls).toHaveLength(0);
|
||
});
|
||
|
||
it('validates all rows upfront and sends zero SQL when any row is invalid or batch exceeds cap', async () => {
|
||
const { executor, calls } = createFakeExecutor();
|
||
|
||
const invalidOverrides: readonly [Partial<TrialRowInput>, TrialLedgerErrorCode][] = [
|
||
[{ dailySeries: [0.01] }, 'SERIES_TOO_SHORT'],
|
||
[{ dailySeries: [0.01, Number.NaN] }, 'INVALID_SERIES_VALUE'],
|
||
[{ dailySeries: [0.01, 1e40] }, 'INVALID_SERIES_VALUE'],
|
||
[{ dailySeries: [0.01, 1e-50] }, 'INVALID_SERIES_VALUE'],
|
||
[{ dailySeries: [0.01, 0.01] }, 'ZERO_VARIANCE_SERIES'],
|
||
[{ sampleStart: '2024-06-02', sampleEnd: '2024-06-01' }, 'INVALID_SAMPLE_WINDOW'],
|
||
[{ principalId: 'bad' }, 'INVALID_PRINCIPAL'],
|
||
[{ expressionHash: 'bad' }, 'INVALID_EXPRESSION_HASH'],
|
||
[{ sampleEnd: VAULT_CUTOFF }, 'VAULT_FENCE_VIOLATION'],
|
||
];
|
||
|
||
for (const [overrides, expectedCode] of invalidOverrides) {
|
||
await expectAsyncLedgerErrorCode(
|
||
() => recordTrials(executor, [makeValidInput(), makeValidInput(overrides)]),
|
||
expectedCode
|
||
);
|
||
}
|
||
|
||
// Forged pre-built row violating vault fence must also be rejected with zero SQL.
|
||
const validBuilt = buildTrialRow(makeValidInput());
|
||
const forgedBuilt: BuiltTrialRow = { ...validBuilt, sampleEnd: VAULT_CUTOFF };
|
||
await expectAsyncLedgerErrorCode(
|
||
() => recordTrials(executor, [validBuilt, forgedBuilt]),
|
||
'VAULT_FENCE_VIOLATION'
|
||
);
|
||
|
||
// Pre-built row whose dailySeries was replaced with a different same-length vector while
|
||
// retaining stale moments must be rejected with zero SQL.
|
||
const replacementSeries = makeSampleSeries(404, validBuilt.dailySeries.length, -0.002, 0.02);
|
||
const staleMomentsBuilt: BuiltTrialRow = {
|
||
...validBuilt,
|
||
expressionHash: 'f'.repeat(64),
|
||
dailySeries: replacementSeries,
|
||
};
|
||
await expectAsyncLedgerErrorCode(
|
||
() => recordTrials(executor, [validBuilt, staleMomentsBuilt]),
|
||
'INVALID_ROW'
|
||
);
|
||
|
||
// Pre-built row whose dailySeries collapses to constant at float32 REAL precision must be
|
||
// rejected with ZERO_VARIANCE_SERIES and zero SQL.
|
||
const float32CollapsedSeries = [1.0, 1.0 + 1e-12, 1.0 + 2e-12];
|
||
const float32CollapsedMoments = trialMoments(float32CollapsedSeries)!;
|
||
const float32CollapsedBuilt: BuiltTrialRow = {
|
||
...validBuilt,
|
||
nObs: float32CollapsedMoments.nObs,
|
||
sharpeUnann: float32CollapsedMoments.sharpeUnann,
|
||
skewness: float32CollapsedMoments.skewness,
|
||
kurtosis: float32CollapsedMoments.kurtosis,
|
||
dailySeries: float32CollapsedSeries,
|
||
};
|
||
await expectAsyncLedgerErrorCode(
|
||
() => recordTrials(executor, [validBuilt, float32CollapsedBuilt]),
|
||
'ZERO_VARIANCE_SERIES'
|
||
);
|
||
|
||
// Oversized batch rejected before any SQL.
|
||
const oversized = new Array<BuiltTrialRow>(MAX_TRIAL_BATCH_SIZE + 1).fill(validBuilt);
|
||
await expectAsyncLedgerErrorCode(() => recordTrials(executor, oversized), 'BATCH_TOO_LARGE');
|
||
|
||
expect(calls).toHaveLength(0);
|
||
});
|
||
|
||
it('executes one parameterised multi-row INSERT for a 3-horizon batch', async () => {
|
||
const { executor, calls } = createFakeExecutor(() => ({
|
||
rows: [
|
||
{ trial_id: '101', created_at: new Date('2025-04-01T10:00:00.000Z') },
|
||
{ trial_id: '102', created_at: new Date('2025-04-01T10:00:00.001Z') },
|
||
{ trial_id: '103', created_at: new Date('2025-04-01T10:00:00.002Z') },
|
||
],
|
||
}));
|
||
|
||
const horizons = ['1d', '5d', '20d'] as const;
|
||
const batch = horizons.map((horizon, idx) =>
|
||
buildTrialRow(
|
||
makeValidInput({
|
||
horizonBucket: horizon === '20d' ? 'position_10d_plus' : 'swing_1_10d',
|
||
expressionHash: canonicalExpressionHash({
|
||
expression: 'rank(ret_20d)',
|
||
params: { lookback: 20 },
|
||
universe: 'US_EQ',
|
||
sampleStart: '2020-01-02',
|
||
sampleEnd: '2024-12-31',
|
||
horizon,
|
||
}),
|
||
dailySeries: makeSampleSeries(100 + idx, 10),
|
||
})
|
||
)
|
||
);
|
||
|
||
const receipts = await recordTrials(executor, batch);
|
||
expect(calls).toHaveLength(1);
|
||
expect(calls[0]!.text).toContain('INSERT INTO trial_ledger');
|
||
expect(calls[0]!.text).toContain('RETURNING trial_id,');
|
||
expect(calls[0]!.text).toContain('AS created_at');
|
||
expect(calls[0]!.params).toHaveLength(3 * 14);
|
||
expect(receipts).toEqual([
|
||
{ trialId: 101, createdAt: '2025-04-01T10:00:00.000Z' },
|
||
{ trialId: 102, createdAt: '2025-04-01T10:00:00.001Z' },
|
||
{ trialId: 103, createdAt: '2025-04-01T10:00:00.002Z' },
|
||
]);
|
||
});
|
||
|
||
it('preserves PostgreSQL microsecond UTC timestamps across Z and explicit offsets in receipts and asOf queries', async () => {
|
||
const microTs = '2025-04-01T10:00:00.123456Z';
|
||
const rowAtBoundary = builtRowToDbRow(buildTrialRow(makeValidInput()), 7, microTs);
|
||
rowAtBoundary.created_at = microTs;
|
||
const { executor, calls } = createFakeExecutor((text, params) => {
|
||
if (text.startsWith('INSERT INTO trial_ledger')) {
|
||
return { rows: [{ trial_id: '7', created_at: microTs }] };
|
||
}
|
||
const asOfParam = params?.[2] as string | undefined;
|
||
if (asOfParam !== undefined && microTs <= asOfParam) {
|
||
return { rows: [rowAtBoundary] };
|
||
}
|
||
return { rows: [] };
|
||
});
|
||
|
||
const receipts = await recordTrials(executor, [makeValidInput()]);
|
||
expect(receipts).toEqual([{ trialId: 7, createdAt: microTs }]);
|
||
|
||
const zRows = await loadClusterTrials(executor, {
|
||
universeMarket: 'US_EQ',
|
||
horizonBucket: 'swing_1_10d',
|
||
asOf: receipts[0]!.createdAt,
|
||
});
|
||
const plusZeroRows = await loadClusterTrials(executor, {
|
||
universeMarket: 'US_EQ',
|
||
horizonBucket: 'swing_1_10d',
|
||
asOf: '2025-04-01T10:00:00.123456+00:00',
|
||
});
|
||
const plusTwoRows = await loadClusterTrials(executor, {
|
||
universeMarket: 'US_EQ',
|
||
horizonBucket: 'swing_1_10d',
|
||
asOf: '2025-04-01T12:00:00.123456+02:00',
|
||
});
|
||
|
||
expect(calls).toHaveLength(4);
|
||
expect(calls[1]!.params).toEqual(['US_EQ', 'swing_1_10d', microTs]);
|
||
expect(calls[2]!.params).toEqual(['US_EQ', 'swing_1_10d', microTs]);
|
||
expect(calls[3]!.params).toEqual(['US_EQ', 'swing_1_10d', microTs]);
|
||
expect(zRows).toHaveLength(1);
|
||
expect(plusZeroRows).toHaveLength(1);
|
||
expect(plusTwoRows).toHaveLength(1);
|
||
expect(plusZeroRows[0]!.trialId).toBe(zRows[0]!.trialId);
|
||
expect(plusTwoRows[0]!.trialId).toBe(zRows[0]!.trialId);
|
||
});
|
||
});
|
||
|
||
describe('loadClusterTrials and clusterDeflatedSharpe', () => {
|
||
it('validates cluster query inputs before issuing SQL and supports asOf normalization', async () => {
|
||
const { executor, calls } = createFakeExecutor(() => ({ rows: [] }));
|
||
|
||
await expectAsyncLedgerErrorCode(
|
||
() =>
|
||
loadClusterTrials(executor, {
|
||
universeMarket: 'EU_EQ' as 'US_EQ',
|
||
horizonBucket: 'swing_1_10d',
|
||
}),
|
||
'INVALID_UNIVERSE_MARKET'
|
||
);
|
||
await expectAsyncLedgerErrorCode(
|
||
() =>
|
||
loadClusterTrials(executor, {
|
||
universeMarket: 'US_EQ',
|
||
horizonBucket: 'daily' as 'swing_1_10d',
|
||
}),
|
||
'INVALID_HORIZON_BUCKET'
|
||
);
|
||
await expectAsyncLedgerErrorCode(
|
||
() =>
|
||
loadClusterTrials(executor, {
|
||
universeMarket: 'US_EQ',
|
||
horizonBucket: 'swing_1_10d',
|
||
asOf: '2025-04-01T12:00:00', // naive datetime rejected
|
||
}),
|
||
'INVALID_DATE'
|
||
);
|
||
expect(calls).toHaveLength(0);
|
||
|
||
await loadClusterTrials(executor, {
|
||
universeMarket: 'US_EQ',
|
||
horizonBucket: 'swing_1_10d',
|
||
asOf: '2025-04-01',
|
||
});
|
||
expect(calls).toHaveLength(1);
|
||
expect(calls[0]!.text).toContain('AND created_at <= $3::timestamptz');
|
||
expect(calls[0]!.params).toEqual(['US_EQ', 'swing_1_10d', '2025-04-01T23:59:59.999Z']);
|
||
});
|
||
|
||
it('computes exact N-hat and DSR for proven shared-grid prefix/suffix/disjoint windows and sparse observation-date alignment', async () => {
|
||
const baseSeries = makeSampleSeries(701, 100, 0.001, 0.01);
|
||
const twinSeries = baseSeries.map((v, i) => v * 0.98 + (i % 2 === 0 ? 0.0005 : -0.0005));
|
||
const calendar100 = makeBusinessDates('2020-01-02', 100);
|
||
|
||
// 1. Same-start, different-end (prefix overlap) with proven sessionDates grid
|
||
const rowPrefixA = buildTrialRow(
|
||
makeValidInput({
|
||
sampleStart: calendar100[0]!,
|
||
sampleEnd: calendar100[99]!,
|
||
dailySeries: baseSeries,
|
||
})
|
||
);
|
||
const rowPrefixB = buildTrialRow(
|
||
makeValidInput({
|
||
sampleStart: calendar100[0]!,
|
||
sampleEnd: calendar100[69]!,
|
||
dailySeries: twinSeries.slice(0, 70),
|
||
})
|
||
);
|
||
|
||
const dbPrefix = [builtRowToDbRow(rowPrefixA, 1), builtRowToDbRow(rowPrefixB, 2)];
|
||
const prefixExec = createFakeExecutor(text =>
|
||
text.includes('WHERE trial_id = $1') ? { rows: [dbPrefix[0]!] } : { rows: dbPrefix }
|
||
);
|
||
const prefixRes = await clusterDeflatedSharpe(prefixExec.executor, {
|
||
trialId: 1,
|
||
sessionDates: calendar100,
|
||
});
|
||
expect(prefixRes.pairsUsed).toBe(1);
|
||
expect(prefixRes.pairsSkipped).toBe(0);
|
||
expect(prefixRes.meanCorrelation).not.toBeNull();
|
||
expect(prefixRes.meanCorrelation!).toBeGreaterThan(0.95);
|
||
expect(prefixRes.effectiveTrials).toBeLessThan(1.1);
|
||
|
||
// Without proven sessionDates or observationDatesByTrialId, pairs are skipped conservatively.
|
||
const unalignedRes = await clusterDeflatedSharpe(prefixExec.executor, { trialId: 1 });
|
||
expect(unalignedRes.pairsUsed).toBe(0);
|
||
expect(unalignedRes.pairsSkipped).toBe(1);
|
||
expect(unalignedRes.meanCorrelation).toBeNull();
|
||
expect(unalignedRes.effectiveTrials).toBe(2);
|
||
|
||
// 2. Same-end, different-start (suffix overlap) with proven sessionDates grid
|
||
const rowSuffixA = buildTrialRow(
|
||
makeValidInput({
|
||
sampleStart: calendar100[0]!,
|
||
sampleEnd: calendar100[99]!,
|
||
dailySeries: baseSeries,
|
||
})
|
||
);
|
||
const rowSuffixB = buildTrialRow(
|
||
makeValidInput({
|
||
sampleStart: calendar100[30]!,
|
||
sampleEnd: calendar100[99]!,
|
||
dailySeries: twinSeries.slice(30),
|
||
})
|
||
);
|
||
const dbSuffix = [builtRowToDbRow(rowSuffixA, 10), builtRowToDbRow(rowSuffixB, 11)];
|
||
const suffixExec = createFakeExecutor(text =>
|
||
text.includes('WHERE trial_id = $1') ? { rows: [dbSuffix[0]!] } : { rows: dbSuffix }
|
||
);
|
||
const suffixRes = await clusterDeflatedSharpe(suffixExec.executor, {
|
||
trialId: 10,
|
||
sessionDates: calendar100,
|
||
});
|
||
expect(suffixRes.pairsUsed).toBe(1);
|
||
expect(suffixRes.pairsSkipped).toBe(0);
|
||
expect(suffixRes.meanCorrelation!).toBeGreaterThan(0.95);
|
||
|
||
// 3. Disjoint windows on a shared calendar -> pairsSkipped > 0, meanCorrelation === null, effectiveTrials === clusterSize
|
||
const calendar220 = makeBusinessDates('2019-01-02', 220);
|
||
const rowDisjointA = buildTrialRow(
|
||
makeValidInput({
|
||
sampleStart: calendar220[0]!,
|
||
sampleEnd: calendar220[99]!,
|
||
dailySeries: baseSeries,
|
||
})
|
||
);
|
||
const rowDisjointB = buildTrialRow(
|
||
makeValidInput({
|
||
sampleStart: calendar220[120]!,
|
||
sampleEnd: calendar220[219]!,
|
||
dailySeries: twinSeries,
|
||
})
|
||
);
|
||
const dbDisjoint = [builtRowToDbRow(rowDisjointA, 20), builtRowToDbRow(rowDisjointB, 21)];
|
||
const disjointExec = createFakeExecutor(text =>
|
||
text.includes('WHERE trial_id = $1') ? { rows: [dbDisjoint[0]!] } : { rows: dbDisjoint }
|
||
);
|
||
const disjointRes = await clusterDeflatedSharpe(disjointExec.executor, {
|
||
trialId: 20,
|
||
sessionDates: calendar220,
|
||
});
|
||
expect(disjointRes.pairsUsed).toBe(0);
|
||
expect(disjointRes.pairsSkipped).toBe(1);
|
||
expect(disjointRes.meanCorrelation).toBeNull();
|
||
expect(disjointRes.effectiveTrials).toBe(2);
|
||
|
||
const directDsr = deflatedSharpeRatio({
|
||
sharpeUnann: rowDisjointA.sharpeUnann,
|
||
nObs: rowDisjointA.nObs,
|
||
skewness: rowDisjointA.skewness,
|
||
kurtosis: rowDisjointA.kurtosis,
|
||
nHat: 2,
|
||
clusterSharpes: [rowDisjointA.sharpeUnann, rowDisjointB.sharpeUnann],
|
||
});
|
||
expect(disjointRes.dsr).toBeCloseTo(directDsr!.dsr, 12);
|
||
|
||
// 4. Regression: equal-length sparse signal_ic vectors with the same [sampleStart, sampleEnd]
|
||
// where trial 30 omits Tuesday and trial 31 omits Thursday.
|
||
// Values are constructed so naive index pairing yields +1.0, while true date pairing on
|
||
// [Mon, Wed, Fri] yields -1.0.
|
||
const weekDates = ['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04', '2024-01-05'];
|
||
const datesSkipTue = ['2024-01-01', '2024-01-03', '2024-01-04', '2024-01-05'];
|
||
const datesSkipThu = ['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-05'];
|
||
// Index values: A=[+0.02, -0.02, +0.01, -0.01] on [Mon, Wed, Thu, Fri]
|
||
// B=[+0.02, -0.02, +0.01, -0.01] on [Mon, Tue, Wed, Fri]
|
||
// Naive index pairing: identical vectors -> rho = +1.0!
|
||
// True date pairing on [Mon, Wed, Fri]: A=[+0.02, -0.02, -0.01], B=[+0.02, +0.01, -0.01] -> rho != +1.0.
|
||
// Let's make true date pairing strongly negative on [Mon, Wed, Fri]:
|
||
// Mon: A=-0.02, B=+0.02; Wed: A=+0.02, B=-0.02; Fri: A=0.00, B=0.00 -> exact rho = -1.0!
|
||
// And put Tue (B only) = +0.02, Thu (A only) = -0.02 so index-aligned A=[-0.02, +0.02, -0.02, 0.00]
|
||
// vs B=[+0.02, +0.02, -0.02, 0.00] has positive index correlation (+0.333) while true date correlation is -1.0!
|
||
const sparseA = buildTrialRow(
|
||
makeValidInput({
|
||
stage: 'signal_ic',
|
||
sampleStart: weekDates[0]!,
|
||
sampleEnd: weekDates[4]!,
|
||
dailySeries: [-0.02, 0.02, -0.02, 0.0],
|
||
})
|
||
);
|
||
const sparseB = buildTrialRow(
|
||
makeValidInput({
|
||
stage: 'signal_ic',
|
||
sampleStart: weekDates[0]!,
|
||
sampleEnd: weekDates[4]!,
|
||
dailySeries: [0.02, 0.02, -0.02, 0.0],
|
||
})
|
||
);
|
||
const dbSparse = [builtRowToDbRow(sparseA, 30), builtRowToDbRow(sparseB, 31)];
|
||
const sparseExec = createFakeExecutor(text =>
|
||
text.includes('WHERE trial_id = $1') ? { rows: [dbSparse[0]!] } : { rows: dbSparse }
|
||
);
|
||
|
||
// Without observation dates (even when the 5-day session calendar is given), 4 !== 5 proves
|
||
// the vectors are sparse -> skip pair rather than inventing an index-aligned correlation.
|
||
const sparseNoDatesRes = await clusterDeflatedSharpe(sparseExec.executor, {
|
||
trialId: 30,
|
||
sessionDates: weekDates,
|
||
});
|
||
expect(sparseNoDatesRes.pairsUsed).toBe(0);
|
||
expect(sparseNoDatesRes.pairsSkipped).toBe(1);
|
||
expect(sparseNoDatesRes.meanCorrelation).toBeNull();
|
||
expect(sparseNoDatesRes.effectiveTrials).toBe(2);
|
||
|
||
// With explicit observation dates, Mon/Wed/Fri align accurately (rho = -1.0, never mis-pairing Wed with Tue).
|
||
const sparseAlignedRes = await clusterDeflatedSharpe(sparseExec.executor, {
|
||
trialId: 30,
|
||
observationDatesByTrialId: {
|
||
30: datesSkipTue,
|
||
31: datesSkipThu,
|
||
},
|
||
});
|
||
expect(sparseAlignedRes.pairsUsed).toBe(1);
|
||
expect(sparseAlignedRes.pairsSkipped).toBe(0);
|
||
expect(sparseAlignedRes.meanCorrelation).not.toBeNull();
|
||
expect(sparseAlignedRes.meanCorrelation!).toBeCloseTo(-1.0, 6);
|
||
expect(sparseAlignedRes.effectiveTrials).toBe(2);
|
||
|
||
// 5. Regression: clipped sessionDates calendar whose count matches a sparse older trial.
|
||
// Calendar covers only Wed–Fri; older trial spans Tue–Fri and skipped Wed (3 entries).
|
||
const wedToFri = ['2024-01-03', '2024-01-04', '2024-01-05'];
|
||
const targetWedFri = buildTrialRow(
|
||
makeValidInput({
|
||
stage: 'signal_ic',
|
||
sampleStart: '2024-01-03',
|
||
sampleEnd: '2024-01-05',
|
||
dailySeries: [0.01, -0.02, 0.03],
|
||
})
|
||
);
|
||
const olderSparseTueFri = buildTrialRow(
|
||
makeValidInput({
|
||
stage: 'signal_ic',
|
||
sampleStart: '2024-01-02',
|
||
sampleEnd: '2024-01-05',
|
||
dailySeries: [0.01, -0.02, 0.03],
|
||
})
|
||
);
|
||
const dbClippedStart = [
|
||
builtRowToDbRow(targetWedFri, 40),
|
||
builtRowToDbRow(olderSparseTueFri, 41),
|
||
];
|
||
const clippedStartExec = createFakeExecutor(text =>
|
||
text.includes('WHERE trial_id = $1')
|
||
? { rows: [dbClippedStart[0]!] }
|
||
: { rows: dbClippedStart }
|
||
);
|
||
const clippedStartRes = await clusterDeflatedSharpe(clippedStartExec.executor, {
|
||
trialId: 40,
|
||
sessionDates: wedToFri,
|
||
});
|
||
expect(clippedStartRes.pairsUsed).toBe(0);
|
||
expect(clippedStartRes.pairsSkipped).toBe(1);
|
||
expect(clippedStartRes.meanCorrelation).toBeNull();
|
||
expect(clippedStartRes.effectiveTrials).toBe(2);
|
||
|
||
// Symmetric regression: calendar clipped at the end (Tue–Thu) vs a Tue–Fri sparse trial.
|
||
const tueToThu = ['2024-01-02', '2024-01-03', '2024-01-04'];
|
||
const targetTueThu = buildTrialRow(
|
||
makeValidInput({
|
||
stage: 'signal_ic',
|
||
sampleStart: '2024-01-02',
|
||
sampleEnd: '2024-01-04',
|
||
dailySeries: [0.01, -0.02, 0.03],
|
||
})
|
||
);
|
||
const dbClippedEnd = [
|
||
builtRowToDbRow(targetTueThu, 42),
|
||
builtRowToDbRow(olderSparseTueFri, 43),
|
||
];
|
||
const clippedEndExec = createFakeExecutor(text =>
|
||
text.includes('WHERE trial_id = $1') ? { rows: [dbClippedEnd[0]!] } : { rows: dbClippedEnd }
|
||
);
|
||
const clippedEndRes = await clusterDeflatedSharpe(clippedEndExec.executor, {
|
||
trialId: 42,
|
||
sessionDates: tueToThu,
|
||
});
|
||
expect(clippedEndRes.pairsUsed).toBe(0);
|
||
expect(clippedEndRes.pairsSkipped).toBe(1);
|
||
expect(clippedEndRes.meanCorrelation).toBeNull();
|
||
expect(clippedEndRes.effectiveTrials).toBe(2);
|
||
|
||
// 6. Regression: cross-window Pearson skips pairs whose overlap slice is constant even when
|
||
// floating-point rounding in the prefix-sum mean leaves identical nonzero residuals.
|
||
const constOverlapA = buildTrialRow(
|
||
makeValidInput({
|
||
stage: 'signal_ic',
|
||
sampleStart: weekDates[0]!,
|
||
sampleEnd: weekDates[3]!,
|
||
dailySeries: [0, 0.1, 0.1, 0.1],
|
||
})
|
||
);
|
||
const constOverlapB = buildTrialRow(
|
||
makeValidInput({
|
||
stage: 'signal_ic',
|
||
sampleStart: weekDates[1]!,
|
||
sampleEnd: weekDates[4]!,
|
||
dailySeries: [0.1, 0.1, 0.1, -0.1],
|
||
})
|
||
);
|
||
const dbConstOverlap = [
|
||
builtRowToDbRow(constOverlapA, 50),
|
||
builtRowToDbRow(constOverlapB, 51),
|
||
];
|
||
const constOverlapExec = createFakeExecutor(text =>
|
||
text.includes('WHERE trial_id = $1')
|
||
? { rows: [dbConstOverlap[0]!] }
|
||
: { rows: dbConstOverlap }
|
||
);
|
||
const constOverlapRes = await clusterDeflatedSharpe(constOverlapExec.executor, {
|
||
trialId: 50,
|
||
sessionDates: weekDates,
|
||
});
|
||
expect(constOverlapRes.pairsUsed).toBe(0);
|
||
expect(constOverlapRes.pairsSkipped).toBe(1);
|
||
expect(constOverlapRes.meanCorrelation).toBeNull();
|
||
expect(constOverlapRes.effectiveTrials).toBe(2);
|
||
});
|
||
|
||
it('rejects invalid trialId with zero SQL and throws TRIAL_NOT_FOUND when absent or excluded by asOf', async () => {
|
||
const { executor, calls } = createFakeExecutor(() => ({ rows: [] }));
|
||
await expectAsyncLedgerErrorCode(
|
||
() => clusterDeflatedSharpe(executor, { trialId: 0 }),
|
||
'INVALID_TRIAL_ID'
|
||
);
|
||
await expectAsyncLedgerErrorCode(
|
||
() => clusterDeflatedSharpe(executor, { trialId: -5 }),
|
||
'INVALID_TRIAL_ID'
|
||
);
|
||
await expectAsyncLedgerErrorCode(
|
||
() => clusterDeflatedSharpe(executor, { trialId: 'abc' }),
|
||
'INVALID_TRIAL_ID'
|
||
);
|
||
expect(calls).toHaveLength(0);
|
||
|
||
await expectAsyncLedgerErrorCode(
|
||
() => clusterDeflatedSharpe(executor, { trialId: 999 }),
|
||
'TRIAL_NOT_FOUND'
|
||
);
|
||
|
||
const row = buildTrialRow(makeValidInput());
|
||
const dbRow = builtRowToDbRow(row, 42, '2025-04-10T00:00:00.000Z');
|
||
const asOfExec = createFakeExecutor(text =>
|
||
text.includes('WHERE trial_id = $1') ? { rows: [dbRow] } : { rows: [] }
|
||
);
|
||
await expectAsyncLedgerErrorCode(
|
||
() =>
|
||
clusterDeflatedSharpe(asOfExec.executor, {
|
||
trialId: 42,
|
||
asOf: '2025-04-01T00:00:00Z',
|
||
}),
|
||
'TRIAL_NOT_FOUND'
|
||
);
|
||
});
|
||
});
|
||
|
||
describe('trial-ledger in-memory benchmark', () => {
|
||
it('benchmarks 200 trials x 5,000 daily observations for shared-window and staggered-window clusters', async () => {
|
||
const trialCount = 200;
|
||
const obsPerTrial = 5_000;
|
||
const gauss = createGaussianSampler(20260403);
|
||
const sharedSessionDates = makeBusinessDates('2005-01-03', obsPerTrial);
|
||
const sharedStart = sharedSessionDates[0]!;
|
||
const sharedEnd = sharedSessionDates[obsPerTrial - 1]!;
|
||
|
||
// Pre-generate common factor + idiosyncratic series outside the timed region.
|
||
const common = new Array<number>(obsPerTrial);
|
||
for (let t = 0; t < obsPerTrial; t += 1) {
|
||
common[t] = 0.0003 + 0.008 * gauss();
|
||
}
|
||
const rawInputs: TrialRowInput[] = new Array(trialCount);
|
||
for (let k = 0; k < trialCount; k += 1) {
|
||
const series = new Array<number>(obsPerTrial);
|
||
const loading = 0.35 + (k % 5) * 0.05;
|
||
const noiseScale = Math.sqrt(1 - loading * loading) * 0.01;
|
||
for (let t = 0; t < obsPerTrial; t += 1) {
|
||
series[t] = loading * (common[t] as number) + noiseScale * gauss();
|
||
}
|
||
rawInputs[k] = {
|
||
principalId: 'operator',
|
||
stage: 'signal_ic',
|
||
universeMarket: 'US_EQ',
|
||
horizonBucket: 'swing_1_10d',
|
||
expressionHash: k.toString(16).padStart(64, '0'),
|
||
sampleStart: sharedStart,
|
||
sampleEnd: sharedEnd,
|
||
vaultCutoffDate: VAULT_CUTOFF,
|
||
dailySeries: series,
|
||
};
|
||
}
|
||
|
||
const startNs = Bun.nanoseconds();
|
||
|
||
const builtRows: BuiltTrialRow[] = new Array(trialCount);
|
||
const dbRows: Record<string, unknown>[] = new Array(trialCount);
|
||
for (let k = 0; k < trialCount; k += 1) {
|
||
const built = buildTrialRow(rawInputs[k] as TrialRowInput);
|
||
builtRows[k] = built;
|
||
dbRows[k] = {
|
||
trial_id: String(k + 1),
|
||
created_at: '2025-04-01T12:00:00.000Z',
|
||
principal_id: built.principalId,
|
||
campaign_id: built.campaignId,
|
||
stage: built.stage,
|
||
universe_market: built.universeMarket,
|
||
horizon_bucket: built.horizonBucket,
|
||
hypothesis_id: built.hypothesisId,
|
||
expression_hash: built.expressionHash,
|
||
sample_start: built.sampleStart,
|
||
sample_end: built.sampleEnd,
|
||
n_obs: built.nObs,
|
||
sharpe_unann: built.sharpeUnann,
|
||
skewness: built.skewness,
|
||
kurtosis: built.kurtosis,
|
||
daily_series: built.dailySeries,
|
||
};
|
||
}
|
||
|
||
const memExecutor: TrialLedgerExecutor = {
|
||
async query<Row = Record<string, unknown>>(text: string) {
|
||
if (text.includes('WHERE trial_id = $1')) {
|
||
return { rows: [dbRows[0] as unknown as Row] };
|
||
}
|
||
return { rows: dbRows as unknown as Row[] };
|
||
},
|
||
};
|
||
|
||
const result = await clusterDeflatedSharpe(memExecutor, {
|
||
trialId: 1,
|
||
sessionDates: sharedSessionDates,
|
||
});
|
||
const elapsedMs = (Bun.nanoseconds() - startNs) / 1e6;
|
||
const trialsPerSec = trialCount / (elapsedMs / 1000);
|
||
|
||
// Staggered rolling-window benchmark: 200 distinct shifted windows (each shifted by 1 session
|
||
// across a 5,199-session calendar) verifying zero dense NaN padding overhead.
|
||
const staggeredCalendar = makeBusinessDates('2004-01-02', obsPerTrial + trialCount - 1);
|
||
const staggeredDbRows: Record<string, unknown>[] = new Array(trialCount);
|
||
for (let k = 0; k < trialCount; k += 1) {
|
||
const built = builtRows[k] as BuiltTrialRow;
|
||
staggeredDbRows[k] = {
|
||
...dbRows[k],
|
||
sample_start: staggeredCalendar[k]!,
|
||
sample_end: staggeredCalendar[k + obsPerTrial - 1]!,
|
||
n_obs: built.nObs,
|
||
};
|
||
}
|
||
const staggeredExec: TrialLedgerExecutor = {
|
||
async query<Row = Record<string, unknown>>(text: string) {
|
||
if (text.includes('WHERE trial_id = $1')) {
|
||
return { rows: [staggeredDbRows[0] as unknown as Row] };
|
||
}
|
||
return { rows: staggeredDbRows as unknown as Row[] };
|
||
},
|
||
};
|
||
|
||
const staggeredStartNs = Bun.nanoseconds();
|
||
const staggeredResult = await clusterDeflatedSharpe(staggeredExec, {
|
||
trialId: 1,
|
||
sessionDates: staggeredCalendar,
|
||
});
|
||
const staggeredElapsedMs = (Bun.nanoseconds() - staggeredStartNs) / 1e6;
|
||
const staggeredTrialsPerSec = trialCount / (staggeredElapsedMs / 1000);
|
||
|
||
process.stdout.write(
|
||
`[trial-ledger benchmark] trials=${trialCount} obsPerTrial=${obsPerTrial} elapsedMs=${elapsedMs.toFixed(2)} trialsPerSec=${trialsPerSec.toFixed(1)} effectiveTrials=${result.effectiveTrials.toFixed(2)} dsr=${(result.dsr ?? Number.NaN).toFixed(6)} staggeredElapsedMs=${staggeredElapsedMs.toFixed(2)} staggeredTrialsPerSec=${staggeredTrialsPerSec.toFixed(1)} staggeredPairsUsed=${staggeredResult.pairsUsed}\n`
|
||
);
|
||
|
||
expect(result.clusterSize).toBe(trialCount);
|
||
expect(Number.isFinite(elapsedMs)).toBe(true);
|
||
expect(Number.isFinite(trialsPerSec)).toBe(true);
|
||
expect(result.effectiveTrials).toBeGreaterThan(1);
|
||
expect(result.effectiveTrials).toBeLessThan(trialCount);
|
||
expect(result.dsr).not.toBeNull();
|
||
|
||
expect(staggeredResult.clusterSize).toBe(trialCount);
|
||
expect(staggeredResult.pairsUsed).toBe((trialCount * (trialCount - 1)) / 2);
|
||
expect(staggeredResult.pairsSkipped).toBe(0);
|
||
expect(Number.isFinite(staggeredElapsedMs)).toBe(true);
|
||
expect(staggeredResult.dsr).not.toBeNull();
|
||
|
||
// Cross-check against direct calculations on the same cluster.
|
||
const directEff = effectiveIndependentTrials(builtRows.map(r => r.dailySeries));
|
||
expect(result.effectiveTrials).toBeCloseTo(directEff.nHat, 12);
|
||
});
|
||
});
|