From bbc31b9cd723f40e2eed52b05f6ed4cd642f6633 Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 02:43:59 -0500 Subject: [PATCH] =?UTF-8?q?T-84:=20M1.3d=20=E2=80=94=20`trial=5Fledger`=20?= =?UTF-8?q?writer=20+=20cluster=20N=CC=82-deflated=20Sharpe=20reader=20in?= =?UTF-8?q?=20`@stock-bot/research`=20(append=20one=20row=20per=20horizon,?= =?UTF-8?q?=20vault-fenced=20`sample=5Fend`,=20PostgreSQL=20integration=20?= =?UTF-8?q?test=20+=20local=20benchmark)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/README.md | 27 + libs/research/package.json | 3 +- libs/research/src/index.ts | 1 + libs/research/src/trial-ledger.ts | 1291 +++++++++++++++++++++ libs/research/test/trial-ledger.test.ts | 766 ++++++++++++ test/postgres/trial-ledger-writer.test.ts | 380 ++++++ 6 files changed, 2467 insertions(+), 1 deletion(-) create mode 100644 libs/research/README.md create mode 100644 libs/research/src/trial-ledger.ts create mode 100644 libs/research/test/trial-ledger.test.ts create mode 100644 test/postgres/trial-ledger-writer.test.ts diff --git a/libs/research/README.md b/libs/research/README.md new file mode 100644 index 00000000..1353f998 --- /dev/null +++ b/libs/research/README.md @@ -0,0 +1,27 @@ +# `@stock-bot/research` + +Browser-safe research contracts, rolling 6-month Vault holdout fencing, and append-only `trial_ledger` accounting (`design/DATA-CONTRACTS.md`, `design/VALIDATION-AND-RIGOR.md`). + +## `trial_ledger` Writer & Cluster N-hat-Deflated Sharpe Reader + +Exported from both `@stock-bot/research` and `@stock-bot/research/trial-ledger` (`libs/research/src/trial-ledger.ts`). The module is dependency-free and browser-safe; PostgreSQL access is injected via `TrialLedgerExecutor` (`{ query(text, params) }`). + +### 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:`), 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 }`. + +### Vault Holdout Fence Rule + +Every row built by `buildTrialRow` or persisted by `recordTrials` requires an explicit `vaultCutoffDate` (`YYYY-MM-DD`) and delegates calendar validation and holdout enforcement to `applyVaultFence` in `libs/research/src/market-data-store.ts`. Any trial with `sampleEnd >= vaultCutoffDate` (or `sampleStart >= vaultCutoffDate`) is rejected with `TrialLedgerError('VAULT_FENCE_VIOLATION')` before any SQL is executed. + +### 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: + +- **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`) diff --git a/libs/research/package.json b/libs/research/package.json index d4190a7f..e56f6f65 100644 --- a/libs/research/package.json +++ b/libs/research/package.json @@ -12,7 +12,8 @@ "./datasets": "./src/datasets.ts", "./market-data-store": "./src/market-data-store.ts", "./results": "./src/results.ts", - "./strategy-api": "./src/strategy-api.ts" + "./strategy-api": "./src/strategy-api.ts", + "./trial-ledger": "./src/trial-ledger.ts" }, "scripts": { "build": "tsc", diff --git a/libs/research/src/index.ts b/libs/research/src/index.ts index c979d987..583b1599 100644 --- a/libs/research/src/index.ts +++ b/libs/research/src/index.ts @@ -1,3 +1,4 @@ // The default entrypoint is browser safe; server validation is an explicit subpath. export * from './dataset-contracts'; export * from './market-data-store'; +export * from './trial-ledger'; diff --git a/libs/research/src/trial-ledger.ts b/libs/research/src/trial-ledger.ts new file mode 100644 index 00000000..9295a0ec --- /dev/null +++ b/libs/research/src/trial-ledger.ts @@ -0,0 +1,1291 @@ +/** + * Append-only `trial_ledger` writer and relatedness-cluster N-hat-deflated Sharpe + * reader (`design/VALIDATION-AND-RIGOR.md` §2.B–§2.C, `database/postgres/init/36-trial-ledger.sql`). + * + * Browser-safe and dependency-free: zero `node:*` imports, zero `pg` dependency, + * zero bare `process` access. SQL execution is injected via {@link TrialLedgerExecutor}. + */ + +import { + DSR_VALIDATION_GATE, + deflatedSharpeRatio, + effectiveIndependentTrials, + passesDsrGate, + trialMoments, +} from '@stock-bot/calculations'; +import { + MarketDataStoreValidationError, + VaultHoldoutFenceError, + applyVaultFence, +} from './market-data-store'; + +export const TRIAL_STAGES = ['signal_ic', 'event_study', 'screen', 'engine_backtest'] as const; +export type TrialStage = (typeof TRIAL_STAGES)[number]; + +export const UNIVERSE_MARKETS = ['US_EQ', 'CA_EQ', 'US_CA_EQ', 'FX'] as const; +export type UniverseMarket = (typeof UNIVERSE_MARKETS)[number]; + +export const HORIZON_BUCKETS = ['intraday', 'swing_1_10d', 'position_10d_plus'] as const; +export type HorizonBucket = (typeof HORIZON_BUCKETS)[number]; + +/** Maximum rows per single parameterised INSERT (`floor(65535 / 14)` PG protocol bind cap). */ +export const MAX_TRIAL_BATCH_SIZE = 4681; + +export type TrialLedgerErrorCode = + | 'INVALID_PRINCIPAL' + | 'INVALID_UUID' + | 'INVALID_STAGE' + | 'INVALID_UNIVERSE_MARKET' + | 'INVALID_HORIZON_BUCKET' + | 'INVALID_EXPRESSION_HASH' + | 'INVALID_EXPRESSION_INPUT' + | 'INVALID_DATE' + | 'INVALID_SAMPLE_WINDOW' + | 'VAULT_FENCE_VIOLATION' + | 'SERIES_TOO_SHORT' + | 'INVALID_SERIES_VALUE' + | 'ZERO_VARIANCE_SERIES' + | 'BATCH_TOO_LARGE' + | 'INVALID_TRIAL_ID' + | 'TRIAL_NOT_FOUND' + | 'INVALID_ROW'; + +/** Typed validation and lookup error thrown by `trial_ledger` helpers. */ +export class TrialLedgerError extends RangeError { + readonly code: TrialLedgerErrorCode; + + constructor(code: TrialLedgerErrorCode, message: string) { + super(message); + this.name = 'TrialLedgerError'; + this.code = code; + Object.setPrototypeOf(this, new.target.prototype); + } +} + +export interface TrialLedgerQueryResult> { + readonly rows: readonly Row[]; + readonly rowCount?: number | null; +} + +/** + * Structural `pg.Pool` / `pg.PoolClient`-compatible query interface so this module + * has no runtime dependency on `pg` and is unit-testable with a fake executor. + */ +export interface TrialLedgerExecutor { + query>( + text: string, + params?: readonly unknown[] + ): Promise>; +} + +export interface CanonicalExpressionInput { + readonly expression: string; + readonly params: unknown; + readonly universe: unknown; + readonly sampleStart: string; + readonly sampleEnd: string; + readonly horizon: string | number; +} + +export interface TrialRowInput { + readonly principalId: string; + readonly campaignId?: string | null; + readonly hypothesisId?: string | null; + readonly stage: TrialStage; + readonly universeMarket: UniverseMarket; + readonly horizonBucket: HorizonBucket; + readonly expressionHash: string; + readonly sampleStart: string; + readonly sampleEnd: string; + readonly dailySeries: readonly number[] | Float32Array | Float64Array; + readonly vaultCutoffDate: string; + readonly dailyRiskFree?: number; +} + +export interface BuiltTrialRow { + readonly principalId: string; + readonly campaignId: string | null; + readonly hypothesisId: string | null; + readonly stage: TrialStage; + readonly universeMarket: UniverseMarket; + readonly horizonBucket: HorizonBucket; + readonly expressionHash: string; + readonly sampleStart: string; + readonly sampleEnd: string; + readonly vaultCutoffDate: string; + readonly nObs: number; + readonly sharpeUnann: number; + readonly skewness: number; + readonly kurtosis: number; + readonly dailySeries: readonly number[]; +} + +export interface RecordedTrialReceipt { + readonly trialId: number; + readonly createdAt: string; +} + +export interface LoadClusterTrialsQuery { + readonly universeMarket: UniverseMarket; + readonly horizonBucket: HorizonBucket; + readonly asOf?: string | Date; +} + +export interface TrialLedgerRow { + readonly trialId: number; + readonly createdAt: string; + readonly principalId: string; + readonly campaignId: string | null; + readonly stage: TrialStage; + readonly universeMarket: UniverseMarket; + readonly horizonBucket: HorizonBucket; + readonly hypothesisId: string | null; + readonly expressionHash: string; + readonly sampleStart: string; + readonly sampleEnd: string; + readonly nObs: number; + readonly sharpeUnann: number; + readonly skewness: number; + readonly kurtosis: number; + readonly dailySeries: readonly number[]; +} + +export interface ClusterDeflatedSharpeQuery { + readonly trialId: number | bigint | string; + readonly asOf?: string | Date; + readonly dsrGate?: number; +} + +export interface ClusterDeflatedSharpeResult { + readonly trialId: number; + readonly universeMarket: UniverseMarket; + readonly horizonBucket: HorizonBucket; + readonly clusterSize: number; + readonly effectiveTrials: number; + readonly meanCorrelation: number | null; + readonly pairsUsed: number; + readonly pairsSkipped: number; + readonly sr0: number | null; + readonly standardError: number | null; + readonly dsr: number | null; + readonly passesGate: boolean; +} + +const DATE_ONLY_PATTERN = /^\d{4}-\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 TRIAL_STAGE_SET: ReadonlySet = new Set(TRIAL_STAGES); +const UNIVERSE_MARKET_SET: ReadonlySet = new Set(UNIVERSE_MARKETS); +const HORIZON_BUCKET_SET: ReadonlySet = new Set(HORIZON_BUCKETS); + +const COLUMNS_PER_ROW = 14; + +const SELECT_TRIAL_COLUMNS = ` + trial_id, + created_at, + principal_id, + campaign_id, + stage, + universe_market, + horizon_bucket, + hypothesis_id, + expression_hash, + sample_start::text AS sample_start, + sample_end::text AS sample_end, + n_obs, + sharpe_unann, + skewness, + kurtosis, + daily_series`; + +// FIPS 180-4 SHA-256 round constants. +const SHA256_K = new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +]); + +const UTF8_ENCODER = new TextEncoder(); + +function sha256HexUtf8(text: string): string { + const bytes = UTF8_ENCODER.encode(text); + const byteLen = bytes.length; + const paddedLen = (((byteLen + 9 + 63) >> 6) << 6) >>> 0; + const buffer = new Uint8Array(paddedLen); + buffer.set(bytes); + buffer[byteLen] = 0x80; + + const view = new DataView(buffer.buffer); + const bitLenHigh = Math.floor((byteLen * 8) / 0x1_0000_0000); + const bitLenLow = (byteLen * 8) >>> 0; + view.setUint32(paddedLen - 8, bitLenHigh, false); + view.setUint32(paddedLen - 4, bitLenLow, false); + + let h0 = 0x6a09e667; + let h1 = 0xbb67ae85; + let h2 = 0x3c6ef372; + let h3 = 0xa54ff53a; + let h4 = 0x510e527f; + let h5 = 0x9b05688c; + let h6 = 0x1f83d9ab; + let h7 = 0x5be0cd19; + + const w = new Uint32Array(64); + + for (let offset = 0; offset < paddedLen; offset += 64) { + for (let i = 0; i < 16; i += 1) { + w[i] = view.getUint32(offset + i * 4, false); + } + for (let i = 16; i < 64; i += 1) { + const w15 = w[i - 15] as number; + const w2 = w[i - 2] as number; + const s0 = ((w15 >>> 7) | (w15 << 25)) ^ ((w15 >>> 18) | (w15 << 14)) ^ (w15 >>> 3); + const s1 = ((w2 >>> 17) | (w2 << 15)) ^ ((w2 >>> 19) | (w2 << 13)) ^ (w2 >>> 10); + w[i] = (((w[i - 16] as number) + s0 + (w[i - 7] as number) + s1) | 0) >>> 0; + } + + let a = h0; + let b = h1; + let c = h2; + let d = h3; + let e = h4; + let f = h5; + let g = h6; + let h = h7; + + for (let i = 0; i < 64; i += 1) { + const s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7)); + const ch = (e & f) ^ (~e & g); + const temp1 = (h + s1 + ch + (SHA256_K[i] as number) + (w[i] as number)) | 0; + const s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10)); + const maj = (a & b) ^ (a & c) ^ (b & c); + const temp2 = (s0 + maj) | 0; + + h = g; + g = f; + f = e; + e = (d + temp1) | 0; + d = c; + c = b; + b = a; + a = (temp1 + temp2) | 0; + } + + h0 = (h0 + a) >>> 0; + h1 = (h1 + b) >>> 0; + h2 = (h2 + c) >>> 0; + h3 = (h3 + d) >>> 0; + h4 = (h4 + e) >>> 0; + h5 = (h5 + f) >>> 0; + h6 = (h6 + g) >>> 0; + h7 = (h7 + h) >>> 0; + } + + return ( + h0.toString(16).padStart(8, '0') + + h1.toString(16).padStart(8, '0') + + h2.toString(16).padStart(8, '0') + + h3.toString(16).padStart(8, '0') + + h4.toString(16).padStart(8, '0') + + h5.toString(16).padStart(8, '0') + + h6.toString(16).padStart(8, '0') + + h7.toString(16).padStart(8, '0') + ); +} + +function compareAscii(a: string, b: string): number { + return a < b ? -1 : a > b ? 1 : 0; +} + +function isPlainObject(value: unknown): value is Record { + if (typeof value !== 'object' || value === null) { + return false; + } + const proto: unknown = Object.getPrototypeOf(value); + return proto === Object.prototype || proto === null; +} + +function canonicalizeJsonValue(value: unknown, path: string, seen: Set): string { + if (value === null) { + return 'null'; + } + + const valueType = typeof value; + if (valueType === 'boolean') { + return value ? 'true' : 'false'; + } + if (valueType === 'string') { + return JSON.stringify(value); + } + if (valueType === 'number') { + if (!Number.isFinite(value)) { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_INPUT', + `Non-finite number at "${path}" is not allowed in canonicalExpressionHash.` + ); + } + return JSON.stringify(Object.is(value, -0) ? 0 : value); + } + if (valueType === 'undefined') { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_INPUT', + `Undefined value at "${path}" is not allowed in canonicalExpressionHash.` + ); + } + if (valueType !== 'object') { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_INPUT', + `Unsupported value type "${valueType}" at "${path}" in canonicalExpressionHash.` + ); + } + + const obj = value as object; + if (seen.has(obj)) { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_INPUT', + `Circular reference detected at "${path}" in canonicalExpressionHash.` + ); + } + + if (Array.isArray(obj)) { + seen.add(obj); + try { + const parts: string[] = new Array(obj.length); + for (let i = 0; i < obj.length; i += 1) { + parts[i] = canonicalizeJsonValue(obj[i], `${path}[${i}]`, seen); + } + return `[${parts.join(',')}]`; + } finally { + seen.delete(obj); + } + } + + if (!isPlainObject(obj)) { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_INPUT', + `Unsupported non-plain object at "${path}" in canonicalExpressionHash.` + ); + } + + seen.add(obj); + try { + const keys = Object.keys(obj).sort(compareAscii); + const entries: string[] = []; + for (let i = 0; i < keys.length; i += 1) { + const key = keys[i] as string; + const entryValue = obj[key]; + if (entryValue === undefined) { + continue; + } + entries.push(`${JSON.stringify(key)}:${canonicalizeJsonValue(entryValue, `${path}.${key}`, seen)}`); + } + return `{${entries.join(',')}}`; + } finally { + seen.delete(obj); + } +} + +function assertDateOnlyFormat(value: unknown, field: string): string { + if (typeof value !== 'string' || !DATE_ONLY_PATTERN.test(value)) { + throw new TrialLedgerError( + 'INVALID_DATE', + `Invalid "${field}": expected strict YYYY-MM-DD date string, got "${String(value)}".` + ); + } + return value; +} + +function validateSampleWindowUnfenced(sampleStart: unknown, sampleEnd: unknown): { + sampleStart: string; + sampleEnd: string; +} { + const start = assertDateOnlyFormat(sampleStart, 'sampleStart'); + const end = assertDateOnlyFormat(sampleEnd, 'sampleEnd'); + try { + applyVaultFence( + { from: start, to: end, scope: 'vault_evaluation_only' }, + { vaultCutoffTs: 0, vaultOperatorAuthorized: true } + ); + } catch (error) { + if (error instanceof MarketDataStoreValidationError) { + if (error.message.includes('must not be after end')) { + throw new TrialLedgerError( + 'INVALID_SAMPLE_WINDOW', + `sampleStart "${start}" must not be after sampleEnd "${end}".` + ); + } + throw new TrialLedgerError('INVALID_DATE', error.message); + } + throw error; + } + return { sampleStart: start, sampleEnd: end }; +} + +function validateSampleWindowFenced( + sampleStart: unknown, + sampleEnd: unknown, + vaultCutoffDate: unknown +): { + sampleStart: string; + sampleEnd: string; + vaultCutoffDate: string; +} { + const start = assertDateOnlyFormat(sampleStart, 'sampleStart'); + const end = assertDateOnlyFormat(sampleEnd, 'sampleEnd'); + const cutoff = assertDateOnlyFormat(vaultCutoffDate, 'vaultCutoffDate'); + + let cutoffMs: number; + try { + const cutoffRange = applyVaultFence( + { from: cutoff, to: cutoff, scope: 'vault_evaluation_only' }, + { vaultCutoffTs: 0, vaultOperatorAuthorized: true } + ); + cutoffMs = cutoffRange.fromMs; + } catch (error) { + if (error instanceof MarketDataStoreValidationError) { + throw new TrialLedgerError('INVALID_DATE', `Invalid vaultCutoffDate "${cutoff}": ${error.message}`); + } + throw error; + } + + let fenced; + try { + fenced = applyVaultFence({ from: start, to: end, scope: 'vault_fenced' }, { vaultCutoffTs: cutoffMs }); + } catch (error) { + if (error instanceof VaultHoldoutFenceError) { + throw new TrialLedgerError( + 'VAULT_FENCE_VIOLATION', + `Sample window [${start}, ${end}] violates exclusive vaultCutoffDate "${cutoff}".` + ); + } + if (error instanceof MarketDataStoreValidationError) { + if (error.message.includes('must not be after end')) { + throw new TrialLedgerError( + 'INVALID_SAMPLE_WINDOW', + `sampleStart "${start}" must not be after sampleEnd "${end}".` + ); + } + throw new TrialLedgerError('INVALID_DATE', error.message); + } + throw error; + } + + if (fenced.clampedTo) { + throw new TrialLedgerError( + 'VAULT_FENCE_VIOLATION', + `sampleEnd "${end}" must be strictly before vaultCutoffDate "${cutoff}".` + ); + } + + return { sampleStart: start, sampleEnd: end, vaultCutoffDate: cutoff }; +} + +function validatePrincipalId(value: unknown): string { + if (typeof value !== 'string' || (value !== 'operator' && !AGENT_PRINCIPAL_PATTERN.test(value))) { + throw new TrialLedgerError( + 'INVALID_PRINCIPAL', + `Invalid principalId "${String(value)}": expected 'operator' or 'agent:'.` + ); + } + return value; +} + +function validateOptionalUuid(value: unknown, field: string): string | null { + if (value === undefined || value === null) { + return null; + } + if (typeof value !== 'string' || !UUID_PATTERN.test(value)) { + throw new TrialLedgerError('INVALID_UUID', `Invalid UUID for "${field}": "${String(value)}".`); + } + return value.toLowerCase(); +} + +function validateStage(value: unknown): TrialStage { + if (typeof value !== 'string' || !TRIAL_STAGE_SET.has(value)) { + throw new TrialLedgerError( + 'INVALID_STAGE', + `Invalid stage "${String(value)}". Expected one of: ${TRIAL_STAGES.join(', ')}.` + ); + } + return value as TrialStage; +} + +function validateUniverseMarket(value: unknown): UniverseMarket { + if (typeof value !== 'string' || !UNIVERSE_MARKET_SET.has(value)) { + throw new TrialLedgerError( + 'INVALID_UNIVERSE_MARKET', + `Invalid universeMarket "${String(value)}". Expected one of: ${UNIVERSE_MARKETS.join(', ')}.` + ); + } + return value as UniverseMarket; +} + +function validateHorizonBucket(value: unknown): HorizonBucket { + if (typeof value !== 'string' || !HORIZON_BUCKET_SET.has(value)) { + throw new TrialLedgerError( + 'INVALID_HORIZON_BUCKET', + `Invalid horizonBucket "${String(value)}". Expected one of: ${HORIZON_BUCKETS.join(', ')}.` + ); + } + return value as HorizonBucket; +} + +function validateExpressionHash(value: unknown): string { + if (typeof value !== 'string' || !EXPRESSION_HASH_PATTERN.test(value)) { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_HASH', + `Invalid expressionHash "${String(value)}": expected 64 lowercase hexadecimal characters.` + ); + } + return value; +} + +function validateDailySeries(value: unknown): number[] { + const isTyped = value instanceof Float32Array || value instanceof Float64Array; + if (!Array.isArray(value) && !isTyped) { + throw new TrialLedgerError( + 'INVALID_SERIES_VALUE', + 'dailySeries must be an array, Float32Array, or Float64Array of finite numbers.' + ); + } + const len = value.length; + if (len < 2) { + throw new TrialLedgerError( + 'SERIES_TOO_SHORT', + `dailySeries must contain at least 2 finite observations (got ${len}).` + ); + } + + const normalized: number[] = new Array(len); + for (let i = 0; i < len; i += 1) { + const v: unknown = value[i]; + if (typeof v !== 'number' || !Number.isFinite(v)) { + throw new TrialLedgerError( + 'INVALID_SERIES_VALUE', + `dailySeries[${i}] is not a finite number: ${String(v)}.` + ); + } + const asReal = Math.fround(v); + if (!Number.isFinite(asReal) || (v !== 0 && asReal === 0)) { + throw new TrialLedgerError( + 'INVALID_SERIES_VALUE', + `dailySeries[${i}] (${v}) is outside finite PostgreSQL REAL (float32) range.` + ); + } + normalized[i] = Object.is(v, -0) ? 0 : v; + } + return normalized; +} + +function assertExecutor(executor: unknown): asserts executor is TrialLedgerExecutor { + if ( + typeof executor !== 'object' || + executor === null || + typeof (executor as { query?: unknown }).query !== 'function' + ) { + throw new TrialLedgerError( + 'INVALID_ROW', + 'Expected a TrialLedgerExecutor object with a query(text, params) method.' + ); + } +} + +function parseTrialId(value: unknown): number { + if (typeof value === 'number') { + if (!Number.isSafeInteger(value) || value < 1) { + throw new TrialLedgerError( + 'INVALID_TRIAL_ID', + `Invalid trialId "${String(value)}": expected a positive safe integer.` + ); + } + return value; + } + if (typeof value === 'bigint') { + if (value < 1n || value > BigInt(Number.MAX_SAFE_INTEGER)) { + throw new TrialLedgerError( + 'INVALID_TRIAL_ID', + `Invalid trialId "${value.toString()}": expected a positive safe integer.` + ); + } + return Number(value); + } + if (typeof value === 'string' && POSITIVE_INT_PATTERN.test(value)) { + const parsed = Number(value); + if (Number.isSafeInteger(parsed) && parsed >= 1) { + return parsed; + } + } + throw new TrialLedgerError( + 'INVALID_TRIAL_ID', + `Invalid trialId "${String(value)}": expected a positive safe integer.` + ); +} + +function normalizeAsOf(asOf: unknown): string | undefined { + if (asOf === undefined) { + return undefined; + } + if (asOf instanceof Date) { + const ms = asOf.getTime(); + if (!Number.isFinite(ms)) { + throw new TrialLedgerError('INVALID_DATE', 'Invalid asOf Date instance.'); + } + return asOf.toISOString(); + } + if (typeof asOf !== 'string') { + throw new TrialLedgerError( + 'INVALID_DATE', + `Invalid asOf "${String(asOf)}": expected ISO-8601 UTC timestamp, YYYY-MM-DD date, or Date.` + ); + } + try { + const fenced = applyVaultFence( + { from: '1970-01-01', to: '1970-01-01', asOf, scope: 'vault_evaluation_only' }, + { vaultCutoffTs: 0, vaultOperatorAuthorized: true } + ); + return new Date(fenced.asOfMs).toISOString(); + } catch (error) { + if (error instanceof MarketDataStoreValidationError) { + throw new TrialLedgerError('INVALID_DATE', error.message); + } + throw error; + } +} + +function formatUtcTimestamp(value: unknown, field: string): string { + if (value instanceof Date) { + if (!Number.isFinite(value.getTime())) { + throw new TrialLedgerError('INVALID_ROW', `Invalid timestamp for "${field}".`); + } + return value.toISOString(); + } + if (typeof value === 'string') { + const ms = Date.parse(value); + if (!Number.isFinite(ms)) { + throw new TrialLedgerError('INVALID_ROW', `Invalid timestamp string for "${field}": "${value}".`); + } + return new Date(ms).toISOString(); + } + throw new TrialLedgerError('INVALID_ROW', `Unexpected timestamp value for "${field}".`); +} + +function formatDateOnlyFromDb(value: unknown, field: string): string { + if (typeof value === 'string' && DATE_ONLY_PATTERN.test(value)) { + return value; + } + if (value instanceof Date && Number.isFinite(value.getTime())) { + return value.toISOString().slice(0, 10); + } + throw new TrialLedgerError('INVALID_ROW', `Unexpected date value for "${field}": "${String(value)}".`); +} + +function parsePgRealArray(value: unknown): number[] { + if (Array.isArray(value)) { + return validateDailySeries(value.map(v => Number(v))); + } + if (value instanceof Float32Array || value instanceof Float64Array) { + return validateDailySeries(value); + } + if (typeof value === 'string' && value.startsWith('{') && value.endsWith('}')) { + const inner = value.slice(1, -1).trim(); + if (inner.length === 0) { + throw new TrialLedgerError('SERIES_TOO_SHORT', 'Empty daily_series returned from database.'); + } + const elements = inner.split(',').map(token => Number(token)); + return validateDailySeries(elements); + } + throw new TrialLedgerError('INVALID_ROW', 'Unexpected daily_series value returned from database.'); +} + +function parseDbTrialRow(raw: Record): TrialLedgerRow { + const trialId = parseTrialId(raw.trial_id); + const createdAt = formatUtcTimestamp(raw.created_at, 'created_at'); + const principalId = validatePrincipalId(raw.principal_id); + const campaignId = validateOptionalUuid(raw.campaign_id, 'campaign_id'); + const stage = validateStage(raw.stage); + const universeMarket = validateUniverseMarket(raw.universe_market); + const horizonBucket = validateHorizonBucket(raw.horizon_bucket); + const hypothesisId = validateOptionalUuid(raw.hypothesis_id, 'hypothesis_id'); + const expressionHash = validateExpressionHash( + typeof raw.expression_hash === 'string' ? raw.expression_hash.trim() : raw.expression_hash + ); + const sampleStart = formatDateOnlyFromDb(raw.sample_start, 'sample_start'); + const sampleEnd = formatDateOnlyFromDb(raw.sample_end, 'sample_end'); + const nObs = Number(raw.n_obs); + const sharpeUnann = Number(raw.sharpe_unann); + const skewness = Number(raw.skewness); + const kurtosis = Number(raw.kurtosis); + if ( + !Number.isSafeInteger(nObs) || + nObs < 2 || + !Number.isFinite(sharpeUnann) || + !Number.isFinite(skewness) || + !Number.isFinite(kurtosis) + ) { + throw new TrialLedgerError('INVALID_ROW', `Corrupted numeric moments for trial_id=${trialId}.`); + } + const dailySeries = parsePgRealArray(raw.daily_series); + + return Object.freeze({ + trialId, + createdAt, + principalId, + campaignId, + stage, + universeMarket, + horizonBucket, + hypothesisId, + expressionHash, + sampleStart, + sampleEnd, + nObs, + sharpeUnann, + skewness, + kurtosis, + dailySeries: Object.freeze(dailySeries), + }); +} + +function isPreBuiltTrialRow(row: TrialRowInput | BuiltTrialRow): row is BuiltTrialRow { + return ( + 'nObs' in row || 'sharpeUnann' in row || 'skewness' in row || 'kurtosis' in row + ); +} + +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.`); + } + + if (!isPreBuiltTrialRow(row)) { + return buildTrialRow(row); + } + + const principalId = validatePrincipalId(row.principalId); + const campaignId = validateOptionalUuid(row.campaignId, 'campaignId'); + const hypothesisId = validateOptionalUuid(row.hypothesisId, 'hypothesisId'); + const stage = validateStage(row.stage); + const universeMarket = validateUniverseMarket(row.universeMarket); + const horizonBucket = validateHorizonBucket(row.horizonBucket); + const expressionHash = validateExpressionHash(row.expressionHash); + const { sampleStart, sampleEnd, vaultCutoffDate } = validateSampleWindowFenced( + row.sampleStart, + row.sampleEnd, + row.vaultCutoffDate + ); + const dailySeries = validateDailySeries(row.dailySeries); + + if (!Number.isSafeInteger(row.nObs) || row.nObs !== dailySeries.length) { + throw new TrialLedgerError( + 'INVALID_ROW', + `Row at index ${index} has nObs=${String(row.nObs)} which does not match dailySeries.length (${dailySeries.length}).` + ); + } + if ( + typeof row.sharpeUnann !== 'number' || + !Number.isFinite(row.sharpeUnann) || + typeof row.skewness !== 'number' || + !Number.isFinite(row.skewness) || + typeof row.kurtosis !== 'number' || + !Number.isFinite(row.kurtosis) + ) { + throw new TrialLedgerError( + 'INVALID_ROW', + `Row at index ${index} has non-finite moments (sharpeUnann, skewness, kurtosis).` + ); + } + + // Ensure the series itself has non-zero variance so forged rows cannot bypass moment invariants. + if (trialMoments(dailySeries) === null) { + throw new TrialLedgerError( + 'ZERO_VARIANCE_SERIES', + `Row at index ${index} has a zero-variance or degenerate dailySeries.` + ); + } + + return Object.freeze({ + principalId, + campaignId, + hypothesisId, + stage, + universeMarket, + horizonBucket, + expressionHash, + sampleStart, + sampleEnd, + vaultCutoffDate, + nObs: row.nObs, + sharpeUnann: row.sharpeUnann, + skewness: row.skewness, + kurtosis: row.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 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; + } + if (trial.sampleEnd !== first.sampleEnd) { + allSameEnd = false; + } + } + + // Fast zero-copy path: all trials share sampleStart, so index t is the same trading day. + if (allSameStart) { + return cluster.map(trial => trial.dailySeries); + } + + // 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(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; + }); + } + + // 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(); + const byEnd = new Map(); + 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; + } else { + byStart.set(trial.sampleStart, [i]); + } + const endGroup = byEnd.get(trial.sampleEnd); + if (endGroup !== undefined) { + endGroup.push(i); + hasSharedEnd = true; + } else { + byEnd.set(trial.sampleEnd, [i]); + } + } + + const alignMode: 'start' | 'end' = hasSharedStart || !hasSharedEnd ? 'start' : 'end'; + const groups = alignMode === 'start' ? byStart : byEnd; + const aligned: (readonly number[])[] = new Array(count); + let blockOffset = 0; + + 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; + } + } + + 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; + } else { + const padded = new Array(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; + } + } + + blockOffset += blockWidth; + } + + return aligned; +} + +/** + * Computes a deterministic 64-character lowercase SHA-256 hex digest over the + * canonical, ASCII-key-sorted JSON representation of + * `{ expression, params, universe, sampleStart, sampleEnd, horizon }`. + */ +export function canonicalExpressionHash(input: CanonicalExpressionInput): string { + if (typeof input !== 'object' || input === null) { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_INPUT', + 'canonicalExpressionHash input must be a non-null object.' + ); + } + + if (typeof input.expression !== 'string') { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_INPUT', + 'canonicalExpressionHash requires a non-empty string expression.' + ); + } + const normalizedExpression = input.expression.trim().replace(/\s+/g, ' '); + if (normalizedExpression.length === 0) { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_INPUT', + 'canonicalExpressionHash expression must not be empty or whitespace-only.' + ); + } + + const { sampleStart, sampleEnd } = validateSampleWindowUnfenced( + input.sampleStart, + input.sampleEnd + ); + + let normalizedHorizon: string | number; + if (typeof input.horizon === 'string') { + if (input.horizon.trim().length === 0) { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_INPUT', + 'canonicalExpressionHash horizon string must not be empty.' + ); + } + normalizedHorizon = input.horizon; + } else if (typeof input.horizon === 'number' && Number.isFinite(input.horizon)) { + normalizedHorizon = Object.is(input.horizon, -0) ? 0 : input.horizon; + } else { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_INPUT', + 'canonicalExpressionHash horizon must be a non-empty string or finite number.' + ); + } + + if (input.params === undefined) { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_INPUT', + 'canonicalExpressionHash params must be defined (use null or {} when empty).' + ); + } + if (input.universe === undefined) { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_INPUT', + 'canonicalExpressionHash universe must be defined.' + ); + } + + const envelope = { + expression: normalizedExpression, + horizon: normalizedHorizon, + params: input.params, + sampleEnd, + sampleStart, + universe: input.universe, + }; + + const canonicalJson = canonicalizeJsonValue(envelope, '$', new Set()); + return sha256HexUtf8(canonicalJson); +} + +/** + * Pure validator and moment builder for a single `trial_ledger` row. + * + * Enforces the exclusive Vault holdout fence (`sampleEnd < vaultCutoffDate`) via + * {@link applyVaultFence} and computes `{ nObs, sharpeUnann, skewness, kurtosis }` + * via {@link trialMoments} from `@stock-bot/calculations`. + */ +export function buildTrialRow(input: TrialRowInput): BuiltTrialRow { + if (typeof input !== 'object' || input === null) { + throw new TrialLedgerError('INVALID_ROW', 'buildTrialRow input must be a non-null object.'); + } + + const principalId = validatePrincipalId(input.principalId); + const campaignId = validateOptionalUuid(input.campaignId, 'campaignId'); + const hypothesisId = validateOptionalUuid(input.hypothesisId, 'hypothesisId'); + const stage = validateStage(input.stage); + const universeMarket = validateUniverseMarket(input.universeMarket); + const horizonBucket = validateHorizonBucket(input.horizonBucket); + const expressionHash = validateExpressionHash(input.expressionHash); + const { sampleStart, sampleEnd, vaultCutoffDate } = validateSampleWindowFenced( + input.sampleStart, + input.sampleEnd, + input.vaultCutoffDate + ); + const dailySeries = validateDailySeries(input.dailySeries); + + const dailyRiskFree = input.dailyRiskFree ?? 0; + if (typeof dailyRiskFree !== 'number' || !Number.isFinite(dailyRiskFree)) { + throw new TrialLedgerError( + 'INVALID_ROW', + `Invalid dailyRiskFree "${String(input.dailyRiskFree)}": expected a finite number.` + ); + } + + const moments = trialMoments(dailySeries, dailyRiskFree); + if (moments === null) { + throw new TrialLedgerError( + 'ZERO_VARIANCE_SERIES', + 'dailySeries has zero variance or degenerate moments (trialMoments returned null).' + ); + } + + return Object.freeze({ + principalId, + campaignId, + hypothesisId, + stage, + universeMarket, + horizonBucket, + expressionHash, + sampleStart, + sampleEnd, + vaultCutoffDate, + nObs: moments.nObs, + sharpeUnann: moments.sharpeUnann, + skewness: moments.skewness, + kurtosis: moments.kurtosis, + dailySeries: Object.freeze(dailySeries), + }); +} + +/** + * Atomically appends one or more validated rows to `trial_ledger` in a single + * parameterised multi-row `INSERT ... RETURNING trial_id, created_at`. + * + * All rows are validated upfront before any SQL is sent. + */ +export async function recordTrials( + executor: TrialLedgerExecutor, + rows: readonly (TrialRowInput | BuiltTrialRow)[] +): Promise { + assertExecutor(executor); + + if (!Array.isArray(rows)) { + throw new TrialLedgerError('INVALID_ROW', 'recordTrials rows must be an array.'); + } + if (rows.length === 0) { + return []; + } + if (rows.length > MAX_TRIAL_BATCH_SIZE) { + throw new TrialLedgerError( + 'BATCH_TOO_LARGE', + `Batch size ${rows.length} exceeds MAX_TRIAL_BATCH_SIZE (${MAX_TRIAL_BATCH_SIZE}).` + ); + } + + const validated: BuiltTrialRow[] = new Array(rows.length); + for (let i = 0; i < rows.length; i += 1) { + validated[i] = validateRowForInsert(rows[i] as TrialRowInput | BuiltTrialRow, i); + } + + const valueTuples: string[] = new Array(validated.length); + const params: unknown[] = new Array(validated.length * COLUMNS_PER_ROW); + + for (let i = 0; i < validated.length; i += 1) { + const row = validated[i] as BuiltTrialRow; + const base = i * COLUMNS_PER_ROW; + const p = base + 1; + valueTuples[i] = + `($${p}, $${p + 1}, $${p + 2}, $${p + 3}, $${p + 4}, $${p + 5}, $${p + 6}, $${p + 7}, $${p + 8}, $${p + 9}, $${p + 10}::double precision, $${p + 11}::double precision, $${p + 12}::double precision, $${p + 13}::real[])`; + + params[base] = row.principalId; + params[base + 1] = row.campaignId; + params[base + 2] = row.stage; + params[base + 3] = row.universeMarket; + params[base + 4] = row.horizonBucket; + params[base + 5] = row.hypothesisId; + params[base + 6] = row.expressionHash; + params[base + 7] = row.sampleStart; + params[base + 8] = row.sampleEnd; + params[base + 9] = row.nObs; + params[base + 10] = row.sharpeUnann; + params[base + 11] = row.skewness; + params[base + 12] = row.kurtosis; + params[base + 13] = row.dailySeries; + } + + const sql = `INSERT INTO trial_ledger ( + 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 ${valueTuples.join(', ')} +RETURNING trial_id, created_at`; + + const result = await executor.query>(sql, params); + if (result.rows.length !== validated.length) { + throw new TrialLedgerError( + 'INVALID_ROW', + `Expected ${validated.length} returned receipts from trial_ledger INSERT, got ${result.rows.length}.` + ); + } + + const receipts: RecordedTrialReceipt[] = new Array(result.rows.length); + for (let i = 0; i < result.rows.length; i += 1) { + const returned = result.rows[i] as Record; + receipts[i] = { + trialId: parseTrialId(returned.trial_id), + createdAt: formatUtcTimestamp(returned.created_at, 'created_at'), + }; + } + return receipts; +} + +/** + * Loads all trials in a `(universeMarket, horizonBucket)` relatedness cluster + * ordered by `trial_id ASC`, optionally capped at `created_at <= asOf`. + */ +export async function loadClusterTrials( + executor: TrialLedgerExecutor, + query: LoadClusterTrialsQuery +): Promise { + assertExecutor(executor); + if (typeof query !== 'object' || query === null) { + throw new TrialLedgerError('INVALID_ROW', 'loadClusterTrials query must be a non-null object.'); + } + + const universeMarket = validateUniverseMarket(query.universeMarket); + const horizonBucket = validateHorizonBucket(query.horizonBucket); + const normalizedAsOf = normalizeAsOf(query.asOf); + + const sql = + normalizedAsOf === undefined + ? `SELECT${SELECT_TRIAL_COLUMNS} +FROM trial_ledger +WHERE universe_market = $1 + AND horizon_bucket = $2 +ORDER BY trial_id ASC` + : `SELECT${SELECT_TRIAL_COLUMNS} +FROM trial_ledger +WHERE universe_market = $1 + AND horizon_bucket = $2 + AND created_at <= $3::timestamptz +ORDER BY trial_id ASC`; + + const params: readonly unknown[] = + normalizedAsOf === undefined + ? [universeMarket, horizonBucket] + : [universeMarket, horizonBucket, normalizedAsOf]; + + const result = await executor.query>(sql, params); + return result.rows.map(row => parseDbTrialRow(row)); +} + +/** + * Loads the target trial's `(universe_market, horizon_bucket)` relatedness cluster + * and computes its N-hat-deflated Sharpe Ratio via {@link effectiveIndependentTrials} + * and {@link deflatedSharpeRatio}. + */ +export async function clusterDeflatedSharpe( + executor: TrialLedgerExecutor, + query: ClusterDeflatedSharpeQuery +): Promise { + assertExecutor(executor); + if (typeof query !== 'object' || query === null) { + throw new TrialLedgerError( + 'INVALID_ROW', + 'clusterDeflatedSharpe query must be a non-null object.' + ); + } + + const trialId = parseTrialId(query.trialId); + const normalizedAsOf = normalizeAsOf(query.asOf); + const dsrGate = query.dsrGate ?? DSR_VALIDATION_GATE; + if (typeof dsrGate !== 'number' || !Number.isFinite(dsrGate)) { + throw new TrialLedgerError( + 'INVALID_ROW', + `Invalid dsrGate "${String(query.dsrGate)}": expected a finite number.` + ); + } + + const targetResult = await executor.query>( + `SELECT${SELECT_TRIAL_COLUMNS} +FROM trial_ledger +WHERE trial_id = $1::bigint`, + [trialId] + ); + + if (targetResult.rows.length === 0) { + throw new TrialLedgerError('TRIAL_NOT_FOUND', `Trial ${trialId} was not found in trial_ledger.`); + } + + const target = parseDbTrialRow(targetResult.rows[0] as Record); + const cluster = await loadClusterTrials(executor, { + universeMarket: target.universeMarket, + horizonBucket: target.horizonBucket, + asOf: normalizedAsOf, + }); + + const targetInCluster = cluster.find(row => row.trialId === target.trialId); + if (targetInCluster === undefined) { + throw new TrialLedgerError( + 'TRIAL_NOT_FOUND', + `Trial ${trialId} is not visible in cluster (${target.universeMarket}, ${target.horizonBucket}) as of ${normalizedAsOf ?? 'latest'}.` + ); + } + + const alignedSeries = buildAlignedClusterSeries(cluster); + const eff = effectiveIndependentTrials(alignedSeries); + const clusterSharpes = cluster.map(row => row.sharpeUnann); + + const dsrResult = deflatedSharpeRatio({ + sharpeUnann: targetInCluster.sharpeUnann, + nObs: targetInCluster.nObs, + skewness: targetInCluster.skewness, + kurtosis: targetInCluster.kurtosis, + nHat: eff.nHat, + clusterSharpes, + }); + + const dsr = dsrResult?.dsr ?? null; + const passesGate = passesDsrGate(dsr, dsrGate); + + return { + trialId: targetInCluster.trialId, + universeMarket: targetInCluster.universeMarket, + horizonBucket: targetInCluster.horizonBucket, + clusterSize: cluster.length, + effectiveTrials: eff.nHat, + meanCorrelation: eff.meanCorrelation, + pairsUsed: eff.pairsUsed, + pairsSkipped: eff.pairsSkipped, + sr0: dsrResult?.sr0 ?? null, + standardError: dsrResult?.standardError ?? null, + dsr, + passesGate, + }; +} diff --git a/libs/research/test/trial-ledger.test.ts b/libs/research/test/trial-ledger.test.ts new file mode 100644 index 00000000..c0adb090 --- /dev/null +++ b/libs/research/test/trial-ledger.test.ts @@ -0,0 +1,766 @@ +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 makeSampleSeries(seed: number, length: number, mean = 0.0004, std = 0.01): number[] { + const gauss = createGaussianSampler(seed); + const out = new Array(length); + for (let i = 0; i < length; i += 1) { + out[i] = mean + std * gauss(); + } + return out; +} + +function makeValidInput(overrides: Partial = {}): 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, + expectedCode: TrialLedgerErrorCode +): Promise { + 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[] } +): { executor: TrialLedgerExecutor; calls: FakeCall[] } { + const calls: FakeCall[] = []; + const executor: TrialLedgerExecutor = { + async query>(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 { + 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) + .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).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).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 = {}; + 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, 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'], + [{ 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, 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' + ); + + // Oversized batch rejected before any SQL. + const oversized = new Array(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, 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' }, + ]); + }); +}); + +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 same-window, prefix-overlap, suffix-overlap, and unalignable clusters', 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)); + + // 1. Same-start, different-end (prefix overlap) + const rowPrefixA = buildTrialRow( + makeValidInput({ + sampleStart: '2020-01-02', + sampleEnd: '2020-05-26', + dailySeries: baseSeries, + }) + ); + const rowPrefixB = buildTrialRow( + makeValidInput({ + sampleStart: '2020-01-02', + sampleEnd: '2020-04-15', + 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 }); + 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) + const rowSuffixA = buildTrialRow( + makeValidInput({ + sampleStart: '2020-01-02', + sampleEnd: '2020-05-26', + dailySeries: baseSeries, + }) + ); + const rowSuffixB = buildTrialRow( + makeValidInput({ + sampleStart: '2020-02-15', + sampleEnd: '2020-05-26', + 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 }); + 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 + const rowDisjointA = buildTrialRow( + makeValidInput({ + sampleStart: '2019-01-02', + sampleEnd: '2020-12-31', + dailySeries: baseSeries, + }) + ); + const rowDisjointB = buildTrialRow( + makeValidInput({ + sampleStart: '2021-01-04', + sampleEnd: '2022-12-30', + 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 }); + 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); + }); + + 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 through buildTrialRow + clusterDeflatedSharpe', async () => { + const trialCount = 200; + const obsPerTrial = 5_000; + const gauss = createGaussianSampler(20260403); + + // Pre-generate common factor + idiosyncratic series outside the timed region. + const common = new Array(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(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: '2005-01-03', + sampleEnd: '2024-11-15', + vaultCutoffDate: VAULT_CUTOFF, + dailySeries: series, + }; + } + + const startNs = Bun.nanoseconds(); + + const builtRows: BuiltTrialRow[] = new Array(trialCount); + const dbRows: Record[] = 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>(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 }); + const elapsedMs = (Bun.nanoseconds() - startNs) / 1e6; + const trialsPerSec = trialCount / (elapsedMs / 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` + ); + + 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(); + + // Cross-check against direct calculations on the same cluster. + const directEff = effectiveIndependentTrials(builtRows.map(r => r.dailySeries)); + expect(result.effectiveTrials).toBeCloseTo(directEff.nHat, 12); + }); +}); diff --git a/test/postgres/trial-ledger-writer.test.ts b/test/postgres/trial-ledger-writer.test.ts new file mode 100644 index 00000000..d28d9188 --- /dev/null +++ b/test/postgres/trial-ledger-writer.test.ts @@ -0,0 +1,380 @@ +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Pool } from 'pg'; +import { deflatedSharpeRatio, effectiveIndependentTrials } from '@stock-bot/calculations'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; +import { + TrialLedgerError, + buildTrialRow, + canonicalExpressionHash, + clusterDeflatedSharpe, + loadClusterTrials, + recordTrials, + type TrialRowInput, +} from '@stock-bot/research'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('trial-ledger-writer-test'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; +const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); +const VAULT_CUTOFF = '2025-05-01'; + +const cleanup: (() => Promise | void)[] = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); + +async function createIsolatedFixture() { + if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { + throw new Error('Dedicated stock_bot_safety database required'); + } + const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; + const admin = new Pool({ connectionString: url }); + await admin.query(`CREATE SCHEMA ${schema}`); + const pool = new Pool({ + connectionString: url, + options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`, + }); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + + // Bootstrap pre-additive tables needed by the research migration track. + for (const filename of [ + '06-create-backtest-tables.sql', + '07-fix-execution-time-type.sql', + '08-create-runs-table.sql', + ]) { + await pool.query(readFileSync(`${initDir}${filename}`, 'utf8')); + } + + const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, + logger + ); + Object.defineProperty(postgres, 'connectionPool', { + get: () => ({ + connect: () => pool.connect(), + }), + }); + + await runPostgresMigrations(postgres, { track: 'research' }); + + return { pool, schema, postgres }; +} + +async function expectPgErrorCode( + operation: Promise, + expectedCode: string, + messagePattern?: RegExp +): Promise { + try { + await operation; + } catch (error) { + const pgError = error as { code?: string; message?: string } | null; + expect(pgError?.code).toBe(expectedCode); + if (messagePattern) { + expect(pgError?.message ?? '').toMatch(messagePattern); + } + return; + } + throw new Error(`Expected PostgreSQL error code ${expectedCode}, but query succeeded`); +} + +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; + while (u <= 1e-12) { + u = next(); + } + const 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 makeSeries(seed: number, length: number, mean = 0.0005, std = 0.01): number[] { + const gauss = createGaussianSampler(seed); + const out = new Array(length); + for (let i = 0; i < length; i += 1) { + out[i] = mean + std * gauss(); + } + return out; +} + +describe.skipIf(!url)('trial_ledger PostgreSQL writer and cluster DSR reader', () => { + test('3-horizon recordTrials inserts 3 ascending rows, round-trips REAL series, rejects bad batch atomically, and preserves immutability triggers', async () => { + const f = await createIsolatedFixture(); + + const horizons = [ + { label: '1d', bucket: 'swing_1_10d' as const, seed: 1001 }, + { label: '5d', bucket: 'swing_1_10d' as const, seed: 1002 }, + { label: '20d', bucket: 'position_10d_plus' as const, seed: 1003 }, + ]; + + const rows = horizons.map(h => + buildTrialRow({ + principalId: 'operator', + stage: 'signal_ic', + universeMarket: 'US_EQ', + horizonBucket: h.bucket, + expressionHash: canonicalExpressionHash({ + expression: 'rank(ret_20d) - zscore(vol_20d)', + params: { lookback: 20 }, + universe: 'US_EQ', + sampleStart: '2020-01-02', + sampleEnd: '2024-12-31', + horizon: h.label, + }), + sampleStart: '2020-01-02', + sampleEnd: '2024-12-31', + vaultCutoffDate: VAULT_CUTOFF, + dailySeries: makeSeries(h.seed, 25), + }) + ); + + const receipts = await recordTrials(f.pool, rows); + expect(receipts).toHaveLength(3); + expect(receipts[0]!.trialId).toBeLessThan(receipts[1]!.trialId); + expect(receipts[1]!.trialId).toBeLessThan(receipts[2]!.trialId); + + const swingRows = await loadClusterTrials(f.pool, { + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + const positionRows = await loadClusterTrials(f.pool, { + universeMarket: 'US_EQ', + horizonBucket: 'position_10d_plus', + }); + expect(swingRows).toHaveLength(2); + expect(positionRows).toHaveLength(1); + + // Verify daily_series round-trips within IEEE-754 REAL precision. + for (let i = 0; i < rows[0]!.dailySeries.length; i += 1) { + expect(swingRows[0]!.dailySeries[i]).toBe(Math.fround(rows[0]!.dailySeries[i]!)); + } + + // Batch with one invalid row throws TrialLedgerError and inserts 0 additional rows. + const badBatch: TrialRowInput[] = [ + { + principalId: 'operator', + stage: 'event_study', + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + expressionHash: 'b'.repeat(64), + sampleStart: '2020-01-02', + sampleEnd: '2024-12-31', + vaultCutoffDate: VAULT_CUTOFF, + dailySeries: makeSeries(2001, 10), + }, + { + principalId: 'operator', + stage: 'event_study', + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + expressionHash: 'c'.repeat(64), + sampleStart: '2020-01-02', + sampleEnd: VAULT_CUTOFF, // violates exclusive vault fence + vaultCutoffDate: VAULT_CUTOFF, + dailySeries: makeSeries(2002, 10), + }, + ]; + + try { + await recordTrials(f.pool, badBatch); + throw new Error('Expected VAULT_FENCE_VIOLATION'); + } catch (error) { + expect(error).toBeInstanceOf(TrialLedgerError); + expect((error as TrialLedgerError).code).toBe('VAULT_FENCE_VIOLATION'); + } + + const caRows = await loadClusterTrials(f.pool, { + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + }); + expect(caRows).toHaveLength(0); + + // Existing append-only triggers still block UPDATE, DELETE, and TRUNCATE. + const expectedMsg = /Retained research evidence cannot be rewritten or deleted/; + await expectPgErrorCode( + f.pool.query('UPDATE trial_ledger SET n_obs = 999'), + '23514', + expectedMsg + ); + await expectPgErrorCode(f.pool.query('DELETE FROM trial_ledger'), '23514', expectedMsg); + await expectPgErrorCode(f.pool.query('TRUNCATE trial_ledger'), '23514', expectedMsg); + + const totalCount = (await f.pool.query('SELECT count(*)::int AS c FROM trial_ledger')).rows[0] + .c as number; + expect(totalCount).toBe(3); + }); + + test('computes N-hat and DSR end-to-end through PostgreSQL for near-duplicate vs independent clusters, cluster isolation, and asOf', async () => { + const f = await createIsolatedFixture(); + const nObs = 500; + const clusterK = 12; + + // 1. Near-duplicate cluster in (US_EQ, swing_1_10d): target pairwise rho ~ 0.97 + const factorGauss = createGaussianSampler(9001); + const baseFactor = new Array(nObs); + for (let t = 0; t < nObs; t += 1) { + baseFactor[t] = 0.0008 + 0.01 * factorGauss(); + } + const noiseGauss = createGaussianSampler(9002); + const nearDupRows = new Array(clusterK); + const loading = Math.sqrt(0.97); + const noiseWeight = Math.sqrt(1 - 0.97); + for (let k = 0; k < clusterK; k += 1) { + const series = new Array(nObs); + for (let t = 0; t < nObs; t += 1) { + series[t] = loading * (baseFactor[t] as number) + noiseWeight * 0.01 * noiseGauss(); + } + nearDupRows[k] = { + principalId: 'operator', + stage: 'screen', + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expressionHash: canonicalExpressionHash({ + expression: `dup_signal_${k}`, + params: { k }, + universe: 'US_EQ', + sampleStart: '2022-01-03', + sampleEnd: '2024-01-02', + horizon: '5d', + }), + sampleStart: '2022-01-03', + sampleEnd: '2024-01-02', + vaultCutoffDate: VAULT_CUTOFF, + dailySeries: series, + }; + } + + const nearDupReceipts = await recordTrials(f.pool, nearDupRows); + + // 2. Independent cluster in (CA_EQ, swing_1_10d) — also tests cluster isolation from US_EQ! + const indepRows = new Array(clusterK); + for (let k = 0; k < clusterK; k += 1) { + indepRows[k] = { + principalId: 'operator', + stage: 'screen', + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + expressionHash: canonicalExpressionHash({ + expression: `indep_signal_${k}`, + params: { k }, + universe: 'CA_EQ', + sampleStart: '2022-01-03', + sampleEnd: '2024-01-02', + horizon: '5d', + }), + sampleStart: '2022-01-03', + sampleEnd: '2024-01-02', + vaultCutoffDate: VAULT_CUTOFF, + dailySeries: makeSeries(5000 + k, nObs, 0.0005, 0.01), + }; + } + const indepReceipts = await recordTrials(f.pool, indepRows); + + // 3. Another cluster in (US_EQ, position_10d_plus) to verify horizon_bucket isolation. + await recordTrials(f.pool, [ + { + principalId: 'operator', + stage: 'engine_backtest', + universeMarket: 'US_EQ', + horizonBucket: 'position_10d_plus', + expressionHash: 'd'.repeat(64), + sampleStart: '2022-01-03', + sampleEnd: '2024-01-02', + vaultCutoffDate: VAULT_CUTOFF, + dailySeries: makeSeries(7777, nObs), + }, + ]); + + const nearDupDsr = await clusterDeflatedSharpe(f.pool, { + trialId: nearDupReceipts[0]!.trialId, + }); + expect(nearDupDsr.clusterSize).toBe(clusterK); + expect(nearDupDsr.meanCorrelation).not.toBeNull(); + expect(nearDupDsr.meanCorrelation!).toBeGreaterThan(0.95); + expect(nearDupDsr.effectiveTrials).toBeLessThan(clusterK * 0.25); + + const indepDsr = await clusterDeflatedSharpe(f.pool, { + trialId: indepReceipts[0]!.trialId, + }); + expect(indepDsr.clusterSize).toBe(clusterK); + expect(indepDsr.effectiveTrials).toBeGreaterThan(clusterK * 0.85); + expect(indepDsr.effectiveTrials).toBeLessThanOrEqual(clusterK); + + // Direct deflatedSharpeRatio parity within 1e-9 on the persisted cluster rows. + const persistedNearDup = await loadClusterTrials(f.pool, { + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + const directEff = effectiveIndependentTrials(persistedNearDup.map(r => r.dailySeries)); + const directDsr = deflatedSharpeRatio({ + sharpeUnann: persistedNearDup[0]!.sharpeUnann, + nObs: persistedNearDup[0]!.nObs, + skewness: persistedNearDup[0]!.skewness, + kurtosis: persistedNearDup[0]!.kurtosis, + nHat: directEff.nHat, + clusterSharpes: persistedNearDup.map(r => r.sharpeUnann), + }); + 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), + }, + ]); + + const fullCluster = await loadClusterTrials(f.pool, { + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + const asOfCluster = await loadClusterTrials(f.pool, { + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + asOf: cutoffTs, + }); + expect(fullCluster).toHaveLength(clusterK + 1); + expect(asOfCluster).toHaveLength(clusterK); + }); +});