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:
parent
feb8b7079b
commit
97907f7666
2 changed files with 337 additions and 31 deletions
|
|
@ -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<Iterable<T> | AsyncIterable<T>> | Iterable<T> | AsyncIterable<T>;
|
||||
}
|
||||
|
||||
// Compile-time structural compatibility check (type-only, erased at runtime):
|
||||
// ensures MongoDBClient satisfies BarSpanAggregateReader under `bun run typecheck`.
|
||||
type AssertAssignable<Target, _Candidate extends Target> = true;
|
||||
export type MongoDBClientBarSpanReaderCheck = AssertAssignable<
|
||||
BarSpanAggregateReader,
|
||||
MongoDBClient
|
||||
>;
|
||||
|
||||
export interface ComputeBarSpansOptions {
|
||||
sources?: readonly BarSpanSource[];
|
||||
sourceIdsBySource?: Partial<Record<BarSpanSource, readonly string[]>>;
|
||||
|
|
@ -350,23 +360,78 @@ export function assertReadOnlyBarSpanPipeline(pipeline: readonly Record<string,
|
|||
}
|
||||
|
||||
/**
|
||||
* 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`.
|
||||
* 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
export function buildEodBarSpansPipeline(sourceIds?: readonly string[]): Record<string, unknown>[] {
|
||||
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,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
default: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildNormalizedSpanStages(spec: BarSpanCollectionSpec): Record<string, unknown>[] {
|
||||
const projectStage: Record<string, unknown> = {
|
||||
$project: {
|
||||
_id: 0,
|
||||
sourceId: `$${spec.idField}`,
|
||||
normalizedDate: buildNormalizedUtcDateExpr(spec.dateField),
|
||||
},
|
||||
};
|
||||
const groupStage: Record<string, unknown> = {
|
||||
$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<string, unknown>[] {
|
||||
const spanStages = buildNormalizedSpanStages(BAR_SPAN_COLLECTIONS.eod);
|
||||
const pipeline: Record<string, unknown>[] =
|
||||
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<string, unknown>[] {
|
||||
const groupStage: Record<string, unknown> = {
|
||||
$group: {
|
||||
_id: '$qmSearchCode',
|
||||
firstBarDate: { $min: '$date' },
|
||||
lastBarDate: { $max: '$date' },
|
||||
barCount: { $sum: 1 },
|
||||
},
|
||||
};
|
||||
const spanStages = buildNormalizedSpanStages(BAR_SPAN_COLLECTIONS.qm);
|
||||
const pipeline: Record<string, unknown>[] =
|
||||
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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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[] = [
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue