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:37:52 -05:00
parent feb8b7079b
commit 97907f7666
2 changed files with 337 additions and 31 deletions

View file

@ -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<string, unknown>): 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<string, unknown>;
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<string, unknown>[],
pipeline: Record<string, unknown>[]
): Record<string, unknown>[] => {
let docs = rawDocs.map(d => ({ ...d }));
for (const stage of pipeline) {
if ('$match' in stage) {
const cond = stage.$match as Record<string, { $in?: unknown[] }>;
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<string, number>);
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<string, unknown>;
docs = docs.map(doc => {
const out: Record<string, unknown> = {};
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<string, unknown>;
const groups = new Map<unknown, Record<string, unknown>[]>();
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<string, unknown>[] = [];
for (const [key, bucket] of groups.entries()) {
const out: Record<string, unknown> = { _id: key };
for (const [field, acc] of Object.entries(groupSpec)) {
if (field === '_id') continue;
const accObj = acc as Record<string, unknown>;
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<string, unknown>[] = [
// 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<string, unknown>[] = [
{ qmSearchCode: 'MIXED:TO', date: new Date('2024-06-07T00:00:00.000Z') },
{ qmSearchCode: 'MIXED:TO', date: '2024-06-10' },
];
const reader: BarSpanAggregateReader = {
aggregate<T extends Record<string, unknown>>(
collectionName: string,
pipeline: Record<string, unknown>[]
): 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<string, unknown>[],
options?: BarSpanAggregateOptions
): Promise<T[]> {
): Promise<Iterable<T> | AsyncIterable<T>> {
calls.push({ collection: collectionName, pipeline, options });
if (collectionName === BAR_SPAN_COLLECTIONS.eod.collection) {
const rows: GroupedBarSpanRow[] = [