feat(research): add financial contracts and availability-aware datasets

Implement reviewed F01/D01 foundations without changing active trading runtimes. Validate strict Rust/TypeScript financial wire contracts, decimal postings, versioned datasets, explicit calendars, provenance, and v1 compatibility.
This commit is contained in:
Boki 2026-10-22 20:51:25 -04:00
parent 243e9ab43f
commit b4af840d4e
25 changed files with 4071 additions and 43 deletions

View file

@ -0,0 +1,159 @@
import { expect, test } from 'bun:test';
import {
parseEngineFinancialCommand,
parseFinancialDecimal,
parseFinancialEffects,
parseFinancialSnapshot,
parseFinancialStrategyDecision,
} from '../../libs/core/types/src/financial-engine';
import contracts from '../fixtures/economics/contracts.json';
import ledgerSpecs from '../fixtures/economics/ledger-specs.json';
import scalars from '../fixtures/economics/scalars.json';
function parse(kind: string, value: unknown): unknown {
switch (kind) {
case 'command':
return parseEngineFinancialCommand(value);
case 'decision':
return parseFinancialStrategyDecision(value);
case 'snapshot':
return parseFinancialSnapshot(value);
case 'effects':
return parseFinancialEffects(value);
default:
throw new Error(`Unknown contract fixture ${kind}`);
}
}
function annotate(value: {
id: string;
owningTask: string;
assumptions: string;
handCalculation: string;
}) {
for (const key of ['id', 'owningTask', 'assumptions', 'handCalculation'] as const) {
expect(value[key].length).toBeGreaterThan(0);
}
}
test('rust_ts_fixture_parse_parity: shared scalar and versioned wire fixtures', () => {
for (const fixture of scalars.cases) {
annotate(fixture);
if (fixture.canonical === null) {
expect(() => parseFinancialDecimal(fixture.input)).toThrow();
} else {
expect(String(parseFinancialDecimal(fixture.input))).toBe(fixture.canonical);
}
}
for (const fixture of contracts.valid) {
annotate(fixture);
const result = parse(fixture.type, fixture.input);
expect(result).toEqual(fixture.canonical);
expect(parse(fixture.type, JSON.parse(JSON.stringify(result)))).toEqual(result);
}
for (const fixture of contracts.invalid) {
annotate(fixture);
const base = contracts.valid.find(candidate => candidate.id === fixture.base)!;
const input: unknown = structuredClone(base.input);
let parent = input as Record<string, unknown>;
for (const key of fixture.path.slice(0, -1)) {
parent = parent[key] as Record<string, unknown>;
}
parent[fixture.path.at(-1)!] = fixture.value;
expect(() => parse(base.type, input)).toThrow();
}
});
test('safe_integer_json_number_parity: integral lexical forms and exact boundaries', () => {
annotate(contracts.numeric);
const base = contracts.valid.find(candidate => candidate.id === 'fillCommand')!.input;
const snapshot = contracts.valid.find(candidate => candidate.id === 'snapshot')!.input;
for (const fixture of contracts.numeric.cases) {
const value: unknown = JSON.parse(fixture.raw);
const command = parseEngineFinancialCommand(base);
const timestamp = () => parseEngineFinancialCommand({ ...command, eventTime: value });
const sequence = () =>
parseEngineFinancialCommand({
...command,
body: { ...command.body, decision: { ownerId: 'A', decisionId: 'd', sequence: value } },
});
const revision = () => parseFinancialSnapshot({ ...snapshot, revision: value });
if (fixture.timestampValid) {
expect(value === 0 ? 0 : value).toBe(timestamp().eventTime);
} else {
expect(timestamp).toThrow();
}
for (const counter of [sequence, revision]) {
if (fixture.counterValid) {
expect(counter).not.toThrow();
} else {
expect(counter).toThrow();
}
}
}
});
test('rounding_ties_positive_negative: TypeScript rejects internal-only precision', () => {
for (const fixture of scalars.rounding) {
annotate(fixture);
expect(() => parseFinancialDecimal(fixture.input)).toThrow();
expect(String(parseFinancialDecimal(fixture.expected))).toBe(fixture.expected);
}
});
test('overflow_rejected: exact lexical bound with no floating-point conversion', () => {
annotate(scalars.overflow);
expect(String(parseFinancialDecimal(scalars.overflow.maximum))).toBe(scalars.overflow.maximum);
expect(() => parseFinancialDecimal('792281625142643375935.43950336')).toThrow();
expect(() => parseFinancialDecimal('-792281625142643375935.43950336')).toThrow();
expect(() => parseFinancialDecimal(scalars.overflow.roundingOverflow)).toThrow();
});
test('basis_residual_spec: F02 owns transition behavior, TS validates documented values only', () => {
annotate(ledgerSpecs.basis);
expect(ledgerSpecs.basis.owningTask).toBe('F02');
expect(ledgerSpecs.basis.releases).toEqual(['1.66666667', '1.66666667', '1.66666666']);
expect(ledgerSpecs.basis.remainingCosts).toEqual(['3.33333333', '1.66666666', '0.00000000']);
for (const value of [...ledgerSpecs.basis.releases, ...ledgerSpecs.basis.remainingCosts]) {
expect(String(parseFinancialDecimal(value))).toBe(value);
}
});
test('command_id_conflict_spec: typed canonical payload, not a second dedup engine', () => {
annotate(ledgerSpecs.commandIds);
expect(ledgerSpecs.commandIds.owningTask).toBe('F02');
const original = parseEngineFinancialCommand(ledgerSpecs.commandIds.original);
const retry = parseEngineFinancialCommand(ledgerSpecs.commandIds.retry);
const conflict = parseEngineFinancialCommand(ledgerSpecs.commandIds.conflict);
const independent = parseEngineFinancialCommand(ledgerSpecs.commandIds.independent);
expect(retry).toEqual(original);
expect([conflict.sessionId, conflict.accountId, conflict.commandId]).toEqual([
original.sessionId,
original.accountId,
original.commandId,
]);
expect(conflict.body).not.toEqual(original.body);
expect(independent.sessionId).not.toBe(original.sessionId);
expect(independent.body).toEqual(original.body);
});
test('strategy submission contract cannot accept internal financial mutations', () => {
const command = contracts.valid.find(candidate => candidate.id === 'fillCommand')!.input;
const decision = contracts.valid.find(candidate => candidate.id === 'targetDecision')!.input;
expect(() => parseFinancialStrategyDecision(command)).toThrow();
expect(() => parseEngineFinancialCommand(decision)).toThrow();
});
test('non-JSON sparse arrays cannot become valid wire contracts', () => {
const snapshot = contracts.valid.find(candidate => candidate.id === 'snapshot')!.input;
expect(() => parseFinancialSnapshot({ ...snapshot, positions: Array(1) })).toThrow();
});
test('identity text must round-trip through Rust UTF-8 without losing Unicode identifiers', () => {
const command = contracts.valid.find(candidate => candidate.id === 'markCommand')!.input;
for (const commandId of ['\ud800', '\udfff', 'a\ud800b']) {
expect(() => parseEngineFinancialCommand({ ...command, commandId })).toThrow();
}
expect(parseEngineFinancialCommand({ ...command, commandId: '命令:🧪' }).commandId).toBe(
'命令:🧪'
);
});

