From 97907f7666a943a5233bda90295fec9a77ca3e28 Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 15:37:52 -0500 Subject: [PATCH] =?UTF-8?q?T-43:=20M1.1d=20=E2=80=94=20Pass=202=20observed?= =?UTF-8?q?=20bar=20spans:=20read-only=20`[first=5Fbar=5Fdate,=20last=5Fba?= =?UTF-8?q?r=5Fdate]`=20per=20`(source,=20source=5Fid)`=20+=20overlap=20he?= =?UTF-8?q?lper?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/normalization/bar-spans.ts | 101 +++++-- test/unit/normalization-bar-spans.test.ts | 267 +++++++++++++++++- 2 files changed, 337 insertions(+), 31 deletions(-) diff --git a/apps/stock/data-pipeline/src/normalization/bar-spans.ts b/apps/stock/data-pipeline/src/normalization/bar-spans.ts index e34b078d..9905a923 100644 --- a/apps/stock/data-pipeline/src/normalization/bar-spans.ts +++ b/apps/stock/data-pipeline/src/normalization/bar-spans.ts @@ -1,3 +1,5 @@ +import type { MongoDBClient } from '@stock-bot/mongodb'; + export type BarSpanSource = 'eod' | 'qm'; export interface BarSpanCollectionSpec { @@ -62,6 +64,14 @@ export interface BarSpanAggregateReader { ): Promise | AsyncIterable> | Iterable | AsyncIterable; } +// Compile-time structural compatibility check (type-only, erased at runtime): +// ensures MongoDBClient satisfies BarSpanAggregateReader under `bun run typecheck`. +type AssertAssignable = true; +export type MongoDBClientBarSpanReaderCheck = AssertAssignable< + BarSpanAggregateReader, + MongoDBClient +>; + export interface ComputeBarSpansOptions { sources?: readonly BarSpanSource[]; sourceIdsBySource?: Partial>; @@ -350,23 +360,78 @@ export function assertReadOnlyBarSpanPipeline(pipeline: readonly Record[] { +function buildNormalizedUtcDateExpr(dateField: string): Record { + const fieldRef = `$${dateField}`; + return { + $dateToString: { + format: '%Y-%m-%d', + timezone: 'UTC', + onNull: null, + date: { + $switch: { + branches: [ + { + case: { $eq: [{ $type: fieldRef }, 'date'] }, + then: fieldRef, + }, + { + case: { $eq: [{ $type: fieldRef }, 'string'] }, + then: { + $dateFromString: { + dateString: { $trim: { input: fieldRef } }, + onError: null, + onNull: null, + }, + }, + }, + ], + default: null, + }, + }, + }, + }; +} + +function buildNormalizedSpanStages(spec: BarSpanCollectionSpec): Record[] { + const projectStage: Record = { + $project: { + _id: 0, + sourceId: `$${spec.idField}`, + normalizedDate: buildNormalizedUtcDateExpr(spec.dateField), + }, + }; const groupStage: Record = { $group: { - _id: '$eodSearchCode', - firstBarDate: { $min: '$date' }, - lastBarDate: { $max: '$date' }, + _id: '$sourceId', + firstBarDate: { $min: '$normalizedDate' }, + lastBarDate: { $max: '$normalizedDate' }, barCount: { $sum: 1 }, }, }; + return [projectStage, groupStage]; +} + +/** + * Builds the read-only aggregation pipeline for `eodPrices`. + * - Full mode (`sourceIds === undefined`): single-pass `$project` + `$group` by `eodSearchCode` + * (run with `allowDiskUse: true`), normalizing `date` to UTC `YYYY-MM-DD` before `$min`/`$max`. + * - Targeted mode (`sourceIds` provided): `$match` on `eodSearchCode: { $in: [...] }` followed by + * `$project` and `$group`. + */ +export function buildEodBarSpansPipeline(sourceIds?: readonly string[]): Record[] { + const spanStages = buildNormalizedSpanStages(BAR_SPAN_COLLECTIONS.eod); const pipeline: Record[] = sourceIds !== undefined - ? [{ $match: { eodSearchCode: { $in: [...sourceIds] } } }, groupStage] - : [groupStage]; + ? [{ $match: { eodSearchCode: { $in: [...sourceIds] } } }, ...spanStages] + : spanStages; assertReadOnlyBarSpanPipeline(pipeline); return pipeline; } @@ -374,22 +439,16 @@ export function buildEodBarSpansPipeline(sourceIds?: readonly string[]): Record< /** * 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`. + * the compound index, followed by `$project` (UTC `YYYY-MM-DD` normalization) and `$group` by `qmSearchCode`. + * - Targeted mode (`sourceIds` provided): `$match` on `qmSearchCode: { $in: [...] }` followed by + * `$project` and `$group`. */ export function buildQmBarSpansPipeline(sourceIds?: readonly string[]): Record[] { - const groupStage: Record = { - $group: { - _id: '$qmSearchCode', - firstBarDate: { $min: '$date' }, - lastBarDate: { $max: '$date' }, - barCount: { $sum: 1 }, - }, - }; + const spanStages = buildNormalizedSpanStages(BAR_SPAN_COLLECTIONS.qm); const pipeline: Record[] = sourceIds !== undefined - ? [{ $match: { qmSearchCode: { $in: [...sourceIds] } } }, groupStage] - : [{ $sort: { qmSearchCode: 1, date: 1 } }, groupStage]; + ? [{ $match: { qmSearchCode: { $in: [...sourceIds] } } }, ...spanStages] + : [{ $sort: { qmSearchCode: 1, date: 1 } }, ...spanStages]; assertReadOnlyBarSpanPipeline(pipeline); return pipeline; } diff --git a/test/unit/normalization-bar-spans.test.ts b/test/unit/normalization-bar-spans.test.ts index 0b160c40..15b1af53 100644 --- a/test/unit/normalization-bar-spans.test.ts +++ b/test/unit/normalization-bar-spans.test.ts @@ -115,19 +115,266 @@ describe('bar-span pipeline builders and safety guards', () => { assertPipelineStrictlyReadOnly(pipeline); } - expect(eodFull).toEqual([ - { - $group: { - _id: '$eodSearchCode', - firstBarDate: { $min: '$date' }, - lastBarDate: { $max: '$date' }, - barCount: { $sum: 1 }, - }, + expect(eodFull).toHaveLength(2); + expect(eodFull[0]).toHaveProperty('$project'); + expect(eodFull[1]).toEqual({ + $group: { + _id: '$sourceId', + firstBarDate: { $min: '$normalizedDate' }, + lastBarDate: { $max: '$normalizedDate' }, + barCount: { $sum: 1 }, }, - ]); + }); + expect(eodTargeted).toHaveLength(3); expect(eodTargeted[0]).toEqual({ $match: { eodSearchCode: { $in: ['AAPL.US', 'FB.US'] } } }); + expect(eodTargeted[1]).toHaveProperty('$project'); + expect(eodTargeted[2]).toEqual(eodFull[1]); + expect(qmFull).toHaveLength(3); expect(qmFull[0]).toEqual({ $sort: { qmSearchCode: 1, date: 1 } }); + expect(qmFull[1]).toHaveProperty('$project'); + expect(qmFull[2]).toEqual(eodFull[1]); + expect(qmTargeted).toHaveLength(3); expect(qmTargeted[0]).toEqual({ $match: { qmSearchCode: { $in: ['AAPL', 'VOY:CNX'] } } }); + expect(qmTargeted[1]).toHaveProperty('$project'); + expect(qmTargeted[2]).toEqual(eodFull[1]); + }); + + test('regression: normalizes mixed BSON Dates and ISO strings to UTC before $min/$max so spans are never inverted or dropped', async () => { + // MongoDB BSON comparison order: strings (rank 2) sort BEFORE Dates (rank 9). + // https://www.mongodb.com/docs/manual/reference/bson-type-comparison-order/ + const bsonTypeRank = (val: unknown): number => { + if (val === null || val === undefined) return 0; + if (typeof val === 'number') return 1; + if (typeof val === 'string') return 2; + if (val instanceof Date) return 9; + return 10; + }; + + const compareBson = (a: unknown, b: unknown): number => { + const rankDiff = bsonTypeRank(a) - bsonTypeRank(b); + if (rankDiff !== 0) return rankDiff; + if (typeof a === 'string' && typeof b === 'string') { + return a < b ? -1 : a > b ? 1 : 0; + } + if (a instanceof Date && b instanceof Date) { + return a.getTime() - b.getTime(); + } + if (typeof a === 'number' && typeof b === 'number') { + return a - b; + } + return 0; + }; + + const evalExpr = (expr: unknown, doc: Record): unknown => { + if (typeof expr === 'string' && expr.startsWith('$')) { + return doc[expr.slice(1)]; + } + if (expr === null || typeof expr !== 'object' || Array.isArray(expr)) { + return expr; + } + const obj = expr as Record; + if ('$type' in obj) { + const val = evalExpr(obj.$type, doc); + if (val === null) return 'null'; + if (val === undefined) return 'missing'; + if (val instanceof Date) return 'date'; + if (typeof val === 'string') return 'string'; + if (typeof val === 'number') return 'double'; + return 'object'; + } + if ('$eq' in obj) { + const [left, right] = obj.$eq as [unknown, unknown]; + return evalExpr(left, doc) === evalExpr(right, doc); + } + if ('$trim' in obj) { + const cfg = obj.$trim as { input: unknown }; + const val = evalExpr(cfg.input, doc); + return typeof val === 'string' ? val.trim() : null; + } + if ('$switch' in obj) { + const cfg = obj.$switch as { + branches: Array<{ case: unknown; then: unknown }>; + default: unknown; + }; + for (const branch of cfg.branches) { + if (evalExpr(branch.case, doc) === true) { + return evalExpr(branch.then, doc); + } + } + return evalExpr(cfg.default, doc); + } + if ('$dateFromString' in obj) { + const cfg = obj.$dateFromString as { + dateString: unknown; + onError?: unknown; + onNull?: unknown; + }; + const raw = evalExpr(cfg.dateString, doc); + if (raw === null || raw === undefined) { + return cfg.onNull ?? null; + } + if (typeof raw !== 'string') { + return cfg.onError ?? null; + } + const normalized = normalizeBarDate(raw); + if (normalized === null) { + return cfg.onError ?? null; + } + return new Date(`${normalized}T00:00:00.000Z`); + } + if ('$dateToString' in obj) { + const cfg = obj.$dateToString as { + format: string; + timezone?: string; + date: unknown; + onNull?: unknown; + }; + const raw = evalExpr(cfg.date, doc); + if (raw === null || raw === undefined) { + return cfg.onNull ?? null; + } + if (!(raw instanceof Date) || !Number.isFinite(raw.getTime())) { + return null; + } + expect(cfg.format).toBe('%Y-%m-%d'); + expect(cfg.timezone).toBe('UTC'); + return raw.toISOString().slice(0, 10); + } + throw new Error(`Unsupported test aggregation expression: ${JSON.stringify(obj)}`); + }; + + const runPipeline = ( + rawDocs: Record[], + pipeline: Record[] + ): Record[] => { + let docs = rawDocs.map(d => ({ ...d })); + for (const stage of pipeline) { + if ('$match' in stage) { + const cond = stage.$match as Record; + docs = docs.filter(doc => + Object.entries(cond).every(([field, pred]) => + Array.isArray(pred.$in) ? pred.$in.includes(doc[field]) : doc[field] === pred + ) + ); + } else if ('$sort' in stage) { + const sortSpec = Object.entries(stage.$sort as Record); + docs = [...docs].sort((a, b) => { + for (const [field, dir] of sortSpec) { + const cmp = compareBson(a[field], b[field]); + if (cmp !== 0) return cmp * dir; + } + return 0; + }); + } else if ('$project' in stage) { + const proj = stage.$project as Record; + docs = docs.map(doc => { + const out: Record = {}; + for (const [key, spec] of Object.entries(proj)) { + if (key === '_id' && spec === 0) continue; + out[key] = evalExpr(spec, doc); + } + return out; + }); + } else if ('$group' in stage) { + const groupSpec = stage.$group as Record; + const groups = new Map[]>(); + for (const doc of docs) { + const key = evalExpr(groupSpec._id, doc); + const bucket = groups.get(key); + if (bucket) { + bucket.push(doc); + } else { + groups.set(key, [doc]); + } + } + const grouped: Record[] = []; + for (const [key, bucket] of groups.entries()) { + const out: Record = { _id: key }; + for (const [field, acc] of Object.entries(groupSpec)) { + if (field === '_id') continue; + const accObj = acc as Record; + if ('$min' in accObj) { + let minVal: unknown = null; + for (const doc of bucket) { + const val = evalExpr(accObj.$min, doc); + if (val === null || val === undefined) continue; + if (minVal === null || compareBson(val, minVal) < 0) { + minVal = val; + } + } + out[field] = minVal; + } else if ('$max' in accObj) { + let maxVal: unknown = null; + for (const doc of bucket) { + const val = evalExpr(accObj.$max, doc); + if (val === null || val === undefined) continue; + if (maxVal === null || compareBson(val, maxVal) > 0) { + maxVal = val; + } + } + out[field] = maxVal; + } else if ('$sum' in accObj) { + out[field] = bucket.length; + } + } + grouped.push(out); + } + docs = grouped; + } + } + return docs; + }; + + const rawEodDocs: Record[] = [ + // Mixed BSON Date (older) + string (newer): raw BSON ordering would invert min/max! + { eodSearchCode: 'MIXED.US', date: new Date('2024-06-07T00:00:00.000Z') }, + { eodSearchCode: 'MIXED.US', date: '2024-06-10' }, + { eodSearchCode: 'MIXED.US', date: '2024-06-07T23:30:00-04:00' }, // 2024-06-08 UTC + // All-invalid dates must still yield null bounds so computeBarSpans counts them as skipped. + { eodSearchCode: 'ALL_BAD.US', date: 'not-a-date' }, + { eodSearchCode: 'ALL_BAD.US', date: null }, + ]; + + const rawQmDocs: Record[] = [ + { qmSearchCode: 'MIXED:TO', date: new Date('2024-06-07T00:00:00.000Z') }, + { qmSearchCode: 'MIXED:TO', date: '2024-06-10' }, + ]; + + const reader: BarSpanAggregateReader = { + aggregate>( + collectionName: string, + pipeline: Record[] + ): T[] { + assertPipelineStrictlyReadOnly(pipeline); + const docs = + collectionName === BAR_SPAN_COLLECTIONS.eod.collection ? rawEodDocs : rawQmDocs; + return runPipeline(docs, pipeline) as unknown as T[]; + }, + }; + + const result = await computeBarSpans(reader, { sources: ['eod', 'qm'] }); + + expect(result.index.get('eod', 'MIXED.US')).toEqual({ + source: 'eod', + sourceId: 'MIXED.US', + firstBarDate: '2024-06-07', + lastBarDate: '2024-06-10', + barCount: 3, + }); + expect(result.index.get('qm', 'MIXED:TO')).toEqual({ + source: 'qm', + sourceId: 'MIXED:TO', + firstBarDate: '2024-06-07', + lastBarDate: '2024-06-10', + barCount: 2, + }); + expect(result.index.get('eod', 'ALL_BAD.US')).toBeUndefined(); + expect(result.skipped).toEqual({ + invalidId: 0, + invalidDate: 1, + invalidCount: 0, + total: 1, + }); }); test('assertReadOnlyBarSpanPipeline rejects $out, $merge (top-level and nested), and disallowed stages', () => { @@ -165,7 +412,7 @@ describe('computeBarSpans', () => { collectionName: string, pipeline: Record[], options?: BarSpanAggregateOptions - ): Promise { + ): Promise | AsyncIterable> { calls.push({ collection: collectionName, pipeline, options }); if (collectionName === BAR_SPAN_COLLECTIONS.eod.collection) { const rows: GroupedBarSpanRow[] = [