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:45:59 -05:00
parent 97907f7666
commit 627995c091
2 changed files with 282 additions and 63 deletions

View file

@ -359,41 +359,115 @@ export function assertReadOnlyBarSpanPipeline(pipeline: readonly Record<string,
}
}
// Strict calendar-shape regexes for MongoDB `$regexMatch` (PCRE2) so `$dateFromString`
// only parses the exact string shapes accepted by `normalizeBarDate`:
// - exact `YYYY-MM-DD` (year 0001..9999)
// - ISO-8601 timestamp with an explicit timezone (`Z` or `[+-]HH:MM` / `[+-]HHMM`)
// Timezone-less datetimes (e.g. `2024-06-10T12:00:00`) are rejected before `$dateFromString`.
const MONGO_VALID_YMD_REGEX =
'^(?:000[1-9]|00[1-9]\\d|0[1-9]\\d{2}|[1-9]\\d{3})-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\d|3[01])$';
const MONGO_VALID_ISO_DATETIME_TZ_REGEX =
'^(?:000[1-9]|00[1-9]\\d|0[1-9]\\d{2}|[1-9]\\d{3})-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\d|3[01])[T ](?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d{1,9})?)?(?:Z|[+-](?:[01]\\d|2[0-3]):?[0-5]\\d)$';
/**
* Builds a MongoDB aggregation expression that normalizes a raw date field
* (BSON `Date` or ISO-8601 date/timestamp string) to a UTC `YYYY-MM-DD` string
* before `$min`/`$max` comparison.
* Builds a MongoDB aggregation expression that validates and normalizes a raw date field
* (BSON `Date`, exact `YYYY-MM-DD` string, or timezone-qualified ISO-8601 timestamp string)
* to a UTC `YYYY-MM-DD` string before `$min`/`$max` comparison.
*
* Normalizing before `$group` avoids MongoDB's BSON type comparison order
* (strings sort before Dates), which would otherwise invert `[firstBarDate, lastBarDate]`
* when a provider ID has mixed string and BSON Date bars.
* - Normalizing before `$group` avoids MongoDB's BSON type comparison order
* (strings sort before Dates), which would otherwise invert `[firstBarDate, lastBarDate]`
* when a provider ID has mixed string and BSON Date bars.
* - Gating strings with `$regexMatch` before `$dateFromString` prevents MongoDB from
* silently accepting timezone-less timestamps (e.g. `2024-06-10T12:00:00`) or unpadded
* dates (`2024-6-8`), while `$dateFromString` enforces strict Gregorian calendar rules
* (rejecting rollover dates like `2023-02-29`) and converts explicit offsets to UTC.
*/
function buildNormalizedUtcDateExpr(dateField: string): Record<string, unknown> {
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,
const parsedDateExpr: Record<string, unknown> = {
$switch: {
branches: [
{
case: { $eq: [{ $type: fieldRef }, 'date'] },
then: fieldRef,
},
{
case: { $eq: [{ $type: fieldRef }, 'string'] },
then: {
$let: {
vars: {
trimmed: { $trim: { input: fieldRef } },
},
in: {
$switch: {
branches: [
{
case: {
$regexMatch: {
input: '$$trimmed',
regex: MONGO_VALID_YMD_REGEX,
},
},
then: {
$dateFromString: {
dateString: '$$trimmed',
format: '%Y-%m-%d',
timezone: 'UTC',
onError: null,
onNull: null,
},
},
},
{
case: {
$regexMatch: {
input: '$$trimmed',
regex: MONGO_VALID_ISO_DATETIME_TZ_REGEX,
},
},
then: {
$dateFromString: {
dateString: '$$trimmed',
onError: null,
onNull: null,
},
},
},
],
default: null,
},
},
},
],
default: null,
},
},
],
default: null,
},
};
return {
$let: {
vars: {
parsedDate: parsedDateExpr,
},
in: {
$cond: {
if: {
$and: [
{ $eq: [{ $type: '$$parsedDate' }, 'date'] },
{ $gte: [{ $year: { date: '$$parsedDate', timezone: 'UTC' } }, 1] },
{ $lte: [{ $year: { date: '$$parsedDate', timezone: 'UTC' } }, 9999] },
],
},
then: {
$dateToString: {
format: '%Y-%m-%d',
timezone: 'UTC',
date: '$$parsedDate',
onNull: null,
},
},
else: null,
},
},
},

View file

@ -139,20 +139,20 @@ describe('bar-span pipeline builders and safety guards', () => {
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 () => {
test('regression: normalizes mixed BSON Dates/strings and rejects timezone-less or malformed dates before $min/$max', 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;
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 (rankDiff !== 0) {return rankDiff;}
if (typeof a === 'string' && typeof b === 'string') {
return a < b ? -1 : a > b ? 1 : 0;
}
@ -165,62 +165,170 @@ describe('bar-span pipeline builders and safety guards', () => {
return 0;
};
const evalExpr = (expr: unknown, doc: Record<string, unknown>): unknown => {
if (typeof expr === 'string' && expr.startsWith('$')) {
return doc[expr.slice(1)];
// Simulates MongoDB 7.0 `$dateFromString` faithfully — crucially, WITHOUT `format`,
// MongoDB 7.0 accepts timezone-less ISO timestamps (treating them as UTC) and unpadded
// dates, so only the pipeline's `$regexMatch` gate can reject them.
const simulateMongoDateFromString = (raw: string, format?: string): Date | null => {
if (format === '%Y-%m-%d') {
const m = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(raw);
if (!m) {return null;}
const year = Number(m[1]);
const month = Number(m[2]);
const day = Number(m[3]);
const d = new Date(Date.UTC(year, month - 1, day));
if (
d.getUTCFullYear() !== year ||
d.getUTCMonth() + 1 !== month ||
d.getUTCDate() !== day
) {
return null;
}
return d;
}
// MongoDB 7.0 default ISO-8601 parser accepts timezone-less datetimes as UTC.
const isoMatch =
/^(\d{4})-(\d{1,2})-(\d{1,2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,9}))?)?(Z|[+-]\d{2}:?\d{2})?)?$/.exec(
raw
);
if (!isoMatch) {return null;}
const year = Number(isoMatch[1]);
const month = Number(isoMatch[2]);
const day = Number(isoMatch[3]);
const hour = isoMatch[4] !== undefined ? Number(isoMatch[4]) : 0;
const minute = isoMatch[5] !== undefined ? Number(isoMatch[5]) : 0;
const second = isoMatch[6] !== undefined ? Number(isoMatch[6]) : 0;
const tz = isoMatch[8];
if (hour > 23 || minute > 59 || second > 59) {return null;}
const checkDate = new Date(Date.UTC(year, month - 1, day));
if (
checkDate.getUTCFullYear() !== year ||
checkDate.getUTCMonth() + 1 !== month ||
checkDate.getUTCDate() !== day
) {
return null;
}
let offsetMs = 0;
if (tz !== undefined && tz !== 'Z') {
const sign = tz[0] === '-' ? -1 : 1;
const digits = tz.replace(/[^0-9]/g, '');
const tzH = Number(digits.slice(0, 2));
const tzM = Number(digits.slice(2, 4));
if (tzH > 23 || tzM > 59) {return null;}
offsetMs = sign * (tzH * 60 + tzM) * 60_000;
}
return new Date(Date.UTC(year, month - 1, day, hour, minute, second) - offsetMs);
};
const evalExpr = (
expr: unknown,
doc: Record<string, unknown>,
vars: Record<string, unknown> = {}
): unknown => {
if (typeof expr === 'string') {
if (expr.startsWith('$$')) {
return vars[expr.slice(2)];
}
if (expr.startsWith('$')) {
return doc[expr.slice(1)];
}
return expr;
}
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';
const val = evalExpr(obj.$type, doc, vars);
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);
return evalExpr(left, doc, vars) === evalExpr(right, doc, vars);
}
if ('$gte' in obj) {
const [left, right] = obj.$gte as [unknown, unknown];
return (evalExpr(left, doc, vars) as number) >= (evalExpr(right, doc, vars) as number);
}
if ('$lte' in obj) {
const [left, right] = obj.$lte as [unknown, unknown];
return (evalExpr(left, doc, vars) as number) <= (evalExpr(right, doc, vars) as number);
}
if ('$and' in obj) {
const items = obj.$and as unknown[];
for (const item of items) {
if (!evalExpr(item, doc, vars)) {return false;}
}
return true;
}
if ('$cond' in obj) {
const cfg = obj.$cond as { if: unknown; then: unknown; else: unknown };
return evalExpr(cfg.if, doc, vars)
? evalExpr(cfg.then, doc, vars)
: evalExpr(cfg.else, doc, vars);
}
if ('$let' in obj) {
const cfg = obj.$let as { vars: Record<string, unknown>; in: unknown };
const nextVars: Record<string, unknown> = { ...vars };
for (const [k, v] of Object.entries(cfg.vars)) {
nextVars[k] = evalExpr(v, doc, vars);
}
return evalExpr(cfg.in, doc, nextVars);
}
if ('$trim' in obj) {
const cfg = obj.$trim as { input: unknown };
const val = evalExpr(cfg.input, doc);
const val = evalExpr(cfg.input, doc, vars);
return typeof val === 'string' ? val.trim() : null;
}
if ('$regexMatch' in obj) {
const cfg = obj.$regexMatch as { input: unknown; regex: string; options?: string };
const val = evalExpr(cfg.input, doc, vars);
if (typeof val !== 'string') {return false;}
return new RegExp(cfg.regex, cfg.options ?? '').test(val);
}
if ('$year' in obj) {
const cfg = obj.$year as { date: unknown; timezone?: string };
const val = evalExpr(cfg.date, doc, vars);
if (val === null || val === undefined) {return null;}
if (!(val instanceof Date) || !Number.isFinite(val.getTime())) {return null;}
expect(cfg.timezone).toBe('UTC');
return val.getUTCFullYear();
}
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);
if (evalExpr(branch.case, doc, vars) === true) {
return evalExpr(branch.then, doc, vars);
}
}
return evalExpr(cfg.default, doc);
return evalExpr(cfg.default, doc, vars);
}
if ('$dateFromString' in obj) {
const cfg = obj.$dateFromString as {
dateString: unknown;
format?: string;
onError?: unknown;
onNull?: unknown;
};
const raw = evalExpr(cfg.dateString, doc);
const raw = evalExpr(cfg.dateString, doc, vars);
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`);
const parsed = simulateMongoDateFromString(raw, cfg.format);
return parsed ?? cfg.onError ?? null;
}
if ('$dateToString' in obj) {
const cfg = obj.$dateToString as {
@ -229,7 +337,7 @@ describe('bar-span pipeline builders and safety guards', () => {
date: unknown;
onNull?: unknown;
};
const raw = evalExpr(cfg.date, doc);
const raw = evalExpr(cfg.date, doc, vars);
if (raw === null || raw === undefined) {
return cfg.onNull ?? null;
}
@ -238,7 +346,10 @@ describe('bar-span pipeline builders and safety guards', () => {
}
expect(cfg.format).toBe('%Y-%m-%d');
expect(cfg.timezone).toBe('UTC');
return raw.toISOString().slice(0, 10);
const y = String(raw.getUTCFullYear()).padStart(4, '0');
const m = String(raw.getUTCMonth() + 1).padStart(2, '0');
const d = String(raw.getUTCDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
}
throw new Error(`Unsupported test aggregation expression: ${JSON.stringify(obj)}`);
};
@ -261,7 +372,7 @@ describe('bar-span pipeline builders and safety guards', () => {
docs = [...docs].sort((a, b) => {
for (const [field, dir] of sortSpec) {
const cmp = compareBson(a[field], b[field]);
if (cmp !== 0) return cmp * dir;
if (cmp !== 0) {return cmp * dir;}
}
return 0;
});
@ -270,7 +381,7 @@ describe('bar-span pipeline builders and safety guards', () => {
docs = docs.map(doc => {
const out: Record<string, unknown> = {};
for (const [key, spec] of Object.entries(proj)) {
if (key === '_id' && spec === 0) continue;
if (key === '_id' && spec === 0) {continue;}
out[key] = evalExpr(spec, doc);
}
return out;
@ -291,13 +402,13 @@ describe('bar-span pipeline builders and safety guards', () => {
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;
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 (val === null || val === undefined) {continue;}
if (minVal === null || compareBson(val, minVal) < 0) {
minVal = val;
}
@ -307,7 +418,7 @@ describe('bar-span pipeline builders and safety guards', () => {
let maxVal: unknown = null;
for (const doc of bucket) {
const val = evalExpr(accObj.$max, doc);
if (val === null || val === undefined) continue;
if (val === null || val === undefined) {continue;}
if (maxVal === null || compareBson(val, maxVal) > 0) {
maxVal = val;
}
@ -330,7 +441,13 @@ describe('bar-span pipeline builders and safety guards', () => {
{ 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.
// Timezone-less timestamp would become a false max extremum if unvalidated `$dateFromString` ran.
{ eodSearchCode: 'TZLESS_EXTREMUM.US', date: '2024-06-03' },
{ eodSearchCode: 'TZLESS_EXTREMUM.US', date: '2024-06-07' },
{ eodSearchCode: 'TZLESS_EXTREMUM.US', date: '2024-06-10T12:00:00' },
{ eodSearchCode: 'TZLESS_EXTREMUM.US', date: '2023-02-29' },
{ eodSearchCode: 'TZLESS_EXTREMUM.US', date: '2024-6-9' },
// All-invalid dates (including timezone-less only) must yield null bounds and be skipped.
{ eodSearchCode: 'ALL_BAD.US', date: 'not-a-date' },
{ eodSearchCode: 'ALL_BAD.US', date: null },
];
@ -338,6 +455,13 @@ describe('bar-span pipeline builders and safety guards', () => {
const rawQmDocs: Record<string, unknown>[] = [
{ qmSearchCode: 'MIXED:TO', date: new Date('2024-06-07T00:00:00.000Z') },
{ qmSearchCode: 'MIXED:TO', date: '2024-06-10' },
// QuoteMedia listing with valid bars through June 7 and a timezone-less row on June 10:
// must NOT extend to June 10 or create a false overlap with a listing starting June 10.
{ qmSearchCode: 'QM_OLD:TO', date: '2024-06-03' },
{ qmSearchCode: 'QM_OLD:TO', date: '2024-06-07' },
{ qmSearchCode: 'QM_OLD:TO', date: '2024-06-10T12:00:00' },
// Listing whose only bar is a timezone-less timestamp must be skipped as invalidDate.
{ qmSearchCode: 'QM_TZLESS_ONLY:TO', date: '2024-06-10T12:00:00' },
];
const reader: BarSpanAggregateReader = {
@ -361,6 +485,13 @@ describe('bar-span pipeline builders and safety guards', () => {
lastBarDate: '2024-06-10',
barCount: 3,
});
expect(result.index.get('eod', 'TZLESS_EXTREMUM.US')).toEqual({
source: 'eod',
sourceId: 'TZLESS_EXTREMUM.US',
firstBarDate: '2024-06-03',
lastBarDate: '2024-06-07',
barCount: 5,
});
expect(result.index.get('qm', 'MIXED:TO')).toEqual({
source: 'qm',
sourceId: 'MIXED:TO',
@ -368,12 +499,26 @@ describe('bar-span pipeline builders and safety guards', () => {
lastBarDate: '2024-06-10',
barCount: 2,
});
const qmOld = result.index.get('qm', 'QM_OLD:TO');
expect(qmOld).toEqual({
source: 'qm',
sourceId: 'QM_OLD:TO',
firstBarDate: '2024-06-03',
lastBarDate: '2024-06-07',
barCount: 3,
});
// Must not falsely overlap a different listing starting June 10.
expect(
spansOverlap(qmOld!, { firstBarDate: '2024-06-10', lastBarDate: '2024-06-20' })
).toBe(false);
expect(result.index.get('eod', 'ALL_BAD.US')).toBeUndefined();
expect(result.index.get('qm', 'QM_TZLESS_ONLY:TO')).toBeUndefined();
expect(result.skipped).toEqual({
invalidId: 0,
invalidDate: 1,
invalidDate: 2,
invalidCount: 0,
total: 1,
total: 2,
});
});