T-43: M1.1d — Pass 2 observed bar spans: read-only [first_bar_date, last_bar_date] per (source, source_id) + overlap helper

This commit is contained in:
Studio 2026-11-27 15:31:43 -05:00
parent 19ca16bdf1
commit feb8b7079b
2 changed files with 1307 additions and 0 deletions

View file

@ -0,0 +1,746 @@
export type BarSpanSource = 'eod' | 'qm';
export interface BarSpanCollectionSpec {
readonly source: BarSpanSource;
readonly collection: string;
readonly idField: string;
readonly dateField: string;
}
export const BAR_SPAN_COLLECTIONS: Readonly<Record<BarSpanSource, BarSpanCollectionSpec>> = {
eod: {
source: 'eod',
collection: 'eodPrices',
idField: 'eodSearchCode',
dateField: 'date',
},
qm: {
source: 'qm',
collection: 'qmPrices',
idField: 'qmSearchCode',
dateField: 'date',
},
};
export interface SpanDateRange {
readonly firstBarDate: string;
readonly lastBarDate: string;
}
export interface BarSpan extends SpanDateRange {
readonly source: BarSpanSource;
readonly sourceId: string;
readonly barCount: number;
}
export interface BarSpanSkipCounts {
invalidId: number;
invalidDate: number;
invalidCount: number;
total: number;
}
export interface BarSpanSourceStats {
source: BarSpanSource;
collection: string;
batchesRun: number;
rowsRead: number;
spansIndexed: number;
skipped: BarSpanSkipCounts;
}
export interface BarSpanAggregateOptions {
allowDiskUse?: boolean;
batchSize?: number;
}
export interface BarSpanAggregateReader {
aggregate<T extends Record<string, unknown> = Record<string, unknown>>(
collectionName: string,
pipeline: Record<string, unknown>[],
options?: BarSpanAggregateOptions
): Promise<Iterable<T> | AsyncIterable<T>> | Iterable<T> | AsyncIterable<T>;
}
export interface ComputeBarSpansOptions {
sources?: readonly BarSpanSource[];
sourceIdsBySource?: Partial<Record<BarSpanSource, readonly string[]>>;
batchSize?: number;
cursorBatchSize?: number;
}
export interface ComputeBarSpansResult {
index: BarSpanIndex;
bySource: Partial<Record<BarSpanSource, BarSpanSourceStats>>;
skipped: BarSpanSkipCounts;
totalRowsRead: number;
totalSpans: number;
}
export interface SpansOverlapOptions {
toleranceDays?: number;
}
export interface GroupedBarSpanRow extends Record<string, unknown> {
_id?: unknown;
firstBarDate?: unknown;
lastBarDate?: unknown;
barCount?: unknown;
}
const DEFAULT_SOURCES: readonly BarSpanSource[] = ['eod', 'qm'];
const DEFAULT_BATCH_SIZE = 1000;
const ALLOWED_STAGE_KEYS = new Set(['$match', '$group', '$project', '$sort']);
const FORBIDDEN_WRITE_STAGES = new Set(['$out', '$merge']);
const CODE_0 = 48;
const CODE_9 = 57;
const CODE_DASH = 45;
const ISO_DATETIME_TZ_RE =
/^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,9}))?)?(Z|[+-]\d{2}:?\d{2})$/;
function isBarSpanSource(value: unknown): value is BarSpanSource {
return value === 'eod' || value === 'qm';
}
function isLeapYear(year: number): boolean {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
function daysInMonth(year: number, month: number): number {
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
return isLeapYear(year) ? 29 : 28;
default:
return 0;
}
}
/**
* Proleptic Gregorian calendar date to days since 1970-01-01 (Howard Hinnant's algorithm).
* Pure integer math: no Date allocation, immune to local timezone and DST.
*/
function daysFromCivil(year: number, month: number, day: number): number {
const y = month <= 2 ? year - 1 : year;
const era = Math.floor(y / 400);
const yoe = y - era * 400;
const doy = Math.floor((153 * (month + (month > 2 ? -3 : 9)) + 2) / 5) + day - 1;
const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy;
return era * 146097 + doe - 719468;
}
/** Inverse of `daysFromCivil`: days since 1970-01-01 to proleptic Gregorian (year, month, day). */
function civilFromDays(daysSinceEpoch: number): { year: number; month: number; day: number } {
const shifted = daysSinceEpoch + 719468;
const era = Math.floor(shifted / 146097);
const doe = shifted - era * 146097;
const yoe = Math.floor(
(doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365
);
const y = yoe + era * 400;
const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100));
const mp = Math.floor((5 * doy + 2) / 153);
const day = doy - Math.floor((153 * mp + 2) / 5) + 1;
const month = mp + (mp < 10 ? 3 : -9);
const year = y + (month <= 2 ? 1 : 0);
return { year, month, day };
}
function formatUtcYmd(year: number, month: number, day: number): string {
const y = String(year).padStart(4, '0');
const m = month < 10 ? '0' + String(month) : String(month);
const d = day < 10 ? '0' + String(day) : String(day);
return `${y}-${m}-${d}`;
}
function parseAsciiDigit(str: string, index: number): number {
const code = str.charCodeAt(index);
return code >= CODE_0 && code <= CODE_9 ? code - CODE_0 : -1;
}
function parseYmdComponents(str: string): { year: number; month: number; day: number } | null {
if (str.length !== 10 || str.charCodeAt(4) !== CODE_DASH || str.charCodeAt(7) !== CODE_DASH) {
return null;
}
const y0 = parseAsciiDigit(str, 0);
const y1 = parseAsciiDigit(str, 1);
const y2 = parseAsciiDigit(str, 2);
const y3 = parseAsciiDigit(str, 3);
const m0 = parseAsciiDigit(str, 5);
const m1 = parseAsciiDigit(str, 6);
const d0 = parseAsciiDigit(str, 8);
const d1 = parseAsciiDigit(str, 9);
if ((y0 | y1 | y2 | y3 | m0 | m1 | d0 | d1) < 0) {
return null;
}
const year = y0 * 1000 + y1 * 100 + y2 * 10 + y3;
const month = m0 * 10 + m1;
const day = d0 * 10 + d1;
if (year < 1 || year > 9999 || month < 1 || month > 12) {
return null;
}
if (day < 1 || day > daysInMonth(year, month)) {
return null;
}
return { year, month, day };
}
function parseUtcDayNumber(ymd: string): number | null {
if (typeof ymd !== 'string') {
return null;
}
const parsed = parseYmdComponents(ymd);
if (parsed === null) {
return null;
}
return daysFromCivil(parsed.year, parsed.month, parsed.day);
}
/**
* Normalizes a bar date value into a UTC calendar `YYYY-MM-DD` string.
* Accepts:
* - `Date` instances with a finite timestamp and UTC year in `1..9999`
* - Exact `YYYY-MM-DD` calendar strings (validated with strict leap-year rules)
* - ISO-8601 timestamp strings with an explicit timezone (`Z` or `[+-]HH:MM` / `[+-]HHMM`)
* Returns `null` for missing, malformed, timezone-less datetime, or calendar-invalid inputs.
*/
export function normalizeBarDate(value: unknown): string | null {
if (value instanceof Date) {
const ts = value.getTime();
if (!Number.isFinite(ts)) {
return null;
}
const year = value.getUTCFullYear();
if (year < 1 || year > 9999) {
return null;
}
return formatUtcYmd(year, value.getUTCMonth() + 1, value.getUTCDate());
}
if (typeof value !== 'string') {
return null;
}
const trimmed = value.trim();
if (trimmed.length === 10) {
return parseYmdComponents(trimmed) !== null ? trimmed : null;
}
const match = ISO_DATETIME_TZ_RE.exec(trimmed);
if (match === null) {
return null;
}
const year = Number(match[1]);
const month = Number(match[2]);
const day = Number(match[3]);
const hour = Number(match[4]);
const minute = Number(match[5]);
const second = match[6] !== undefined ? Number(match[6]) : 0;
const tz = match[8];
if (tz === undefined) {
return null;
}
if (
year < 1 ||
year > 9999 ||
month < 1 ||
month > 12 ||
day < 1 ||
day > daysInMonth(year, month) ||
hour > 23 ||
minute > 59 ||
second > 59
) {
return null;
}
let offsetMinutes = 0;
if (tz !== 'Z') {
const sign = tz.charCodeAt(0) === CODE_DASH ? -1 : 1;
const tzDigits = tz.length === 6 ? tz.slice(1, 3) + tz.slice(4, 6) : tz.slice(1, 5);
const tzHour = Number(tzDigits.slice(0, 2));
const tzMinute = Number(tzDigits.slice(2, 4));
if (tzHour > 23 || tzMinute > 59) {
return null;
}
offsetMinutes = sign * (tzHour * 60 + tzMinute);
}
const totalUtcMinutes = hour * 60 + minute - offsetMinutes;
const dayShift = Math.floor(totalUtcMinutes / 1440);
const utcDate = civilFromDays(daysFromCivil(year, month, day) + dayShift);
if (utcDate.year < 1 || utcDate.year > 9999) {
return null;
}
return formatUtcYmd(utcDate.year, utcDate.month, utcDate.day);
}
function scanForForbiddenWriteStages(node: unknown, seen: WeakSet<object>): void {
if (node === null || typeof node !== 'object') {
return;
}
if (seen.has(node)) {
return;
}
seen.add(node);
if (Array.isArray(node)) {
for (let i = 0; i < node.length; i++) {
scanForForbiddenWriteStages(node[i], seen);
}
return;
}
for (const [key, val] of Object.entries(node)) {
if (FORBIDDEN_WRITE_STAGES.has(key.toLowerCase())) {
throw new Error(`Bar span pipeline contains forbidden write stage "${key}"`);
}
scanForForbiddenWriteStages(val, seen);
}
}
/**
* Verifies that an aggregation pipeline contains only read-only bar-span stages
* (`$match`, `$group`, `$project`, `$sort`) and never contains `$out` or `$merge`
* at top level or nested inside sub-pipelines.
*/
export function assertReadOnlyBarSpanPipeline(pipeline: readonly Record<string, unknown>[]): void {
if (!Array.isArray(pipeline)) {
throw new TypeError('Bar span pipeline must be an array of stage objects');
}
const seen = new WeakSet<object>();
for (let i = 0; i < pipeline.length; i++) {
const stage = pipeline[i];
if (stage === null || typeof stage !== 'object' || Array.isArray(stage)) {
throw new TypeError(`Bar span pipeline stage at index ${i} must be a plain object`);
}
const keys = Object.keys(stage);
if (keys.length === 0) {
throw new Error(`Bar span pipeline stage at index ${i} is empty`);
}
for (const key of keys) {
if (FORBIDDEN_WRITE_STAGES.has(key.toLowerCase())) {
throw new Error(`Bar span pipeline contains forbidden write stage "${key}"`);
}
if (!ALLOWED_STAGE_KEYS.has(key)) {
throw new Error(
`Bar span pipeline stage "${key}" at index ${i} is not an allowed read-only stage`
);
}
}
scanForForbiddenWriteStages(stage, seen);
}
}
/**
* Builds the read-only aggregation pipeline for `eodPrices`.
* - Full mode (`sourceIds === undefined`): single-pass `$group` by `eodSearchCode` (run with `allowDiskUse: true`).
* - Targeted mode (`sourceIds` provided): `$match` on `eodSearchCode: { $in: [...] }` followed by `$group`.
*/
export function buildEodBarSpansPipeline(sourceIds?: readonly string[]): Record<string, unknown>[] {
const groupStage: Record<string, unknown> = {
$group: {
_id: '$eodSearchCode',
firstBarDate: { $min: '$date' },
lastBarDate: { $max: '$date' },
barCount: { $sum: 1 },
},
};
const pipeline: Record<string, unknown>[] =
sourceIds !== undefined
? [{ $match: { eodSearchCode: { $in: [...sourceIds] } } }, groupStage]
: [groupStage];
assertReadOnlyBarSpanPipeline(pipeline);
return pipeline;
}
/**
* Builds the read-only aggregation pipeline for `qmPrices`.
* - Full mode (`sourceIds === undefined`): `$sort` on `{ qmSearchCode: 1, date: 1 }` to leverage
* the compound index, followed by `$group` by `qmSearchCode`.
* - Targeted mode (`sourceIds` provided): `$match` on `qmSearchCode: { $in: [...] }` followed by `$group`.
*/
export function buildQmBarSpansPipeline(sourceIds?: readonly string[]): Record<string, unknown>[] {
const groupStage: Record<string, unknown> = {
$group: {
_id: '$qmSearchCode',
firstBarDate: { $min: '$date' },
lastBarDate: { $max: '$date' },
barCount: { $sum: 1 },
},
};
const pipeline: Record<string, unknown>[] =
sourceIds !== undefined
? [{ $match: { qmSearchCode: { $in: [...sourceIds] } } }, groupStage]
: [{ $sort: { qmSearchCode: 1, date: 1 } }, groupStage];
assertReadOnlyBarSpanPipeline(pipeline);
return pipeline;
}
/** Dispatches to the per-source read-only bar-span pipeline builder. */
export function buildBarSpansPipeline(
source: BarSpanSource,
sourceIds?: readonly string[]
): Record<string, unknown>[] {
if (source === 'eod') {
return buildEodBarSpansPipeline(sourceIds);
}
if (source === 'qm') {
return buildQmBarSpansPipeline(sourceIds);
}
throw new RangeError(`Unsupported bar span source: "${String(source)}"`);
}
/**
* In-memory lookup of observed `[firstBarDate, lastBarDate]` spans keyed by `(source, sourceId)`.
* Uses per-source `Map`s to avoid composite key string allocations on large symbol sets.
*/
export class BarSpanIndex {
private readonly bySource: Readonly<Record<BarSpanSource, Map<string, BarSpan>>> = {
eod: new Map<string, BarSpan>(),
qm: new Map<string, BarSpan>(),
};
/** Inserts a span or merges it into an existing `(source, sourceId)` entry. */
merge(span: BarSpan): void {
const map = this.bySource[span.source];
const existing = map.get(span.sourceId);
if (existing === undefined) {
map.set(span.sourceId, span);
return;
}
const firstBarDate =
span.firstBarDate < existing.firstBarDate ? span.firstBarDate : existing.firstBarDate;
const lastBarDate =
span.lastBarDate > existing.lastBarDate ? span.lastBarDate : existing.lastBarDate;
map.set(span.sourceId, {
source: existing.source,
sourceId: existing.sourceId,
firstBarDate,
lastBarDate,
barCount: existing.barCount + span.barCount,
});
}
/** Returns the observed span for `(source, sourceId)`, or `undefined` when absent. */
get(source: BarSpanSource, sourceId: string): BarSpan | undefined {
return this.bySource[source]?.get(sourceId);
}
has(source: BarSpanSource, sourceId: string): boolean {
return this.bySource[source]?.has(sourceId) ?? false;
}
get size(): number {
return this.bySource.eod.size + this.bySource.qm.size;
}
sizeForSource(source: BarSpanSource): number {
return this.bySource[source]?.size ?? 0;
}
*values(): IterableIterator<BarSpan> {
yield* this.bySource.eod.values();
yield* this.bySource.qm.values();
}
[Symbol.iterator](): IterableIterator<BarSpan> {
return this.values();
}
}
function createEmptySkipCounts(): BarSpanSkipCounts {
return { invalidId: 0, invalidDate: 0, invalidCount: 0, total: 0 };
}
function isSyncIterable<T>(value: unknown): value is Iterable<T> {
return (
value !== null &&
(typeof value === 'object' || typeof value === 'function') &&
typeof (value as Record<symbol, unknown>)[Symbol.iterator] === 'function'
);
}
function isAsyncIterable<T>(value: unknown): value is AsyncIterable<T> {
return (
value !== null &&
(typeof value === 'object' || typeof value === 'function') &&
typeof (value as Record<symbol, unknown>)[Symbol.asyncIterator] === 'function'
);
}
function validatePositiveSafeInt(value: number, name: string): void {
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {
throw new RangeError(`${name} must be a positive safe integer, received ${String(value)}`);
}
}
function normalizeRequestedSourceIds(source: BarSpanSource, rawIds: readonly string[]): string[] {
if (!Array.isArray(rawIds)) {
throw new TypeError(`sourceIdsBySource.${source} must be an array of strings`);
}
const seen = new Set<string>();
const deduped: string[] = [];
for (let i = 0; i < rawIds.length; i++) {
const raw = rawIds[i];
if (typeof raw !== 'string') {
throw new TypeError(
`sourceIdsBySource.${source}[${i}] must be a string, received ${typeof raw}`
);
}
const trimmed = raw.trim();
if (trimmed.length === 0 || seen.has(trimmed)) {
continue;
}
seen.add(trimmed);
deduped.push(trimmed);
}
return deduped;
}
function foldGroupedRow(
source: BarSpanSource,
row: unknown,
index: BarSpanIndex,
sourceSkipped: BarSpanSkipCounts,
totalSkipped: BarSpanSkipCounts
): void {
if (row === null || typeof row !== 'object') {
sourceSkipped.invalidId++;
sourceSkipped.total++;
totalSkipped.invalidId++;
totalSkipped.total++;
return;
}
const record = row as GroupedBarSpanRow;
if (typeof record._id !== 'string') {
sourceSkipped.invalidId++;
sourceSkipped.total++;
totalSkipped.invalidId++;
totalSkipped.total++;
return;
}
const sourceId = record._id.trim();
if (sourceId.length === 0) {
sourceSkipped.invalidId++;
sourceSkipped.total++;
totalSkipped.invalidId++;
totalSkipped.total++;
return;
}
const firstBarDate = normalizeBarDate(record.firstBarDate);
const lastBarDate = normalizeBarDate(record.lastBarDate);
if (firstBarDate === null || lastBarDate === null || firstBarDate > lastBarDate) {
sourceSkipped.invalidDate++;
sourceSkipped.total++;
totalSkipped.invalidDate++;
totalSkipped.total++;
return;
}
const barCount = record.barCount;
if (typeof barCount !== 'number' || !Number.isSafeInteger(barCount) || barCount <= 0) {
sourceSkipped.invalidCount++;
sourceSkipped.total++;
totalSkipped.invalidCount++;
totalSkipped.total++;
return;
}
index.merge({
source,
sourceId,
firstBarDate,
lastBarDate,
barCount,
});
}
/**
* Streams grouped `[firstBarDate, lastBarDate]` spans from an injected read-only MongoDB reader
* into a `BarSpanIndex` without buffering raw price documents or intermediate row arrays.
*/
export async function computeBarSpans(
reader: BarSpanAggregateReader,
options: ComputeBarSpansOptions = {}
): Promise<ComputeBarSpansResult> {
if (reader === null || typeof reader !== 'object' || typeof reader.aggregate !== 'function') {
throw new TypeError('reader must implement aggregate(collectionName, pipeline, options)');
}
const rawSources = options.sources ?? DEFAULT_SOURCES;
if (!Array.isArray(rawSources) || rawSources.length === 0) {
throw new RangeError('options.sources must be a non-empty array of supported sources');
}
const sources: BarSpanSource[] = [];
const seenSources = new Set<BarSpanSource>();
for (const source of rawSources) {
if (!isBarSpanSource(source)) {
throw new RangeError(`Unsupported bar span source: "${String(source)}"`);
}
if (!seenSources.has(source)) {
seenSources.add(source);
sources.push(source);
}
}
const batchSize = options.batchSize ?? DEFAULT_BATCH_SIZE;
validatePositiveSafeInt(batchSize, 'options.batchSize');
if (options.cursorBatchSize !== undefined) {
validatePositiveSafeInt(options.cursorBatchSize, 'options.cursorBatchSize');
}
const preparedSourceIds: Partial<Record<BarSpanSource, string[]>> = {};
if (options.sourceIdsBySource !== undefined) {
for (const key of Object.keys(options.sourceIdsBySource)) {
if (!isBarSpanSource(key)) {
throw new RangeError(`Unsupported source in options.sourceIdsBySource: "${key}"`);
}
const list = options.sourceIdsBySource[key];
if (list !== undefined) {
preparedSourceIds[key] = normalizeRequestedSourceIds(key, list);
}
}
}
const aggOptions: BarSpanAggregateOptions =
options.cursorBatchSize !== undefined
? { allowDiskUse: true, batchSize: options.cursorBatchSize }
: { allowDiskUse: true };
const index = new BarSpanIndex();
const bySource: Partial<Record<BarSpanSource, BarSpanSourceStats>> = {};
const totalSkipped = createEmptySkipCounts();
let totalRowsRead = 0;
for (const source of sources) {
const spec = BAR_SPAN_COLLECTIONS[source];
const sourceSkipped = createEmptySkipCounts();
let batchesRun = 0;
let sourceRowsRead = 0;
const targetIds = preparedSourceIds[source];
const pipelines: Record<string, unknown>[][] = [];
if (targetIds === undefined) {
pipelines.push(buildBarSpansPipeline(source));
} else if (targetIds.length > 0) {
for (let offset = 0; offset < targetIds.length; offset += batchSize) {
pipelines.push(buildBarSpansPipeline(source, targetIds.slice(offset, offset + batchSize)));
}
}
for (const pipeline of pipelines) {
batchesRun++;
try {
const rows = await reader.aggregate<GroupedBarSpanRow>(
spec.collection,
pipeline,
aggOptions
);
if (isSyncIterable<GroupedBarSpanRow>(rows)) {
for (const row of rows) {
sourceRowsRead++;
totalRowsRead++;
foldGroupedRow(source, row, index, sourceSkipped, totalSkipped);
}
} else if (isAsyncIterable<GroupedBarSpanRow>(rows)) {
for await (const row of rows) {
sourceRowsRead++;
totalRowsRead++;
foldGroupedRow(source, row, index, sourceSkipped, totalSkipped);
}
} else {
throw new TypeError('reader.aggregate() must return an Iterable or AsyncIterable');
}
} catch (error) {
const detail = error instanceof Error ? error.message : String(error);
throw new Error(
`Failed to compute bar spans for source "${source}" (collection "${spec.collection}"): ${detail}`,
{ cause: error }
);
}
}
bySource[source] = {
source,
collection: spec.collection,
batchesRun,
rowsRead: sourceRowsRead,
spansIndexed: index.sizeForSource(source),
skipped: sourceSkipped,
};
}
return {
index,
bySource,
skipped: totalSkipped,
totalRowsRead,
totalSpans: index.size,
};
}
/**
* Checks whether two observed `[firstBarDate, lastBarDate]` ranges overlap inclusively,
* optionally allowing a non-negative integer `toleranceDays` gap in UTC calendar days.
*/
export function spansOverlap(
a: SpanDateRange,
b: SpanDateRange,
options: SpansOverlapOptions = {}
): boolean {
const toleranceDays = options.toleranceDays ?? 0;
if (
typeof toleranceDays !== 'number' ||
!Number.isSafeInteger(toleranceDays) ||
toleranceDays < 0
) {
throw new RangeError(
`options.toleranceDays must be a non-negative safe integer, received ${String(toleranceDays)}`
);
}
if (a === null || typeof a !== 'object' || b === null || typeof b !== 'object') {
throw new TypeError('spansOverlap requires two valid span objects');
}
const aStart = parseUtcDayNumber(a.firstBarDate);
const aEnd = parseUtcDayNumber(a.lastBarDate);
if (aStart === null || aEnd === null || aStart > aEnd) {
throw new RangeError(
`Invalid first span date range: [${String(a.firstBarDate)}, ${String(a.lastBarDate)}]`
);
}
const bStart = parseUtcDayNumber(b.firstBarDate);
const bEnd = parseUtcDayNumber(b.lastBarDate);
if (bStart === null || bEnd === null || bStart > bEnd) {
throw new RangeError(
`Invalid second span date range: [${String(b.firstBarDate)}, ${String(b.lastBarDate)}]`
);
}
return aStart <= bEnd + toleranceDays && bStart <= aEnd + toleranceDays;
}