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

@ -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;
}