T-84: M1.3d — trial_ledger writer + cluster N̂-deflated Sharpe reader in @stock-bot/research (append one row per horizon, vault-fenced sample_end, PostgreSQL integration test + local benchmark)

This commit is contained in:
Studio 2026-11-28 03:03:17 -05:00
parent 9b57ea9677
commit dd05e20325
4 changed files with 919 additions and 178 deletions

View file

@ -9,10 +9,10 @@ Exported from both `@stock-bot/research` and `@stock-bot/research/trial-ledger`
### API
- **`canonicalExpressionHash(input)`** — Returns a 64-character lowercase SHA-256 hex digest over the recursively ASCII-key-sorted compact JSON of `{ expression, params, universe, sampleStart, sampleEnd, horizon }`. Leading/trailing/internal whitespace in `expression` is collapsed, `undefined` object keys are omitted, `-0` is normalized to `0`, and non-JSON values (`NaN`, `±Infinity`, functions, symbols, `BigInt`, cycles) are rejected with `TrialLedgerError`.
- **`buildTrialRow(input)`** — Pure validator and moment builder for a single `trial_ledger` row. Validates principal (`operator` or `agent:<uuid>`), optional UUIDs, schema enums (`stage`, `universeMarket`, `horizonBucket`), 64-hex `expressionHash`, strict `YYYY-MM-DD` dates, the exclusive Vault fence, and IEEE-754 `REAL` (float32) representability for every `dailySeries` element. Computes `{ nObs, sharpeUnann, skewness, kurtosis }` via `trialMoments` from `@stock-bot/calculations`.
- **`recordTrials(executor, rows)`** — Validates every row upfront (sending zero SQL on any invalid row or batch > `MAX_TRIAL_BATCH_SIZE = 4681`) and appends the batch atomically in one parameterised multi-row `INSERT ... RETURNING trial_id, created_at`. Multi-horizon analyses (e.g. `1d`, `5d`, `20d`) record one row per horizon.
- **`loadClusterTrials(executor, { universeMarket, horizonBucket, asOf? })`** — Loads a `(universe_market, horizon_bucket)` relatedness cluster ordered by `trial_id ASC` (backed by `idx_trial_ledger_cluster`), optionally capped at `created_at <= asOf`.
- **`clusterDeflatedSharpe(executor, { trialId, asOf?, dsrGate? })`** — Loads the target trial and its relatedness cluster, aligns series without fabricating correlations across unalignable sample windows (shared `sampleStart` uses zero-copy left alignment; shared `sampleEnd` uses leading-`NaN` right alignment; unalignable windows are placed in disjoint `NaN`-padded blocks so `effectiveIndependentTrials` surfaces `pairsSkipped` and `meanCorrelation: null`), and computes `{ trialId, clusterSize, effectiveTrials, meanCorrelation, pairsUsed, pairsSkipped, sr0, standardError, dsr, passesGate }`.
- **`buildTrialRow(input)`** — Pure validator and moment builder for a single `trial_ledger` row. Validates principal (`operator` or `agent:<uuid>`), optional UUIDs, schema enums (`stage`, `universeMarket`, `horizonBucket`), 64-hex `expressionHash`, strict `YYYY-MM-DD` dates, the exclusive Vault fence, and IEEE-754 `REAL` (float32) representability and non-zero variance at `REAL` storage precision for `dailySeries`. Computes `{ nObs, sharpeUnann, skewness, kurtosis }` via `trialMoments` from `@stock-bot/calculations`.
- **`recordTrials(executor, rows)`** — Validates every row upfront (re-verifying that pre-built rows' moments match their `dailySeries`, sending zero SQL on any invalid row or batch > `MAX_TRIAL_BATCH_SIZE = 4681`) and appends the batch atomically in one parameterised multi-row `INSERT ... RETURNING trial_id, created_at`. Multi-horizon analyses (e.g. `1d`, `5d`, `20d`) record one row per horizon.
- **`loadClusterTrials(executor, { universeMarket, horizonBucket, asOf? })`** — Loads a `(universe_market, horizon_bucket)` relatedness cluster ordered by `trial_id ASC` (backed by `idx_trial_ledger_cluster`), optionally capped at `created_at <= asOf` while preserving PostgreSQL's 6-digit microsecond UTC precision across `Z` and explicit `±HH:MM` offsets.
- **`clusterDeflatedSharpe(executor, { trialId, asOf?, dsrGate?, sessionDates?, observationDatesByTrialId? })`** — Loads the target trial and its relatedness cluster and computes `{ trialId, clusterSize, effectiveTrials, meanCorrelation, pairsUsed, pairsSkipped, sr0, standardError, dsr, passesGate }`. Index alignment requires a proven shared session grid (`sessionDates` where the trial's series length matches the session count in `[sampleStart, sampleEnd]`) or explicit per-trial `observationDatesByTrialId` (for sparse `signal_ic` / `event_study` series); trials without proven alignment are counted in `pairsSkipped` without inventing correlations. Cross-window correlations are computed directly within and across alignment groups without materializing dense `NaN` padding.
### Vault Holdout Fence Rule
@ -20,8 +20,10 @@ Every row built by `buildTrialRow` or persisted by `recordTrials` requires an ex
### Local In-Memory Benchmark
Fixed-seed (`20260403`) in-memory benchmark covering `200` trials × `5,000` daily observations (`1,000,000` observations total, `19,900` pairwise correlations) through `buildTrialRow` + `clusterDeflatedSharpe` with no PostgreSQL dependency:
Fixed-seed (`20260403`) in-memory benchmark covering `200` trials × `5,000` daily observations (`1,000,000` observations total, `19,900` pairwise correlations) through `buildTrialRow` + `clusterDeflatedSharpe` with no PostgreSQL dependency, for both shared-window and 200-distinct-window staggered rolling clusters:
- **Command:** `bun test libs/research/test/trial-ledger.test.ts`
- **Workload:** 200 trials × 5,000 daily observations (seed `20260403`)
- **Measured (Bun 1.2.16):** `elapsedMs = 732.35 ms`, `trialsPerSec = 273.1 trials/s` (`effectiveTrials = 171.85`, `dsr = 0.011891`)
- **Workload:** 200 trials × 5,000 daily observations (seed `20260403`), shared 5,000-session grid and 200-window staggered rolling grid (shifted by 1 session per trial across 5,199 sessions)
- **Measured (Bun 1.2.16):**
- **Shared window (`buildTrialRow` + `clusterDeflatedSharpe`):** `elapsedMs = 732.33 ms`, `trialsPerSec = 273.1 trials/s` (`effectiveTrials = 171.85`, `dsr = 0.011891`)
- **Staggered rolling windows (`clusterDeflatedSharpe`, 200 distinct windows, `19,900` overlapping pairs, zero `NaN` padding):** `staggeredElapsedMs = 509.45 ms`, `staggeredTrialsPerSec = 392.6 trials/s`

View file

@ -113,6 +113,7 @@ export interface BuiltTrialRow {
readonly sampleStart: string;
readonly sampleEnd: string;
readonly vaultCutoffDate: string;
readonly dailyRiskFree?: number;
readonly nObs: number;
readonly sharpeUnann: number;
readonly skewness: number;
@ -154,6 +155,19 @@ export interface ClusterDeflatedSharpeQuery {
readonly trialId: number | bigint | string;
readonly asOf?: string | Date;
readonly dsrGate?: number;
/**
* Optional strictly-ascending `YYYY-MM-DD` trading calendar for the cluster's market.
* A trial without explicit observation dates is index-aligned only when its `dailySeries`
* length exactly matches the number of sessions in `[sampleStart, sampleEnd]`.
*/
readonly sessionDates?: readonly string[];
/**
* Optional per-trial strictly-ascending `YYYY-MM-DD` observation dates for sparse series
* (e.g. `signal_ic` or `event_study`) that may omit dates within `[sampleStart, sampleEnd]`.
*/
readonly observationDatesByTrialId?:
| ReadonlyMap<number | bigint | string, readonly string[]>
| Readonly<Record<string, readonly string[]>>;
}
export interface ClusterDeflatedSharpeResult {
@ -172,12 +186,14 @@ export interface ClusterDeflatedSharpeResult {
}
const DATE_ONLY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
const UTC_ISO_TIMESTAMP_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?Z$/;
const ISO_OFFSET_TIMESTAMP_PATTERN =
/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})$/;
const AGENT_PRINCIPAL_PATTERN =
/^agent:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const EXPRESSION_HASH_PATTERN = /^[0-9a-f]{64}$/;
const POSITIVE_INT_PATTERN = /^[1-9]\d*$/;
const MOMENT_MATCH_REL_TOL = 1e-12;
const TRIAL_STAGE_SET: ReadonlySet<string> = new Set(TRIAL_STAGES);
const UNIVERSE_MARKET_SET: ReadonlySet<string> = new Set(UNIVERSE_MARKETS);
@ -551,7 +567,7 @@ function validateExpressionHash(value: unknown): string {
return value;
}
function validateDailySeries(value: unknown): number[] {
function validateDailySeries(value: unknown, allowZeroVariance = false): number[] {
const isTyped = value instanceof Float32Array || value instanceof Float64Array;
if (!Array.isArray(value) && !isTyped) {
throw new TrialLedgerError(
@ -568,6 +584,8 @@ function validateDailySeries(value: unknown): number[] {
}
const normalized: number[] = new Array(len);
let firstReal = 0;
let allEqualReal = true;
for (let i = 0; i < len; i += 1) {
const v: unknown = value[i];
if (typeof v !== 'number' || !Number.isFinite(v)) {
@ -583,8 +601,19 @@ function validateDailySeries(value: unknown): number[] {
`dailySeries[${i}] (${v}) is outside finite PostgreSQL REAL (float32) range.`
);
}
if (i === 0) {
firstReal = asReal;
} else if (asReal !== firstReal) {
allEqualReal = false;
}
normalized[i] = Object.is(v, -0) ? 0 : v;
}
if (!allowZeroVariance && allEqualReal) {
throw new TrialLedgerError(
'ZERO_VARIANCE_SERIES',
'dailySeries has zero variance at PostgreSQL REAL (float32) storage precision.'
);
}
return normalized;
}
@ -632,6 +661,15 @@ function parseTrialId(value: unknown): number {
);
}
function formatUtcInstantFromMs(epochMs: number, fractionalDigits?: string): string {
const baseIso = new Date(epochMs).toISOString();
if (fractionalDigits === undefined || fractionalDigits.length <= 3) {
return baseIso;
}
const micros = fractionalDigits.slice(3, 6).padEnd(3, '0');
return `${baseIso.slice(0, -1)}${micros}Z`;
}
function normalizeAsOf(asOf: unknown): string | undefined {
if (asOf === undefined) {
return undefined;
@ -654,8 +692,9 @@ function normalizeAsOf(asOf: unknown): string | undefined {
{ from: '1970-01-01', to: '1970-01-01', asOf, scope: 'vault_evaluation_only' },
{ vaultCutoffTs: 0, vaultOperatorAuthorized: true }
);
if (UTC_ISO_TIMESTAMP_PATTERN.test(asOf)) {
return asOf;
const instantMatch = ISO_OFFSET_TIMESTAMP_PATTERN.exec(asOf);
if (instantMatch !== null) {
return formatUtcInstantFromMs(fenced.asOfMs, instantMatch[2]);
}
return new Date(fenced.asOfMs).toISOString();
} catch (error) {
@ -678,8 +717,9 @@ function formatUtcTimestamp(value: unknown, field: string): string {
if (!Number.isFinite(ms)) {
throw new TrialLedgerError('INVALID_ROW', `Invalid timestamp string for "${field}": "${value}".`);
}
if (UTC_ISO_TIMESTAMP_PATTERN.test(value)) {
return value;
const instantMatch = ISO_OFFSET_TIMESTAMP_PATTERN.exec(value);
if (instantMatch !== null) {
return formatUtcInstantFromMs(ms, instantMatch[2]);
}
return new Date(ms).toISOString();
}
@ -698,10 +738,13 @@ function formatDateOnlyFromDb(value: unknown, field: string): string {
function parsePgRealArray(value: unknown): number[] {
if (Array.isArray(value)) {
return validateDailySeries(value.map(v => Number(v)));
return validateDailySeries(
value.map(v => Number(v)),
true
);
}
if (value instanceof Float32Array || value instanceof Float64Array) {
return validateDailySeries(value);
return validateDailySeries(value, true);
}
if (typeof value === 'string' && value.startsWith('{') && value.endsWith('}')) {
const inner = value.slice(1, -1).trim();
@ -709,7 +752,7 @@ function parsePgRealArray(value: unknown): number[] {
throw new TrialLedgerError('SERIES_TOO_SHORT', 'Empty daily_series returned from database.');
}
const elements = inner.split(',').map(token => Number(token));
return validateDailySeries(elements);
return validateDailySeries(elements, true);
}
throw new TrialLedgerError('INVALID_ROW', 'Unexpected daily_series value returned from database.');
}
@ -769,6 +812,11 @@ function isPreBuiltTrialRow(row: TrialRowInput | BuiltTrialRow): row is BuiltTri
);
}
function momentsClose(actual: number, expected: number): boolean {
const scale = Math.max(1, Math.abs(expected));
return Math.abs(actual - expected) <= MOMENT_MATCH_REL_TOL * scale;
}
function validateRowForInsert(row: TrialRowInput | BuiltTrialRow, index: number): BuiltTrialRow {
if (typeof row !== 'object' || row === null) {
throw new TrialLedgerError('INVALID_ROW', `Row at index ${index} must be a non-null object.`);
@ -792,6 +840,14 @@ function validateRowForInsert(row: TrialRowInput | BuiltTrialRow, index: number)
);
const dailySeries = validateDailySeries(row.dailySeries);
const dailyRiskFree = row.dailyRiskFree ?? 0;
if (typeof dailyRiskFree !== 'number' || !Number.isFinite(dailyRiskFree)) {
throw new TrialLedgerError(
'INVALID_ROW',
`Row at index ${index} has invalid dailyRiskFree "${String(row.dailyRiskFree)}": expected a finite number.`
);
}
if (!Number.isSafeInteger(row.nObs) || row.nObs !== dailySeries.length) {
throw new TrialLedgerError(
'INVALID_ROW',
@ -812,13 +868,25 @@ function validateRowForInsert(row: TrialRowInput | BuiltTrialRow, index: number)
);
}
// Ensure the series itself has non-zero variance so forged rows cannot bypass moment invariants.
if (trialMoments(dailySeries) === null) {
// Recompute moments from dailySeries and verify the pre-built row matches them so stale
// template moments cannot be persisted alongside a different return/IC vector.
const computed = trialMoments(dailySeries, dailyRiskFree);
if (computed === null) {
throw new TrialLedgerError(
'ZERO_VARIANCE_SERIES',
`Row at index ${index} has a zero-variance or degenerate dailySeries.`
);
}
if (
!momentsClose(row.sharpeUnann, computed.sharpeUnann) ||
!momentsClose(row.skewness, computed.skewness) ||
!momentsClose(row.kurtosis, computed.kurtosis)
) {
throw new TrialLedgerError(
'INVALID_ROW',
`Row at index ${index} has moments (sharpeUnann, skewness, kurtosis) that do not match dailySeries.`
);
}
return Object.freeze({
principalId,
@ -831,127 +899,504 @@ function validateRowForInsert(row: TrialRowInput | BuiltTrialRow, index: number)
sampleStart,
sampleEnd,
vaultCutoffDate,
nObs: row.nObs,
sharpeUnann: row.sharpeUnann,
skewness: row.skewness,
kurtosis: row.kurtosis,
dailyRiskFree,
nObs: computed.nObs,
sharpeUnann: computed.sharpeUnann,
skewness: computed.skewness,
kurtosis: computed.kurtosis,
dailySeries: Object.freeze(dailySeries),
});
}
function buildAlignedClusterSeries(cluster: readonly TrialLedgerRow[]): readonly (readonly number[])[] {
const count = cluster.length;
if (count <= 1) {
return cluster.map(trial => trial.dailySeries);
}
const DAYS_IN_CALENDAR_MONTH: readonly number[] = [
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
];
const first = cluster[0] as TrialLedgerRow;
let allSameStart = true;
let allSameEnd = true;
for (let i = 1; i < count; i += 1) {
const trial = cluster[i] as TrialLedgerRow;
if (trial.sampleStart !== first.sampleStart) {
allSameStart = false;
function assertValidCalendarDate(raw: unknown, field: string): string {
const dateStr = assertDateOnlyFormat(raw, field);
const year = Number(dateStr.slice(0, 4));
const month = Number(dateStr.slice(5, 7));
const day = Number(dateStr.slice(8, 10));
if (month < 1 || month > 12) {
throw new TrialLedgerError('INVALID_DATE', `Invalid calendar month in "${field}": "${dateStr}".`);
}
const isLeap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
const maxDay = month === 2 && isLeap ? 29 : (DAYS_IN_CALENDAR_MONTH[month - 1] as number);
if (day < 1 || day > maxDay) {
throw new TrialLedgerError('INVALID_DATE', `Invalid calendar day in "${field}": "${dateStr}".`);
}
return dateStr;
}
function validateSortedDates(raw: unknown, field: string): readonly string[] {
if (!Array.isArray(raw)) {
throw new TrialLedgerError(
'INVALID_DATE',
`Invalid "${field}": expected an array of strictly ascending YYYY-MM-DD dates.`
);
}
const len = raw.length;
const validated: string[] = new Array(len);
for (let i = 0; i < len; i += 1) {
const dateStr = assertValidCalendarDate(raw[i], `${field}[${i}]`);
if (i > 0 && dateStr <= (validated[i - 1] as string)) {
throw new TrialLedgerError(
'INVALID_DATE',
`Dates in "${field}" must be strictly ascending: "${dateStr}" <= "${validated[i - 1] as string}".`
);
}
if (trial.sampleEnd !== first.sampleEnd) {
allSameEnd = false;
validated[i] = dateStr;
}
return validated;
}
function normalizeObservationDatesMap(
raw: ClusterDeflatedSharpeQuery['observationDatesByTrialId']
): Map<number, readonly string[]> | undefined {
if (raw === undefined) {
return undefined;
}
const result = new Map<number, readonly string[]>();
if (raw instanceof Map) {
for (const [key, dates] of raw.entries()) {
const id = parseTrialId(key);
if (result.has(id)) {
throw new TrialLedgerError(
'INVALID_ROW',
`Duplicate trialId ${id} in observationDatesByTrialId.`
);
}
result.set(id, validateSortedDates(dates, `observationDatesByTrialId[${id}]`));
}
return result;
}
// Fast zero-copy path: all trials share sampleStart, so index t is the same trading day.
if (allSameStart) {
return cluster.map(trial => trial.dailySeries);
if (!isPlainObject(raw)) {
throw new TrialLedgerError(
'INVALID_ROW',
'observationDatesByTrialId must be a Map or plain object mapping trialId to YYYY-MM-DD[].'
);
}
// Right-aligned leading-NaN path: all trials share sampleEnd.
if (allSameEnd) {
let maxLen = 0;
for (let i = 0; i < count; i += 1) {
const len = (cluster[i] as TrialLedgerRow).dailySeries.length;
if (len > maxLen) {
maxLen = len;
}
}
return cluster.map(trial => {
const series = trial.dailySeries;
const pad = maxLen - series.length;
if (pad === 0) {
return series;
}
const padded = new Array<number>(maxLen);
for (let t = 0; t < pad; t += 1) {
padded[t] = Number.NaN;
}
for (let t = 0; t < series.length; t += 1) {
padded[pad + t] = series[t] as number;
}
return padded;
});
for (const [key, dates] of Object.entries(raw)) {
const id = parseTrialId(key);
result.set(id, validateSortedDates(dates, `observationDatesByTrialId[${id}]`));
}
return result;
}
// Mixed sampleStart and sampleEnd: only trials sharing an anchor (start or end) share index slots;
// distinct anchors are placed in disjoint NaN-padded blocks so effectiveIndependentTrials skips
// unalignable pairs instead of fabricating correlations.
const byStart = new Map<string, number[]>();
const byEnd = new Map<string, number[]>();
let hasSharedStart = false;
let hasSharedEnd = false;
for (let i = 0; i < count; i += 1) {
const trial = cluster[i] as TrialLedgerRow;
const startGroup = byStart.get(trial.sampleStart);
if (startGroup !== undefined) {
startGroup.push(i);
hasSharedStart = true;
function lowerBoundDate(sorted: readonly string[], target: string): number {
let lo = 0;
let hi = sorted.length;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
if ((sorted[mid] as string) < target) {
lo = mid + 1;
} else {
byStart.set(trial.sampleStart, [i]);
hi = mid;
}
const endGroup = byEnd.get(trial.sampleEnd);
if (endGroup !== undefined) {
endGroup.push(i);
hasSharedEnd = true;
}
return lo;
}
function upperBoundDate(sorted: readonly string[], target: string): number {
let lo = 0;
let hi = sorted.length;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
if ((sorted[mid] as string) <= target) {
lo = mid + 1;
} else {
byEnd.set(trial.sampleEnd, [i]);
hi = mid;
}
}
return lo;
}
interface PreparedDenseSeries {
readonly values: Float64Array;
readonly prefixSum: Float64Array;
}
function prepareDenseSeries(series: readonly number[]): PreparedDenseSeries {
const len = series.length;
const values = new Float64Array(len);
const prefixSum = new Float64Array(len + 1);
let running = 0;
for (let t = 0; t < len; t += 1) {
const v = series[t] as number;
values[t] = v;
running += v;
prefixSum[t + 1] = running;
}
return { values, prefixSum };
}
function pearsonSliceCorrelation(
a: PreparedDenseSeries,
offsetA: number,
b: PreparedDenseSeries,
offsetB: number,
len: number
): number | null {
if (len < 2) {
return null;
}
const meanA =
((a.prefixSum[offsetA + len] as number) - (a.prefixSum[offsetA] as number)) / len;
const meanB =
((b.prefixSum[offsetB + len] as number) - (b.prefixSum[offsetB] as number)) / len;
const aVals = a.values;
const bVals = b.values;
let cov = 0;
let varA = 0;
let varB = 0;
for (let t = 0; t < len; t += 1) {
const da = (aVals[offsetA + t] as number) - meanA;
const db = (bVals[offsetB + t] as number) - meanB;
cov += da * db;
varA += da * da;
varB += db * db;
}
if (!Number.isFinite(varA) || !Number.isFinite(varB) || varA <= 0 || varB <= 0) {
return null;
}
const denom = Math.sqrt(varA * varB);
if (!Number.isFinite(denom) || denom <= 0) {
return null;
}
const rawRho = cov / denom;
if (!Number.isFinite(rawRho)) {
return null;
}
return rawRho < -1 ? -1 : rawRho > 1 ? 1 : rawRho;
}
function pearsonDateMergedCorrelation(
aSeries: readonly number[],
aDates: readonly string[],
aStart: number,
aEnd: number,
bSeries: readonly number[],
bDates: readonly string[],
bStart: number,
bEnd: number
): number | null {
if (aEnd - aStart < 2 || bEnd - bStart < 2) {
return null;
}
if ((aDates[aEnd - 1] as string) < (bDates[bStart] as string)) {
return null;
}
if ((bDates[bEnd - 1] as string) < (aDates[aStart] as string)) {
return null;
}
let ia = aStart;
let ib = bStart;
let overlap = 0;
let sumA = 0;
let sumB = 0;
let firstA = 0;
let firstB = 0;
let allEqualA = true;
let allEqualB = true;
while (ia < aEnd && ib < bEnd) {
const da = aDates[ia] as string;
const db = bDates[ib] as string;
if (da === db) {
const va = aSeries[ia - aStart] as number;
const vb = bSeries[ib - bStart] as number;
if (Number.isFinite(va) && Number.isFinite(vb)) {
if (overlap === 0) {
firstA = va;
firstB = vb;
} else {
if (va !== firstA) {
allEqualA = false;
}
if (vb !== firstB) {
allEqualB = false;
}
}
sumA += va;
sumB += vb;
overlap += 1;
}
ia += 1;
ib += 1;
} else if (da < db) {
ia += 1;
} else {
ib += 1;
}
}
const alignMode: 'start' | 'end' = hasSharedStart || !hasSharedEnd ? 'start' : 'end';
const groups = alignMode === 'start' ? byStart : byEnd;
const aligned: (readonly number[])[] = new Array(count);
let blockOffset = 0;
if (overlap < 2 || allEqualA || allEqualB) {
return null;
}
for (const indices of groups.values()) {
let blockWidth = 0;
for (let g = 0; g < indices.length; g += 1) {
const len = (cluster[indices[g] as number] as TrialLedgerRow).dailySeries.length;
if (len > blockWidth) {
blockWidth = len;
const meanA = sumA / overlap;
const meanB = sumB / overlap;
let cov = 0;
let varA = 0;
let varB = 0;
ia = aStart;
ib = bStart;
while (ia < aEnd && ib < bEnd) {
const da = aDates[ia] as string;
const db = bDates[ib] as string;
if (da === db) {
const va = aSeries[ia - aStart] as number;
const vb = bSeries[ib - bStart] as number;
if (Number.isFinite(va) && Number.isFinite(vb)) {
const diffA = va - meanA;
const diffB = vb - meanB;
cov += diffA * diffB;
varA += diffA * diffA;
varB += diffB * diffB;
}
ia += 1;
ib += 1;
} else if (da < db) {
ia += 1;
} else {
ib += 1;
}
}
if (!Number.isFinite(varA) || !Number.isFinite(varB) || varA <= 0 || varB <= 0) {
return null;
}
const denom = Math.sqrt(varA * varB);
if (!Number.isFinite(denom) || denom <= 0) {
return null;
}
const rawRho = cov / denom;
if (!Number.isFinite(rawRho)) {
return null;
}
return rawRho < -1 ? -1 : rawRho > 1 ? 1 : rawRho;
}
interface DenseWindowGroup {
readonly startIdx: number;
readonly endExclusive: number;
readonly seriesList: (readonly number[])[];
}
interface ExplicitDateTrial {
readonly series: readonly number[];
readonly dates: readonly string[];
}
interface ClusterEffectiveTrials {
readonly pairsUsed: number;
readonly pairsSkipped: number;
readonly meanCorrelation: number | null;
readonly nHat: number;
}
function computeClusterEffectiveTrials(
cluster: readonly TrialLedgerRow[],
sessionDates: readonly string[] | undefined,
observationDatesMap: ReadonlyMap<number, readonly string[]> | undefined
): ClusterEffectiveTrials {
const k = cluster.length;
if (k <= 1) {
return { pairsUsed: 0, pairsSkipped: 0, meanCorrelation: null, nHat: 1 };
}
const denseGroupByKey = new Map<string, DenseWindowGroup>();
const denseGroups: DenseWindowGroup[] = [];
const explicitTrials: ExplicitDateTrial[] = [];
let unalignedCount = 0;
for (let i = 0; i < k; i += 1) {
const trial = cluster[i] as TrialLedgerRow;
const explicitDates = observationDatesMap?.get(trial.trialId);
if (explicitDates !== undefined) {
if (explicitDates.length !== trial.dailySeries.length) {
throw new TrialLedgerError(
'INVALID_ROW',
`observationDatesByTrialId[${trial.trialId}] length (${explicitDates.length}) does not match dailySeries.length (${trial.dailySeries.length}).`
);
}
const firstDate = explicitDates[0] as string;
const lastDate = explicitDates[explicitDates.length - 1] as string;
if (firstDate < trial.sampleStart || lastDate > trial.sampleEnd) {
throw new TrialLedgerError(
'INVALID_SAMPLE_WINDOW',
`observationDatesByTrialId[${trial.trialId}] range [${firstDate}, ${lastDate}] lies outside trial window [${trial.sampleStart}, ${trial.sampleEnd}].`
);
}
explicitTrials.push({ series: trial.dailySeries, dates: explicitDates });
continue;
}
if (sessionDates !== undefined) {
const startIdx = lowerBoundDate(sessionDates, trial.sampleStart);
const endExclusive = upperBoundDate(sessionDates, trial.sampleEnd);
if (endExclusive - startIdx === trial.dailySeries.length) {
const key = `${startIdx}:${endExclusive}`;
let group = denseGroupByKey.get(key);
if (group === undefined) {
group = { startIdx, endExclusive, seriesList: [] };
denseGroupByKey.set(key, group);
denseGroups.push(group);
}
group.seriesList.push(trial.dailySeries);
continue;
}
}
for (let g = 0; g < indices.length; g += 1) {
const idx = indices[g] as number;
const series = (cluster[idx] as TrialLedgerRow).dailySeries;
const leadingNaNs =
alignMode === 'start' ? blockOffset : blockOffset + (blockWidth - series.length);
if (leadingNaNs === 0) {
aligned[idx] = series;
unalignedCount += 1;
}
// Fast path: all K trials are proven dense on the exact same session window.
if (denseGroups.length === 1 && (denseGroups[0] as DenseWindowGroup).seriesList.length === k) {
const eff = effectiveIndependentTrials((denseGroups[0] as DenseWindowGroup).seriesList);
return {
pairsUsed: eff.pairsUsed,
pairsSkipped: eff.pairsSkipped,
meanCorrelation: eff.meanCorrelation,
nHat: eff.nHat,
};
}
let rhoSum = 0;
let pairsUsed = 0;
let pairsSkipped = 0;
// 1. Within-group correlations for dense groups (uses fast unit-vector dot-product path).
for (let g = 0; g < denseGroups.length; g += 1) {
const group = denseGroups[g] as DenseWindowGroup;
if (group.seriesList.length < 2) {
continue;
}
const eff = effectiveIndependentTrials(group.seriesList);
if (eff.meanCorrelation !== null) {
rhoSum += eff.meanCorrelation * eff.pairsUsed;
}
pairsUsed += eff.pairsUsed;
pairsSkipped += eff.pairsSkipped;
}
// 2. Cross-group correlations between distinct dense windows (zero NaN padding).
if (denseGroups.length > 1) {
const preparedGroups: PreparedDenseSeries[][] = denseGroups.map(group =>
group.seriesList.map(series => prepareDenseSeries(series))
);
for (let ga = 0; ga < denseGroups.length - 1; ga += 1) {
const groupA = denseGroups[ga] as DenseWindowGroup;
const prepA = preparedGroups[ga] as PreparedDenseSeries[];
for (let gb = ga + 1; gb < denseGroups.length; gb += 1) {
const groupB = denseGroups[gb] as DenseWindowGroup;
const ovStart = groupA.startIdx > groupB.startIdx ? groupA.startIdx : groupB.startIdx;
const ovEnd =
groupA.endExclusive < groupB.endExclusive ? groupA.endExclusive : groupB.endExclusive;
const ovLen = ovEnd - ovStart;
if (ovLen < 2) {
pairsSkipped += groupA.seriesList.length * groupB.seriesList.length;
continue;
}
const offsetA = ovStart - groupA.startIdx;
const offsetB = ovStart - groupB.startIdx;
const prepB = preparedGroups[gb] as PreparedDenseSeries[];
for (let ia = 0; ia < prepA.length; ia += 1) {
const seriesA = prepA[ia] as PreparedDenseSeries;
for (let ib = 0; ib < prepB.length; ib += 1) {
const seriesB = prepB[ib] as PreparedDenseSeries;
const rho = pearsonSliceCorrelation(seriesA, offsetA, seriesB, offsetB, ovLen);
if (rho === null) {
pairsSkipped += 1;
} else {
rhoSum += rho;
pairsUsed += 1;
}
}
}
}
}
}
// 3. Explicit-date trial vs explicit-date trial (exact two-pointer date merge).
for (let i = 0; i < explicitTrials.length - 1; i += 1) {
const a = explicitTrials[i] as ExplicitDateTrial;
for (let j = i + 1; j < explicitTrials.length; j += 1) {
const b = explicitTrials[j] as ExplicitDateTrial;
const rho = pearsonDateMergedCorrelation(
a.series,
a.dates,
0,
a.dates.length,
b.series,
b.dates,
0,
b.dates.length
);
if (rho === null) {
pairsSkipped += 1;
} else {
const padded = new Array<number>(leadingNaNs + series.length);
for (let t = 0; t < leadingNaNs; t += 1) {
padded[t] = Number.NaN;
}
for (let t = 0; t < series.length; t += 1) {
padded[leadingNaNs + t] = series[t] as number;
}
aligned[idx] = padded;
rhoSum += rho;
pairsUsed += 1;
}
}
blockOffset += blockWidth;
}
return aligned;
// 4. Explicit-date trial vs dense-grid trial (zero-slice merge against sessionDates).
if (sessionDates !== undefined && explicitTrials.length > 0 && denseGroups.length > 0) {
for (let i = 0; i < explicitTrials.length; i += 1) {
const exp = explicitTrials[i] as ExplicitDateTrial;
for (let g = 0; g < denseGroups.length; g += 1) {
const group = denseGroups[g] as DenseWindowGroup;
if (
(exp.dates[exp.dates.length - 1] as string) < (sessionDates[group.startIdx] as string) ||
(sessionDates[group.endExclusive - 1] as string) < (exp.dates[0] as string)
) {
pairsSkipped += group.seriesList.length;
continue;
}
for (let s = 0; s < group.seriesList.length; s += 1) {
const denseSeries = group.seriesList[s] as readonly number[];
const rho = pearsonDateMergedCorrelation(
exp.series,
exp.dates,
0,
exp.dates.length,
denseSeries,
sessionDates,
group.startIdx,
group.endExclusive
);
if (rho === null) {
pairsSkipped += 1;
} else {
rhoSum += rho;
pairsUsed += 1;
}
}
}
}
}
// 5. Pairs involving trials without proven date/grid alignment are skipped in O(1).
if (unalignedCount > 0) {
const alignedCount = k - unalignedCount;
pairsSkipped += unalignedCount * alignedCount + (unalignedCount * (unalignedCount - 1)) / 2;
}
if (pairsUsed === 0) {
return { pairsUsed: 0, pairsSkipped, meanCorrelation: null, nHat: k };
}
const meanCorrelation = rhoSum / pairsUsed;
const nHat = Math.max(1, 1 + (k - 1) * (1 - Math.max(0, meanCorrelation)));
return { pairsUsed, pairsSkipped, meanCorrelation, nHat };
}
/**
@ -1083,6 +1528,7 @@ export function buildTrialRow(input: TrialRowInput): BuiltTrialRow {
sampleStart,
sampleEnd,
vaultCutoffDate,
dailyRiskFree,
nObs: moments.nObs,
sharpeUnann: moments.sharpeUnann,
skewness: moments.skewness,
@ -1239,6 +1685,11 @@ export async function clusterDeflatedSharpe(
`Invalid dsrGate "${String(query.dsrGate)}": expected a finite number.`
);
}
const sessionDates =
query.sessionDates !== undefined
? validateSortedDates(query.sessionDates, 'sessionDates')
: undefined;
const observationDatesMap = normalizeObservationDatesMap(query.observationDatesByTrialId);
const targetResult = await executor.query<Record<string, unknown>>(
`SELECT${SELECT_TRIAL_COLUMNS}
@ -1266,8 +1717,7 @@ WHERE trial_id = $1::bigint`,
);
}
const alignedSeries = buildAlignedClusterSeries(cluster);
const eff = effectiveIndependentTrials(alignedSeries);
const eff = computeClusterEffectiveTrials(cluster, sessionDates, observationDatesMap);
const clusterSharpes = cluster.map(row => row.sharpeUnann);
const dsrResult = deflatedSharpeRatio({

View file

@ -72,6 +72,21 @@ function createGaussianSampler(seed: number): () => number {
};
}
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);
@ -394,6 +409,7 @@ describe('buildTrialRow', () => {
[{ 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'],
@ -460,6 +476,36 @@ describe('recordTrials', () => {
'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');
@ -507,25 +553,49 @@ describe('recordTrials', () => {
]);
});
it('preserves PostgreSQL microsecond UTC timestamps across receipts and asOf queries', async () => {
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 { executor, calls } = createFakeExecutor(text => {
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 }]);
await loadClusterTrials(executor, {
const zRows = await loadClusterTrials(executor, {
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
asOf: receipts[0]!.createdAt,
});
expect(calls).toHaveLength(2);
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);
});
});
@ -570,22 +640,23 @@ describe('loadClusterTrials and clusterDeflatedSharpe', () => {
expect(calls[0]!.params).toEqual(['US_EQ', 'swing_1_10d', '2025-04-01T23:59:59.999Z']);
});
it('computes exact N-hat and DSR for same-window, prefix-overlap, suffix-overlap, and unalignable clusters', async () => {
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)
// 1. Same-start, different-end (prefix overlap) with proven sessionDates grid
const rowPrefixA = buildTrialRow(
makeValidInput({
sampleStart: '2020-01-02',
sampleEnd: '2020-05-26',
sampleStart: calendar100[0]!,
sampleEnd: calendar100[99]!,
dailySeries: baseSeries,
})
);
const rowPrefixB = buildTrialRow(
makeValidInput({
sampleStart: '2020-01-02',
sampleEnd: '2020-04-15',
sampleStart: calendar100[0]!,
sampleEnd: calendar100[69]!,
dailySeries: twinSeries.slice(0, 70),
})
);
@ -594,25 +665,35 @@ describe('loadClusterTrials and clusterDeflatedSharpe', () => {
const prefixExec = createFakeExecutor(text =>
text.includes('WHERE trial_id = $1') ? { rows: [dbPrefix[0]!] } : { rows: dbPrefix }
);
const prefixRes = await clusterDeflatedSharpe(prefixExec.executor, { trialId: 1 });
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);
// 2. Same-end, different-start (suffix overlap)
// 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: '2020-01-02',
sampleEnd: '2020-05-26',
sampleStart: calendar100[0]!,
sampleEnd: calendar100[99]!,
dailySeries: baseSeries,
})
);
const rowSuffixB = buildTrialRow(
makeValidInput({
sampleStart: '2020-02-15',
sampleEnd: '2020-05-26',
sampleStart: calendar100[30]!,
sampleEnd: calendar100[99]!,
dailySeries: twinSeries.slice(30),
})
);
@ -620,23 +701,27 @@ describe('loadClusterTrials and clusterDeflatedSharpe', () => {
const suffixExec = createFakeExecutor(text =>
text.includes('WHERE trial_id = $1') ? { rows: [dbSuffix[0]!] } : { rows: dbSuffix }
);
const suffixRes = await clusterDeflatedSharpe(suffixExec.executor, { trialId: 10 });
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 / staggered unalignable windows -> pairsSkipped > 0, meanCorrelation === null, effectiveTrials === clusterSize
// 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: '2019-01-02',
sampleEnd: '2020-12-31',
sampleStart: calendar220[0]!,
sampleEnd: calendar220[99]!,
dailySeries: baseSeries,
})
);
const rowDisjointB = buildTrialRow(
makeValidInput({
sampleStart: '2021-01-04',
sampleEnd: '2022-12-30',
sampleStart: calendar220[120]!,
sampleEnd: calendar220[219]!,
dailySeries: twinSeries,
})
);
@ -644,7 +729,10 @@ describe('loadClusterTrials and clusterDeflatedSharpe', () => {
const disjointExec = createFakeExecutor(text =>
text.includes('WHERE trial_id = $1') ? { rows: [dbDisjoint[0]!] } : { rows: dbDisjoint }
);
const disjointRes = await clusterDeflatedSharpe(disjointExec.executor, { trialId: 20 });
const disjointRes = await clusterDeflatedSharpe(disjointExec.executor, {
trialId: 20,
sessionDates: calendar220,
});
expect(disjointRes.pairsUsed).toBe(0);
expect(disjointRes.pairsSkipped).toBe(1);
expect(disjointRes.meanCorrelation).toBeNull();
@ -659,6 +747,67 @@ describe('loadClusterTrials and clusterDeflatedSharpe', () => {
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);
});
it('rejects invalid trialId with zero SQL and throws TRIAL_NOT_FOUND when absent or excluded by asOf', async () => {
@ -699,10 +848,13 @@ describe('loadClusterTrials and clusterDeflatedSharpe', () => {
});
describe('trial-ledger in-memory benchmark', () => {
it('benchmarks 200 trials x 5,000 daily observations through buildTrialRow + clusterDeflatedSharpe', async () => {
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);
@ -723,8 +875,8 @@ describe('trial-ledger in-memory benchmark', () => {
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
expressionHash: k.toString(16).padStart(64, '0'),
sampleStart: '2005-01-03',
sampleEnd: '2024-11-15',
sampleStart: sharedStart,
sampleEnd: sharedEnd,
vaultCutoffDate: VAULT_CUTOFF,
dailySeries: series,
};
@ -766,12 +918,45 @@ describe('trial-ledger in-memory benchmark', () => {
},
};
const result = await clusterDeflatedSharpe(memExecutor, { trialId: 1 });
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)}\n`
`[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);
@ -781,6 +966,12 @@ describe('trial-ledger in-memory benchmark', () => {
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);

View file

@ -119,6 +119,21 @@ function createGaussianSampler(seed: number): () => number {
};
}
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 makeSeries(seed: number, length: number, mean = 0.0005, std = 0.01): number[] {
const gauss = createGaussianSampler(seed);
const out = new Array<number>(length);
@ -239,6 +254,9 @@ describe.skipIf(!url)('trial_ledger PostgreSQL writer and cluster DSR reader', (
const f = await createIsolatedFixture();
const nObs = 500;
const clusterK = 12;
const sessionDates = makeBusinessDates('2022-01-03', nObs);
const sampleStart = sessionDates[0]!;
const sampleEnd = sessionDates[nObs - 1]!;
// 1. Near-duplicate cluster in (US_EQ, swing_1_10d): target pairwise rho ~ 0.97
const factorGauss = createGaussianSampler(9001);
@ -264,12 +282,12 @@ describe.skipIf(!url)('trial_ledger PostgreSQL writer and cluster DSR reader', (
expression: `dup_signal_${k}`,
params: { k },
universe: 'US_EQ',
sampleStart: '2022-01-03',
sampleEnd: '2024-01-02',
sampleStart,
sampleEnd,
horizon: '5d',
}),
sampleStart: '2022-01-03',
sampleEnd: '2024-01-02',
sampleStart,
sampleEnd,
vaultCutoffDate: VAULT_CUTOFF,
dailySeries: series,
};
@ -289,12 +307,12 @@ describe.skipIf(!url)('trial_ledger PostgreSQL writer and cluster DSR reader', (
expression: `indep_signal_${k}`,
params: { k },
universe: 'CA_EQ',
sampleStart: '2022-01-03',
sampleEnd: '2024-01-02',
sampleStart,
sampleEnd,
horizon: '5d',
}),
sampleStart: '2022-01-03',
sampleEnd: '2024-01-02',
sampleStart,
sampleEnd,
vaultCutoffDate: VAULT_CUTOFF,
dailySeries: makeSeries(5000 + k, nObs, 0.0005, 0.01),
};
@ -309,8 +327,8 @@ describe.skipIf(!url)('trial_ledger PostgreSQL writer and cluster DSR reader', (
universeMarket: 'US_EQ',
horizonBucket: 'position_10d_plus',
expressionHash: 'd'.repeat(64),
sampleStart: '2022-01-03',
sampleEnd: '2024-01-02',
sampleStart,
sampleEnd,
vaultCutoffDate: VAULT_CUTOFF,
dailySeries: makeSeries(7777, nObs),
},
@ -318,6 +336,7 @@ describe.skipIf(!url)('trial_ledger PostgreSQL writer and cluster DSR reader', (
const nearDupDsr = await clusterDeflatedSharpe(f.pool, {
trialId: nearDupReceipts[0]!.trialId,
sessionDates,
});
expect(nearDupDsr.clusterSize).toBe(clusterK);
expect(nearDupDsr.meanCorrelation).not.toBeNull();
@ -326,6 +345,7 @@ describe.skipIf(!url)('trial_ledger PostgreSQL writer and cluster DSR reader', (
const indepDsr = await clusterDeflatedSharpe(f.pool, {
trialId: indepReceipts[0]!.trialId,
sessionDates,
});
expect(indepDsr.clusterSize).toBe(clusterK);
expect(indepDsr.effectiveTrials).toBeGreaterThan(clusterK * 0.85);
@ -348,33 +368,111 @@ describe.skipIf(!url)('trial_ledger PostgreSQL writer and cluster DSR reader', (
expect(directDsr).not.toBeNull();
expect(Math.abs((nearDupDsr.dsr ?? Number.NaN) - directDsr!.dsr)).toBeLessThan(1e-9);
// asOf filtering: record a newer row after a brief delay and verify asOf excludes it.
const cutoffTs = nearDupReceipts[clusterK - 1]!.createdAt;
await Bun.sleep(15);
await recordTrials(f.pool, [
{
principalId: 'operator',
stage: 'screen',
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
expressionHash: 'e'.repeat(64),
sampleStart: '2022-01-03',
sampleEnd: '2024-01-02',
vaultCutoffDate: VAULT_CUTOFF,
dailySeries: makeSeries(9999, nObs),
},
]);
// Writer receipt timestamp round-trip: exact receipt timestamp with Z and +00:00 select the same rows.
const receiptTs = nearDupReceipts[clusterK - 1]!.createdAt;
const atReceiptZ = await loadClusterTrials(f.pool, {
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
asOf: receiptTs,
});
const atReceiptOffset = await loadClusterTrials(f.pool, {
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
asOf: receiptTs.replace(/Z$/, '+00:00'),
});
expect(atReceiptZ).toHaveLength(clusterK);
expect(atReceiptOffset.map(r => r.trialId)).toEqual(atReceiptZ.map(r => r.trialId));
const fullCluster = await loadClusterTrials(f.pool, {
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
// Deterministic asOf ordering fixture: explicit distinct microsecond created_at values (no wall-clock sleep).
const olderRow = buildTrialRow({
principalId: 'operator',
stage: 'screen',
universeMarket: 'FX',
horizonBucket: 'intraday',
expressionHash: 'e'.repeat(64),
sampleStart,
sampleEnd,
vaultCutoffDate: VAULT_CUTOFF,
dailySeries: makeSeries(9998, 10),
});
const asOfCluster = await loadClusterTrials(f.pool, {
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
asOf: cutoffTs,
const newerRow = buildTrialRow({
principalId: 'operator',
stage: 'screen',
universeMarket: 'FX',
horizonBucket: 'intraday',
expressionHash: 'f'.repeat(64),
sampleStart,
sampleEnd,
vaultCutoffDate: VAULT_CUTOFF,
dailySeries: makeSeries(9999, 10),
});
expect(fullCluster).toHaveLength(clusterK + 1);
expect(asOfCluster).toHaveLength(clusterK);
await f.pool.query(
`INSERT INTO trial_ledger (
created_at, principal_id, campaign_id, stage, universe_market, horizon_bucket,
hypothesis_id, expression_hash, sample_start, sample_end, n_obs,
sharpe_unann, skewness, kurtosis, daily_series
) VALUES
($1::timestamptz, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12::double precision, $13::double precision, $14::double precision, $15::real[]),
($16::timestamptz, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27::double precision, $28::double precision, $29::double precision, $30::real[])`,
[
'2025-04-01T10:00:00.123456Z',
olderRow.principalId,
olderRow.campaignId,
olderRow.stage,
olderRow.universeMarket,
olderRow.horizonBucket,
olderRow.hypothesisId,
olderRow.expressionHash,
olderRow.sampleStart,
olderRow.sampleEnd,
olderRow.nObs,
olderRow.sharpeUnann,
olderRow.skewness,
olderRow.kurtosis,
olderRow.dailySeries,
'2025-04-01T10:00:00.123457Z',
newerRow.principalId,
newerRow.campaignId,
newerRow.stage,
newerRow.universeMarket,
newerRow.horizonBucket,
newerRow.hypothesisId,
newerRow.expressionHash,
newerRow.sampleStart,
newerRow.sampleEnd,
newerRow.nObs,
newerRow.sharpeUnann,
newerRow.skewness,
newerRow.kurtosis,
newerRow.dailySeries,
]
);
const fxAll = await loadClusterTrials(f.pool, {
universeMarket: 'FX',
horizonBucket: 'intraday',
});
const fxAtZ = await loadClusterTrials(f.pool, {
universeMarket: 'FX',
horizonBucket: 'intraday',
asOf: '2025-04-01T10:00:00.123456Z',
});
const fxAtPlusZero = await loadClusterTrials(f.pool, {
universeMarket: 'FX',
horizonBucket: 'intraday',
asOf: '2025-04-01T10:00:00.123456+00:00',
});
const fxAtPlusTwo = await loadClusterTrials(f.pool, {
universeMarket: 'FX',
horizonBucket: 'intraday',
asOf: '2025-04-01T12:00:00.123456+02:00',
});
expect(fxAll).toHaveLength(2);
expect(fxAtZ).toHaveLength(1);
expect(fxAtPlusZero).toHaveLength(1);
expect(fxAtPlusTwo).toHaveLength(1);
expect(fxAtPlusZero[0]!.trialId).toBe(fxAtZ[0]!.trialId);
expect(fxAtPlusTwo[0]!.trialId).toBe(fxAtZ[0]!.trialId);
});
});