View file

@ -0,0 +1,374 @@
import { describe, expect, test } from 'bun:test';
import { createHash } from 'node:crypto';
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> = T extends readonly (infer V)[]
? Mutable<V>[]
: T extends object
? { -readonly [K in keyof T]: Mutable<T[K]> }
: T;
const input = () => structuredClone(datasetInput()) as Mutable<HistoricalDatasetInputV2>;
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<typeof input>) => {
value.metadata.calendars[0]!.revision = 'v2';
},
(value: ReturnType<typeof input>) => {
value.metadata.calendars[0]!.source = 'another-retained-source';
},
(value: ReturnType<typeof input>) => {
value.metadata.universe.revision = 'new-universe';
},
(value: ReturnType<typeof input>) => {
value.metadata.bounds.tradeStart++;
},
(value: ReturnType<typeof input>) => {
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<typeof dataset>;
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<typeof createDatasetV2>
>;
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<typeof createDatasetV2>
>;
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<ReturnType<typeof createDatasetV2>>;
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<typeof input>) => {
value.metadata.series[0]!.calendarId = 'unknown';
},
(value: ReturnType<typeof input>) => {
value.metadata.series[0]!.venue = 'guessed';
},
(value: ReturnType<typeof input>) => {
value.metadata.calendars[0]!.endDate = '2024-11-01';
},
(value: ReturnType<typeof input>) => {
value.metadata.bounds.tradeEnd = value.metadata.bounds.tradeStart;
},
(value: ReturnType<typeof input>) => {
value.metadata.corporateActions[0]!.end = value.metadata.bounds.tradeStart;
},
(value: ReturnType<typeof input>) => {
value.bars[0]!.close = NaN;
},
(value: ReturnType<typeof input>) => {
value.bars[0]!.volume = -1;
},
(value: ReturnType<typeof input>) => {
value.bars[0]!.sourceSequence = Number.MAX_SAFE_INTEGER + 1;
},
]) {
const value = input();
change(value);
expect(() => createDatasetV2(value)).toThrow();
}
});
});