import { createHash } from 'node:crypto'; import { describe, expect, test } from 'bun:test'; import { createDatasetV2FromLegacy } from '@stock-bot/research/datasets'; import { validateDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset'; import { assertDatasetV2Executable, convertDatasetV1ToV2, createDatasetV2, validateDatasetV2, } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2'; import type { HistoricalDataset, HistoricalDatasetInputV2, } from '../../libs/core/types/src/historical-data'; import { datasetInput } from '../fixtures/historical-v2/dataset'; type Mutable = T extends readonly (infer V)[] ? Mutable[] : T extends object ? { -readonly [K in keyof T]: Mutable } : T; const input = () => structuredClone(datasetInput()) as Mutable; function legacyFixture(): HistoricalDataset { const bars = datasetInput().bars.map(row => ({ symbol: 'A.US', timestamp: Date.parse(String(row.timestamp)), open: row.open, high: row.high, low: row.low, close: row.close, volume: row.volume, vwap: 101, })); const manifest = { version: 1 as const, instruments: [{ id: 'A.US', symbol: 'A', exchange: 'US' }], startDate: '2024-03-08T00:00:00.000Z', endDate: '2024-11-30T00:00:00.000Z', interval: '1d', policy: { adjustment: 'raw' as const, timestamp: 'utc-session-date' as const }, volumePolicy: 'reported' as const, qualityPolicy: 'reject-invalid-no-interpolation' as const, sources: [ { instrumentId: 'A.US', provider: 'eod' as const, revision: 'historical-normalization-v1' }, ], barCount: bars.length, }; return { manifest: { ...manifest, hash: createHash('sha256').update(JSON.stringify({ manifest, bars })).digest('hex'), }, bars, }; } describe('availability-aware dataset v2', () => { test('dataset_v1_compatibility: old hashes/read semantics stay unchanged and conversion is explicit', () => { const old = legacyFixture(), before = structuredClone(old); const validated = validateDataset(old); expect(validated).toEqual(before); const converted = convertDatasetV1ToV2(old, input().metadata); expect(converted.manifest.version).toBe(2); expect(converted.manifest.parentDatasetHash).toBe(old.manifest.hash); expect(converted.manifest.hash).not.toBe(old.manifest.hash); expect(converted.bars.every(bar => bar.vwap === null)).toBe(true); expect(converted.manifest.limitations.some(value => value.includes('VWAP provenance'))).toBe( true ); expect(validateDataset(old)).toEqual(before); expect(old).toEqual(before); expect(() => validateDataset(converted)).toThrow(); expect(() => validateDatasetV2(old)).toThrow(); const changed = input().metadata; changed.series[0]!.source.revision = 'different-source'; expect(() => convertDatasetV1ToV2(old, changed)).toThrow('matching'); }); test('dataset_v2_hash: stable canonical serialization includes calendar and policy provenance', () => { const first = createDatasetV2(input()); const reordered = JSON.parse(JSON.stringify(input()), (_key, value) => value && typeof value === 'object' && !Array.isArray(value) ? Object.fromEntries(Object.entries(value).reverse()) : value ); reordered.bars.reverse(); expect(createDatasetV2(reordered)).toEqual(first); expect(validateDatasetV2(JSON.parse(JSON.stringify(first)))).toEqual(first); const { hash, ...manifest } = first.manifest; expect( createHash('sha256') .update(JSON.stringify({ manifest, bars: first.bars })) .digest('hex') ).toBe(hash); for (const change of [ (value: ReturnType) => { value.metadata.calendars[0]!.revision = 'v2'; }, (value: ReturnType) => { value.metadata.calendars[0]!.source = 'another-retained-source'; }, (value: ReturnType) => { value.metadata.universe.revision = 'new-universe'; }, (value: ReturnType) => { value.metadata.bounds.tradeStart++; }, (value: ReturnType) => { value.bars[0]!.volume++; }, ]) { const changed = input(); change(changed); expect(createDatasetV2(changed).manifest.hash).not.toBe(hash); } }); test('DST_half_day: labels map only through retained session boundaries', () => { const dataset = createDatasetV2(input()); expect(dataset.bars.map(b => new Date(b.availableAt).toISOString())).toEqual([ '2024-03-08T21:00:00.000Z', '2024-03-11T20:00:00.000Z', '2024-11-29T18:00:00.000Z', ]); expect(dataset.bars.map(b => new Date(b.intervalStart).toISOString())).toEqual([ '2024-03-08T14:30:00.000Z', '2024-03-11T13:30:00.000Z', '2024-11-29T14:30:00.000Z', ]); const bad = input(); bad.bars[0]!.timestamp = '2024-03-09'; expect(() => createDatasetV2(bad)).toThrow('session mapping'); bad.bars[0]!.timestamp = '2024-02-30'; expect(() => createDatasetV2(bad)).toThrow(); const wrongDate = input(); wrongDate.metadata.calendars[0]!.sessions[0]!.open = Date.parse('2024-03-08T01:00:00Z'); expect(() => createDatasetV2(wrongDate)).toThrow('calendar session'); }); test('missing_vwap: preserve missingness and genuine supplied values without interpolation', () => { const result = createDatasetV2(input()); expect(result.bars.map(b => b.vwap)).toEqual([null, 101, null]); expect(result.bars).toHaveLength(3); expect(result.manifest.qualityPolicy).toBe('reject-invalid-no-interpolation'); }); test('conflicting_duplicate: interval identity cannot be evaded through availability or sequence', () => { const duplicate = input(); duplicate.bars.push({ ...duplicate.bars[0]!, sourceSequence: 99 }); expect(() => createDatasetV2(duplicate)).toThrow('Duplicate or conflicting'); const conflicting = input(); conflicting.metadata.series[0]!.availability = 'explicit'; conflicting.bars = conflicting.bars.map((bar, i) => ({ ...bar, availableAt: conflicting.metadata.calendars[0]!.sessions[i]!.close, })); conflicting.bars.push({ ...conflicting.bars[0]!, volume: 7, availableAt: conflicting.bars[0]!.availableAt! + 1, sourceSequence: 100, }); expect(() => createDatasetV2(conflicting)).toThrow('Duplicate or conflicting'); const sequence = input(); sequence.bars[1]!.sourceSequence = 0; expect(() => createDatasetV2(sequence)).toThrow('source sequence'); }); test('future_suffix_mutation: prior available observations and per-series sequence stay identical', () => { const first = input(); first.metadata.series[0]!.availability = 'explicit'; first.bars = first.bars.map((bar, i) => ({ ...bar, availableAt: first.metadata.calendars[0]!.sessions[i]!.close + 1000, })); const last = input().metadata.calendars[0]!.sessions[1]!.close + 1000; const before = createDatasetV2(first); const changed = structuredClone(first); changed.bars[2]!.volume = 9_000_000; changed.bars[2]!.close = 109; const after = createDatasetV2(changed); expect(after.manifest.hash).not.toBe(before.manifest.hash); expect(after.bars.filter(bar => bar.availableAt <= last)).toEqual( before.bars.filter(bar => bar.availableAt <= last) ); expect(before.bars.filter(bar => bar.availableAt <= last - 1)).toHaveLength(1); expect(before.manifest.bounds.warmupStart).toBeLessThan(before.manifest.bounds.tradeStart); expect( before.bars.filter(bar => bar.availableAt < before.manifest.bounds.tradeStart) ).toHaveLength(1); }); test('detaches and deeply freezes every nested value; untrusted mutation never uses cached validation', () => { const source = input(), dataset = createDatasetV2(source); function frozen(value: unknown): void { if (value && typeof value === 'object') { expect(Object.isFrozen(value)).toBe(true); for (const child of Object.values(value)) { frozen(child); } } } frozen(dataset); expect(validateDatasetV2(dataset)).toBe(dataset); source.bars[0]!.volume = 999; expect(dataset.bars[0]!.volume).toBe(1000); const tampered = structuredClone(dataset) as Mutable; tampered.bars[0]!.volume++; expect(() => validateDatasetV2(tampered)).toThrow('hash/content'); expect(() => { (dataset.bars[0] as Mutable<(typeof dataset.bars)[number]>).volume++; }).toThrow(); }); test('canonical validation rechecks timing and derived eligibility even with recomputed hash', () => { const tampered = structuredClone(createDatasetV2(input())) as Mutable< ReturnType >; tampered.bars[0]!.availableAt = tampered.bars[0]!.intervalStart; const { hash: _hash, ...manifest } = tampered.manifest; tampered.manifest.hash = createHash('sha256') .update(JSON.stringify({ manifest, bars: tampered.bars })) .digest('hex'); expect(() => assertDatasetV2Executable(tampered)).toThrow('availability'); const changed = structuredClone(createDatasetV2(input())) as Mutable< ReturnType >; changed.manifest.eligibility = 'ineligible'; expect(() => validateDatasetV2(changed)).toThrow('derived policy'); }); test('parent hash rejects trailing newline even when the current hash is recomputed', () => { const tampered = structuredClone( convertDatasetV1ToV2(legacyFixture(), input().metadata) ) as Mutable>; tampered.manifest.parentDatasetHash += '\n'; const { hash: _hash, ...manifest } = tampered.manifest; tampered.manifest.hash = createHash('sha256') .update(JSON.stringify({ manifest, bars: tampered.bars })) .digest('hex'); expect(tampered.bars.every(bar => bar.vwap === null)).toBe(true); expect(() => validateDatasetV2(tampered)).toThrow(); }); test('availability assumptions are retained; explicit input cannot silently default to the close', () => { const assumed = createDatasetV2(input()); expect(assumed.manifest.limitations.some(s => s.includes('zero data delay'))).toBe(true); const explicit = input(); explicit.metadata.series[0]!.availability = 'explicit'; expect(() => createDatasetV2(explicit)).toThrow('requires availableAt'); const early = input(); early.bars[0]!.availableAt = early.metadata.calendars[0]!.sessions[0]!.close - 1; expect(() => createDatasetV2(early)).toThrow('availability'); const lateAssumption = input(); lateAssumption.bars[0]!.availableAt = lateAssumption.metadata.calendars[0]!.sessions[0]!.close + 1; expect(() => createDatasetV2(lateAssumption)).toThrow('availability'); }); test('unknown coverage is exploratory; known unsupported actions and adjusted execution fail closed', () => { expect(assertDatasetV2Executable(createDatasetV2(input())).manifest.eligibility).toBe( 'eligible' ); const unknown = input(); unknown.metadata.corporateActions[0]!.status = 'unknown'; expect(assertDatasetV2Executable(createDatasetV2(unknown)).manifest.eligibility).toBe( 'exploratory' ); const action = input(); action.metadata.corporateActions[0]!.status = 'known-actions'; action.metadata.corporateActions[0]!.actions.push({ effectiveAt: action.metadata.bounds.tradeStart, kind: 'split', reference: 'test-split', }); expect(() => assertDatasetV2Executable(createDatasetV2(action))).toThrow( 'Unsupported corporate actions' ); const adjusted = input(); adjusted.metadata.series[0]!.adjustment = 'provider-adjusted'; expect(() => assertDatasetV2Executable(createDatasetV2(adjusted))).toThrow('Adjusted prices'); const universe = input(); universe.metadata.universe.selection = 'current-constituents'; expect(createDatasetV2(universe).manifest.eligibility).toBe('exploratory'); const future = input(); future.metadata.universe.asOf = future.metadata.bounds.tradeEnd; expect(() => createDatasetV2(future)).toThrow('universe/as-of'); }); test('one execution series per instrument; adjusted feature series cannot duplicate liquidity selection', () => { const value = input(); value.metadata.series.push({ ...value.metadata.series[0]!, id: 'feature', adjustment: 'provider-adjusted', }); value.bars.push(...value.bars.map(bar => ({ ...bar, seriesId: 'feature' }))); const dataset = createDatasetV2(value); expect(dataset.manifest.executionSeries).toHaveLength(1); expect(dataset.manifest.eligibility).toBe('eligible'); value.metadata.executionSeries.push({ instrumentId: 'A.US', seriesId: 'feature' }); expect(() => createDatasetV2(value)).toThrow('execution instrument'); const missing = input(); missing.metadata.executionSeries[0]!.seriesId = 'missing'; expect(() => createDatasetV2(missing)).toThrow('exactly one'); }); test('intraday explicit start/end semantics agree, partial session bars reject', () => { const start = input(); start.metadata.series[0]!.interval = '1h'; start.metadata.series[0]!.timestamp = 'interval-start'; start.bars = start.bars.map((bar, i) => ({ ...bar, timestamp: start.metadata.calendars[0]!.sessions[i]!.open, })); const end = structuredClone(start); end.metadata.series[0]!.timestamp = 'interval-end'; end.bars = end.bars.map(bar => ({ ...bar, timestamp: Number(bar.timestamp) + 3_600_000 })); expect(createDatasetV2(start).bars).toEqual(createDatasetV2(end).bars); const overlapping = structuredClone(start); overlapping.bars.push({ ...overlapping.bars[0]!, sourceSequence: 99, timestamp: Number(overlapping.bars[0]!.timestamp) + 30_000, }); expect(() => createDatasetV2(overlapping)).toThrow('Overlapping intervals'); start.bars[2]!.timestamp = start.metadata.calendars[0]!.sessions[2]!.close - 30 * 60_000; expect(() => createDatasetV2(start)).toThrow('session interval'); }); test('terminal boundary retains the completed interval, not a new interval or decision permission', () => { const value = input(), dataset = createDatasetV2(value); expect(dataset.bars.at(-1)!.intervalEnd).toBe(dataset.manifest.bounds.tradeEnd); expect(dataset.bars.at(-1)!.availableAt).toBe(dataset.manifest.bounds.tradeEnd); value.metadata.bounds.tradeEnd--; expect(() => createDatasetV2(value)).toThrow('session interval'); }); test('rejects invalid bars, uncovered ranges, identity mappings and malformed metadata', () => { for (const change of [ (value: ReturnType) => { value.metadata.series[0]!.calendarId = 'unknown'; }, (value: ReturnType) => { value.metadata.series[0]!.venue = 'guessed'; }, (value: ReturnType) => { value.metadata.calendars[0]!.endDate = '2024-11-01'; }, (value: ReturnType) => { value.metadata.bounds.tradeEnd = value.metadata.bounds.tradeStart; }, (value: ReturnType) => { value.metadata.corporateActions[0]!.end = value.metadata.bounds.tradeStart; }, (value: ReturnType) => { value.bars[0]!.close = NaN; }, (value: ReturnType) => { value.bars[0]!.volume = -1; }, (value: ReturnType) => { value.bars[0]!.sourceSequence = Number.MAX_SAFE_INTEGER + 1; }, ]) { const value = input(); change(value); expect(() => createDatasetV2(value)).toThrow(); } }); }); test('shared legacy factory preserves the adapter invariant before returning a prepared dataset', () => { const source = input(); expect(() => createDatasetV2FromLegacy(source, 'a'.repeat(64))).toThrow('unknown VWAP'); source.bars.forEach(bar => { bar.vwap = null; }); const dataset = createDatasetV2FromLegacy(source, 'a'.repeat(64)); expect(validateDatasetV2(structuredClone(dataset))).toEqual(dataset); expect(() => createDatasetV2FromLegacy(source, 'not-a-hash')).toThrow(); });