T-176: M2.2q — tools/curate-etl: pure macro curation stage (TeDataPoint + caller-supplied series map → build_macro_rows → MacroParquetRows → macro/part.parquet) in curate_macro.rs with tests (no new crates, no CLI/bench/stream changes, no live Mongo)

This commit is contained in:
Studio 2026-12-02 16:05:23 -05:00
commit daeeb9af96
23 changed files with 17568 additions and 8 deletions

View file

@ -271,6 +271,12 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported
- **Atomic idempotency & autocommit requirement:** Unkeyed appends execute a plain `INSERT ... RETURNING id, created_at`. Keyed appends use `INSERT ... ON CONFLICT (idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING RETURNING id, created_at` followed by a separate keyed `SELECT` on zero rows (and on same-ID `23505` primary-key retries), comparing normalized `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs` via `areFiledFindingPayloadsEqual`. Pass an autocommit, fresh-snapshot `READ COMMITTED` executor (such as a `pg.Pool`, not a `REPEATABLE READ`/`SERIALIZABLE` or explicit `BEGIN` transaction unless the executor rolls back a `SAVEPOINT` before rethrowing errors) so concurrent callers observe the committed winner and `23505` retry lookups do not hit `25P02`.
- **Reader filtering & research-visible corpus boundary:** `listFindings` and `listProviderCaveats` push down case-sensitive exact `id` (taking precedence over `query`), escaped `ILIKE` substring matching (`%`, `_`, `\`) for ASCII queries, and `lower(provider) = lower($n::text)` (matching `idx_provider_caveats_lower_provider`) for ASCII provider filters while retaining non-ASCII stored rows as candidates (and omitting SQL casing filters for non-ASCII selectors), then applying JavaScript `.toLowerCase()` matching after row validation so PostgreSQL libc/C collation casing (e.g., Greek final sigma or `BİST` / `K`) never drops `read_knowledge` matches. All eligible rows are returned ordered by `id ASC` with no `LIMIT` so `createReadKnowledgeTool` owns ranking and global limits. Because `findings` and `provider_caveats` carry no Vault visibility column, callers must bind the adapter to a research-visible corpus and keep `createFileFindingTool` responsible for verifying `trialRefs` via `trialLookup` before writing.
### Exchange Calendar Resolver
- **`createPostgresListingCalendarPort({ executor, schema? })`** and **`createExchangeCalendarResolver({ listingCalendars, sessionDates, earlyCloses? })`** (exported from `@stock-bot/research/mcp` alongside `ListingCalendarPort`, `SessionDatesPort`, `EarlyCloseOverrides`, `PostgresListingCalendarError`, and `ExchangeCalendarResolverError`) implement `EventStudyExchangeCalendarResolver` for `createEventStudyTool` with zero `node:*` imports and zero runtime `pg` dependency.
- **Injected ports & fail-closed validation:** `createPostgresListingCalendarPort` issues one read-only parameterized `SELECT` joining `listing.mic` to `exchange.mic` (`WHERE l.listing_id = ANY($1::integer[])`), validating `executor.query` (`INVALID_EXECUTOR`), optional `schema` (`^[a-z_][a-z0-9_]*$`, `INVALID_SCHEMA`), and returned rows (`INVALID_ROW`). `SessionDatesPort.listSessionDates({ calendarCode, fromDate, toDate })` is called once per distinct calendar code in sorted order; the resolver fails closed with no partial result on missing, unrequested, or conflicting listing mappings or on malformed, duplicate, unsorted, or out-of-window session dates. Empty `listingIds` returns empty `{ calendars, listingCalendarId }` with zero port calls.
- **Supported DST range & default half-day close:** Session close timestamps convert Eastern Time (`America/New_York` / `America/Toronto`) to UTC epoch milliseconds across `1976-01-01` through `2030-12-31` inclusive (matching `tools/curate-etl/src/session_close.rs` across the `1976–1986`, `1987–2006`, and `2007–2030` DST eras) and throw `ExchangeCalendarResolverError('UNSUPPORTED_DATE')` outside that range. Optional `earlyCloses` (`{ [calendarCode]: { [YYYY-MM-DD]: minuteOfDayEastern } }`, integer minutes in `1..=960`, e.g. `780` for `13:00 ET`) overrides the close on listed dates; when `earlyCloses` is omitted, every session closes at `16:00 ET` and exchange half-days are treated as full `16:00 ET` trading days.
### Filesystem Library Cards Adapter
- **`createLibraryCardReader({ root, fs })`** (exported from `@stock-bot/research/mcp` alongside `createNodeLibraryCardFs`, `LibraryCardFs`, `LibraryCardDirHandle`, `LibraryCardDirEntry`, `LibraryCardReaderOptions`, `LibraryCardReader`, `LibraryCardError`, and `LibraryCardErrorCode`) implements `Pick<KnowledgePort, 'listLibraryCards'>` over a configured read-only library root (`<root>/library.yml` and `<root>/cards/<sectionId>/<slug>.md`) with zero new dependencies.

View file

@ -0,0 +1,749 @@
/**
* Exchange-calendar resolver and read-only PostgreSQL listing-calendar adapter
* for the MCP copilot `event_study` tool (`EventStudyExchangeCalendarResolver`).
*
* Pure, dependency-free, and browser-safe: zero `node:*` imports, zero bare
* `process` access, and no runtime `pg` dependency.
*
* Eastern Time DST schedule (`1976-01-01..=2030-12-31`, matching
* `tools/curate-etl/src/session_close.rs` for `America/New_York` /
* `America/Toronto`):
* - `1976..=1986`: last Sunday of April -> last Sunday of October.
* - `1987..=2006`: first Sunday of April -> last Sunday of October.
* - `2007..=2030`: second Sunday of March -> first Sunday of November.
*
* Using the session-date convention (inclusive spring boundary, exclusive fall
* boundary), EDT is `UTC-4` and EST is `UTC-5`.
*/
import type {
EventStudyExchangeCalendars,
ExchangeSessionClose,
} from '../../event-panel';
import {
MS_PER_DAY,
isPlainRecord,
isValidInt32,
parseCalendarDayKey,
} from '../../panel-shared';
import type {
EventStudyExchangeCalendarQuery,
EventStudyExchangeCalendarResolver,
} from '../tools/event-study';
const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/;
const MS_PER_MINUTE = 60_000;
const EDT_UTC_OFFSET_MINUTES = 4 * 60;
const EST_UTC_OFFSET_MINUTES = 5 * 60;
/** First Gregorian year supported by the Eastern Time DST schedule. */
export const EXCHANGE_CALENDAR_MIN_SUPPORTED_YEAR = 1976;
/** Last Gregorian year supported by the Eastern Time DST schedule. */
export const EXCHANGE_CALENDAR_MAX_SUPPORTED_YEAR = 2030;
/** Inclusive lower bound (`YYYY-MM-DD`) of the supported Eastern Time DST schedule. */
export const EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE = '1976-01-01';
/** Inclusive upper bound (`YYYY-MM-DD`) of the supported Eastern Time DST schedule. */
export const EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE = '2030-12-31';
/** Default Eastern Time close minute of day (`16:00 ET` = `960`). */
export const EXCHANGE_CALENDAR_DEFAULT_CLOSE_MINUTE_ET = 16 * 60;
/** Minimum allowed Eastern Time early-close override minute of day (`00:01 ET`). */
export const EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET = 1;
/** Maximum allowed Eastern Time close minute of day (`16:00 ET`). */
export const EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET = 16 * 60;
/** Epoch day for `1976-01-01` (`Date.UTC(1976, 0, 1) / MS_PER_DAY`). */
const MIN_SUPPORTED_DAY_KEY = 2_191;
/** Epoch day for `2030-12-31` (`Date.UTC(2030, 11, 31) / MS_PER_DAY`). */
const MAX_SUPPORTED_DAY_KEY = 22_279;
const SUPPORTED_YEAR_COUNT =
EXCHANGE_CALENDAR_MAX_SUPPORTED_YEAR - EXCHANGE_CALENDAR_MIN_SUPPORTED_YEAR + 1;
/** Error codes thrown by {@link PostgresListingCalendarError}. */
export type PostgresListingCalendarErrorCode =
| 'INVALID_EXECUTOR'
| 'INVALID_SCHEMA'
| 'INVALID_ROW';
/** Typed validation error thrown by the PostgreSQL listing-calendar adapter. */
export class PostgresListingCalendarError extends RangeError {
readonly code: PostgresListingCalendarErrorCode;
constructor(code: PostgresListingCalendarErrorCode, message: string) {
super(message);
this.name = 'PostgresListingCalendarError';
this.code = code;
Object.setPrototypeOf(this, new.target.prototype);
}
}
/** Error codes thrown by {@link ExchangeCalendarResolverError}. */
export type ExchangeCalendarResolverErrorCode =
| 'INVALID_OPTION'
| 'INVALID_QUERY'
| 'UNSUPPORTED_DATE'
| 'INVALID_LISTING_CALENDAR_ROW'
| 'MISSING_LISTING_CALENDAR'
| 'UNEXPECTED_LISTING_CALENDAR'
| 'CONFLICTING_LISTING_CALENDAR'
| 'INVALID_SESSION_DATES';
/** Optional error constructor metadata for {@link ExchangeCalendarResolverError}. */
export interface ExchangeCalendarResolverErrorOptions {
readonly cause?: unknown;
}
/** Typed validation and fail-closed integrity error thrown by {@link createExchangeCalendarResolver}. */
export class ExchangeCalendarResolverError extends RangeError {
readonly code: ExchangeCalendarResolverErrorCode;
override readonly cause?: unknown;
constructor(
code: ExchangeCalendarResolverErrorCode,
message: string,
options?: ExchangeCalendarResolverErrorOptions
) {
super(message, options?.cause !== undefined ? { cause: options.cause } : undefined);
this.name = 'ExchangeCalendarResolverError';
this.code = code;
if (options?.cause !== undefined) {
this.cause = options.cause;
}
Object.setPrototypeOf(this, new.target.prototype);
}
}
/**
* Structural `pg.Pool` / `pg.PoolClient`-compatible query interface so this module
* has no runtime dependency on `pg` and is unit-testable with a fake executor.
*/
export interface ListingCalendarExecutor {
query<Row = Record<string, unknown>>(
text: string,
params?: readonly unknown[]
): Promise<{ readonly rows: readonly Row[] }>;
}
/** Factory options for {@link createPostgresListingCalendarPort}. */
export interface PostgresListingCalendarPortOptions {
readonly executor: ListingCalendarExecutor;
/** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */
readonly schema?: string;
}
/** One listing-to-exchange-calendar mapping row returned by {@link ListingCalendarPort}. */
export interface ListingCalendarRow {
readonly listingId: number;
readonly calendarCode: string;
}
/** Injected port resolving `listingId` -> `exchange.calendar_code`. */
export interface ListingCalendarPort {
getListingCalendars(
listingIds: readonly number[]
): Promise<readonly ListingCalendarRow[]> | readonly ListingCalendarRow[];
}
/** Query passed to {@link SessionDatesPort.listSessionDates}. */
export interface SessionDatesQuery {
readonly calendarCode: string;
readonly fromDate: string;
readonly toDate: string;
}
/**
* Injected port supplying strictly ascending, unique `YYYY-MM-DD` exchange session
* dates inside `[fromDate, toDate]` for one exchange calendar code.
*/
export interface SessionDatesPort {
listSessionDates(query: SessionDatesQuery): Promise<readonly string[]> | readonly string[];
}
/**
* Optional caller-supplied early-close overrides keyed by
* `{ [calendarCode]: { [YYYY-MM-DD]: minuteOfDayEastern } }`, where
* `minuteOfDayEastern` is an integer in `(0, 960]` (e.g. `780` = `13:00 ET`).
*/
export type EarlyCloseOverrides = Readonly<Record<string, Readonly<Record<string, number>>>>;
/** Factory options for {@link createExchangeCalendarResolver}. */
export interface ExchangeCalendarResolverOptions {
readonly listingCalendars: ListingCalendarPort;
readonly sessionDates: SessionDatesPort;
readonly earlyCloses?: EarlyCloseOverrides;
}
interface RawListingCalendarRow {
readonly listing_id: unknown;
readonly calendar_code: unknown;
}
interface DstBoundsTable {
readonly startDay: Int32Array;
readonly endDay: Int32Array;
}
let cachedDstBounds: DstBoundsTable | null = null;
/** ISO-8601 weekday for an epoch day: `1 = Monday`, ..., `7 = Sunday`. */
function isoWeekday(epochDay: number): number {
// 1970-01-01 (epochDay === 0) was Thursday (ISO 4).
return (((epochDay + 3) % 7) + 7) % 7 + 1;
}
function ymdToEpochDay(year: number, month: number, day: number): number {
return Date.UTC(year, month - 1, day) / MS_PER_DAY;
}
function nthSundayOfMonth(year: number, month: number, nth: number): number {
const first = ymdToEpochDay(year, month, 1);
const firstWd = isoWeekday(first);
const delta = (7 - firstWd) % 7;
return first + delta + (nth - 1) * 7;
}
function lastSundayOfMonth(year: number, month: number): number {
const nextYear = month === 12 ? year + 1 : year;
const nextMonth = month === 12 ? 1 : month + 1;
const last = ymdToEpochDay(nextYear, nextMonth, 1) - 1;
const lastWd = isoWeekday(last);
return last - (lastWd % 7);
}
function getDstBoundsTable(): DstBoundsTable {
if (cachedDstBounds !== null) {
return cachedDstBounds;
}
const startDay = new Int32Array(SUPPORTED_YEAR_COUNT);
const endDay = new Int32Array(SUPPORTED_YEAR_COUNT);
for (
let year = EXCHANGE_CALENDAR_MIN_SUPPORTED_YEAR;
year <= EXCHANGE_CALENDAR_MAX_SUPPORTED_YEAR;
year += 1
) {
let dstStart: number;
let dstEnd: number;
if (year <= 1986) {
dstStart = lastSundayOfMonth(year, 4);
dstEnd = lastSundayOfMonth(year, 10);
} else if (year <= 2006) {
dstStart = nthSundayOfMonth(year, 4, 1);
dstEnd = lastSundayOfMonth(year, 10);
} else {
dstStart = nthSundayOfMonth(year, 3, 2);
dstEnd = nthSundayOfMonth(year, 11, 1);
}
const idx = year - EXCHANGE_CALENDAR_MIN_SUPPORTED_YEAR;
startDay[idx] = dstStart;
endDay[idx] = dstEnd;
}
cachedDstBounds = { startDay, endDay };
return cachedDstBounds;
}
function assertSupportedDayKey(dayKey: number, dateStr: string, field: string): void {
if (dayKey < MIN_SUPPORTED_DAY_KEY || dayKey > MAX_SUPPORTED_DAY_KEY) {
throw new ExchangeCalendarResolverError(
'UNSUPPORTED_DATE',
`Unsupported "${field}" date "${dateStr}": must fall within ${EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE}..=${EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE}.`
);
}
}
function easternSessionCloseUtcMs(dayKey: number, closeMinuteEt: number): number {
const year = new Date(dayKey * MS_PER_DAY).getUTCFullYear();
const table = getDstBoundsTable();
const idx = year - EXCHANGE_CALENDAR_MIN_SUPPORTED_YEAR;
const isEdt =
dayKey >= (table.startDay[idx] as number) && dayKey < (table.endDay[idx] as number);
const utcOffsetMinutes = isEdt ? EDT_UTC_OFFSET_MINUTES : EST_UTC_OFFSET_MINUTES;
return dayKey * MS_PER_DAY + (closeMinuteEt + utcOffsetMinutes) * MS_PER_MINUTE;
}
function defineDataProperty<T>(target: Record<string, T>, key: string, value: T): void {
Object.defineProperty(target, key, {
value,
enumerable: true,
writable: true,
configurable: true,
});
}
function buildListingCalendarSql(schemaPrefix: string): string {
const listingTable = `${schemaPrefix}listing`;
const exchangeTable = `${schemaPrefix}exchange`;
return [
'SELECT',
' l.listing_id AS listing_id,',
' e.calendar_code AS calendar_code',
`FROM ${listingTable} l`,
`INNER JOIN ${exchangeTable} e ON e.mic = l.mic`,
'WHERE l.listing_id = ANY($1::integer[])',
'ORDER BY l.listing_id ASC',
].join('\n');
}
function validatePostgresFactoryOptions(options: PostgresListingCalendarPortOptions): {
readonly executor: ListingCalendarExecutor;
readonly schemaPrefix: string;
} {
if (typeof options !== 'object' || options === null) {
throw new PostgresListingCalendarError(
'INVALID_EXECUTOR',
'Invalid options: expected an object with a ListingCalendarExecutor.'
);
}
const { executor, schema } = options;
if (typeof executor !== 'object' || executor === null || typeof executor.query !== 'function') {
throw new PostgresListingCalendarError(
'INVALID_EXECUTOR',
'Invalid executor: expected an object with a callable query(text, params?) method.'
);
}
if (schema === undefined) {
return { executor, schemaPrefix: '' };
}
if (typeof schema !== 'string' || !SCHEMA_IDENT_RE.test(schema)) {
throw new PostgresListingCalendarError(
'INVALID_SCHEMA',
'Invalid schema: expected an identifier matching ^[a-z_][a-z0-9_]*$.'
);
}
return { executor, schemaPrefix: `"${schema}".` };
}
function mapRawListingCalendarRow(raw: unknown): ListingCalendarRow {
if (!isPlainRecord(raw)) {
throw new PostgresListingCalendarError(
'INVALID_ROW',
'Invalid security-master row: expected a non-null plain object.'
);
}
const row = raw as unknown as RawListingCalendarRow;
if (!isValidInt32(row.listing_id)) {
throw new PostgresListingCalendarError(
'INVALID_ROW',
'Invalid security-master row: "listing_id" must be a safe 32-bit integer.'
);
}
if (typeof row.calendar_code !== 'string' || row.calendar_code.trim().length === 0) {
throw new PostgresListingCalendarError(
'INVALID_ROW',
'Invalid security-master row: "calendar_code" must be a non-empty string.'
);
}
return {
listingId: row.listing_id,
calendarCode: row.calendar_code.trim(),
};
}
/**
* Creates a read-only PostgreSQL {@link ListingCalendarPort} backed by the M1
* security master (`listing` joined to `exchange` on `mic`), binding listing IDs
* as a single `$1::integer[]` parameter.
*/
export function createPostgresListingCalendarPort(
options: PostgresListingCalendarPortOptions
): ListingCalendarPort {
const { executor, schemaPrefix } = validatePostgresFactoryOptions(options);
const sql = buildListingCalendarSql(schemaPrefix);
return {
async getListingCalendars(
listingIds: readonly number[]
): Promise<readonly ListingCalendarRow[]> {
if (!Array.isArray(listingIds)) {
throw new PostgresListingCalendarError(
'INVALID_ROW',
'Invalid listingIds: expected an array of 32-bit integers.'
);
}
const boundIds: number[] = [];
for (let i = 0; i < listingIds.length; i += 1) {
const id = listingIds[i];
if (!isValidInt32(id)) {
throw new PostgresListingCalendarError(
'INVALID_ROW',
`Invalid listingIds[${i}]: expected a safe 32-bit integer.`
);
}
boundIds.push(id);
}
if (boundIds.length === 0) {
return [];
}
const result = await executor.query<RawListingCalendarRow>(sql, [boundIds]);
if (typeof result !== 'object' || result === null || !Array.isArray(result.rows)) {
throw new PostgresListingCalendarError(
'INVALID_ROW',
'Invalid executor response: expected an object with a rows array.'
);
}
const mapped: ListingCalendarRow[] = [];
for (let i = 0; i < result.rows.length; i += 1) {
mapped.push(mapRawListingCalendarRow(result.rows[i]));
}
return mapped;
},
};
}
function parseResolverDayKey(
value: unknown,
field: string,
code: 'INVALID_OPTION' | 'INVALID_QUERY' | 'INVALID_SESSION_DATES'
): number {
return parseCalendarDayKey(value, field, (message, cause) =>
new ExchangeCalendarResolverError(
code,
message,
cause !== undefined ? { cause } : undefined
)
);
}
function isPlainObjectRecord(value: unknown): value is Record<string, unknown> {
if (typeof value !== 'object' || value === null) {
return false;
}
const proto: unknown = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
}
function parseEarlyCloses(
raw: unknown
): Map<string, Map<string, number>> {
const result = new Map<string, Map<string, number>>();
if (raw === undefined) {
return result;
}
if (!isPlainObjectRecord(raw)) {
throw new ExchangeCalendarResolverError(
'INVALID_OPTION',
'Invalid "earlyCloses": expected a plain object mapping calendarCode to { [YYYY-MM-DD]: minuteOfDay }.'
);
}
const calendarEntries = Object.entries(raw);
for (let i = 0; i < calendarEntries.length; i += 1) {
const [calendarCode, rawDates] = calendarEntries[i] as [string, unknown];
if (calendarCode.trim().length === 0 || calendarCode !== calendarCode.trim()) {
throw new ExchangeCalendarResolverError(
'INVALID_OPTION',
`Invalid "earlyCloses" calendar code "${calendarCode}": expected a non-blank trimmed string.`
);
}
if (!isPlainObjectRecord(rawDates)) {
throw new ExchangeCalendarResolverError(
'INVALID_OPTION',
`Invalid "earlyCloses.${calendarCode}": expected a plain object mapping YYYY-MM-DD dates to Eastern close minutes.`
);
}
const dateOverrides = new Map<string, number>();
const dateEntries = Object.entries(rawDates);
for (let j = 0; j < dateEntries.length; j += 1) {
const [dateStr, minute] = dateEntries[j] as [string, unknown];
const field = `earlyCloses.${calendarCode}["${dateStr}"]`;
const dayKey = parseResolverDayKey(dateStr, field, 'INVALID_OPTION');
assertSupportedDayKey(dayKey, dateStr, field);
if (
typeof minute !== 'number' ||
!Number.isSafeInteger(minute) ||
minute < EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET ||
minute > EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET
) {
throw new ExchangeCalendarResolverError(
'INVALID_OPTION',
`Invalid "${field}": expected an integer Eastern minute in (${EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET - 1}, ${EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET}], got ${String(minute)}.`
);
}
dateOverrides.set(dateStr, minute);
}
result.set(calendarCode, dateOverrides);
}
return result;
}
function validateResolverOptions(options: ExchangeCalendarResolverOptions): {
readonly listingCalendars: ListingCalendarPort;
readonly sessionDates: SessionDatesPort;
readonly earlyCloseMap: Map<string, Map<string, number>>;
} {
if (!isPlainRecord(options)) {
throw new ExchangeCalendarResolverError(
'INVALID_OPTION',
'Invalid options: expected an object with listingCalendars and sessionDates ports.'
);
}
const { listingCalendars, sessionDates, earlyCloses } = options;
if (
typeof listingCalendars !== 'object' ||
listingCalendars === null ||
typeof listingCalendars.getListingCalendars !== 'function'
) {
throw new ExchangeCalendarResolverError(
'INVALID_OPTION',
'Invalid "listingCalendars": expected an object with a callable getListingCalendars(listingIds) method.'
);
}
if (
typeof sessionDates !== 'object' ||
sessionDates === null ||
typeof sessionDates.listSessionDates !== 'function'
) {
throw new ExchangeCalendarResolverError(
'INVALID_OPTION',
'Invalid "sessionDates": expected an object with a callable listSessionDates({ calendarCode, fromDate, toDate }) method.'
);
}
const earlyCloseMap = parseEarlyCloses(earlyCloses);
return { listingCalendars, sessionDates, earlyCloseMap };
}
function compareAscii(a: string, b: string): number {
return a < b ? -1 : a > b ? 1 : 0;
}
/**
* Creates an {@link EventStudyExchangeCalendarResolver} over injected
* {@link ListingCalendarPort} and {@link SessionDatesPort} implementations,
* converting each validated exchange session date into its UTC epoch-ms close
* timestamp (`16:00 ET` by default, or caller-supplied `earlyCloses` override).
*/
export function createExchangeCalendarResolver(
options: ExchangeCalendarResolverOptions
): EventStudyExchangeCalendarResolver {
const { listingCalendars, sessionDates, earlyCloseMap } = validateResolverOptions(options);
return async function resolveExchangeCalendars(
query: EventStudyExchangeCalendarQuery
): Promise<EventStudyExchangeCalendars> {
if (!isPlainRecord(query)) {
throw new ExchangeCalendarResolverError(
'INVALID_QUERY',
'Invalid query: expected a plain object with listingIds, fromDate, and toDate.'
);
}
if (!Array.isArray(query.listingIds)) {
throw new ExchangeCalendarResolverError(
'INVALID_QUERY',
'Invalid "listingIds": expected an array of 32-bit integer listing IDs.'
);
}
if (query.listingIds.length === 0) {
return {
calendars: {},
listingCalendarId: {},
};
}
const fromDayKey = parseResolverDayKey(query.fromDate, 'fromDate', 'INVALID_QUERY');
const toDayKey = parseResolverDayKey(query.toDate, 'toDate', 'INVALID_QUERY');
if (fromDayKey > toDayKey) {
throw new ExchangeCalendarResolverError(
'INVALID_QUERY',
`Invalid date window: fromDate "${query.fromDate}" is after toDate "${query.toDate}".`
);
}
assertSupportedDayKey(fromDayKey, query.fromDate, 'fromDate');
assertSupportedDayKey(toDayKey, query.toDate, 'toDate');
const requestedSet = new Set<number>();
for (let i = 0; i < query.listingIds.length; i += 1) {
const id: unknown = query.listingIds[i];
if (!isValidInt32(id)) {
throw new ExchangeCalendarResolverError(
'INVALID_QUERY',
`Invalid "listingIds[${i}]": expected a safe 32-bit integer.`
);
}
requestedSet.add(id);
}
const sortedListingIds = Array.from(requestedSet).sort((a, b) => a - b);
const rawMappings = await listingCalendars.getListingCalendars(sortedListingIds);
if (!Array.isArray(rawMappings)) {
throw new ExchangeCalendarResolverError(
'INVALID_LISTING_CALENDAR_ROW',
'Invalid listingCalendars response: expected an array of { listingId, calendarCode } rows.'
);
}
const listingToCalendar = new Map<number, string>();
for (let i = 0; i < rawMappings.length; i += 1) {
const row: unknown = rawMappings[i];
if (!isPlainRecord(row)) {
throw new ExchangeCalendarResolverError(
'INVALID_LISTING_CALENDAR_ROW',
`Invalid listingCalendars[${i}]: expected a plain object.`
);
}
const listingId = row.listingId;
const calendarCode = row.calendarCode;
if (!isValidInt32(listingId)) {
throw new ExchangeCalendarResolverError(
'INVALID_LISTING_CALENDAR_ROW',
`Invalid listingCalendars[${i}].listingId: expected a safe 32-bit integer.`
);
}
if (
typeof calendarCode !== 'string' ||
calendarCode.trim().length === 0 ||
calendarCode !== calendarCode.trim()
) {
throw new ExchangeCalendarResolverError(
'INVALID_LISTING_CALENDAR_ROW',
`Invalid listingCalendars[${i}].calendarCode: expected a non-blank trimmed string.`
);
}
if (!requestedSet.has(listingId)) {
throw new ExchangeCalendarResolverError(
'UNEXPECTED_LISTING_CALENDAR',
`Listing calendar port returned unrequested listingId ${listingId}.`
);
}
const existing = listingToCalendar.get(listingId);
if (existing !== undefined && existing !== calendarCode) {
throw new ExchangeCalendarResolverError(
'CONFLICTING_LISTING_CALENDAR',
`Conflicting calendar codes for listingId ${listingId}: "${existing}" vs "${calendarCode}".`
);
}
listingToCalendar.set(listingId, calendarCode);
}
const missingIds: number[] = [];
for (let i = 0; i < sortedListingIds.length; i += 1) {
const id = sortedListingIds[i] as number;
if (!listingToCalendar.has(id)) {
missingIds.push(id);
}
}
if (missingIds.length > 0) {
throw new ExchangeCalendarResolverError(
'MISSING_LISTING_CALENDAR',
`Missing exchange calendar mapping for listingId(s): ${missingIds.join(', ')}.`
);
}
const distinctCalendars = Array.from(new Set(listingToCalendar.values())).sort(compareAscii);
const sessionsByCalendar = new Map<string, readonly ExchangeSessionClose[]>();
for (let c = 0; c < distinctCalendars.length; c += 1) {
const calendarCode = distinctCalendars[c] as string;
const rawDates = await sessionDates.listSessionDates({
calendarCode,
fromDate: query.fromDate,
toDate: query.toDate,
});
if (!Array.isArray(rawDates)) {
throw new ExchangeCalendarResolverError(
'INVALID_SESSION_DATES',
`Invalid session dates for "${calendarCode}": expected an array of YYYY-MM-DD strings.`
);
}
const overrides = earlyCloseMap.get(calendarCode);
const sessions: ExchangeSessionClose[] = [];
let prevDayKey = Number.NEGATIVE_INFINITY;
for (let i = 0; i < rawDates.length; i += 1) {
const dateStr: unknown = rawDates[i];
const field = `sessionDates["${calendarCode}"][${i}]`;
const dayKey = parseResolverDayKey(dateStr, field, 'INVALID_SESSION_DATES');
const validDate = dateStr as string;
assertSupportedDayKey(dayKey, validDate, field);
if (dayKey < fromDayKey || dayKey > toDayKey) {
throw new ExchangeCalendarResolverError(
'INVALID_SESSION_DATES',
`Session date "${validDate}" for "${calendarCode}" is outside requested window [${query.fromDate}, ${query.toDate}].`
);
}
if (dayKey === prevDayKey) {
throw new ExchangeCalendarResolverError(
'INVALID_SESSION_DATES',
`Duplicate session date "${validDate}" for "${calendarCode}".`
);
}
if (dayKey < prevDayKey) {
throw new ExchangeCalendarResolverError(
'INVALID_SESSION_DATES',
`Session dates for "${calendarCode}" must be strictly ascending (saw "${validDate}" out of order).`
);
}
prevDayKey = dayKey;
const closeMinuteEt =
overrides?.get(validDate) ?? EXCHANGE_CALENDAR_DEFAULT_CLOSE_MINUTE_ET;
sessions.push({
date: validDate,
closeTs: easternSessionCloseUtcMs(dayKey, closeMinuteEt),
});
}
sessionsByCalendar.set(calendarCode, sessions);
}
const calendars: Record<string, readonly ExchangeSessionClose[]> = {};
for (let c = 0; c < distinctCalendars.length; c += 1) {
const calendarCode = distinctCalendars[c] as string;
defineDataProperty(
calendars,
calendarCode,
sessionsByCalendar.get(calendarCode) as readonly ExchangeSessionClose[]
);
}
const listingCalendarId: Record<number, string> = {};
for (let i = 0; i < sortedListingIds.length; i += 1) {
const id = sortedListingIds[i] as number;
defineDataProperty(
listingCalendarId as unknown as Record<string, string>,
String(id),
listingToCalendar.get(id) as string
);
}
return {
calendars,
listingCalendarId,
};
};
}

View file

@ -2,6 +2,7 @@ export * from './adapters/library-cards';
export * from './adapters/postgres-findings';
export * from './adapters/postgres-symbol-search';
export * from './adapters/postgres-trial-ref';
export * from './adapters/exchange-calendars';
export * from './copilot-server';
export * from './protocol';
export * from './server';

View file

@ -0,0 +1,430 @@
import { describe, expect, test } from 'bun:test';
import { type EventObservation, buildEventStudyInput } from '../src/event-panel';
import type { BarRecord } from '../src/market-data-store';
import {
ExchangeCalendarResolverError,
type ListingCalendarExecutor,
type ListingCalendarRow,
PostgresListingCalendarError,
type SessionDatesQuery,
createExchangeCalendarResolver,
createPostgresListingCalendarPort,
} from '../src/mcp/index';
const MS_PER_DAY = 86_400_000;
function utcMs(dateStr: string, hour: number, minute = 0): number {
const [y, m, d] = dateStr.split('-').map(Number) as [number, number, number];
return Date.UTC(y, m - 1, d, hour, minute, 0, 0);
}
function isoDate(epochMs: number): string {
return new Date(epochMs).toISOString().slice(0, 10);
}
function allDatesInclusive(from: string, to: string): string[] {
const out: string[] = [];
for (let t = utcMs(from, 0); t <= utcMs(to, 0); t += MS_PER_DAY) {
out.push(isoDate(t));
}
return out;
}
/** Independent oracle: local wall-clock date/time of `epochMs` in an IANA zone (ICU tzdata). */
function makeZoneFormatter(timeZone: string): (epochMs: number) => string {
const fmt = new Intl.DateTimeFormat('en-CA', {
timeZone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hourCycle: 'h23',
});
return (epochMs) => {
const parts = Object.fromEntries(fmt.formatToParts(new Date(epochMs)).map((p) => [p.type, p.value]));
return `${parts.year}-${parts.month}-${parts.day} ${parts.hour}:${parts.minute}`;
};
}
async function captureError(fn: () => unknown): Promise<unknown> {
try {
await fn();
} catch (err) {
return err;
}
return undefined;
}
function countingPorts(
rows: readonly ListingCalendarRow[] | (() => unknown),
sessions: (q: SessionDatesQuery) => unknown
) {
const counts = { listing: 0, session: 0 };
const sessionCalls: SessionDatesQuery[] = [];
return {
counts,
sessionCalls,
listingCalendars: {
getListingCalendars: () => {
counts.listing += 1;
return (typeof rows === 'function' ? rows() : rows) as readonly ListingCalendarRow[];
},
},
sessionDates: {
listSessionDates: (q: SessionDatesQuery) => {
counts.session += 1;
sessionCalls.push(q);
return sessions(q) as readonly string[];
},
},
};
}
describe('QA: Eastern close timestamps vs ICU tzdata oracle', () => {
test('every day 1976-01-01..=2030-12-31 closes at exactly 16:00 local in America/New_York and America/Toronto', async () => {
const days = allDatesInclusive('1976-01-01', '2030-12-31');
expect(days).toHaveLength(20_089);
const ports = countingPorts(
[
{ listingId: 1, calendarCode: 'XNYS' },
{ listingId: 2, calendarCode: 'XTSE' },
],
() => days
);
const resolver = createExchangeCalendarResolver(ports);
const result = await resolver({ listingIds: [1, 2], fromDate: days[0]!, toDate: days[days.length - 1]! });
const calendars = result.calendars as Record<string, readonly { date: string; closeTs: number }[]>;
const ny = makeZoneFormatter('America/New_York');
const to = makeZoneFormatter('America/Toronto');
const mismatches: string[] = [];
for (const code of ['XNYS', 'XTSE'] as const) {
const sessions = calendars[code]!;
expect(sessions).toHaveLength(days.length);
for (let i = 0; i < days.length; i += 1) {
const s = sessions[i]!;
const expected = `${days[i]} 16:00`;
if (s.date !== days[i] || ny(s.closeTs) !== expected || to(s.closeTs) !== expected) {
mismatches.push(`${code} ${days[i]} -> ${new Date(s.closeTs).toISOString()}`);
}
}
}
expect(mismatches).toEqual([]);
expect(ports.counts).toEqual({ listing: 1, session: 2 });
});
test('each supported year has exactly two offset flips, both on Sundays, and closes are only 20:00Z or 21:00Z', async () => {
const days = allDatesInclusive('1976-01-01', '2030-12-31');
const resolver = createExchangeCalendarResolver(
countingPorts([{ listingId: 1, calendarCode: 'XNYS' }], () => days)
);
const result = await resolver({ listingIds: [1], fromDate: days[0]!, toDate: days[days.length - 1]! });
const sessions = (result.calendars as Record<string, readonly { date: string; closeTs: number }[]>).XNYS!;
const flipsByYear = new Map<number, string[]>();
let prevHour = -1;
for (const s of sessions) {
const hour = (s.closeTs - utcMs(s.date, 0)) / 3_600_000;
expect(hour === 20 || hour === 21).toBe(true);
if (prevHour !== -1 && hour !== prevHour) {
const year = Number(s.date.slice(0, 4));
flipsByYear.set(year, [...(flipsByYear.get(year) ?? []), s.date]);
expect(new Date(utcMs(s.date, 0)).getUTCDay()).toBe(0);
}
prevHour = hour;
}
// 1976 starts in EST, so every year (1976..=2030) has exactly spring + fall flips.
expect(flipsByYear.size).toBe(55);
for (const [, flips] of flipsByYear) {
expect(flips).toHaveLength(2);
}
});
test('remaining session_close.rs known vectors (mid-season and 1986/2006 boundaries) match exactly', async () => {
const vectors: ReadonlyArray<readonly [string, number]> = [
['1980-01-15', 21],
['1980-07-15', 20],
['1986-04-26', 21],
['1986-04-27', 20],
['1999-01-15', 21],
['1999-07-15', 20],
['2006-04-01', 21],
['2006-04-02', 20],
['2006-10-28', 20],
['2006-10-29', 21],
['2024-01-15', 21],
['2024-07-15', 20],
];
const resolver = createExchangeCalendarResolver(
countingPorts([{ listingId: 1, calendarCode: 'XNYS' }], () => vectors.map(([d]) => d))
);
const result = await resolver({ listingIds: [1], fromDate: '1980-01-15', toDate: '2024-07-15' });
expect(result.calendars).toEqual({
XNYS: vectors.map(([date, hour]) => ({ date, closeTs: utcMs(date, hour) })),
});
});
});
describe('QA: earlyCloses edge cases', () => {
test('override applies in EDT and EST, 960 equals default, and minute 1 is 00:01 ET', async () => {
const dates = ['2024-07-03', '2024-11-29', '2024-12-24', '2024-12-26'];
const resolver = createExchangeCalendarResolver({
...countingPorts([{ listingId: 1, calendarCode: 'XNYS' }], () => dates),
earlyCloses: { XNYS: { '2024-07-03': 780, '2024-11-29': 960, '2024-12-24': 1 } },
});
const result = await resolver({ listingIds: [1], fromDate: '2024-07-01', toDate: '2024-12-31' });
expect(result.calendars).toEqual({
XNYS: [
{ date: '2024-07-03', closeTs: utcMs('2024-07-03', 17) }, // 13:00 EDT
{ date: '2024-11-29', closeTs: utcMs('2024-11-29', 21) }, // 16:00 EST (== default)
{ date: '2024-12-24', closeTs: utcMs('2024-12-24', 5, 1) }, // 00:01 EST
{ date: '2024-12-26', closeTs: utcMs('2024-12-26', 21) },
],
});
});
test('overrides for unrequested calendars or non-session dates are ignored without error', async () => {
const ports = countingPorts([{ listingId: 1, calendarCode: 'XTSE' }], () => ['2024-11-29']);
const resolver = createExchangeCalendarResolver({
...ports,
earlyCloses: { XNYS: { '2024-11-29': 780 }, XTSE: { '2024-12-25': 780 } },
});
const result = await resolver({ listingIds: [1], fromDate: '2024-11-29', toDate: '2024-11-29' });
expect(result.calendars).toEqual({
XTSE: [{ date: '2024-11-29', closeTs: utcMs('2024-11-29', 21) }],
});
});
test('calendar code matching for overrides is exact (case-sensitive)', async () => {
const resolver = createExchangeCalendarResolver({
...countingPorts([{ listingId: 1, calendarCode: 'XNYS' }], () => ['2024-11-29']),
earlyCloses: { xnys: { '2024-11-29': 780 } },
});
const result = await resolver({ listingIds: [1], fromDate: '2024-11-29', toDate: '2024-11-29' });
expect(result.calendars).toEqual({
XNYS: [{ date: '2024-11-29', closeTs: utcMs('2024-11-29', 21) }],
});
});
test('earlyCloses parsed from JSON with a "__proto__" calendar key does not pollute Object.prototype', async () => {
const earlyCloses = JSON.parse('{"__proto__": {"2024-11-29": 780}, "XNYS": {"2024-11-29": 780}}');
const resolver = createExchangeCalendarResolver({
...countingPorts([{ listingId: 1, calendarCode: 'XNYS' }], () => ['2024-11-29']),
earlyCloses,
});
const result = await resolver({ listingIds: [1], fromDate: '2024-11-29', toDate: '2024-11-29' });
expect(result.calendars).toEqual({
XNYS: [{ date: '2024-11-29', closeTs: utcMs('2024-11-29', 18) }],
});
expect(({} as Record<string, unknown>)['2024-11-29']).toBeUndefined();
});
});
describe('QA: query validation and port failures fail closed', () => {
test('invalid queries throw INVALID_QUERY with zero port calls', async () => {
const bad: unknown[] = [
null,
[],
{ listingIds: 'x', fromDate: '2024-01-02', toDate: '2024-01-03' },
{ listingIds: [1], fromDate: '2024-01-03', toDate: '2024-01-02' },
{ listingIds: [1], fromDate: '2024-1-2', toDate: '2024-01-03' },
{ listingIds: [1], fromDate: '2024-01-02', toDate: undefined },
{ listingIds: [1.5], fromDate: '2024-01-02', toDate: '2024-01-03' },
{ listingIds: ['1'], fromDate: '2024-01-02', toDate: '2024-01-03' },
{ listingIds: [2_147_483_648], fromDate: '2024-01-02', toDate: '2024-01-03' },
];
for (const q of bad) {
const ports = countingPorts([{ listingId: 1, calendarCode: 'XNYS' }], () => ['2024-01-02']);
const err = await captureError(() => createExchangeCalendarResolver(ports)(q as never));
expect(err, JSON.stringify(q)).toBeInstanceOf(ExchangeCalendarResolverError);
expect((err as ExchangeCalendarResolverError).code, JSON.stringify(q)).toBe('INVALID_QUERY');
expect(ports.counts, JSON.stringify(q)).toEqual({ listing: 0, session: 0 });
}
});
test('malformed listing port responses throw INVALID_LISTING_CALENDAR_ROW before any session call', async () => {
const badResponses: unknown[] = [
null,
{ rows: [] },
[null],
[{ listingId: '1', calendarCode: 'XNYS' }],
[{ listingId: 1, calendarCode: ' XNYS' }],
[{ listingId: 1, calendarCode: '' }],
[{ listingId: 1 }],
];
for (const resp of badResponses) {
const ports = countingPorts(() => resp, () => ['2024-01-02']);
const err = await captureError(() =>
createExchangeCalendarResolver(ports)({ listingIds: [1], fromDate: '2024-01-02', toDate: '2024-01-02' })
);
expect(err, JSON.stringify(resp)).toBeInstanceOf(ExchangeCalendarResolverError);
expect((err as ExchangeCalendarResolverError).code).toBe('INVALID_LISTING_CALENDAR_ROW');
expect(ports.counts.session).toBe(0);
}
});
test('port errors propagate unchanged and no partial result is returned', async () => {
const listingBoom = new Error('pg down');
const ports1 = countingPorts(() => {
throw listingBoom;
}, () => []);
expect(
await captureError(() =>
createExchangeCalendarResolver(ports1)({ listingIds: [1], fromDate: '2024-01-02', toDate: '2024-01-02' })
)
).toBe(listingBoom);
expect(ports1.counts.session).toBe(0);
const sessionBoom = new Error('sessions down');
const ports2 = countingPorts(
[
{ listingId: 1, calendarCode: 'XNYS' },
{ listingId: 2, calendarCode: 'XTSE' },
],
(q) => (q.calendarCode === 'XTSE' ? Promise.reject(sessionBoom) : ['2024-01-02'])
);
expect(
await captureError(() =>
createExchangeCalendarResolver(ports2)({ listingIds: [2, 1], fromDate: '2024-01-02', toDate: '2024-01-02' })
)
).toBe(sessionBoom);
expect(ports2.sessionCalls.map((q) => q.calendarCode)).toEqual(['XNYS', 'XTSE']);
});
test('session dates outside the supported DST range fail closed even when the window would allow them', async () => {
// Query window is in range; port returns a pre-1976 date which is also outside the window.
const ports = countingPorts([{ listingId: 1, calendarCode: 'XNYS' }], () => ['1975-12-31']);
const err = await captureError(() =>
createExchangeCalendarResolver(ports)({ listingIds: [1], fromDate: '1976-01-01', toDate: '1976-01-05' })
);
expect(err).toBeInstanceOf(ExchangeCalendarResolverError);
expect((err as ExchangeCalendarResolverError).code).toBe('UNSUPPORTED_DATE');
});
test('an empty session list for a calendar is returned as an empty array (not dropped)', async () => {
const resolver = createExchangeCalendarResolver(
countingPorts([{ listingId: 5, calendarCode: 'XTSE' }], () => [])
);
const result = await resolver({ listingIds: [5], fromDate: '2024-01-01', toDate: '2024-01-01' });
expect(result).toEqual({ calendars: { XTSE: [] }, listingCalendarId: { 5: 'XTSE' } });
});
});
describe('QA: output safety and isolation', () => {
test('a "__proto__" calendar code becomes an own property and does not pollute Object.prototype', async () => {
const resolver = createExchangeCalendarResolver(
countingPorts([{ listingId: 1, calendarCode: '__proto__' }], () => ['2024-01-02'])
);
const result = await resolver({ listingIds: [1], fromDate: '2024-01-02', toDate: '2024-01-02' });
expect(Object.keys(result.calendars)).toEqual(['__proto__']);
expect(Object.getPrototypeOf(result.calendars)).toBe(Object.prototype);
expect(Object.hasOwn(result.calendars, '__proto__')).toBe(true);
expect(({} as Record<string, unknown>).date).toBeUndefined();
});
test('repeated calls return fresh objects; mutating one result does not affect the next', async () => {
const resolver = createExchangeCalendarResolver(
countingPorts([{ listingId: 1, calendarCode: 'XNYS' }], () => ['2024-01-02'])
);
const q = { listingIds: [1], fromDate: '2024-01-02', toDate: '2024-01-02' };
const first = await resolver(q);
(first.calendars as Record<string, { date: string; closeTs: number }[]>).XNYS!.push({
date: '2024-01-03',
closeTs: 0,
});
(first.listingCalendarId as Record<number, string>)[1] = 'XTSE';
const second = await resolver(q);
expect(second).toEqual({
calendars: { XNYS: [{ date: '2024-01-02', closeTs: utcMs('2024-01-02', 21) }] },
listingCalendarId: { 1: 'XNYS' },
});
});
});
describe('QA: Postgres port → resolver → buildEventStudyInput (fake executor)', () => {
test('rejects invalid listingIds with INVALID_ROW and zero queries; propagates executor rejection', async () => {
let queries = 0;
const executor: ListingCalendarExecutor = {
async query() {
queries += 1;
return { rows: [] };
},
};
const port = createPostgresListingCalendarPort({ executor, schema: 'public' });
for (const bad of ['1' as unknown, [1.5], ['1'], [Number.NaN], [-2_147_483_649]]) {
const err = await captureError(() => port.getListingCalendars(bad as never));
expect(err).toBeInstanceOf(PostgresListingCalendarError);
expect((err as PostgresListingCalendarError).code).toBe('INVALID_ROW');
}
expect(queries).toBe(0);
const boom = new Error('connection reset');
const failing = createPostgresListingCalendarPort({
executor: {
async query() {
throw boom;
},
},
});
expect(await captureError(() => failing.getListingCalendars([1]))).toBe(boom);
});
test('padded VARCHAR calendar_code is trimmed and the composed result feeds buildEventStudyInput', async () => {
const calls: Array<{ text: string; params: readonly unknown[] | undefined }> = [];
const executor: ListingCalendarExecutor = {
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
calls.push({ text, params });
return {
rows: [
{ listing_id: 202, calendar_code: 'XTSE ' },
{ listing_id: 101, calendar_code: 'XNYS' },
] as unknown as readonly Row[],
};
},
};
const sessions: Record<string, readonly string[]> = {
XNYS: ['2024-11-27', '2024-11-29', '2024-12-02'],
XTSE: ['2024-11-27', '2024-11-28', '2024-11-29', '2024-12-02'],
};
const resolver = createExchangeCalendarResolver({
listingCalendars: createPostgresListingCalendarPort({ executor, schema: 'public' }),
sessionDates: { listSessionDates: (q) => sessions[q.calendarCode] ?? [] },
earlyCloses: { XNYS: { '2024-11-29': 780 } },
});
const cal = await resolver({ listingIds: [202, 101, 202], fromDate: '2024-11-27', toDate: '2024-12-02' });
expect(calls).toHaveLength(1);
expect(calls[0]!.params).toEqual([[101, 202]]);
expect(calls[0]!.text).toContain('FROM "public".listing l');
expect(cal.listingCalendarId).toEqual({ 101: 'XNYS', 202: 'XTSE' });
const bar = (listingId: number, date: string, close: number): BarRecord => {
const ts = utcMs(date, 21);
return { listingId, ts, open: close, high: close, low: close, close, volume: 1_000, knownAt: ts };
};
const bars: BarRecord[] = [
...sessions.XNYS!.map((d, i) => bar(101, d, 100 + i)),
...sessions.XTSE!.map((d, i) => bar(202, d, 50 + i)),
];
// 18:30Z on 2024-11-29: after XNYS 13:00 ET early close, before XTSE 16:00 ET close.
const knownAt = utcMs('2024-11-29', 18, 30);
const events: EventObservation[] = [
{ listingId: 101, knownAt, kind: 'filing', subtype: '8-K' },
{ listingId: 202, knownAt, kind: 'filing', subtype: '8-K' },
];
const panel = buildEventStudyInput({
bars,
events,
vaultCutoffDate: '2024-12-03',
benchmark: 'equal_weight',
exchangeCalendars: cal,
});
expect(panel.input.sessionDates).toEqual(['2024-11-27', '2024-11-28', '2024-11-29', '2024-12-02']);
expect(panel.input.events).toEqual([
{ entityId: 202, dayIndex: 2 },
{ entityId: 101, dayIndex: 3 },
]);
});
});

View file

@ -0,0 +1,789 @@
import { describe, expect, test } from 'bun:test';
import { type EventObservation, buildEventStudyInput } from '../src/event-panel';
import type { BarRecord } from '../src/market-data-store';
import {
EXCHANGE_CALENDAR_DEFAULT_CLOSE_MINUTE_ET,
EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE,
EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE,
ExchangeCalendarResolverError,
type ListingCalendarExecutor,
type ListingCalendarPort,
type ListingCalendarRow,
PostgresListingCalendarError,
type SessionDatesPort,
type SessionDatesQuery,
createExchangeCalendarResolver,
createPostgresListingCalendarPort,
} from '../src/mcp/index';
function utcMs(
year: number,
month: number,
day: number,
hour = 0,
minute = 0,
second = 0
): number {
return Date.UTC(year, month - 1, day, hour, minute, second, 0);
}
function makeBar(listingId: number, dateStr: string, close: number, closeHourUtc = 21): BarRecord {
const [y, m, d] = dateStr.split('-').map(Number) as [number, number, number];
const ts = utcMs(y, m, d, closeHourUtc, 0, 0);
return {
listingId,
ts,
open: close,
high: close,
low: close,
close,
volume: 100_000,
knownAt: ts,
};
}
describe('createExchangeCalendarResolver — Eastern DST schedule & date bounds', () => {
test('computes exact UTC ms for EDT (2024-07-01 -> 20:00Z) and EST (2024-12-02 -> 21:00Z)', async () => {
const resolver = createExchangeCalendarResolver({
listingCalendars: {
getListingCalendars: () => [{ listingId: 1, calendarCode: 'XNYS' }],
},
sessionDates: {
listSessionDates: () => ['2024-07-01', '2024-12-02'],
},
});
const result = await resolver({
listingIds: [1],
fromDate: '2024-07-01',
toDate: '2024-12-02',
});
expect(result.calendars).toEqual({
XNYS: [
{ date: '2024-07-01', closeTs: utcMs(2024, 7, 1, 20, 0, 0) },
{ date: '2024-12-02', closeTs: utcMs(2024, 12, 2, 21, 0, 0) },
],
});
expect(result.listingCalendarId).toEqual({ 1: 'XNYS' });
});
test('matches session_close.rs DST transition vectors across all three eras (1976, 1987, 2007)', async () => {
const vectors: readonly {
readonly date: string;
readonly expectedUtcHour: number;
}[] = [
// Era 1 (1976..=1986): last Sunday of April -> last Sunday of October
{ date: '1976-04-24', expectedUtcHour: 21 }, // Sat before spring-forward (EST)
{ date: '1976-04-25', expectedUtcHour: 20 }, // Last Sun of April (EDT)
{ date: '1976-10-30', expectedUtcHour: 20 }, // Sat before fall-back (EDT)
{ date: '1976-10-31', expectedUtcHour: 21 }, // Last Sun of October (EST)
// Era 2 (1987..=2006): first Sunday of April -> last Sunday of October
{ date: '1987-04-04', expectedUtcHour: 21 }, // Sat before spring-forward (EST)
{ date: '1987-04-05', expectedUtcHour: 20 }, // First Sun of April (EDT)
{ date: '1987-10-24', expectedUtcHour: 20 }, // Sat before fall-back (EDT)
{ date: '1987-10-25', expectedUtcHour: 21 }, // Last Sun of October (EST)
// Era 3 (2007..=2030): second Sunday of March -> first Sunday of November
{ date: '2007-03-10', expectedUtcHour: 21 }, // Sat before spring-forward (EST)
{ date: '2007-03-11', expectedUtcHour: 20 }, // Second Sun of March (EDT)
{ date: '2007-11-03', expectedUtcHour: 20 }, // Sat before fall-back (EDT)
{ date: '2007-11-04', expectedUtcHour: 21 }, // First Sun of November (EST)
];
const resolver = createExchangeCalendarResolver({
listingCalendars: {
getListingCalendars: () => [{ listingId: 10, calendarCode: 'XNYS' }],
},
sessionDates: {
listSessionDates: () => vectors.map((v) => v.date),
},
});
const result = await resolver({
listingIds: [10],
fromDate: '1976-04-24',
toDate: '2007-11-04',
});
const sessions = (result.calendars as Record<string, readonly { date: string; closeTs: number }[]>)
.XNYS;
expect(sessions).toHaveLength(vectors.length);
for (let i = 0; i < vectors.length; i += 1) {
const vec = vectors[i] as { date: string; expectedUtcHour: number };
const [y, m, d] = vec.date.split('-').map(Number) as [number, number, number];
expect(sessions?.[i]).toEqual({
date: vec.date,
closeTs: utcMs(y, m, d, vec.expectedUtcHour, 0, 0),
});
}
});
test('supports inclusive endpoints 1976-01-01 and 2030-12-31 and fails closed outside range', async () => {
let listingCalls = 0;
let sessionCalls = 0;
const resolver = createExchangeCalendarResolver({
listingCalendars: {
getListingCalendars: () => {
listingCalls += 1;
return [{ listingId: 1, calendarCode: 'XNYS' }];
},
},
sessionDates: {
listSessionDates: () => {
sessionCalls += 1;
return [EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE, EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE];
},
},
});
const ok = await resolver({
listingIds: [1],
fromDate: '1976-01-01',
toDate: '2030-12-31',
});
expect(ok.calendars).toEqual({
XNYS: [
{ date: '1976-01-01', closeTs: utcMs(1976, 1, 1, 21, 0, 0) },
{ date: '2030-12-31', closeTs: utcMs(2030, 12, 31, 21, 0, 0) },
],
});
expect(listingCalls).toBe(1);
expect(sessionCalls).toBe(1);
await expect(
resolver({ listingIds: [1], fromDate: '1975-12-31', toDate: '1976-01-02' })
).rejects.toThrow(ExchangeCalendarResolverError);
try {
await resolver({ listingIds: [1], fromDate: '1975-12-31', toDate: '1976-01-02' });
} catch (err) {
expect(err).toBeInstanceOf(ExchangeCalendarResolverError);
expect((err as ExchangeCalendarResolverError).code).toBe('UNSUPPORTED_DATE');
}
try {
await resolver({ listingIds: [1], fromDate: '2030-12-30', toDate: '2031-01-01' });
expect.unreachable('expected UNSUPPORTED_DATE for 2031-01-01');
} catch (err) {
expect(err).toBeInstanceOf(ExchangeCalendarResolverError);
expect((err as ExchangeCalendarResolverError).code).toBe('UNSUPPORTED_DATE');
}
// Out-of-range query bounds fail before calling either port.
expect(listingCalls).toBe(1);
expect(sessionCalls).toBe(1);
});
});
describe('createPostgresListingCalendarPort', () => {
test('issues one parameterized SELECT joining listing.mic to exchange.mic with no ID literals or writes', async () => {
const calls: Array<{ text: string; params: readonly unknown[] | undefined }> = [];
const executor: ListingCalendarExecutor = {
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
calls.push({ text, params });
const rows = [
{ listing_id: 101, calendar_code: 'XNYS' },
{ listing_id: 202, calendar_code: 'XTSE' },
];
return { rows: rows as unknown as readonly Row[] };
},
};
const port = createPostgresListingCalendarPort({ executor });
const rows = await port.getListingCalendars([101, 202]);
expect(rows).toEqual([
{ listingId: 101, calendarCode: 'XNYS' },
{ listingId: 202, calendarCode: 'XTSE' },
]);
expect(calls).toHaveLength(1);
const call = calls[0] as { text: string; params: readonly unknown[] | undefined };
expect(call.text).toContain('SELECT');
expect(call.text).toContain('FROM listing l');
expect(call.text).toContain('INNER JOIN exchange e ON e.mic = l.mic');
expect(call.text).toContain('WHERE l.listing_id = ANY($1::integer[])');
expect(call.text).not.toContain('101');
expect(call.text).not.toContain('202');
expect(call.text).not.toMatch(/\b(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|TRUNCATE)\b/i);
expect(call.params).toEqual([[101, 202]]);
});
test('supports optional validated schema qualification and short-circuits empty listingIds', async () => {
const calls: Array<{ text: string; params: readonly unknown[] | undefined }> = [];
const executor: ListingCalendarExecutor = {
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
calls.push({ text, params });
return { rows: [{ listing_id: 7, calendar_code: 'XNYS' }] as unknown as readonly Row[] };
},
};
const port = createPostgresListingCalendarPort({ executor, schema: 'sec_master_v1' });
expect(await port.getListingCalendars([])).toEqual([]);
expect(calls).toHaveLength(0);
const rows = await port.getListingCalendars([7]);
expect(rows).toEqual([{ listingId: 7, calendarCode: 'XNYS' }]);
expect(calls).toHaveLength(1);
expect(calls[0]?.text).toContain('FROM "sec_master_v1".listing l');
expect(calls[0]?.text).toContain('INNER JOIN "sec_master_v1".exchange e ON e.mic = l.mic');
});
test('throws typed INVALID_EXECUTOR, INVALID_SCHEMA, and INVALID_ROW errors', async () => {
const badExecutors: unknown[] = [null, undefined, {}, { executor: null }, { executor: {} }];
for (const bad of badExecutors) {
let caught: unknown;
try {
createPostgresListingCalendarPort(bad as never);
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(PostgresListingCalendarError);
expect((caught as PostgresListingCalendarError).code).toBe('INVALID_EXECUTOR');
}
const okExecutor: ListingCalendarExecutor = {
async query() {
return { rows: [] };
},
};
for (const badSchema of ['', 'Public', '1bad', 'bad-schema', 'a; DROP TABLE listing;']) {
let caught: unknown;
try {
createPostgresListingCalendarPort({ executor: okExecutor, schema: badSchema });
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(PostgresListingCalendarError);
expect((caught as PostgresListingCalendarError).code).toBe('INVALID_SCHEMA');
}
const badResponses: unknown[] = [
null,
{ rows: 'not-an-array' },
{ rows: [null] },
{ rows: [{ listing_id: '101', calendar_code: 'XNYS' }] },
{ rows: [{ listing_id: 2_147_483_648, calendar_code: 'XNYS' }] },
{ rows: [{ listing_id: 101, calendar_code: '' }] },
{ rows: [{ listing_id: 101, calendar_code: ' ' }] },
{ rows: [{ listing_id: 101, calendar_code: null }] },
];
for (const badResp of badResponses) {
const port = createPostgresListingCalendarPort({
executor: {
async query() {
return badResp as never;
},
},
});
let caught: unknown;
try {
await port.getListingCalendars([101]);
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(PostgresListingCalendarError);
expect((caught as PostgresListingCalendarError).code).toBe('INVALID_ROW');
}
});
});
describe('createExchangeCalendarResolver — multi-calendar, earlyCloses, and buildEventStudyInput integration', () => {
const createMultiCalendarFixture = () => {
const xnysDates = ['2024-11-27', '2024-11-29', '2024-12-02', '2024-12-03'] as const;
const xtseDates = [
'2024-11-27',
'2024-11-28',
'2024-11-29',
'2024-12-02',
'2024-12-03',
] as const;
const bars: BarRecord[] = [
// Listing 101 (XNYS) — closed on US Thanksgiving 2024-11-28
makeBar(101, '2024-11-27', 100),
makeBar(101, '2024-11-29', 110),
makeBar(101, '2024-12-02', 121),
makeBar(101, '2024-12-03', 121),
makeBar(101, '2024-12-04', 999), // post-Vault bar (must be excluded)
// Listing 102 (XNYS)
makeBar(102, '2024-11-27', 50),
makeBar(102, '2024-11-29', 55),
makeBar(102, '2024-12-02', 60.5),
makeBar(102, '2024-12-03', 60.5),
// Listing 201 (XTSE) — open on 2024-11-28
makeBar(201, '2024-11-27', 200),
makeBar(201, '2024-11-28', 210),
makeBar(201, '2024-11-29', 220.5),
makeBar(201, '2024-12-02', 242.55),
makeBar(201, '2024-12-03', 242.55),
];
// Event at 19:00:00Z on 2024-11-29 (14:00 EST):
// - After XNYS 13:00 EST early close (18:00Z), so with override it anchors to 2024-12-02.
// - Before XTSE 16:00 EST close (21:00Z), so it stays on 2024-11-29.
const eventTs = utcMs(2024, 11, 29, 19, 0, 0);
const events: EventObservation[] = [
{ listingId: 101, knownAt: eventTs, kind: 'filing', subtype: '8-K' },
{ listingId: 201, knownAt: eventTs, kind: 'filing', subtype: '8-K' },
];
return {
xnysDates,
xtseDates,
bars,
events,
fromDate: '2024-11-27',
toDate: '2024-12-03',
vaultCutoffDate: '2024-12-04',
};
};
test('calls listSessionDates once per distinct calendar, anchors early-close vs 16:00 ET in buildEventStudyInput, and respects Vault cutoff', async () => {
const fixture = createMultiCalendarFixture();
const makePorts = () => {
const sessionCalls: SessionDatesQuery[] = [];
const listingPort: ListingCalendarPort = {
async getListingCalendars() {
return [
{ listingId: 101, calendarCode: 'XNYS' },
{ listingId: 102, calendarCode: 'XNYS' },
{ listingId: 201, calendarCode: 'XTSE' },
];
},
};
const sessionPort: SessionDatesPort = {
async listSessionDates(q) {
sessionCalls.push(q);
return q.calendarCode === 'XNYS' ? fixture.xnysDates : fixture.xtseDates;
},
};
return { listingPort, sessionPort, sessionCalls };
};
// 1) Baseline: no earlyCloses (all sessions close at 16:00 ET = 21:00Z in EST)
const baselinePorts = makePorts();
const baselineResolver = createExchangeCalendarResolver({
listingCalendars: baselinePorts.listingPort,
sessionDates: baselinePorts.sessionPort,
});
const baselineCal = await baselineResolver({
listingIds: [101, 102, 201],
fromDate: fixture.fromDate,
toDate: fixture.toDate,
});
expect(baselinePorts.sessionCalls).toEqual([
{ calendarCode: 'XNYS', fromDate: fixture.fromDate, toDate: fixture.toDate },
{ calendarCode: 'XTSE', fromDate: fixture.fromDate, toDate: fixture.toDate },
]);
expect(baselineCal.listingCalendarId).toEqual({
101: 'XNYS',
102: 'XNYS',
201: 'XTSE',
});
const baselinePanel = buildEventStudyInput({
bars: fixture.bars,
events: fixture.events,
vaultCutoffDate: fixture.vaultCutoffDate,
benchmark: 'equal_weight',
exchangeCalendars: baselineCal,
});
expect(baselinePanel.diagnostics.vaultExcludedDates).toBe(1);
expect(baselinePanel.input.sessionDates).toEqual([
'2024-11-27',
'2024-11-28',
'2024-11-29',
'2024-12-02',
'2024-12-03',
]);
// Under 16:00 ET baseline, both listings anchor to 2024-11-29 (index 2).
expect(baselinePanel.input.events).toEqual([
{ entityId: 101, dayIndex: 2 },
{ entityId: 201, dayIndex: 2 },
]);
// Consecutive-session returns: listing 101 has no 2024-11-28 session on XNYS,
// so 2024-11-27 -> 2024-11-29 is consecutive on XNYS (+10%), and 2024-11-28 is NaN.
const returns101 = baselinePanel.input.entityReturns.get(101) as Float64Array;
expect(Number.isNaN(returns101[0] as number)).toBe(true);
expect(Number.isNaN(returns101[1] as number)).toBe(true);
expect(returns101[2]).toBeCloseTo(0.1, 12);
expect(returns101[3]).toBeCloseTo(0.1, 12);
expect(returns101[4]).toBeCloseTo(0.0, 12);
// 2) With XNYS-only early close override (780 = 13:00 ET -> 18:00Z on 2024-11-29)
const overridePorts = makePorts();
const overrideConfig = { XNYS: { '2024-11-29': 780 } };
const overrideResolver = createExchangeCalendarResolver({
listingCalendars: overridePorts.listingPort,
sessionDates: overridePorts.sessionPort,
earlyCloses: overrideConfig,
});
// Mutating caller's override object after construction must not affect resolver.
overrideConfig.XNYS['2024-11-29'] = EXCHANGE_CALENDAR_DEFAULT_CLOSE_MINUTE_ET;
const overrideCal = await overrideResolver({
listingIds: [101, 102, 201],
fromDate: fixture.fromDate,
toDate: fixture.toDate,
});
const xnysSessions = (
overrideCal.calendars as Record<string, readonly { date: string; closeTs: number }[]>
).XNYS;
const xtseSessions = (
overrideCal.calendars as Record<string, readonly { date: string; closeTs: number }[]>
).XTSE;
expect(xnysSessions?.find((s) => s.date === '2024-11-29')?.closeTs).toBe(
utcMs(2024, 11, 29, 18, 0, 0)
);
expect(xnysSessions?.find((s) => s.date === '2024-12-02')?.closeTs).toBe(
utcMs(2024, 12, 2, 21, 0, 0)
);
expect(xtseSessions?.find((s) => s.date === '2024-11-29')?.closeTs).toBe(
utcMs(2024, 11, 29, 21, 0, 0)
);
const overridePanel = buildEventStudyInput({
bars: fixture.bars,
events: fixture.events,
vaultCutoffDate: fixture.vaultCutoffDate,
benchmark: 'equal_weight',
exchangeCalendars: overrideCal,
});
// Listing 201 (XTSE) stays on 2024-11-29 (index 2); listing 101 (XNYS) shifts to 2024-12-02 (index 3).
expect(overridePanel.input.events).toEqual([
{ entityId: 201, dayIndex: 2 },
{ entityId: 101, dayIndex: 3 },
]);
});
test('is deterministic under permuted listingIds and reversed listing rows without mutating caller inputs', async () => {
const fixture = createMultiCalendarFixture();
const runWithOrder = async (
listingIds: number[],
rows: readonly ListingCalendarRow[],
asyncSessionPort: boolean
) => {
const snapshot = [...listingIds];
const resolver = createExchangeCalendarResolver({
listingCalendars: {
getListingCalendars: () => rows,
},
sessionDates: {
listSessionDates: (q) => {
const dates = q.calendarCode === 'XNYS' ? fixture.xnysDates : fixture.xtseDates;
return asyncSessionPort ? Promise.resolve(dates) : dates;
},
},
earlyCloses: { XNYS: { '2024-11-29': 780 } },
});
const resolved = await resolver({
listingIds,
fromDate: fixture.fromDate,
toDate: fixture.toDate,
});
expect(listingIds).toEqual(snapshot);
return resolved;
};
const forward = await runWithOrder(
[101, 102, 201],
[
{ listingId: 101, calendarCode: 'XNYS' },
{ listingId: 102, calendarCode: 'XNYS' },
{ listingId: 201, calendarCode: 'XTSE' },
],
false
);
// Permuted listingIds (including duplicate) + reversed listing rows (including identical duplicate)
const permuted = await runWithOrder(
[201, 102, 101, 102],
[
{ listingId: 201, calendarCode: 'XTSE' },
{ listingId: 102, calendarCode: 'XNYS' },
{ listingId: 102, calendarCode: 'XNYS' },
{ listingId: 101, calendarCode: 'XNYS' },
],
true
);
expect(permuted).toEqual(forward);
expect(Object.keys(permuted.calendars)).toEqual(Object.keys(forward.calendars));
expect(Object.keys(permuted.listingCalendarId)).toEqual(
Object.keys(forward.listingCalendarId)
);
// Replay both resolved calendars through buildEventStudyInput on the same pinned bars,
// events, and Vault cutoff, and assert identical anchors, return series, and diagnostics.
const forwardPanel = buildEventStudyInput({
bars: fixture.bars,
events: fixture.events,
vaultCutoffDate: fixture.vaultCutoffDate,
benchmark: 'equal_weight',
exchangeCalendars: forward,
});
const permutedPanel = buildEventStudyInput({
bars: fixture.bars,
events: fixture.events,
vaultCutoffDate: fixture.vaultCutoffDate,
benchmark: 'equal_weight',
exchangeCalendars: permuted,
});
expect(permutedPanel.input.sessionDates).toEqual(forwardPanel.input.sessionDates);
expect(permutedPanel.input.events).toEqual(forwardPanel.input.events);
expect(permutedPanel.input.events).toEqual([
{ entityId: 201, dayIndex: 2 },
{ entityId: 101, dayIndex: 3 },
]);
expect(Array.from(permutedPanel.input.entityReturns.keys())).toEqual(
Array.from(forwardPanel.input.entityReturns.keys())
);
for (const [entityId, forwardSeries] of forwardPanel.input.entityReturns.entries()) {
const permutedSeries = permutedPanel.input.entityReturns.get(entityId);
expect(permutedSeries).toBeDefined();
expect(Array.from(permutedSeries as Float64Array)).toEqual(Array.from(forwardSeries));
}
expect(Array.from(permutedPanel.input.benchmarkReturns)).toEqual(
Array.from(forwardPanel.input.benchmarkReturns)
);
expect(permutedPanel.diagnostics).toEqual(forwardPanel.diagnostics);
expect(permutedPanel.diagnostics.vaultExcludedDates).toBe(1);
});
});
describe('createExchangeCalendarResolver — fail-closed validation & edge cases', () => {
test('empty listingIds returns empty records with zero port calls', async () => {
let listingCalls = 0;
let sessionCalls = 0;
const resolver = createExchangeCalendarResolver({
listingCalendars: {
getListingCalendars: () => {
listingCalls += 1;
return [];
},
},
sessionDates: {
listSessionDates: () => {
sessionCalls += 1;
return [];
},
},
});
const result = await resolver({
listingIds: [],
fromDate: '2024-01-01',
toDate: '2024-12-31',
});
expect(result).toEqual({ calendars: {}, listingCalendarId: {} });
expect(listingCalls).toBe(0);
expect(sessionCalls).toBe(0);
});
test('fails closed with zero sessionDates calls on missing, unrequested, or conflicting listing rows', async () => {
const cases: readonly {
readonly name: string;
readonly rows: readonly ListingCalendarRow[];
readonly expectedCode: string;
}[] = [
{
name: 'missing requested listing',
rows: [{ listingId: 101, calendarCode: 'XNYS' }],
expectedCode: 'MISSING_LISTING_CALENDAR',
},
{
name: 'unrequested listing returned',
rows: [
{ listingId: 101, calendarCode: 'XNYS' },
{ listingId: 102, calendarCode: 'XNYS' },
{ listingId: 999, calendarCode: 'XTSE' },
],
expectedCode: 'UNEXPECTED_LISTING_CALENDAR',
},
{
name: 'conflicting duplicate listing rows',
rows: [
{ listingId: 101, calendarCode: 'XNYS' },
{ listingId: 101, calendarCode: 'XTSE' },
{ listingId: 102, calendarCode: 'XNYS' },
],
expectedCode: 'CONFLICTING_LISTING_CALENDAR',
},
];
for (const tc of cases) {
let sessionCalls = 0;
const resolver = createExchangeCalendarResolver({
listingCalendars: { getListingCalendars: () => tc.rows },
sessionDates: {
listSessionDates: () => {
sessionCalls += 1;
return ['2024-12-02'];
},
},
});
let caught: unknown;
try {
await resolver({
listingIds: [101, 102],
fromDate: '2024-12-02',
toDate: '2024-12-02',
});
} catch (err) {
caught = err;
}
expect(caught, tc.name).toBeInstanceOf(ExchangeCalendarResolverError);
expect((caught as ExchangeCalendarResolverError).code, tc.name).toBe(tc.expectedCode);
expect(sessionCalls, tc.name).toBe(0);
}
});
test('fails closed with no partial result on unsorted, duplicate, malformed, or out-of-range session dates', async () => {
const badSessionLists: readonly { readonly name: string; readonly dates: unknown }[] = [
{ name: 'non-array response', dates: '2024-12-02' },
{ name: 'unsorted dates', dates: ['2024-12-03', '2024-12-02'] },
{ name: 'duplicate dates', dates: ['2024-12-02', '2024-12-02'] },
{ name: 'malformed date string', dates: ['2024-02-30'] },
{ name: 'non-string date', dates: [20241202] },
{ name: 'date before fromDate', dates: ['2024-12-01', '2024-12-02'] },
{ name: 'date after toDate', dates: ['2024-12-02', '2024-12-04'] },
];
for (const tc of badSessionLists) {
const resolver = createExchangeCalendarResolver({
listingCalendars: {
getListingCalendars: () => [
{ listingId: 101, calendarCode: 'XNYS' },
{ listingId: 201, calendarCode: 'XTSE' },
],
},
sessionDates: {
listSessionDates: (q) =>
q.calendarCode === 'XNYS' ? ['2024-12-02', '2024-12-03'] : (tc.dates as never),
},
});
let caught: unknown;
try {
await resolver({
listingIds: [101, 201],
fromDate: '2024-12-02',
toDate: '2024-12-03',
});
} catch (err) {
caught = err;
}
expect(caught, tc.name).toBeInstanceOf(ExchangeCalendarResolverError);
expect((caught as ExchangeCalendarResolverError).code, tc.name).toBe('INVALID_SESSION_DATES');
}
});
test('rejects invalid earlyCloses minutes, dates, and shapes at construction with zero port calls', () => {
let listingCalls = 0;
let sessionCalls = 0;
const listingCalendars: ListingCalendarPort = {
getListingCalendars: () => {
listingCalls += 1;
return [];
},
};
const sessionDates: SessionDatesPort = {
listSessionDates: () => {
sessionCalls += 1;
return [];
},
};
const invalidCases: readonly { readonly earlyCloses: unknown; readonly expectedCode: string }[] =
[
{ earlyCloses: null, expectedCode: 'INVALID_OPTION' },
{ earlyCloses: [], expectedCode: 'INVALID_OPTION' },
{ earlyCloses: 'XNYS', expectedCode: 'INVALID_OPTION' },
{
earlyCloses: new Map([['XNYS', { '2024-11-29': 780 }]]),
expectedCode: 'INVALID_OPTION',
},
{
earlyCloses: { XNYS: new Map([['2024-11-29', 780]]) },
expectedCode: 'INVALID_OPTION',
},
{ earlyCloses: new Set(['XNYS']), expectedCode: 'INVALID_OPTION' },
{ earlyCloses: { XNYS: new Date('2024-11-29T00:00:00Z') }, expectedCode: 'INVALID_OPTION' },
{ earlyCloses: { '': { '2024-11-29': 780 } }, expectedCode: 'INVALID_OPTION' },
{ earlyCloses: { ' XNYS ': { '2024-11-29': 780 } }, expectedCode: 'INVALID_OPTION' },
{ earlyCloses: { XNYS: null }, expectedCode: 'INVALID_OPTION' },
{ earlyCloses: { XNYS: [] }, expectedCode: 'INVALID_OPTION' },
{ earlyCloses: { XNYS: { '2024-02-30': 780 } }, expectedCode: 'INVALID_OPTION' },
{ earlyCloses: { XNYS: { 'not-a-date': 780 } }, expectedCode: 'INVALID_OPTION' },
{ earlyCloses: { XNYS: { '1975-12-31': 780 } }, expectedCode: 'UNSUPPORTED_DATE' },
{ earlyCloses: { XNYS: { '2031-01-01': 780 } }, expectedCode: 'UNSUPPORTED_DATE' },
{ earlyCloses: { XNYS: { '2024-11-29': 0 } }, expectedCode: 'INVALID_OPTION' },
{ earlyCloses: { XNYS: { '2024-11-29': -1 } }, expectedCode: 'INVALID_OPTION' },
{ earlyCloses: { XNYS: { '2024-11-29': 961 } }, expectedCode: 'INVALID_OPTION' },
{ earlyCloses: { XNYS: { '2024-11-29': 780.5 } }, expectedCode: 'INVALID_OPTION' },
{ earlyCloses: { XNYS: { '2024-11-29': Number.NaN } }, expectedCode: 'INVALID_OPTION' },
{ earlyCloses: { XNYS: { '2024-11-29': '780' } }, expectedCode: 'INVALID_OPTION' },
];
for (const tc of invalidCases) {
let caught: unknown;
try {
createExchangeCalendarResolver({
listingCalendars,
sessionDates,
earlyCloses: tc.earlyCloses as never,
});
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(ExchangeCalendarResolverError);
expect((caught as ExchangeCalendarResolverError).code).toBe(tc.expectedCode);
}
expect(listingCalls).toBe(0);
expect(sessionCalls).toBe(0);
});
test('accepts null-prototype records at both levels of earlyCloses', async () => {
const xnysOverrides = Object.create(null) as Record<string, number>;
xnysOverrides['2024-11-29'] = 780;
const earlyCloses = Object.create(null) as Record<string, Record<string, number>>;
earlyCloses.XNYS = xnysOverrides;
const resolver = createExchangeCalendarResolver({
listingCalendars: {
getListingCalendars: () => [{ listingId: 101, calendarCode: 'XNYS' }],
},
sessionDates: {
listSessionDates: () => ['2024-11-29', '2024-12-02'],
},
earlyCloses,
});
const result = await resolver({
listingIds: [101],
fromDate: '2024-11-29',
toDate: '2024-12-02',
});
expect(result.calendars).toEqual({
XNYS: [
{ date: '2024-11-29', closeTs: utcMs(2024, 11, 29, 18, 0, 0) },
{ date: '2024-12-02', closeTs: utcMs(2024, 12, 2, 21, 0, 0) },
],
});
});
});

View file

@ -1680,3 +1680,43 @@ All `curate-*` commands read local TSV and concatenated raw-BSON files produced
- **MongoDB concatenated raw-BSON files (`<collection>.bson`):** `apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts`
See [apps/stock/data-pipeline/README.md](../../apps/stock/data-pipeline/README.md#read-only-raw-bson-exporter-export-raw-bsonts) for flags, read-only safety guards, and the full M1 Step 2 execution order (`run-export-curate-inputs.ts` → `run-export-raw-bson.ts` → `curate-etl curate-*`).
## Zero-Copy `qmFinancials` BSON Decoder (`M2.2k`)
`src/bson_qm_financials.rs` (tested in `src/bson_qm_financials_tests.rs`) decodes raw `qmFinancials` / `qmFinancials-old` MongoDB BSON documents without allocating a `bson::Document`, emitting `FinancialObservation<&str>` rows (key borrowed verbatim from the input BSON slice; owned `currency` allocated only on emission) through `decode_qm_financials_doc`, `decode_qm_financials_bytes`, and `decode_qm_financials_buffer`:
- **Unverified live schema (explicit caller configuration):** Only the four repo-evidenced top-level field names have defaults (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`). Live inner field names under `BalanceSheet`, `CashFlow`, and `IncomeStatement`, the currency path, `reportPeriod` token strings, and date BSON types are **unverified against a live dump**, so `QmFinancialsFieldNames::with_verified_defaults(currency, revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding)` requires callers to explicitly supply the dotted `currency` path and an `Option<&str>` choice (`Some(path)` or intentional `None` opt-out) for all six `FundamentalsFields` metrics, alongside `QmFinancialsFiscalPeriod` (`ByTokens { quarterly, annual }` or `Fixed(FiscalPeriod)`). Empty paths, empty/blank dotted segments, blank tokens, and overlapping token lists fail closed before decoding.
- **Fail-closed dates, periods & BSON framing:** Every document is structurally validated (nested documents/arrays/JS-with-scope up to depth `128`) before semantic skips run so corrupt BSON always returns `Err(BsonQmFinancialsError::CorruptBson)` with the failing byte offset (in buffer mode, callbacks may have already fired for earlier valid documents). `periodEndDate` (required) and `reportDate` (optional) accept BSON `DateTime` (UTC epoch day) or strict `YYYY-MM-DD` strings within `MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE`; only an absent or BSON `Null` `reportDate` emits `None` (present-but-invalid vintage dates skip the document rather than silently dropping the vintage). Numeric paths accept `Double`, `Int32`, `Int64`, and trimmed numeric strings (`f64`), counting missing paths, wrong types, unparsable strings, and non-finite values on emitted rows while leaving unconfigured (`None`) paths and BSON `Null` leaves uncounted.
- **Accounting invariant & ownership boundary:** `BsonQmFinancialsDecodeStats` satisfies `docs_in == rows_out + skipped_total()`. QuoteMedia owns the source statement inputs; `build_fundamentals_rows` owns filing linkage and `known_at` derivation, while this decoder preserves the supplied `report_date` vintage and `currency`. Chunked streaming (`bson_stream`), file-to-file runner, and CLI wiring are deferred to follow-up tasks.
## `run_curate_fundamentals` File-to-File Runner (`M2.2m`)
`run_curate_fundamentals` / `run_curate_fundamentals_with_readers` (`src/run_curate_fundamentals.rs`) connects concatenated raw BSON `qmFinancials` and `qmFilings` dump files, a headerless 5-column `provider_mapping.tsv`, and a headerless 2-column `listing_venues.tsv` through `decode_qm_financials_chunks` / `decode_qm_filings_chunks` (`src/bson_stream.rs`) and `curate_and_write_fundamentals` into `<out_dir>/fundamentals_pit/year=YYYY/part.parquet` (Zstd Parquet):
- **Explicit field paths & fiscal policy (no unverified defaults):** `CurateFundamentalsArgs::with_verified_defaults(...)` populates only the four verified `qmFinancials` defaults (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`), the two verified `qmFilings` defaults (`symbol`, `timefiled`), and `mapping_source = "qm"`. Callers must explicitly supply the `currency` path, all six numeric metric `Option<String>` paths, `CurateFundamentalsFiscalPeriod` (`Fixed(FiscalPeriod)` or `ByTokens { quarterly, annual }`), `filings_form_type_field`, and snapshot period limit `k >= 1`.
- **`listing_venues.tsv` format (`load_listing_venues_tsv`):** strict headerless 2-column tab-separated file `listing_id<TAB>venue`, where `listing_id` is a strictly positive ASCII base-10 integer and `venue` is exact `us_tsx` (`StatutoryLagVenue::UsTsx`) or `tsxv_cse` (`StatutoryLagVenue::TsxvCse`). Wrong column counts, non-integer/non-positive IDs, unknown venues, duplicate IDs, and interior blank lines fail closed with a single-line error naming the path and 1-based line number.
- **Fail-closed & zero-row behavior:** Config validation, output/input path alias checks (including existing `year=YYYY` partition targets), TSV loading, and both BSON stream decodes complete before `curate_and_write_fundamentals` runs. Empty or all-unmapped inputs return `Ok` with `rows_written == 0` without creating `<out_dir>/fundamentals_pit` or modifying pre-existing partitions. CLI wiring (`curate-fundamentals`) is a separate follow-up.
## Lagged Macro Regime Series Builder (`M2.2n`)
`build_macro_rows` (`src/macro_series.rs`, tested in `src/macro_series_tests.rs`) is a pure, in-memory builder turning `MacroObservation<K>` inputs and a caller-supplied `(country_iso, indicator) -> Option<MacroLagClass>` lookup into sorted, unique `MacroRow<K>` records matching `macro/part.parquet` in `design/DATA-CONTRACTS.md` (§1 and §3A).
- **Governance & provenance:** Quant Research owns the coarse regime-use policy; the caller owns the explicit `(country_iso, indicator)` lag mapping. TradingEconomics indicator names are **not** hardcoded because live `teIndicators` / `teData` names are unverified in this crate. Because `teData` carries final-revised `{d, v}` values without verified release dates or historical vintages, availability starts strictly at `known_at` (`00:00:00 UTC` of `period_date + lag_days`), tagged `known_at_source = "publication_lag_estimate"` (`MACRO_KNOWN_AT_SOURCE`).
- **Locked lag classes (`MacroLagClass`):** `PolicyRate` (`+1d`, `POLICY_RATE_LAG_DAYS`), `MonthlyRelease` (`+35d`, `MONTHLY_RELEASE_LAG_DAYS`), `Gdp65` (`+65d`, `GDP65_LAG_DAYS`), and `Gdp90` (`+90d`, `GDP90_LAG_DAYS`).
- **Fail-closed filtering, deduplication & overflow:** Unmapped `(country_iso, indicator)` pairs are skipped first (`skipped_unmapped_indicator`) and never given a default lag; non-finite values on mapped pairs are skipped (`skipped_non_finite_value`). Surviving rows are sorted by `(country_iso, indicator, period_date)`; bitwise-identical (`f64::to_bits()`) duplicates collapse (`skipped_duplicate`), while conflicting values (including `+0.0` vs. `-0.0`) return `MacroError::ConflictingDuplicate`. Checked `i32` date addition and `i64` microsecond scaling return `MacroError::KnownAtOverflow` rather than panicking. `MacroBuildStats` satisfies `input == emitted + skipped_unmapped_indicator + skipped_non_finite_value + skipped_duplicate`.
- **Parquet writer (`M2.2o`) & deferred items:** `write_macro_dataset` (`src/parquet_macro.rs`, tested in `src/parquet_macro_tests.rs`) writes `MacroParquetRow` (via `From<&MacroRow<K>>`) atomically to `<out_dir>/macro/part.parquet` (6-column Zstd contract schema); deferred: file-to-file runner, CLI command, `macroAsOf` DuckDB reader, and live MongoDB access.
## Zero-Copy `teData` BSON Decoder (`M2.2p`)
`src/bson_te_data.rs` (tested in `src/bson_te_data_tests.rs`) decodes raw `teData` MongoDB BSON documents in a single forward pass without allocating a `bson::Document` or per-point heap memory, emitting borrowed `TeDataPoint<'a>` views through `decode_te_data_doc`, `decode_te_data_bytes`, and `decode_te_data_buffer`.
- **History-only (zero forecast leakage):** Reads only `data` (`[{ d: "YYYY-MM-DD", v: number }]`) and skips `forecast`, descriptive metadata, timestamps, and unknown fields without calling `elem.value()`.
- **Writer-derived schema & no hardcoded mappings:** Field names (`teSymbol`, `country`, `category`, `data`, `forecast`, `d`, `v`) come from `apps/stock/data-ingestion/src/handlers/te/actions/data-fetch.action.ts` and are not verified against a live `mongodump`. Provider `te_symbol`, `country`, and `category` strings are preserved verbatim; downstream runners own country/indicator/lag mapping into `build_macro_rows`.
- **Fail-closed accounting:** Rejects missing/empty/non-string `teSymbol`, `country`, or `category`, and missing/non-array `data` before emitting any point; rejects malformed/non-string `d` and non-numeric `v` per point while passing finite and non-finite `Double` values through unchanged. `BsonTeDataDecodeStats` maintains `docs_in == docs_accepted + docs_rejected_total()` and `points_in == points_decoded + rejected_total()`.
## Pure `macro` Curation Stage (`M2.2q`)
`curate_macro` and `curate_and_write_macro` (`src/curate_macro.rs`, tested in `src/curate_macro_tests.rs`) join decoded `TeDataPoint<'a>` records, `build_macro_rows`, and `write_macro_dataset` into atomically published `<out_dir>/macro/part.parquet`:
- **Explicit caller-supplied series map:** Maps verbatim `(te_symbol, country, category)` triples to `Option<MacroSeriesTarget { country_iso, indicator, lag_class }>`; unmapped points are dropped into `dropped_unmapped_series` with no default lag, and conflicting lag classes targeting the same `(country_iso, indicator)` fail closed with `CurateMacroError::ConflictingLagClass` independent of input order before writing.
- **Delegated builder & atomic publish:** Delegates filtering, sorting, deduplication, and `known_at` calculation unchanged to `build_macro_rows`, emits strictly ascending unique `MacroParquetRow`s with reconciling `CurateMacroStats` (`points_in == dropped_unmapped_series + builder.input`, `rows_out == builder.emitted`), and leaves `<out_dir>/macro/part.parquet` untouched on empty/all-unmapped input or any curation error.

View file

@ -0,0 +1,949 @@
//! Zero-copy raw BSON decoder for MongoDB `qmFinancials` (and `qmFinancials-old`) documents (`M2.2k`).
//!
//! Decodes `&bson::RawDocument` slices without allocating a `bson::Document`, emitting
//! [`FinancialObservation<&str>`] rows (borrowing `key` verbatim from the input BSON slice and
//! allocating the owned `currency: String` only when a row is emitted) via a caller-supplied
//! callback.
//!
//! # Unverified Live Schema & Caller-Supplied Paths
//!
//! QuoteMedia owns the source statement inputs; the existing builder
//! ([`crate::fundamentals::build_fundamentals_rows`]) owns filing linkage and `known_at`
//! derivation, while this decoder preserves the supplied `report_date` vintage and `currency`.
//!
//! Field defaults are restricted strictly to names established by in-repo evidence
//! (`apps/stock/data-ingestion/src/handlers/qm/actions/financials.action.ts` and
//! `design/DATA-CONTRACTS.md` §1):
//! - Verified defaults: `key = "qmSearchCode"` ([`DEFAULT_QM_FINANCIALS_KEY_FIELD`]),
//! `period_end = "periodEndDate"` ([`DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD`]),
//! `report_date = "reportDate"` ([`DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD`]),
//! `report_period = "reportPeriod"` ([`DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD`]).
//! - **Unverified against a live dump:** the inner field names under `BalanceSheet`, `CashFlow`,
//! and `IncomeStatement`, the currency field path, the exact `reportPeriod` token strings, and
//! the live MongoDB BSON types of `periodEndDate` / `reportDate` have **not** been verified
//! against a live `qmFinancials` dump. Callers must therefore explicitly supply:
//! - `currency` path and each of the six numeric value paths (`Option<&str>`, dotted paths such
//! as `"IncomeStatement.totalRevenue"` or `None` to leave a field unconfigured) in
//! [`QmFinancialsFieldNames`];
//! - [`QmFinancialsFiscalPeriod`] (`ByTokens` with explicit quarterly/annual string lists, or
//! `Fixed` for a caller-known uniform input).
//!
//! # Decoding & Validation Rules
//! - Every element and nested subdocument/array/JS-with-scope (up to depth `128`) of each
//! [`RawDocument`] is structurally validated to completion before semantic skip checks run, so
//! structural BSON corruption always returns `Err(BsonQmFinancialsError::CorruptBson)` rather
//! than being masked by an earlier semantic skip.
//! - Deterministic semantic skip priority:
//! `key` → `period_end` → `fiscal_period` (`report_period`) → `report_date` → `currency`.
//! - `key` and `currency`: required non-blank UTF-8 BSON `String`s passed verbatim (no trimming).
//! Missing, wrong-typed (including non-document intermediate segments), or blank values skip the
//! document under their respective counters.
//! - `period_end`: required BSON `DateTime` (UTC epoch day via
//! `timestamp_millis().div_euclid(86_400_000)` with checked `i32` conversion) or strict
//! `YYYY-MM-DD` UTF-8 BSON `String`, validated inclusively against
//! [`MIN_SUPPORTED_DATE`]..=[`MAX_SUPPORTED_DATE`] (`2008-01-01..=2030-12-31`).
//! - `fiscal_period`: under [`QmFinancialsFiscalPeriod::ByTokens`], `report_period` must be a
//! UTF-8 `String` matching an exact configured quarterly or annual token; missing, wrong-typed,
//! or unmapped values skip the document (fail closed). Under
//! [`QmFinancialsFiscalPeriod::Fixed`], the supplied [`FiscalPeriod`] is used without consulting
//! `fields.report_period`.
//! - `report_date` (**point-in-time vintage guard, fail closed**): only an absent path (or null
//! intermediate) or BSON `Null` emits `None`. A present but wrong-typed, malformed/blank, or
//! out-of-range `report_date` skips the document rather than silently dropping a vintage date.
//! - Numeric fields (`FundamentalsFields`): decoded only on rows that pass all skip checks.
//! Unconfigured (`None`) paths emit `None` without incrementing any null counter. Configured
//! (`Some(path)`) paths accept BSON `Double`, `Int32`, `Int64`, and UTF-8 `String`s parsed as
//! finite `f64` (trimmed before parsing); BSON `Null` emits `None` cleanly. Missing paths
//! (including missing or null intermediate subdocuments), wrong types (including non-document
//! intermediates), unparsable strings, and non-finite doubles/strings emit `None` and increment
//! `nulled_missing_path`, `nulled_wrong_type`, `nulled_unparsable_string`, or
//! `nulled_non_finite` respectively.
//! - Buffer error semantics: if [`decode_qm_financials_buffer`] encounters a framing or BSON
//! corruption error after one or more valid documents, `on_row` has already been invoked for
//! those earlier valid documents and the error carries the failing document's byte offset.
//! - Conservation invariant on [`BsonQmFinancialsDecodeStats`]:
//! `docs_in == rows_out + skipped_total()`.
use std::error::Error;
use std::fmt;
use bson::raw::{RawBsonRef, RawDocument};
use crate::bson_eod_prices::{
iter_raw_bson_docs, parse_single_raw_doc, parse_ymd_strict_days, BsonEodPriceError,
MILLIS_PER_DAY,
};
use crate::fundamentals::{FinancialObservation, FiscalPeriod, FundamentalsFields};
use crate::shorts::{MAX_SUPPORTED_DATE, MIN_SUPPORTED_DATE};
/// Verified default BSON field name for the `qmFinancials` security key (`financials.action.ts`).
pub const DEFAULT_QM_FINANCIALS_KEY_FIELD: &str = "qmSearchCode";
/// Verified default BSON field name for `qmFinancials.periodEndDate` (`design/DATA-CONTRACTS.md` §1).
pub const DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD: &str = "periodEndDate";
/// Verified default BSON field name for `qmFinancials.reportDate` (`financials.action.ts`, `DATA-CONTRACTS.md` §1).
pub const DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD: &str = "reportDate";
/// Verified default BSON field name for `qmFinancials.reportPeriod` (`financials.action.ts`).
pub const DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD: &str = "reportPeriod";
/// Borrowed dotted BSON field-path configuration for decoding `qmFinancials` documents.
///
/// Intentionally has no `Default`: live inner field names under `BalanceSheet`, `CashFlow`, and
/// `IncomeStatement` and the currency path are unverified against a live dump. Use
/// [`Self::with_verified_defaults`] to populate only the four repo-evidenced top-level defaults
/// while explicitly supplying `currency` and an `Option<&str>` choice for each of the six numeric
/// value paths.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct QmFinancialsFieldNames<'a> {
pub key: &'a str,
pub period_end: &'a str,
pub report_date: &'a str,
pub report_period: &'a str,
pub currency: &'a str,
pub revenue: Option<&'a str>,
pub net_income: Option<&'a str>,
pub operating_cash_flow: Option<&'a str>,
pub total_assets: Option<&'a str>,
pub total_equity: Option<&'a str>,
pub shares_outstanding: Option<&'a str>,
}
impl<'a> QmFinancialsFieldNames<'a> {
/// Constructs a configuration pre-populated with the four repo-evidenced defaults
/// (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`) while requiring the caller
/// to explicitly supply the `currency` path and an `Option<&str>` choice (`Some(path)` or
/// intentional `None` opt-out) for each of the six numeric value fields.
#[inline]
pub const fn with_verified_defaults(
currency: &'a str,
revenue: Option<&'a str>,
net_income: Option<&'a str>,
operating_cash_flow: Option<&'a str>,
total_assets: Option<&'a str>,
total_equity: Option<&'a str>,
shares_outstanding: Option<&'a str>,
) -> Self {
Self {
key: DEFAULT_QM_FINANCIALS_KEY_FIELD,
period_end: DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD,
report_date: DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD,
report_period: DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD,
currency,
revenue,
net_income,
operating_cash_flow,
total_assets,
total_equity,
shares_outstanding,
}
}
/// Validates that every configured dotted field path is non-empty/non-blank and contains no
/// empty or whitespace-only segments (rejecting leading, trailing, or consecutive dots).
pub fn validate(&self) -> Result<(), BsonQmFinancialsError> {
let roles: [(&'static str, Option<&str>); 11] = [
("key", Some(self.key)),
("period_end", Some(self.period_end)),
("report_date", Some(self.report_date)),
("report_period", Some(self.report_period)),
("currency", Some(self.currency)),
("revenue", self.revenue),
("net_income", self.net_income),
("operating_cash_flow", self.operating_cash_flow),
("total_assets", self.total_assets),
("total_equity", self.total_equity),
("shares_outstanding", self.shares_outstanding),
];
for &(role, path_opt) in &roles {
if let Some(path) = path_opt {
validate_dotted_path(role, path)?;
}
}
Ok(())
}
}
fn validate_dotted_path(role: &'static str, path: &str) -> Result<(), BsonQmFinancialsError> {
if path.is_empty() || path.trim().is_empty() {
return Err(BsonQmFinancialsError::InvalidFieldNames {
detail: format!("field path for '{role}' must not be empty or blank"),
});
}
for segment in path.split('.') {
if segment.is_empty() || segment.trim().is_empty() {
return Err(BsonQmFinancialsError::InvalidFieldNames {
detail: format!(
"field path '{path}' for '{role}' contains an empty or blank segment"
),
});
}
}
Ok(())
}
/// Explicit fiscal-period resolution policy for `qmFinancials` documents.
///
/// Intentionally has no `Default`: the live `reportPeriod` token strings in MongoDB are
/// unverified in the repository, so callers must either supply explicit token lists or a fixed
/// [`FiscalPeriod`] override for a caller-known uniform input.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QmFinancialsFiscalPeriod<'a> {
/// Map exact UTF-8 BSON `String` values of `fields.report_period` against caller-supplied
/// quarterly and annual token slices. Missing, wrong-typed, or unmapped values skip the
/// document (fail closed).
ByTokens {
quarterly: &'a [&'a str],
annual: &'a [&'a str],
},
/// Assign a fixed [`FiscalPeriod`] to every decoded document without consulting
/// `fields.report_period`.
Fixed(FiscalPeriod),
}
impl<'a> QmFinancialsFiscalPeriod<'a> {
/// Validates token-mode configuration, rejecting empty/blank tokens and any token present in
/// both `quarterly` and `annual`.
pub fn validate(&self) -> Result<(), BsonQmFinancialsError> {
match *self {
Self::Fixed(_) => Ok(()),
Self::ByTokens { quarterly, annual } => {
for &tok in quarterly {
if tok.is_empty() || tok.trim().is_empty() {
return Err(BsonQmFinancialsError::InvalidFiscalPeriodConfig {
detail: "quarterly report_period token must not be empty or blank"
.to_string(),
});
}
}
for &tok in annual {
if tok.is_empty() || tok.trim().is_empty() {
return Err(BsonQmFinancialsError::InvalidFiscalPeriodConfig {
detail: "annual report_period token must not be empty or blank"
.to_string(),
});
}
}
for &q_tok in quarterly {
if annual.contains(&q_tok) {
return Err(BsonQmFinancialsError::InvalidFiscalPeriodConfig {
detail: format!(
"report_period token '{q_tok}' cannot appear in both quarterly and annual lists"
),
});
}
}
Ok(())
}
}
}
}
/// Typed errors returned while validating configuration or decoding raw `qmFinancials` BSON.
///
/// Structural BSON framing or element errors fail closed and carry a `u64` byte offset;
/// every variant's `Display` output is a single line.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BsonQmFinancialsError {
/// Invalid [`QmFinancialsFieldNames`] configuration (empty/blank path or segment).
InvalidFieldNames { detail: String },
/// Invalid [`QmFinancialsFiscalPeriod`] configuration (blank token or overlapping token lists).
InvalidFiscalPeriodConfig { detail: String },
/// Buffer ended before a complete 4-byte length prefix or declared document body.
TruncatedDocument {
offset: u64,
remaining: usize,
declared_len: Option<i32>,
},
/// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single
/// document slice).
CorruptDocumentLength { offset: u64, declared_len: i32 },
/// Underlying BSON framing or element bytes were malformed.
CorruptBson { offset: u64, detail: String },
}
impl fmt::Display for BsonQmFinancialsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidFieldNames { detail } => {
write!(f, "invalid qmFinancials field configuration: {detail}")
}
Self::InvalidFiscalPeriodConfig { detail } => {
write!(
f,
"invalid qmFinancials fiscal period configuration: {detail}"
)
}
Self::TruncatedDocument {
offset,
remaining,
declared_len,
} => match declared_len {
Some(len) => write!(
f,
"truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes"
),
None => write!(
f,
"truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining"
),
},
Self::CorruptDocumentLength {
offset,
declared_len,
} => write!(
f,
"corrupt BSON document length {declared_len} at byte offset {offset}"
),
Self::CorruptBson { offset, detail } => {
write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}")
}
}
}
}
impl Error for BsonQmFinancialsError {}
#[inline]
fn map_framing_error(err: BsonEodPriceError) -> BsonQmFinancialsError {
match err {
BsonEodPriceError::TruncatedDocument {
offset,
remaining,
declared_len,
} => BsonQmFinancialsError::TruncatedDocument {
offset: offset as u64,
remaining,
declared_len,
},
BsonEodPriceError::CorruptDocumentLength {
offset,
declared_len,
} => BsonQmFinancialsError::CorruptDocumentLength {
offset: offset as u64,
declared_len,
},
BsonEodPriceError::CorruptBson { offset, detail } => BsonQmFinancialsError::CorruptBson {
offset: offset as u64,
detail,
},
other => BsonQmFinancialsError::CorruptBson {
offset: 0,
detail: other.to_string(),
},
}
}
/// Per-batch decode accounting for `qmFinancials`.
///
/// Conservation invariant:
/// `docs_in == rows_out + skipped_total()`
///
/// Numeric null counters (`nulled_missing_path`, `nulled_wrong_type`,
/// `nulled_unparsable_string`, `nulled_non_finite`) are incremented only on emitted rows and are
/// excluded from [`Self::skipped_total`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct BsonQmFinancialsDecodeStats {
pub docs_in: usize,
pub rows_out: usize,
pub skipped_missing_key: usize,
pub skipped_wrong_key_type: usize,
pub skipped_empty_key: usize,
pub skipped_missing_period_end: usize,
pub skipped_wrong_period_end_type: usize,
pub skipped_invalid_period_end: usize,
pub skipped_period_end_out_of_range: usize,
pub skipped_missing_report_period: usize,
pub skipped_wrong_report_period_type: usize,
pub skipped_unmapped_report_period: usize,
pub skipped_wrong_report_date_type: usize,
pub skipped_invalid_report_date: usize,
pub skipped_report_date_out_of_range: usize,
pub skipped_missing_currency: usize,
pub skipped_wrong_currency_type: usize,
pub skipped_empty_currency: usize,
pub nulled_missing_path: usize,
pub nulled_wrong_type: usize,
pub nulled_unparsable_string: usize,
pub nulled_non_finite: usize,
}
impl BsonQmFinancialsDecodeStats {
/// Total number of semantically skipped `qmFinancials` documents across all skip categories.
#[inline]
pub fn skipped_total(&self) -> usize {
self.skipped_missing_key
+ self.skipped_wrong_key_type
+ self.skipped_empty_key
+ self.skipped_missing_period_end
+ self.skipped_wrong_period_end_type
+ self.skipped_invalid_period_end
+ self.skipped_period_end_out_of_range
+ self.skipped_missing_report_period
+ self.skipped_wrong_report_period_type
+ self.skipped_unmapped_report_period
+ self.skipped_wrong_report_date_type
+ self.skipped_invalid_report_date
+ self.skipped_report_date_out_of_range
+ self.skipped_missing_currency
+ self.skipped_wrong_currency_type
+ self.skipped_empty_currency
}
/// Accumulates counters from another batch into `self`.
#[inline]
pub fn merge(&mut self, other: &Self) {
self.docs_in += other.docs_in;
self.rows_out += other.rows_out;
self.skipped_missing_key += other.skipped_missing_key;
self.skipped_wrong_key_type += other.skipped_wrong_key_type;
self.skipped_empty_key += other.skipped_empty_key;
self.skipped_missing_period_end += other.skipped_missing_period_end;
self.skipped_wrong_period_end_type += other.skipped_wrong_period_end_type;
self.skipped_invalid_period_end += other.skipped_invalid_period_end;
self.skipped_period_end_out_of_range += other.skipped_period_end_out_of_range;
self.skipped_missing_report_period += other.skipped_missing_report_period;
self.skipped_wrong_report_period_type += other.skipped_wrong_report_period_type;
self.skipped_unmapped_report_period += other.skipped_unmapped_report_period;
self.skipped_wrong_report_date_type += other.skipped_wrong_report_date_type;
self.skipped_invalid_report_date += other.skipped_invalid_report_date;
self.skipped_report_date_out_of_range += other.skipped_report_date_out_of_range;
self.skipped_missing_currency += other.skipped_missing_currency;
self.skipped_wrong_currency_type += other.skipped_wrong_currency_type;
self.skipped_empty_currency += other.skipped_empty_currency;
self.nulled_missing_path += other.nulled_missing_path;
self.nulled_wrong_type += other.nulled_wrong_type;
self.nulled_unparsable_string += other.nulled_unparsable_string;
self.nulled_non_finite += other.nulled_non_finite;
}
}
impl std::ops::AddAssign for BsonQmFinancialsDecodeStats {
#[inline]
fn add_assign(&mut self, rhs: Self) {
self.merge(&rhs);
}
}
/// Maximum recursive nesting depth accepted while validating raw BSON documents and arrays.
const MAX_BSON_VALIDATION_DEPTH: usize = 128;
#[inline]
fn is_exact_array_index(key: &str, expected: usize) -> bool {
let bytes = key.as_bytes();
if bytes.is_empty() || (bytes.len() > 1 && bytes[0] == b'0') {
return false;
}
let mut parsed: usize = 0;
for &b in bytes {
if !b.is_ascii_digit() {
return false;
}
let digit = usize::from(b - b'0');
match parsed.checked_mul(10).and_then(|n| n.checked_add(digit)) {
Some(next) => parsed = next,
None => return false,
}
}
parsed == expected
}
fn validate_raw_bson_value(
val: RawBsonRef<'_>,
doc_offset: u64,
field_name: &str,
depth: usize,
) -> Result<(), BsonQmFinancialsError> {
match val {
RawBsonRef::Document(subdoc) => {
validate_raw_document(subdoc, doc_offset, field_name, depth + 1)
}
RawBsonRef::Array(arr) => {
if depth >= MAX_BSON_VALIDATION_DEPTH {
return Err(BsonQmFinancialsError::CorruptBson {
offset: doc_offset,
detail: format!(
"field '{field_name}': nested BSON depth exceeds limit {MAX_BSON_VALIDATION_DEPTH}"
),
});
}
for (expected_idx, elem_res) in arr.iter_elements().enumerate() {
let elem = elem_res.map_err(|err| BsonQmFinancialsError::CorruptBson {
offset: doc_offset,
detail: format!("field '{field_name}': {err}"),
})?;
let key = elem.key().as_str();
if !is_exact_array_index(key, expected_idx) {
return Err(BsonQmFinancialsError::CorruptBson {
offset: doc_offset,
detail: format!(
"field '{field_name}': invalid BSON array index '{key}' at position {expected_idx}"
),
});
}
let item = elem
.value()
.map_err(|err| BsonQmFinancialsError::CorruptBson {
offset: doc_offset,
detail: format!("field '{field_name}': {err}"),
})?;
validate_raw_bson_value(item, doc_offset, field_name, depth + 1)?;
}
Ok(())
}
RawBsonRef::JavaScriptCodeWithScope(code_with_scope) => {
validate_raw_document(code_with_scope.scope, doc_offset, field_name, depth + 1)
}
_ => Ok(()),
}
}
fn validate_raw_document(
doc: &RawDocument,
doc_offset: u64,
field_name: &str,
depth: usize,
) -> Result<(), BsonQmFinancialsError> {
if depth > MAX_BSON_VALIDATION_DEPTH {
return Err(BsonQmFinancialsError::CorruptBson {
offset: doc_offset,
detail: format!(
"field '{field_name}': nested BSON depth exceeds limit {MAX_BSON_VALIDATION_DEPTH}"
),
});
}
for elem_res in doc.iter_elements() {
let elem = elem_res.map_err(|err| BsonQmFinancialsError::CorruptBson {
offset: doc_offset,
detail: format!("field '{field_name}': {err}"),
})?;
let val = elem
.value()
.map_err(|err| BsonQmFinancialsError::CorruptBson {
offset: doc_offset,
detail: format!("field '{field_name}': {err}"),
})?;
validate_raw_bson_value(val, doc_offset, field_name, depth)?;
}
Ok(())
}
fn validate_top_level_document(
doc: &RawDocument,
doc_offset: u64,
) -> Result<(), BsonQmFinancialsError> {
for elem_res in doc.iter_elements() {
let elem = elem_res.map_err(|err| BsonQmFinancialsError::CorruptBson {
offset: doc_offset,
detail: err.to_string(),
})?;
let name = elem.key().as_str();
let val = elem
.value()
.map_err(|err| BsonQmFinancialsError::CorruptBson {
offset: doc_offset,
detail: format!("field '{name}': {err}"),
})?;
validate_raw_bson_value(val, doc_offset, name, 0)?;
}
Ok(())
}
enum PathLookup<'a> {
Found(RawBsonRef<'a>),
Missing,
NonDocumentIntermediate,
}
fn lookup_dotted_path<'a>(
doc: &'a RawDocument,
path: &str,
doc_offset: u64,
) -> Result<PathLookup<'a>, BsonQmFinancialsError> {
let mut current_doc = doc;
let mut segments = path.split('.').peekable();
while let Some(seg) = segments.next() {
let is_last = segments.peek().is_none();
let mut matched: Option<RawBsonRef<'a>> = None;
for elem_res in current_doc.iter_elements() {
let elem = elem_res.map_err(|err| BsonQmFinancialsError::CorruptBson {
offset: doc_offset,
detail: err.to_string(),
})?;
if elem.key().as_str() == seg {
let val = elem
.value()
.map_err(|err| BsonQmFinancialsError::CorruptBson {
offset: doc_offset,
detail: format!("field '{path}': {err}"),
})?;
matched = Some(val);
}
}
let Some(val) = matched else {
return Ok(PathLookup::Missing);
};
if is_last {
return Ok(PathLookup::Found(val));
}
match val {
RawBsonRef::Document(subdoc) => {
current_doc = subdoc;
}
RawBsonRef::Null => return Ok(PathLookup::Missing),
_ => return Ok(PathLookup::NonDocumentIntermediate),
}
}
Ok(PathLookup::Missing)
}
#[inline]
fn is_supported_date(epoch_day: i32) -> bool {
(MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE).contains(&epoch_day)
}
enum DateParseResult {
Valid(i32),
WrongType,
Invalid,
OutOfRange,
}
#[inline]
fn decode_date_value(val: RawBsonRef<'_>) -> DateParseResult {
match val {
RawBsonRef::DateTime(dt) => {
let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY);
match i32::try_from(days) {
Ok(d) if is_supported_date(d) => DateParseResult::Valid(d),
_ => DateParseResult::OutOfRange,
}
}
RawBsonRef::String(s) => match parse_ymd_strict_days(s) {
Some(d) if is_supported_date(d) => DateParseResult::Valid(d),
Some(_) => DateParseResult::OutOfRange,
None => DateParseResult::Invalid,
},
_ => DateParseResult::WrongType,
}
}
fn decode_numeric_field(
doc: &RawDocument,
path_opt: Option<&str>,
doc_offset: u64,
stats: &mut BsonQmFinancialsDecodeStats,
) -> Result<Option<f64>, BsonQmFinancialsError> {
let Some(path) = path_opt else {
return Ok(None);
};
match lookup_dotted_path(doc, path, doc_offset)? {
PathLookup::Missing => {
stats.nulled_missing_path += 1;
Ok(None)
}
PathLookup::NonDocumentIntermediate => {
stats.nulled_wrong_type += 1;
Ok(None)
}
PathLookup::Found(val) => match val {
RawBsonRef::Null => Ok(None),
RawBsonRef::Double(v) => {
if v.is_finite() {
Ok(Some(v))
} else {
stats.nulled_non_finite += 1;
Ok(None)
}
}
RawBsonRef::Int32(v) => Ok(Some(f64::from(v))),
RawBsonRef::Int64(v) => Ok(Some(v as f64)),
RawBsonRef::String(s) => {
let trimmed = s.trim();
match trimmed.parse::<f64>() {
Ok(v) if v.is_finite() => Ok(Some(v)),
Ok(_) => {
stats.nulled_non_finite += 1;
Ok(None)
}
Err(_) => {
stats.nulled_unparsable_string += 1;
Ok(None)
}
}
}
_ => {
stats.nulled_wrong_type += 1;
Ok(None)
}
},
}
}
fn decode_qm_financials_doc_at<'a, F>(
doc: &'a RawDocument,
doc_offset: u64,
fields: &QmFinancialsFieldNames<'_>,
fiscal_period_cfg: QmFinancialsFiscalPeriod<'_>,
mut on_row: F,
) -> Result<BsonQmFinancialsDecodeStats, BsonQmFinancialsError>
where
F: FnMut(FinancialObservation<&'a str>),
{
// Validate the entire raw document structurally first so BSON corruption always returns
// `Err(BsonQmFinancialsError::CorruptBson)` rather than being masked by a semantic skip.
validate_top_level_document(doc, doc_offset)?;
let mut stats = BsonQmFinancialsDecodeStats {
docs_in: 1,
..BsonQmFinancialsDecodeStats::default()
};
// 1. Key (required non-blank UTF-8 string, borrowed verbatim).
let key = match lookup_dotted_path(doc, fields.key, doc_offset)? {
PathLookup::Missing => {
stats.skipped_missing_key += 1;
return Ok(stats);
}
PathLookup::NonDocumentIntermediate => {
stats.skipped_wrong_key_type += 1;
return Ok(stats);
}
PathLookup::Found(RawBsonRef::String(s)) => {
if s.trim().is_empty() {
stats.skipped_empty_key += 1;
return Ok(stats);
}
s
}
PathLookup::Found(_) => {
stats.skipped_wrong_key_type += 1;
return Ok(stats);
}
};
// 2. Period end date (required DateTime or strict YYYY-MM-DD within supported calendar bounds).
let period_end = match lookup_dotted_path(doc, fields.period_end, doc_offset)? {
PathLookup::Missing => {
stats.skipped_missing_period_end += 1;
return Ok(stats);
}
PathLookup::NonDocumentIntermediate => {
stats.skipped_wrong_period_end_type += 1;
return Ok(stats);
}
PathLookup::Found(val) => match decode_date_value(val) {
DateParseResult::Valid(d) => d,
DateParseResult::WrongType => {
stats.skipped_wrong_period_end_type += 1;
return Ok(stats);
}
DateParseResult::Invalid => {
stats.skipped_invalid_period_end += 1;
return Ok(stats);
}
DateParseResult::OutOfRange => {
stats.skipped_period_end_out_of_range += 1;
return Ok(stats);
}
},
};
// 3. Fiscal period (explicit token mapping or fixed override; fail closed in token mode).
let fiscal_period = match fiscal_period_cfg {
QmFinancialsFiscalPeriod::Fixed(fp) => fp,
QmFinancialsFiscalPeriod::ByTokens { quarterly, annual } => {
match lookup_dotted_path(doc, fields.report_period, doc_offset)? {
PathLookup::Missing => {
stats.skipped_missing_report_period += 1;
return Ok(stats);
}
PathLookup::NonDocumentIntermediate => {
stats.skipped_wrong_report_period_type += 1;
return Ok(stats);
}
PathLookup::Found(RawBsonRef::String(s)) => {
if quarterly.contains(&s) {
FiscalPeriod::Quarterly
} else if annual.contains(&s) {
FiscalPeriod::Annual
} else {
stats.skipped_unmapped_report_period += 1;
return Ok(stats);
}
}
PathLookup::Found(_) => {
stats.skipped_wrong_report_period_type += 1;
return Ok(stats);
}
}
}
};
// 4. Report date (optional vintage date: only absent or BSON Null -> None; invalid skips row).
let report_date = match lookup_dotted_path(doc, fields.report_date, doc_offset)? {
PathLookup::Missing => None,
PathLookup::NonDocumentIntermediate => {
stats.skipped_wrong_report_date_type += 1;
return Ok(stats);
}
PathLookup::Found(RawBsonRef::Null) => None,
PathLookup::Found(val) => match decode_date_value(val) {
DateParseResult::Valid(d) => Some(d),
DateParseResult::WrongType => {
stats.skipped_wrong_report_date_type += 1;
return Ok(stats);
}
DateParseResult::Invalid => {
stats.skipped_invalid_report_date += 1;
return Ok(stats);
}
DateParseResult::OutOfRange => {
stats.skipped_report_date_out_of_range += 1;
return Ok(stats);
}
},
};
// 5. Currency (required non-blank UTF-8 string; owned String allocated only on emission).
let currency_str = match lookup_dotted_path(doc, fields.currency, doc_offset)? {
PathLookup::Missing => {
stats.skipped_missing_currency += 1;
return Ok(stats);
}
PathLookup::NonDocumentIntermediate => {
stats.skipped_wrong_currency_type += 1;
return Ok(stats);
}
PathLookup::Found(RawBsonRef::String(s)) => {
if s.trim().is_empty() {
stats.skipped_empty_currency += 1;
return Ok(stats);
}
s
}
PathLookup::Found(_) => {
stats.skipped_wrong_currency_type += 1;
return Ok(stats);
}
};
// Row passed all skip checks: decode configured numeric statement fields and emit.
let statement_fields = FundamentalsFields {
revenue: decode_numeric_field(doc, fields.revenue, doc_offset, &mut stats)?,
net_income: decode_numeric_field(doc, fields.net_income, doc_offset, &mut stats)?,
operating_cash_flow: decode_numeric_field(
doc,
fields.operating_cash_flow,
doc_offset,
&mut stats,
)?,
total_assets: decode_numeric_field(doc, fields.total_assets, doc_offset, &mut stats)?,
total_equity: decode_numeric_field(doc, fields.total_equity, doc_offset, &mut stats)?,
shares_outstanding: decode_numeric_field(
doc,
fields.shares_outstanding,
doc_offset,
&mut stats,
)?,
};
stats.rows_out += 1;
on_row(FinancialObservation {
key,
period_end,
fiscal_period,
currency: currency_str.to_owned(),
report_date,
fields: statement_fields,
});
Ok(stats)
}
/// Decodes a single `&RawDocument` representing a `qmFinancials` MongoDB document without
/// allocating a `bson::Document`.
///
/// Validates `fields` and `fiscal_period` before inspecting the document.
pub fn decode_qm_financials_doc<'a, F>(
doc: &'a RawDocument,
fields: &QmFinancialsFieldNames<'_>,
fiscal_period: QmFinancialsFiscalPeriod<'_>,
on_row: F,
) -> Result<BsonQmFinancialsDecodeStats, BsonQmFinancialsError>
where
F: FnMut(FinancialObservation<&'a str>),
{
fields.validate()?;
fiscal_period.validate()?;
decode_qm_financials_doc_at(doc, 0, fields, fiscal_period, on_row)
}
/// Decodes a single length-prefixed raw BSON document byte slice representing a `qmFinancials`
/// document.
///
/// Validates `fields` and `fiscal_period` before inspecting the bytes.
pub fn decode_qm_financials_bytes<'a, F>(
bytes: &'a [u8],
fields: &QmFinancialsFieldNames<'_>,
fiscal_period: QmFinancialsFiscalPeriod<'_>,
on_row: F,
) -> Result<BsonQmFinancialsDecodeStats, BsonQmFinancialsError>
where
F: FnMut(FinancialObservation<&'a str>),
{
fields.validate()?;
fiscal_period.validate()?;
let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?;
decode_qm_financials_doc_at(doc, 0, fields, fiscal_period, on_row)
}
/// Streams a concatenated length-prefixed BSON buffer of `qmFinancials` documents through
/// [`decode_qm_financials_doc`], emitting every valid [`FinancialObservation<&str>`] to `on_row`
/// and failing closed on the first structural BSON framing or element corruption.
///
/// Validates `fields` and `fiscal_period` once before reading the buffer. If an error occurs after
/// one or more valid documents, `on_row` has already been invoked for those earlier documents and
/// the returned error reports the failing document's byte offset.
///
/// Always maintains `stats.docs_in == stats.rows_out + stats.skipped_total()`.
pub fn decode_qm_financials_buffer<'a, F>(
buf: &'a [u8],
fields: &QmFinancialsFieldNames<'_>,
fiscal_period: QmFinancialsFiscalPeriod<'_>,
mut on_row: F,
) -> Result<BsonQmFinancialsDecodeStats, BsonQmFinancialsError>
where
F: FnMut(FinancialObservation<&'a str>),
{
fields.validate()?;
fiscal_period.validate()?;
let mut total = BsonQmFinancialsDecodeStats::default();
let mut iter = iter_raw_bson_docs(buf);
while let Some(item) = iter.next_with_offset() {
match item {
Ok((offset, doc)) => {
let doc_stats = decode_qm_financials_doc_at(
doc,
offset as u64,
fields,
fiscal_period,
&mut on_row,
)?;
total += doc_stats;
}
Err((_, err)) => return Err(map_framing_error(err)),
}
}
Ok(total)
}
#[cfg(test)]
#[path = "bson_qm_financials_tests.rs"]
mod tests;

File diff suppressed because it is too large Load diff

View file

@ -44,6 +44,10 @@ use crate::bson_qm_events::{
BsonQmEventsError, BsonQmFilingsDecodeStats, QmEarningsFieldNames, QmFilingsFieldNames,
RawQmEarning, RawQmFiling,
};
use crate::bson_qm_financials::{
decode_qm_financials_buffer, BsonQmFinancialsDecodeStats, BsonQmFinancialsError,
QmFinancialsFieldNames, QmFinancialsFiscalPeriod,
};
use crate::bson_qm_intraday::{
decode_qm_intraday_buffer, BsonQmIntradayDecodeStats, BsonQmIntradayError, RawQmIntradayBar,
};
@ -53,6 +57,7 @@ use crate::bson_qm_prices::{
use crate::bson_te_market_data::{
decode_te_market_data_buffer, BsonTeMarketDataDecodeStats, BsonTeMarketDataError,
};
use crate::fundamentals::FinancialObservation;
use crate::fx::FxDailyBar;
use crate::posts::CeoPost;
use crate::shorts::CeoShortReport;
@ -1333,6 +1338,118 @@ where
decode_qm_earnings_chunks(&mut chunk_reader, fields, on_row)
}
/// Terminal error returned by [`decode_qm_financials_chunks`] and [`decode_qm_financials_stream`].
#[derive(Debug)]
pub enum BsonQmFinancialsStreamError {
Stream(BsonStreamError),
Decode(BsonQmFinancialsError),
}
impl fmt::Display for BsonQmFinancialsStreamError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Stream(err) => write!(f, "{err}"),
Self::Decode(err) => write!(f, "{err}"),
}
}
}
impl Error for BsonQmFinancialsStreamError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Stream(err) => Some(err),
Self::Decode(err) => Some(err),
}
}
}
impl From<BsonStreamError> for BsonQmFinancialsStreamError {
fn from(err: BsonStreamError) -> Self {
Self::Stream(err)
}
}
impl From<BsonQmFinancialsError> for BsonQmFinancialsStreamError {
fn from(err: BsonQmFinancialsError) -> Self {
Self::Decode(err)
}
}
#[inline]
fn rebase_qm_financials_error(base: u64, err: BsonQmFinancialsError) -> BsonQmFinancialsError {
match err {
BsonQmFinancialsError::TruncatedDocument {
offset,
remaining,
declared_len,
} => BsonQmFinancialsError::TruncatedDocument {
offset: base.saturating_add(offset),
remaining,
declared_len,
},
BsonQmFinancialsError::CorruptDocumentLength {
offset,
declared_len,
} => BsonQmFinancialsError::CorruptDocumentLength {
offset: base.saturating_add(offset),
declared_len,
},
BsonQmFinancialsError::CorruptBson { offset, detail } => {
BsonQmFinancialsError::CorruptBson {
offset: base.saturating_add(offset),
detail,
}
}
other => other,
}
}
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_financials_buffer`],
/// accumulating [`BsonQmFinancialsDecodeStats`] and rebasing structural BSON error offsets to
/// absolute stream byte offsets.
pub fn decode_qm_financials_chunks<R, F>(
reader: &mut RawBsonChunkReader<R>,
fields: &QmFinancialsFieldNames<'_>,
fiscal_period: QmFinancialsFiscalPeriod<'_>,
mut on_row: F,
) -> Result<BsonQmFinancialsDecodeStats, BsonQmFinancialsStreamError>
where
R: io::Read,
F: for<'a> FnMut(FinancialObservation<&'a str>),
{
fields.validate()?;
fiscal_period.validate()?;
let mut total = BsonQmFinancialsDecodeStats::default();
while let Some(chunk) = reader.next_chunk()? {
let base = chunk.start_offset;
let chunk_stats =
decode_qm_financials_buffer(chunk.bytes, fields, fiscal_period, &mut on_row).map_err(
|err| BsonQmFinancialsStreamError::Decode(rebase_qm_financials_error(base, err)),
)?;
total += chunk_stats;
}
Ok(total)
}
/// Streams a concatenated raw BSON `qmFinancials` [`std::io::Read`] source through
/// [`decode_qm_financials_buffer`] with bounded memory.
pub fn decode_qm_financials_stream<R, F>(
reader: R,
options: BsonStreamOptions,
fields: &QmFinancialsFieldNames<'_>,
fiscal_period: QmFinancialsFiscalPeriod<'_>,
on_row: F,
) -> Result<BsonQmFinancialsDecodeStats, BsonQmFinancialsStreamError>
where
R: io::Read,
F: for<'a> FnMut(FinancialObservation<&'a str>),
{
fields.validate()?;
fiscal_period.validate()?;
let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?;
decode_qm_financials_chunks(&mut chunk_reader, fields, fiscal_period, on_row)
}
#[cfg(test)]
#[path = "bson_stream_tests.rs"]
mod tests;

View file

@ -13,16 +13,22 @@ use crate::bson_eod_prices::{
use crate::bson_qm_actions::{
decode_qm_dividend_buffer, decode_qm_split_buffer, BsonQmActionDecodeStats,
};
use crate::bson_qm_financials::{
decode_qm_financials_buffer, BsonQmFinancialsDecodeStats, BsonQmFinancialsError,
QmFinancialsFieldNames, QmFinancialsFiscalPeriod,
};
use crate::bson_qm_intraday::{
decode_qm_intraday_buffer, BsonQmIntradayDecodeStats, BsonQmIntradayError,
};
use crate::bson_qm_prices::{decode_qm_price_buffer, BsonQmPriceError};
use crate::bson_stream::{
decode_eod_intraday_chunks, decode_eod_intraday_stream, decode_eod_price_stream,
decode_qm_dividend_stream, decode_qm_intraday_chunks, decode_qm_intraday_stream,
decode_qm_price_stream, decode_qm_split_stream, BsonStreamError, BsonStreamOptions,
decode_qm_dividend_stream, decode_qm_financials_chunks, decode_qm_financials_stream,
decode_qm_intraday_chunks, decode_qm_intraday_stream, decode_qm_price_stream,
decode_qm_split_stream, BsonQmFinancialsStreamError, BsonStreamError, BsonStreamOptions,
RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES,
};
use crate::fundamentals::FinancialObservation;
#[derive(Debug, Clone, Copy)]
struct SplitMix64(u64);
@ -2724,3 +2730,365 @@ fn decode_qm_intraday_chunks_and_stream_match_buffer_and_rebase_offsets() {
} if offset == trunc_offset
));
}
#[allow(clippy::too_many_arguments)]
fn make_qm_financials_doc(
key: Option<&str>,
period_end: &str,
report_date: Option<&str>,
report_period: &str,
currency: &str,
revenue: Option<f64>,
net_income_str: Option<&str>,
total_assets: Option<f64>,
) -> Vec<u8> {
let mut doc = RawDocumentBuf::new();
if let Some(k) = key {
doc.append(cstr!("qmSearchCode"), k);
}
doc.append(cstr!("periodEndDate"), period_end);
if let Some(rd) = report_date {
doc.append(cstr!("reportDate"), rd);
}
doc.append(cstr!("reportPeriod"), report_period);
doc.append(cstr!("currency"), currency);
let mut income = RawDocumentBuf::new();
if let Some(rev) = revenue {
income.append(cstr!("revenue"), rev);
}
if let Some(ni) = net_income_str {
income.append(cstr!("netIncome"), ni);
}
doc.append(cstr!("IncomeStatement"), income);
let mut balance = RawDocumentBuf::new();
if let Some(assets) = total_assets {
balance.append(cstr!("totalAssets"), assets);
}
doc.append(cstr!("BalanceSheet"), balance);
doc.into_bytes()
}
fn sample_qm_financials_fields() -> QmFinancialsFieldNames<'static> {
QmFinancialsFieldNames::with_verified_defaults(
"currency",
Some("IncomeStatement.revenue"),
Some("IncomeStatement.netIncome"),
None,
Some("BalanceSheet.totalAssets"),
None,
None,
)
}
fn owned_financial_obs(obs: FinancialObservation<&str>) -> FinancialObservation<String> {
FinancialObservation {
key: obs.key.to_owned(),
period_end: obs.period_end,
fiscal_period: obs.fiscal_period,
currency: obs.currency,
report_date: obs.report_date,
fields: obs.fields,
}
}
#[test]
fn qm_financials_chunks_match_buffer_across_small_chunks() {
let fields = sample_qm_financials_fields();
let fiscal = QmFinancialsFiscalPeriod::ByTokens {
quarterly: &["Q1", "Q2", "Q3", "Q4"],
annual: &["FY"],
};
// Empty input returns zeroed stats and zero rows.
{
let mut empty_rows = 0usize;
let stats = decode_qm_financials_stream(
Cursor::new(Vec::<u8>::new()),
BsonStreamOptions::default(),
&fields,
fiscal,
|_| empty_rows += 1,
)
.unwrap();
assert_eq!(stats, BsonQmFinancialsDecodeStats::default());
assert_eq!(empty_rows, 0);
}
let mut fixture = Vec::new();
// 1. Valid quarterly row with all configured metrics present.
fixture.extend_from_slice(&make_qm_financials_doc(
Some("NVDA"),
"2024-03-31",
Some("2024-05-01"),
"Q1",
"USD",
Some(100.0),
Some("25.5"),
Some(500.0),
));
// 2. Semantic skip: missing key.
fixture.extend_from_slice(&make_qm_financials_doc(
None,
"2024-06-30",
Some("2024-08-01"),
"Q2",
"USD",
Some(120.0),
Some("30.0"),
Some(520.0),
));
// 3. Valid annual row with nullable metric (unparsable netIncome + missing totalAssets).
fixture.extend_from_slice(&make_qm_financials_doc(
Some("SHOP:CA"),
"2024-12-31",
None,
"FY",
"CAD",
Some(450.0),
Some("not-a-number"),
None,
));
// 4. Semantic skip: unmapped report_period token.
fixture.extend_from_slice(&make_qm_financials_doc(
Some("NVDA"),
"2024-09-30",
Some("2024-11-01"),
"SEMIANNUAL",
"USD",
Some(130.0),
Some("32.0"),
Some(540.0),
));
// 5. Valid quarterly row.
fixture.extend_from_slice(&make_qm_financials_doc(
Some("NVDA"),
"2024-06-30",
Some("2024-08-02"),
"Q2",
"USD",
Some(140.0),
Some("35.0"),
Some(560.0),
));
let mut expected_rows = Vec::new();
let expected_stats = decode_qm_financials_buffer(&fixture, &fields, fiscal, |obs| {
expected_rows.push(owned_financial_obs(obs));
})
.unwrap();
assert_eq!(expected_stats.docs_in, 5);
assert_eq!(expected_stats.rows_out, 3);
assert_eq!(expected_stats.skipped_missing_key, 1);
assert_eq!(expected_stats.skipped_unmapped_report_period, 1);
assert_eq!(expected_stats.nulled_unparsable_string, 1);
assert_eq!(expected_stats.nulled_missing_path, 1);
// Force multiple chunks via small chunk_capacity_bytes and short reads.
for (cap, step) in [(1, 1), (3, 2), (32, 7), (128, 17), (256, 29)] {
let opts = BsonStreamOptions {
chunk_capacity_bytes: cap,
max_doc_bytes: 4096,
};
let mut got_rows = Vec::new();
let got_stats = decode_qm_financials_stream(
FixedStepReader::new(&fixture, step),
opts,
&fields,
fiscal,
|obs| got_rows.push(owned_financial_obs(obs)),
)
.unwrap();
assert_eq!(got_stats, expected_stats);
assert_eq!(got_rows, expected_rows);
}
// Exercise decode_qm_financials_chunks directly with random read sizes and EINTR interrupts.
let mut chunk_reader = RawBsonChunkReader::with_options(
RandomInterruptReader::new(&fixture, 0xF1A7, true),
BsonStreamOptions {
chunk_capacity_bytes: 64,
max_doc_bytes: 4096,
},
)
.unwrap();
let mut chunk_rows = Vec::new();
let chunk_stats =
decode_qm_financials_chunks(&mut chunk_reader, &fields, fiscal, |obs| {
chunk_rows.push(owned_financial_obs(obs));
})
.unwrap();
assert_eq!(chunk_stats, expected_stats);
assert_eq!(chunk_rows, expected_rows);
assert_eq!(chunk_reader.docs_framed(), 5);
assert_eq!(chunk_reader.bytes_read(), fixture.len() as u64);
}
#[test]
fn qm_financials_stream_rebases_later_chunk_corruption() {
let fields = sample_qm_financials_fields();
let fiscal = QmFinancialsFiscalPeriod::ByTokens {
quarterly: &["Q1", "Q2"],
annual: &["FY"],
};
let doc1 = make_qm_financials_doc(
Some("NVDA"),
"2024-03-31",
Some("2024-05-01"),
"Q1",
"USD",
Some(100.0),
Some("20.0"),
Some(400.0),
);
let doc2 = make_qm_financials_doc(
Some("NVDA"),
"2024-06-30",
Some("2024-08-01"),
"Q2",
"USD",
Some(110.0),
Some("22.0"),
Some(420.0),
);
let mut corrupt_doc3 = make_qm_financials_doc(
Some("NVDA"),
"2024-09-30",
Some("2024-11-01"),
"Q3",
"USD",
Some(120.0),
Some("24.0"),
Some(440.0),
);
// Corrupt an element type byte while preserving the 4-byte length prefix and trailing 0x00.
// Byte 4 is the type tag of the first element ("qmSearchCode"); 0x7E is an invalid BSON type.
corrupt_doc3[4] = 0x7E;
let mut fixture = Vec::new();
fixture.extend_from_slice(&doc1);
fixture.extend_from_slice(&doc2);
let corrupt_offset = fixture.len() as u64;
fixture.extend_from_slice(&corrupt_doc3);
// Small chunk capacity guarantees corrupt_doc3 lands in a later chunk (start_offset > 0).
let opts = BsonStreamOptions {
chunk_capacity_bytes: doc1.len(),
max_doc_bytes: 4096,
};
let mut seen_rows = Vec::new();
let err = decode_qm_financials_stream(
FixedStepReader::new(&fixture, 11),
opts,
&fields,
fiscal,
|obs| seen_rows.push(owned_financial_obs(obs)),
)
.unwrap_err();
assert_eq!(seen_rows.len(), 2);
assert!(
matches!(
err,
BsonQmFinancialsStreamError::Decode(BsonQmFinancialsError::CorruptBson { offset, .. })
if offset == corrupt_offset
),
"expected rebased CorruptBson at offset {corrupt_offset}, got: {err}"
);
assert!(err.source().is_some());
}
#[test]
fn qm_financials_stream_rejects_invalid_config_before_read() {
struct PanicOnRead;
impl Read for PanicOnRead {
fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
panic!("reader must not be read when config validation fails");
}
}
let valid_fields = sample_qm_financials_fields();
let valid_fiscal = QmFinancialsFiscalPeriod::ByTokens {
quarterly: &["Q1"],
annual: &["FY"],
};
// 1. Invalid dotted path (consecutive dot / empty segment).
let bad_fields = QmFinancialsFieldNames::with_verified_defaults(
"currency",
Some("IncomeStatement..revenue"),
None,
None,
None,
None,
None,
);
let err = decode_qm_financials_stream(
PanicOnRead,
BsonStreamOptions::default(),
&bad_fields,
valid_fiscal,
|_| {},
)
.unwrap_err();
assert!(matches!(
err,
BsonQmFinancialsStreamError::Decode(BsonQmFinancialsError::InvalidFieldNames { .. })
));
let mut chunk_reader = RawBsonChunkReader::new(PanicOnRead);
let err = decode_qm_financials_chunks(&mut chunk_reader, &bad_fields, valid_fiscal, |_| {})
.unwrap_err();
assert!(matches!(
err,
BsonQmFinancialsStreamError::Decode(BsonQmFinancialsError::InvalidFieldNames { .. })
));
// 2. Blank token in ByTokens.
let blank_token_fiscal = QmFinancialsFiscalPeriod::ByTokens {
quarterly: &["Q1", " "],
annual: &["FY"],
};
let err = decode_qm_financials_stream(
PanicOnRead,
BsonStreamOptions::default(),
&valid_fields,
blank_token_fiscal,
|_| {},
)
.unwrap_err();
assert!(matches!(
err,
BsonQmFinancialsStreamError::Decode(BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. })
));
// 3. Overlapping token between quarterly and annual.
let overlap_fiscal = QmFinancialsFiscalPeriod::ByTokens {
quarterly: &["Q1", "FY"],
annual: &["FY"],
};
let err = decode_qm_financials_stream(
PanicOnRead,
BsonStreamOptions::default(),
&valid_fields,
overlap_fiscal,
|_| {},
)
.unwrap_err();
assert!(matches!(
err,
BsonQmFinancialsStreamError::Decode(BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. })
));
let mut chunk_reader = RawBsonChunkReader::new(PanicOnRead);
let err =
decode_qm_financials_chunks(&mut chunk_reader, &valid_fields, overlap_fiscal, |_| {})
.unwrap_err();
assert!(matches!(
err,
BsonQmFinancialsStreamError::Decode(BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. })
));
}

View file

@ -0,0 +1,854 @@
//! Zero-copy raw BSON decoder for MongoDB `teData` documents (`M2.2p`).
//!
//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` without
//! allocating a `bson::Document` or per-point heap memory, emitting borrowed [`TeDataPoint`]
//! values via a caller-supplied callback.
//!
//! # Empirical Field Contract & Unverified Assumptions
//!
//! - Field names are derived strictly from the ingestion writer in
//! `apps/stock/data-ingestion/src/handlers/te/actions/data-fetch.action.ts:87-156`
//! (`teSymbol`, `name`, `unit`, `source`, `frequency`, `country`, `category`, `data`, `forecast`,
//! `lastUpdated`, `createdAt`; `data: [{ d: "YYYY-MM-DD", v: number }]`; `forecast: [{ d, v }]`),
//! and isolated in the `pub const FIELD_*` constants below. They have **not** been verified
//! against a live `mongodump` of `teData`.
//! - **History-only (zero forecast leakage):** `forecast` stores forward-looking provider
//! forecasts. `forecast`, descriptive metadata (`name`, `unit`, `source`, `frequency`),
//! timestamps (`lastUpdated`, `createdAt`), and all unknown fields are skipped by key without
//! calling `elem.value()`, so forecast observations can never leak into research inputs.
//! - **Ownership & no hardcoded mappings:** `TeDataPoint` preserves the verbatim provider
//! `te_symbol`, `country`, and `category` strings. No country-to-ISO, indicator-name, or
//! publication-lag mapping is hardcoded here: Quant Research owns the coarse regime-use policy,
//! and the downstream caller/runner owns all explicit mapping into [`crate::macro_series`].
//! - **Observation dates & provenance:** `period_date` is the provider observation date parsed from
//! strict `YYYY-MM-DD`. Because `teData` carries final-revised values without verified
//! first-release vintages, downstream availability begins strictly at the builder's estimated
//! `known_at` ([`crate::macro_series::build_macro_rows`]).
//! - **Lazy `data` capture:** `data` is retained as a raw [`RawElement`] during the top-level
//! scan and only decoded after `teSymbol`, `country`, and `category` pass validation, so raw
//! BSON field ordering (`data` before metadata) does not affect output or rejection accounting.
//! - **Non-finite doubles:** `v` accepts BSON `Double`, `Int32`, and `Int64` only. Finite and
//! non-finite (`NaN`, `±inf`) doubles are passed through unchanged so the downstream
//! [`crate::macro_series::build_macro_rows`] builder can account for them in
//! `skipped_non_finite_value`.
use std::error::Error;
use std::fmt;
use bson::raw::{RawBsonRef, RawDocument, RawElement};
use bson::spec::ElementType;
use crate::bson_eod_prices::{
iter_raw_bson_docs, parse_single_raw_doc, parse_ymd_strict_days, BsonEodPriceError,
};
/// MongoDB field name for the TradingEconomics symbol key (`data-fetch.action.ts:94`).
pub const FIELD_TE_SYMBOL: &str = "teSymbol";
/// MongoDB field name for the provider country label (`data-fetch.action.ts:99`).
pub const FIELD_COUNTRY: &str = "country";
/// MongoDB field name for the provider category/indicator label (`data-fetch.action.ts:100`).
pub const FIELD_CATEGORY: &str = "category";
/// MongoDB field name for the historical observation array (`data-fetch.action.ts:101`).
pub const FIELD_DATA: &str = "data";
/// MongoDB field name for the forward-looking forecast array, never read (`data-fetch.action.ts:102`).
pub const FIELD_FORECAST: &str = "forecast";
/// Point field name for the `YYYY-MM-DD` observation date string (`data-fetch.action.ts:78`).
pub const FIELD_POINT_D: &str = "d";
/// Point field name for the numeric observation value (`data-fetch.action.ts:78`).
pub const FIELD_POINT_V: &str = "v";
/// Borrowed zero-copy view of a single historical `teData.data` observation.
///
/// `te_symbol`, `country`, and `category` are borrowed verbatim from the underlying
/// `&RawDocument` byte slice with zero per-point heap allocation.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TeDataPoint<'a> {
pub te_symbol: &'a str,
pub country: &'a str,
pub category: &'a str,
/// Observation period date as days since `1970-01-01` (UTC Gregorian).
pub period_date: i32,
pub value: f64,
}
/// Typed errors returned while decoding raw `teData` BSON documents or length-prefixed buffers.
///
/// Every variant's `Display` output is a single line; no input path panics.
#[derive(Debug, Clone, PartialEq)]
pub enum BsonTeDataError {
/// Required top-level `teSymbol` field was absent.
MissingSymbol,
/// Top-level `teSymbol` string was empty or whitespace-only.
EmptySymbol,
/// Top-level `teSymbol` had an unexpected BSON element type.
WrongSymbolType { actual: ElementType },
/// Required top-level `country` field was absent.
MissingCountry,
/// Top-level `country` string was empty or whitespace-only.
EmptyCountry,
/// Top-level `country` had an unexpected BSON element type.
WrongCountryType { actual: ElementType },
/// Required top-level `category` field was absent.
MissingCategory,
/// Top-level `category` string was empty or whitespace-only.
EmptyCategory,
/// Top-level `category` had an unexpected BSON element type.
WrongCategoryType { actual: ElementType },
/// Required top-level `data` field was absent.
MissingData,
/// Top-level `data` field was not a BSON array.
DataNotArray { actual: ElementType },
/// An element inside `data` was not an embedded BSON document.
PointNotDocument {
point_index: usize,
actual: ElementType,
},
/// A required field (`d` or `v`) was absent from a `data` point document.
MissingPointField {
point_index: usize,
field: &'static str,
},
/// A required field (`d` or `v`) in a `data` point document had an unexpected BSON type.
WrongPointFieldType {
point_index: usize,
field: &'static str,
actual: ElementType,
},
/// Point date `d` was not a strict, valid Gregorian `YYYY-MM-DD` string.
InvalidPointDate { point_index: usize },
/// Buffer ended before a complete 4-byte length prefix or declared document body.
TruncatedDocument {
offset: usize,
remaining: usize,
declared_len: Option<i32>,
},
/// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single
/// document slice).
CorruptDocumentLength { offset: usize, declared_len: i32 },
/// Underlying top-level BSON framing or element bytes were malformed.
CorruptBson { offset: usize, detail: String },
/// Underlying BSON bytes inside a `data` array or point document were malformed.
CorruptPointBson {
offset: usize,
point_index: usize,
detail: String,
},
}
impl fmt::Display for BsonTeDataError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MissingSymbol => {
write!(f, "teData BSON missing required field '{FIELD_TE_SYMBOL}'")
}
Self::EmptySymbol => {
write!(
f,
"teData BSON field '{FIELD_TE_SYMBOL}' must not be empty or blank"
)
}
Self::WrongSymbolType { actual } => write!(
f,
"teData BSON field '{FIELD_TE_SYMBOL}' has unexpected BSON type {actual:?}"
),
Self::MissingCountry => {
write!(f, "teData BSON missing required field '{FIELD_COUNTRY}'")
}
Self::EmptyCountry => {
write!(
f,
"teData BSON field '{FIELD_COUNTRY}' must not be empty or blank"
)
}
Self::WrongCountryType { actual } => write!(
f,
"teData BSON field '{FIELD_COUNTRY}' has unexpected BSON type {actual:?}"
),
Self::MissingCategory => {
write!(f, "teData BSON missing required field '{FIELD_CATEGORY}'")
}
Self::EmptyCategory => {
write!(
f,
"teData BSON field '{FIELD_CATEGORY}' must not be empty or blank"
)
}
Self::WrongCategoryType { actual } => write!(
f,
"teData BSON field '{FIELD_CATEGORY}' has unexpected BSON type {actual:?}"
),
Self::MissingData => {
write!(f, "teData BSON missing required field '{FIELD_DATA}'")
}
Self::DataNotArray { actual } => write!(
f,
"teData BSON field '{FIELD_DATA}' has unexpected BSON type {actual:?} (expected Array)"
),
Self::PointNotDocument {
point_index,
actual,
} => write!(
f,
"teData BSON '{FIELD_DATA}[{point_index}]' has unexpected BSON type {actual:?} (expected EmbeddedDocument)"
),
Self::MissingPointField { point_index, field } => write!(
f,
"teData BSON '{FIELD_DATA}[{point_index}]' missing required field '{field}'"
),
Self::WrongPointFieldType {
point_index,
field,
actual,
} => write!(
f,
"teData BSON '{FIELD_DATA}[{point_index}].{field}' has unexpected BSON type {actual:?}"
),
Self::InvalidPointDate { point_index } => write!(
f,
"teData BSON '{FIELD_DATA}[{point_index}].{FIELD_POINT_D}' is not a valid strict YYYY-MM-DD date"
),
Self::TruncatedDocument {
offset,
remaining,
declared_len,
} => match declared_len {
Some(len) => write!(
f,
"truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes"
),
None => write!(
f,
"truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining"
),
},
Self::CorruptDocumentLength {
offset,
declared_len,
} => write!(
f,
"corrupt BSON document length {declared_len} at byte offset {offset}"
),
Self::CorruptBson { offset, detail } => {
write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}")
}
Self::CorruptPointBson {
offset,
point_index,
detail,
} => write!(
f,
"corrupt BSON bytes in '{FIELD_DATA}[{point_index}]' at byte offset {offset}: {detail}"
),
}
}
}
impl Error for BsonTeDataError {}
#[inline]
fn map_framing_error(err: BsonEodPriceError) -> BsonTeDataError {
match err {
BsonEodPriceError::TruncatedDocument {
offset,
remaining,
declared_len,
} => BsonTeDataError::TruncatedDocument {
offset,
remaining,
declared_len,
},
BsonEodPriceError::CorruptDocumentLength {
offset,
declared_len,
} => BsonTeDataError::CorruptDocumentLength {
offset,
declared_len,
},
BsonEodPriceError::CorruptBson { offset, detail } => {
BsonTeDataError::CorruptBson { offset, detail }
}
other => BsonTeDataError::CorruptBson {
offset: 0,
detail: other.to_string(),
},
}
}
/// Per-batch document and point decode accounting for `teData`.
///
/// Conservation invariants:
/// - `docs_in == docs_accepted + docs_rejected_total()`
/// - `points_in == points_decoded + rejected_total()`
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct BsonTeDataDecodeStats {
pub docs_in: usize,
pub docs_accepted: usize,
pub rejected_missing_symbol: usize,
pub rejected_empty_symbol: usize,
pub rejected_wrong_symbol_type: usize,
pub rejected_missing_country: usize,
pub rejected_empty_country: usize,
pub rejected_wrong_country_type: usize,
pub rejected_missing_category: usize,
pub rejected_empty_category: usize,
pub rejected_wrong_category_type: usize,
pub rejected_data_missing: usize,
pub rejected_data_not_array: usize,
pub rejected_corrupt_document: usize,
pub points_in: usize,
pub points_decoded: usize,
pub rejected_point_not_document: usize,
pub rejected_invalid_date: usize,
pub rejected_invalid_value: usize,
pub rejected_corrupt_point: usize,
}
impl BsonTeDataDecodeStats {
/// Total number of document-level rejects across all document error categories.
#[inline]
pub fn docs_rejected_total(&self) -> usize {
self.rejected_missing_symbol
+ self.rejected_empty_symbol
+ self.rejected_wrong_symbol_type
+ self.rejected_missing_country
+ self.rejected_empty_country
+ self.rejected_wrong_country_type
+ self.rejected_missing_category
+ self.rejected_empty_category
+ self.rejected_wrong_category_type
+ self.rejected_data_missing
+ self.rejected_data_not_array
+ self.rejected_corrupt_document
}
/// Total number of point-level rejects across all point error categories.
#[inline]
pub fn rejected_total(&self) -> usize {
self.rejected_point_not_document
+ self.rejected_invalid_date
+ self.rejected_invalid_value
+ self.rejected_corrupt_point
}
/// Increments the document-level rejection counter corresponding to `err`.
#[inline]
fn record_doc_error(&mut self, err: &BsonTeDataError) {
match err {
BsonTeDataError::MissingSymbol => self.rejected_missing_symbol += 1,
BsonTeDataError::EmptySymbol => self.rejected_empty_symbol += 1,
BsonTeDataError::WrongSymbolType { .. } => self.rejected_wrong_symbol_type += 1,
BsonTeDataError::MissingCountry => self.rejected_missing_country += 1,
BsonTeDataError::EmptyCountry => self.rejected_empty_country += 1,
BsonTeDataError::WrongCountryType { .. } => self.rejected_wrong_country_type += 1,
BsonTeDataError::MissingCategory => self.rejected_missing_category += 1,
BsonTeDataError::EmptyCategory => self.rejected_empty_category += 1,
BsonTeDataError::WrongCategoryType { .. } => self.rejected_wrong_category_type += 1,
BsonTeDataError::MissingData => self.rejected_data_missing += 1,
BsonTeDataError::DataNotArray { .. } => self.rejected_data_not_array += 1,
_ => self.rejected_corrupt_document += 1,
}
}
/// Increments the point-level rejection counter corresponding to `err`.
#[inline]
fn record_point_error(&mut self, err: &BsonTeDataError) {
match err {
BsonTeDataError::PointNotDocument { .. } => {
self.rejected_point_not_document += 1;
}
BsonTeDataError::InvalidPointDate { .. } => {
self.rejected_invalid_date += 1;
}
BsonTeDataError::MissingPointField { field, .. }
| BsonTeDataError::WrongPointFieldType { field, .. } => {
if *field == FIELD_POINT_D {
self.rejected_invalid_date += 1;
} else if *field == FIELD_POINT_V {
self.rejected_invalid_value += 1;
} else {
self.rejected_corrupt_point += 1;
}
}
BsonTeDataError::CorruptPointBson { .. } => {
self.rejected_corrupt_point += 1;
}
_ => {
self.rejected_corrupt_point += 1;
}
}
}
/// Accumulates counters from another batch into `self`.
#[inline]
pub fn merge(&mut self, other: &Self) {
self.docs_in += other.docs_in;
self.docs_accepted += other.docs_accepted;
self.rejected_missing_symbol += other.rejected_missing_symbol;
self.rejected_empty_symbol += other.rejected_empty_symbol;
self.rejected_wrong_symbol_type += other.rejected_wrong_symbol_type;
self.rejected_missing_country += other.rejected_missing_country;
self.rejected_empty_country += other.rejected_empty_country;
self.rejected_wrong_country_type += other.rejected_wrong_country_type;
self.rejected_missing_category += other.rejected_missing_category;
self.rejected_empty_category += other.rejected_empty_category;
self.rejected_wrong_category_type += other.rejected_wrong_category_type;
self.rejected_data_missing += other.rejected_data_missing;
self.rejected_data_not_array += other.rejected_data_not_array;
self.rejected_corrupt_document += other.rejected_corrupt_document;
self.points_in += other.points_in;
self.points_decoded += other.points_decoded;
self.rejected_point_not_document += other.rejected_point_not_document;
self.rejected_invalid_date += other.rejected_invalid_date;
self.rejected_invalid_value += other.rejected_invalid_value;
self.rejected_corrupt_point += other.rejected_corrupt_point;
}
}
impl std::ops::AddAssign for BsonTeDataDecodeStats {
#[inline]
fn add_assign(&mut self, rhs: Self) {
self.merge(&rhs);
}
}
#[inline]
fn decode_point_d(point_index: usize, val: RawBsonRef<'_>) -> Result<i32, BsonTeDataError> {
match val {
RawBsonRef::String(s) => {
parse_ymd_strict_days(s).ok_or(BsonTeDataError::InvalidPointDate { point_index })
}
other => Err(BsonTeDataError::WrongPointFieldType {
point_index,
field: FIELD_POINT_D,
actual: other.element_type(),
}),
}
}
#[inline]
fn decode_point_v(point_index: usize, val: RawBsonRef<'_>) -> Result<f64, BsonTeDataError> {
match val {
RawBsonRef::Double(v) => Ok(v),
RawBsonRef::Int32(v) => Ok(f64::from(v)),
RawBsonRef::Int64(v) => Ok(v as f64),
other => Err(BsonTeDataError::WrongPointFieldType {
point_index,
field: FIELD_POINT_V,
actual: other.element_type(),
}),
}
}
fn decode_point_doc(
point_doc: &RawDocument,
doc_offset: usize,
point_index: usize,
) -> Result<(i32, f64), BsonTeDataError> {
let mut period_date: Option<i32> = None;
let mut value: Option<f64> = None;
let mut d_err: Option<BsonTeDataError> = None;
let mut v_err: Option<BsonTeDataError> = None;
for elem_res in point_doc.iter_elements() {
let elem = elem_res.map_err(|err| BsonTeDataError::CorruptPointBson {
offset: doc_offset,
point_index,
detail: err.to_string(),
})?;
let key = elem.key().as_str();
if key == FIELD_POINT_D {
let val = elem
.value()
.map_err(|err| BsonTeDataError::CorruptPointBson {
offset: doc_offset,
point_index,
detail: format!("field '{FIELD_POINT_D}': {err}"),
})?;
match decode_point_d(point_index, val) {
Ok(d) => period_date = Some(d),
Err(err) => {
if d_err.is_none() {
d_err = Some(err);
}
}
}
} else if key == FIELD_POINT_V {
let val = elem
.value()
.map_err(|err| BsonTeDataError::CorruptPointBson {
offset: doc_offset,
point_index,
detail: format!("field '{FIELD_POINT_V}': {err}"),
})?;
match decode_point_v(point_index, val) {
Ok(v) => value = Some(v),
Err(err) => {
if v_err.is_none() {
v_err = Some(err);
}
}
}
}
// Unknown point fields are skipped without calling `elem.value()`.
}
if let Some(err) = d_err {
return Err(err);
}
let Some(period_date) = period_date else {
return Err(BsonTeDataError::MissingPointField {
point_index,
field: FIELD_POINT_D,
});
};
if let Some(err) = v_err {
return Err(err);
}
let Some(value) = value else {
return Err(BsonTeDataError::MissingPointField {
point_index,
field: FIELD_POINT_V,
});
};
Ok((period_date, value))
}
fn decode_te_data_doc_at<'a, F, E>(
doc: &'a RawDocument,
doc_offset: usize,
mut on_point: F,
mut on_error: E,
) -> BsonTeDataDecodeStats
where
F: FnMut(TeDataPoint<'a>),
E: FnMut(BsonTeDataError),
{
let mut stats = BsonTeDataDecodeStats {
docs_in: 1,
..BsonTeDataDecodeStats::default()
};
let mut te_symbol: Option<&'a str> = None;
let mut te_symbol_err: Option<BsonTeDataError> = None;
let mut country: Option<&'a str> = None;
let mut country_err: Option<BsonTeDataError> = None;
let mut category: Option<&'a str> = None;
let mut category_err: Option<BsonTeDataError> = None;
let mut data_elem: Option<RawElement<'a>> = None;
for elem_res in doc.iter_elements() {
let elem = match elem_res {
Ok(elem) => elem,
Err(err) => {
stats.rejected_corrupt_document += 1;
on_error(BsonTeDataError::CorruptBson {
offset: doc_offset,
detail: err.to_string(),
});
return stats;
}
};
let key = elem.key().as_str();
if key == FIELD_TE_SYMBOL {
let val = match elem.value() {
Ok(val) => val,
Err(err) => {
stats.rejected_corrupt_document += 1;
on_error(BsonTeDataError::CorruptBson {
offset: doc_offset,
detail: format!("field '{FIELD_TE_SYMBOL}': {err}"),
});
return stats;
}
};
match val {
RawBsonRef::String(s) => {
if s.trim().is_empty() {
if te_symbol_err.is_none() {
te_symbol_err = Some(BsonTeDataError::EmptySymbol);
}
} else {
te_symbol = Some(s);
}
}
other => {
if te_symbol_err.is_none() {
te_symbol_err = Some(BsonTeDataError::WrongSymbolType {
actual: other.element_type(),
});
}
}
}
} else if key == FIELD_COUNTRY {
let val = match elem.value() {
Ok(val) => val,
Err(err) => {
stats.rejected_corrupt_document += 1;
on_error(BsonTeDataError::CorruptBson {
offset: doc_offset,
detail: format!("field '{FIELD_COUNTRY}': {err}"),
});
return stats;
}
};
match val {
RawBsonRef::String(s) => {
if s.trim().is_empty() {
if country_err.is_none() {
country_err = Some(BsonTeDataError::EmptyCountry);
}
} else {
country = Some(s);
}
}
other => {
if country_err.is_none() {
country_err = Some(BsonTeDataError::WrongCountryType {
actual: other.element_type(),
});
}
}
}
} else if key == FIELD_CATEGORY {
let val = match elem.value() {
Ok(val) => val,
Err(err) => {
stats.rejected_corrupt_document += 1;
on_error(BsonTeDataError::CorruptBson {
offset: doc_offset,
detail: format!("field '{FIELD_CATEGORY}': {err}"),
});
return stats;
}
};
match val {
RawBsonRef::String(s) => {
if s.trim().is_empty() {
if category_err.is_none() {
category_err = Some(BsonTeDataError::EmptyCategory);
}
} else {
category = Some(s);
}
}
other => {
if category_err.is_none() {
category_err = Some(BsonTeDataError::WrongCategoryType {
actual: other.element_type(),
});
}
}
}
} else if key == FIELD_DATA {
data_elem = Some(elem);
}
// `FIELD_FORECAST`, `name`, `unit`, `source`, `frequency`, `lastUpdated`, `createdAt`,
// and all other top-level fields are skipped without calling `elem.value()`.
}
// Deterministic top-level validation order: `teSymbol`, `country`, `category`, then `data`.
if let Some(err) = te_symbol_err {
stats.record_doc_error(&err);
on_error(err);
return stats;
}
let Some(te_symbol) = te_symbol else {
let err = BsonTeDataError::MissingSymbol;
stats.record_doc_error(&err);
on_error(err);
return stats;
};
if let Some(err) = country_err {
stats.record_doc_error(&err);
on_error(err);
return stats;
}
let Some(country) = country else {
let err = BsonTeDataError::MissingCountry;
stats.record_doc_error(&err);
on_error(err);
return stats;
};
if let Some(err) = category_err {
stats.record_doc_error(&err);
on_error(err);
return stats;
}
let Some(category) = category else {
let err = BsonTeDataError::MissingCategory;
stats.record_doc_error(&err);
on_error(err);
return stats;
};
let Some(data_elem) = data_elem else {
let err = BsonTeDataError::MissingData;
stats.record_doc_error(&err);
on_error(err);
return stats;
};
let data_val = match data_elem.value() {
Ok(val) => val,
Err(err) => {
stats.rejected_corrupt_document += 1;
on_error(BsonTeDataError::CorruptBson {
offset: doc_offset,
detail: format!("field '{FIELD_DATA}': {err}"),
});
return stats;
}
};
let data_arr = match data_val {
RawBsonRef::Array(arr) => arr,
other => {
let err = BsonTeDataError::DataNotArray {
actual: other.element_type(),
};
stats.record_doc_error(&err);
on_error(err);
return stats;
}
};
stats.docs_accepted += 1;
for (point_index, item_res) in data_arr.into_iter().enumerate() {
stats.points_in += 1;
let item = match item_res {
Ok(item) => item,
Err(err) => {
let err = BsonTeDataError::CorruptPointBson {
offset: doc_offset,
point_index,
detail: err.to_string(),
};
stats.record_point_error(&err);
on_error(err);
break;
}
};
let point_doc = match item {
RawBsonRef::Document(point_doc) => point_doc,
other => {
let err = BsonTeDataError::PointNotDocument {
point_index,
actual: other.element_type(),
};
stats.record_point_error(&err);
on_error(err);
continue;
}
};
match decode_point_doc(point_doc, doc_offset, point_index) {
Ok((period_date, value)) => {
stats.points_decoded += 1;
on_point(TeDataPoint {
te_symbol,
country,
category,
period_date,
value,
});
}
Err(err) => {
stats.record_point_error(&err);
on_error(err);
}
}
}
stats
}
/// Decodes a single `&RawDocument` representing a `teData` MongoDB document in one forward pass
/// without allocating a `bson::Document` or per-point heap memory.
///
/// Emits each valid historical `data` point as a borrowed [`TeDataPoint`] via `on_point` and
/// reports document- or point-level errors to `on_error` without panicking. `forecast` is never
/// read or emitted.
#[inline]
pub fn decode_te_data_doc<'a, F, E>(
doc: &'a RawDocument,
on_point: F,
on_error: E,
) -> BsonTeDataDecodeStats
where
F: FnMut(TeDataPoint<'a>),
E: FnMut(BsonTeDataError),
{
decode_te_data_doc_at(doc, 0, on_point, on_error)
}
/// Decodes a single length-prefixed raw BSON document byte slice representing a `teData` document.
pub fn decode_te_data_bytes<'a, F, E>(
bytes: &'a [u8],
on_point: F,
mut on_error: E,
) -> BsonTeDataDecodeStats
where
F: FnMut(TeDataPoint<'a>),
E: FnMut(BsonTeDataError),
{
match parse_single_raw_doc(bytes) {
Ok(doc) => decode_te_data_doc_at(doc, 0, on_point, on_error),
Err(err) => {
let mut stats = BsonTeDataDecodeStats {
docs_in: 1,
..BsonTeDataDecodeStats::default()
};
stats.rejected_corrupt_document += 1;
on_error(map_framing_error(err));
stats
}
}
}
/// Streams a concatenated length-prefixed BSON buffer through [`decode_te_data_doc`], emitting
/// every valid historical [`TeDataPoint`] to `on_point` and reporting document- or point-level
/// errors to `on_error(byte_offset, err)` without aborting on per-document semantic errors.
///
/// Always maintains:
/// - `stats.docs_in == stats.docs_accepted + stats.docs_rejected_total()`
/// - `stats.points_in == stats.points_decoded + stats.rejected_total()`
pub fn decode_te_data_buffer<'a, F, E>(
buf: &'a [u8],
mut on_point: F,
mut on_error: E,
) -> BsonTeDataDecodeStats
where
F: FnMut(TeDataPoint<'a>),
E: FnMut(usize, BsonTeDataError),
{
let mut stats = BsonTeDataDecodeStats::default();
let mut iter = iter_raw_bson_docs(buf);
while let Some(item) = iter.next_with_offset() {
match item {
Ok((doc_offset, doc)) => {
let doc_stats = decode_te_data_doc_at(doc, doc_offset, &mut on_point, |err| {
on_error(doc_offset, err)
});
stats += doc_stats;
}
Err((doc_offset, err)) => {
stats.docs_in += 1;
stats.rejected_corrupt_document += 1;
on_error(doc_offset, map_framing_error(err));
}
}
}
stats
}
#[cfg(test)]
#[path = "bson_te_data_tests.rs"]
mod tests;

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,282 @@
//! Pure, in-memory `fundamentals_pit` curation stage joining
//! [`crate::provider_mapping::ProviderMappingTable`],
//! [`crate::fundamentals::build_fundamentals_rows`],
//! [`crate::fundamentals::build_fundamentals_snapshots`], and
//! [`crate::parquet_fundamentals::write_fundamentals_pit_dataset`] into contract
//! [`FundamentalsPitParquetRow`]s.
//!
//! # Contract & Point-in-Time Rules
//! - Resolves provider source keys to permanent `listing_id: i32` **before** building
//! bitemporal rows and snapshots so ticker reuse never mixes issuers or spans TTM windows
//! across distinct listings:
//! - **Observations:** resolved on `(mapping_source, obs.key, obs.period_end)` (the fiscal
//! period end date, not `report_date`).
//! - **Filings:** `filing.timefiled` is parsed first via [`parse_filing_timefiled`]; parse
//! failures are dropped and counted in
//! [`CurateFundamentalsStats::filings_dropped_invalid_timestamp`] (never fabricating a
//! placeholder `listing_id`). Valid filings are resolved on
//! `(mapping_source, filing.key, parsed.et_date)` (Eastern local calendar date, never UTC
//! date).
//! - Unmapped observations and filings are dropped and counted in
//! [`CurateFundamentalsStats::observations_dropped_unmapped`] and
//! [`CurateFundamentalsStats::filings_dropped_unmapped`].
//! - Feeds mapped inputs into [`build_fundamentals_rows`] with `K = i32` and the caller's
//! `venues` map, then [`build_fundamentals_snapshots`] with `k`, then converts each snapshot via
//! [`FundamentalsPitParquetRow::from`]. Output rows preserve the builder's strictly ascending
//! `(listing_id, effective_known_at_micros)` order and are independent of input order.
use std::collections::BTreeMap;
use std::error::Error;
use std::fmt;
use std::path::Path;
use crate::events::{parse_filing_timefiled, QmFiling};
use crate::fundamentals::{
build_fundamentals_rows, build_fundamentals_snapshots, FinancialObservation, FundamentalsError,
FundamentalsStats, StatutoryLagVenue,
};
use crate::parquet_fundamentals::{
write_fundamentals_pit_dataset, FundamentalsPitParquetRow, FundamentalsPitWriteOptions,
FundamentalsPitWriteStats, ParquetFundamentalsError,
};
use crate::provider_mapping::ProviderMappingTable;
/// Accounting summary produced alongside [`CurateFundamentalsOutput::rows`].
///
/// Conservation invariants:
/// - `observations_in == observations_dropped_unmapped + build.observations_in`
/// - `filings_in == filings_dropped_unmapped + filings_dropped_invalid_timestamp + build.filings_in`
/// - `build` independently satisfies all [`FundamentalsStats`] conservation invariants (with
/// `build.filings_dropped_invalid_timestamp == 0` because malformed filings are filtered at the
/// stage before mapping lookup).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct CurateFundamentalsStats {
pub build: FundamentalsStats,
pub observations_in: usize,
pub observations_dropped_unmapped: usize,
pub filings_in: usize,
pub filings_dropped_unmapped: usize,
pub filings_dropped_invalid_timestamp: usize,
pub rows_out: usize,
pub listings_out: usize,
}
/// Output of [`curate_fundamentals`]: contract Parquet rows strictly ascending by
/// `(listing_id, effective_known_at_micros)` and full stage + builder stats.
#[derive(Debug, Clone, PartialEq)]
pub struct CurateFundamentalsOutput {
pub rows: Vec<FundamentalsPitParquetRow>,
pub stats: CurateFundamentalsStats,
}
/// Typed caller errors returned by [`curate_fundamentals`].
///
/// Unmapped inputs and malformed filing timestamps are dropped and counted in
/// [`CurateFundamentalsStats`] rather than aborting the stage.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CurateFundamentalsError {
/// Error propagated from [`build_fundamentals_snapshots`] (e.g., `k == 0`).
Fundamentals(FundamentalsError),
/// Caller-supplied `mapping_source` was empty or contained only whitespace.
EmptyMappingSource,
}
impl fmt::Display for CurateFundamentalsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::Fundamentals(err) => write!(f, "{err}"),
Self::EmptyMappingSource => {
write!(f, "mapping_source must not be empty or blank")
}
}
}
}
impl Error for CurateFundamentalsError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Fundamentals(err) => Some(err),
Self::EmptyMappingSource => None,
}
}
}
impl From<FundamentalsError> for CurateFundamentalsError {
fn from(err: FundamentalsError) -> Self {
Self::Fundamentals(err)
}
}
/// Combined stats returned by [`curate_and_write_fundamentals`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurateFundamentalsWriteReport {
pub curate_stats: CurateFundamentalsStats,
pub write_stats: FundamentalsPitWriteStats,
}
/// Typed error returned by [`curate_and_write_fundamentals`].
#[derive(Debug)]
pub enum CurateFundamentalsWriteError {
Curate(CurateFundamentalsError),
Parquet(ParquetFundamentalsError),
}
impl fmt::Display for CurateFundamentalsWriteError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Curate(err) => write!(f, "fundamentals curation failed: {err}"),
Self::Parquet(err) => write!(f, "fundamentals Parquet write failed: {err}"),
}
}
}
impl Error for CurateFundamentalsWriteError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Curate(err) => Some(err),
Self::Parquet(err) => Some(err),
}
}
}
impl From<CurateFundamentalsError> for CurateFundamentalsWriteError {
fn from(err: CurateFundamentalsError) -> Self {
Self::Curate(err)
}
}
impl From<ParquetFundamentalsError> for CurateFundamentalsWriteError {
fn from(err: ParquetFundamentalsError) -> Self {
Self::Parquet(err)
}
}
/// Pure `fundamentals_pit` curation stage: resolves provider source keys to permanent
/// `listing_id`s via `provider_mapping` (observations on `period_end`, filings on Eastern local
/// date `ParsedFilingTime::et_date`), builds bitemporal rows and 2D point-in-time snapshots via
/// [`build_fundamentals_rows`] and [`build_fundamentals_snapshots`], and emits contract
/// [`FundamentalsPitParquetRow`]s strictly ascending by `(listing_id, effective_known_at_micros)`.
///
/// Rejects blank `mapping_source` with [`CurateFundamentalsError::EmptyMappingSource`] and `k == 0`
/// with [`CurateFundamentalsError::Fundamentals`] (`FundamentalsError::InvalidPeriodLimit`) before
/// consuming input iterators.
pub fn curate_fundamentals<K, IO, IF>(
observations: IO,
filings: IF,
mapping_source: &str,
mapping: &ProviderMappingTable,
venues: &BTreeMap<i32, StatutoryLagVenue>,
k: usize,
) -> Result<CurateFundamentalsOutput, CurateFundamentalsError>
where
K: AsRef<str>,
IO: IntoIterator<Item = FinancialObservation<K>>,
IF: IntoIterator<Item = QmFiling<K>>,
{
if mapping_source.trim().is_empty() {
return Err(CurateFundamentalsError::EmptyMappingSource);
}
if k == 0 {
return Err(FundamentalsError::InvalidPeriodLimit { k }.into());
}
let obs_iter = observations.into_iter();
let filings_iter = filings.into_iter();
let mut stats = CurateFundamentalsStats::default();
let mut mapped_observations: Vec<FinancialObservation<i32>> =
Vec::with_capacity(obs_iter.size_hint().0);
let mut mapped_filings: Vec<QmFiling<i32>> = Vec::with_capacity(filings_iter.size_hint().0);
for obs in obs_iter {
stats.observations_in += 1;
let Some(listing_id) = mapping.resolve(mapping_source, obs.key.as_ref(), obs.period_end)
else {
stats.observations_dropped_unmapped += 1;
continue;
};
mapped_observations.push(FinancialObservation {
key: listing_id,
period_end: obs.period_end,
fiscal_period: obs.fiscal_period,
currency: obs.currency,
report_date: obs.report_date,
fields: obs.fields,
});
}
for filing in filings_iter {
stats.filings_in += 1;
let Ok(parsed_time) = parse_filing_timefiled(&filing.timefiled) else {
stats.filings_dropped_invalid_timestamp += 1;
continue;
};
let Some(listing_id) =
mapping.resolve(mapping_source, filing.key.as_ref(), parsed_time.et_date)
else {
stats.filings_dropped_unmapped += 1;
continue;
};
mapped_filings.push(QmFiling {
key: listing_id,
timefiled: filing.timefiled,
form_type: filing.form_type,
filing_id: filing.filing_id,
url: filing.url,
});
}
let built = build_fundamentals_rows(mapped_observations, mapped_filings, venues);
stats.build = built.stats;
let snapshots = build_fundamentals_snapshots(&built.rows, k)?;
let rows: Vec<FundamentalsPitParquetRow> = snapshots
.into_iter()
.map(FundamentalsPitParquetRow::from)
.collect();
let mut last_listing_id: Option<i32> = None;
for row in &rows {
if last_listing_id != Some(row.listing_id) {
stats.listings_out += 1;
last_listing_id = Some(row.listing_id);
}
}
stats.rows_out = rows.len();
Ok(CurateFundamentalsOutput { rows, stats })
}
/// Thin end-to-end wrapper running [`curate_fundamentals`] and publishing the resulting contract
/// rows via [`write_fundamentals_pit_dataset`] to `<out_dir>/fundamentals_pit/year=YYYY/part.parquet`.
///
/// Any [`CurateFundamentalsError`] returns before [`write_fundamentals_pit_dataset`] is invoked,
/// leaving `out_dir` untouched.
#[allow(clippy::too_many_arguments)]
pub fn curate_and_write_fundamentals<P, K, IO, IF>(
out_dir: P,
observations: IO,
filings: IF,
mapping_source: &str,
mapping: &ProviderMappingTable,
venues: &BTreeMap<i32, StatutoryLagVenue>,
k: usize,
options: FundamentalsPitWriteOptions,
) -> Result<CurateFundamentalsWriteReport, CurateFundamentalsWriteError>
where
P: AsRef<Path>,
K: AsRef<str>,
IO: IntoIterator<Item = FinancialObservation<K>>,
IF: IntoIterator<Item = QmFiling<K>>,
{
let curated = curate_fundamentals(observations, filings, mapping_source, mapping, venues, k)?;
let write_stats = write_fundamentals_pit_dataset(out_dir, &curated.rows, options)?;
Ok(CurateFundamentalsWriteReport {
curate_stats: curated.stats,
write_stats,
})
}
#[cfg(test)]
#[path = "curate_fundamentals_tests.rs"]
mod tests;

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,347 @@
//! Pure, in-memory `macro` curation stage joining [`crate::bson_te_data::TeDataPoint`],
//! [`crate::macro_series::build_macro_rows`], and
//! [`crate::parquet_macro::write_macro_dataset`] into contract [`MacroParquetRow`]s.
//!
//! # Governance & Contract Rules
//! - **Caller-owned series mapping:** Every [`TeDataPoint`] carries verbatim provider
//! `(te_symbol, country, category)` labels. No country-to-ISO, indicator-name, or lag-class
//! mapping is hardcoded here because live `teData` labels are unverified and Quant Research owns
//! the coarse regime-use policy.
//! - **Fail-closed unmapped drop:** Points whose `(te_symbol, country, category)` maps to `None`
//! are dropped and counted in [`CurateMacroStats::dropped_unmapped_series`] without ever
//! assigning a default publication lag.
//! - **Fail-closed lag-class consistency:** If two mapped points reach the same
//! `(country_iso, indicator)` target with different [`MacroLagClass`] values (even if one point
//! has a non-finite value), curation fails with [`CurateMacroError::ConflictingLagClass`]
//! naming the first conflicting target in ascending `(country_iso, indicator)` key order,
//! independent of input order.
//! - **Delegated builder semantics:** Mapped observations pass unchanged to [`build_macro_rows`]
//! for finite-value filtering, sorting, bitwise deduplication / conflict detection, and
//! estimated `known_at` calculation (`00:00:00 UTC` of `period_date + lag_days`,
//! `known_at_source = "publication_lag_estimate"`). Output rows are converted via
//! [`MacroParquetRow::from`] in strictly ascending, unique `(country_iso, indicator, period_date)`
//! order.
use std::collections::BTreeMap;
use std::error::Error;
use std::fmt;
use std::path::Path;
use crate::bson_te_data::TeDataPoint;
use crate::macro_series::{
build_macro_rows, MacroBuildStats, MacroError, MacroLagClass, MacroObservation,
};
use crate::parquet_macro::{
write_macro_dataset, MacroParquetRow, MacroWriteOptions, MacroWriteStats, ParquetMacroError,
};
/// Caller-supplied mapping target for a provider `teData` series.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MacroSeriesTarget {
pub country_iso: String,
pub indicator: String,
pub lag_class: MacroLagClass,
}
/// Accounting summary produced alongside [`CurateMacroOutput::rows`].
///
/// Conservation invariants:
/// - `points_in == dropped_unmapped_series + builder.input`
/// - `rows_out == builder.emitted`
/// - `builder` independently satisfies
/// `builder.input == builder.emitted + builder.skipped_unmapped_indicator + builder.skipped_non_finite_value + builder.skipped_duplicate`
/// (with `builder.skipped_unmapped_indicator == 0` because unmapped series are filtered before
/// calling [`build_macro_rows`]).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct CurateMacroStats {
pub builder: MacroBuildStats,
pub points_in: usize,
pub rows_out: usize,
pub dropped_unmapped_series: usize,
pub series_out: usize,
}
/// Output of [`curate_macro`]: contract Parquet rows strictly ascending and unique by
/// `(country_iso, indicator, period_date)` and reconciling stage + builder stats.
#[derive(Debug, Clone, PartialEq)]
pub struct CurateMacroOutput {
pub rows: Vec<MacroParquetRow>,
pub stats: CurateMacroStats,
}
/// Typed error returned by [`curate_macro`].
///
/// Every variant's `Display` output is guaranteed to be a single line.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CurateMacroError {
/// One `(country_iso, indicator)` target was reached with two different [`MacroLagClass`]
/// values across mapped points. `first_lag_class < second_lag_class` in [`MacroLagClass`]
/// `Ord` order so the error is identical for any input permutation.
ConflictingLagClass {
country_iso: String,
indicator: String,
first_lag_class: MacroLagClass,
second_lag_class: MacroLagClass,
},
/// Error propagated from [`build_macro_rows`] (`ConflictingDuplicate` or `KnownAtOverflow`).
Macro(MacroError<String>),
}
fn fmt_single_line(f: &mut fmt::Formatter<'_>, text: &str) -> fmt::Result {
for ch in text.chars() {
match ch {
'\n' => f.write_str("\\n")?,
'\r' => f.write_str("\\r")?,
other => fmt::Write::write_char(f, other)?,
}
}
Ok(())
}
impl fmt::Display for CurateMacroError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ConflictingLagClass {
country_iso,
indicator,
first_lag_class,
second_lag_class,
} => write!(
f,
"conflicting lag classes for macro target ({country_iso:?}, {indicator:?}): {first_lag_class:?} (+{}d) vs {second_lag_class:?} (+{}d)",
first_lag_class.lag_days(),
second_lag_class.lag_days(),
),
Self::Macro(err) => fmt_single_line(f, &err.to_string()),
}
}
}
impl Error for CurateMacroError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::ConflictingLagClass { .. } => None,
Self::Macro(err) => Some(err),
}
}
}
impl From<MacroError<String>> for CurateMacroError {
fn from(err: MacroError<String>) -> Self {
Self::Macro(err)
}
}
/// Combined stats returned by [`curate_and_write_macro`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CurateMacroWriteReport {
pub curate_stats: CurateMacroStats,
pub write_stats: MacroWriteStats,
}
/// Typed error returned by [`curate_and_write_macro`].
///
/// Every variant's `Display` output is guaranteed to be a single line.
#[derive(Debug)]
pub enum CurateMacroWriteError {
Curate(CurateMacroError),
Parquet(ParquetMacroError),
}
impl fmt::Display for CurateMacroWriteError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Curate(err) => {
f.write_str("macro curation failed: ")?;
fmt_single_line(f, &err.to_string())
}
Self::Parquet(err) => {
f.write_str("macro Parquet write failed: ")?;
fmt_single_line(f, &err.to_string())
}
}
}
}
impl Error for CurateMacroWriteError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Curate(err) => Some(err),
Self::Parquet(err) => Some(err),
}
}
}
impl From<CurateMacroError> for CurateMacroWriteError {
fn from(err: CurateMacroError) -> Self {
Self::Curate(err)
}
}
impl From<ParquetMacroError> for CurateMacroWriteError {
fn from(err: ParquetMacroError) -> Self {
Self::Parquet(err)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LagAssignment {
Single(MacroLagClass),
Conflict {
min_class: MacroLagClass,
max_class: MacroLagClass,
},
}
impl LagAssignment {
#[inline]
fn record(&mut self, lag_class: MacroLagClass) {
match *self {
Self::Single(existing) if existing == lag_class => {}
Self::Single(existing) => {
*self = Self::Conflict {
min_class: existing.min(lag_class),
max_class: existing.max(lag_class),
};
}
Self::Conflict {
min_class,
max_class,
} => {
*self = Self::Conflict {
min_class: min_class.min(lag_class),
max_class: max_class.max(lag_class),
};
}
}
}
#[inline]
fn single(&self) -> Option<MacroLagClass> {
match *self {
Self::Single(class) => Some(class),
Self::Conflict { .. } => None,
}
}
}
/// Pure `macro` curation stage: maps decoded [`TeDataPoint`]s via the caller-supplied
/// `(te_symbol, country, category) -> Option<MacroSeriesTarget>` lookup, verifies lag-class
/// consistency per `(country_iso, indicator)` target, delegates filtering, deduplication, and
/// `known_at` derivation to [`build_macro_rows`], and emits contract [`MacroParquetRow`]s
/// strictly ascending and unique by `(country_iso, indicator, period_date)`.
///
/// The caller lookup `series_for` must be deterministic/stable for each verbatim
/// `(te_symbol, country, category)` triple. Any permutation of `points` produces identical `rows`
/// (including `f64` bit patterns) and `stats`, or the same [`CurateMacroError`].
pub fn curate_macro<'a, I, F>(
points: I,
series_for: F,
) -> Result<CurateMacroOutput, CurateMacroError>
where
I: IntoIterator<Item = TeDataPoint<'a>>,
F: Fn(&str, &str, &str) -> Option<MacroSeriesTarget>,
{
let iter = points.into_iter();
let (lower, _) = iter.size_hint();
let mut stats = CurateMacroStats::default();
let mut observations: Vec<MacroObservation<String>> = Vec::with_capacity(lower);
let mut target_lags: BTreeMap<String, BTreeMap<String, LagAssignment>> = BTreeMap::new();
for point in iter {
stats.points_in += 1;
let Some(target) = series_for(point.te_symbol, point.country, point.category) else {
stats.dropped_unmapped_series += 1;
continue;
};
if let Some(assignment) = target_lags
.get_mut(&target.country_iso)
.and_then(|by_indicator| by_indicator.get_mut(&target.indicator))
{
assignment.record(target.lag_class);
} else {
target_lags
.entry(target.country_iso.clone())
.or_default()
.insert(
target.indicator.clone(),
LagAssignment::Single(target.lag_class),
);
}
observations.push(MacroObservation {
country_iso: target.country_iso,
indicator: target.indicator,
period_date: point.period_date,
value: point.value,
});
}
for (country_iso, by_indicator) in &target_lags {
for (indicator, assignment) in by_indicator {
if let LagAssignment::Conflict {
min_class,
max_class,
} = *assignment
{
return Err(CurateMacroError::ConflictingLagClass {
country_iso: country_iso.clone(),
indicator: indicator.clone(),
first_lag_class: min_class,
second_lag_class: max_class,
});
}
}
}
let built = build_macro_rows(observations, |country_iso, indicator| {
target_lags
.get(country_iso.as_str())
.and_then(|by_indicator| by_indicator.get(indicator.as_str()))
.and_then(LagAssignment::single)
})?;
stats.builder = built.stats;
let rows: Vec<MacroParquetRow> = built.rows.iter().map(MacroParquetRow::from).collect();
stats.rows_out = rows.len();
let mut last_series: Option<(&str, &str)> = None;
for row in &rows {
let series = (row.country_iso.as_ref(), row.indicator.as_ref());
if last_series != Some(series) {
stats.series_out += 1;
last_series = Some(series);
}
}
Ok(CurateMacroOutput { rows, stats })
}
/// Thin end-to-end wrapper running [`curate_macro`] and publishing the resulting contract rows
/// via [`write_macro_dataset`] to `<out_dir>/macro/part.parquet`.
///
/// Any [`CurateMacroError`] returns before [`write_macro_dataset`] is invoked, leaving `out_dir`
/// and any pre-existing `macro/part.parquet` completely untouched.
pub fn curate_and_write_macro<'a, P, I, F>(
out_dir: P,
points: I,
series_for: F,
options: MacroWriteOptions,
) -> Result<CurateMacroWriteReport, CurateMacroWriteError>
where
P: AsRef<Path>,
I: IntoIterator<Item = TeDataPoint<'a>>,
F: Fn(&str, &str, &str) -> Option<MacroSeriesTarget>,
{
let curated = curate_macro(points, series_for)?;
let write_stats = write_macro_dataset(out_dir, &curated.rows, options)?;
Ok(CurateMacroWriteReport {
curate_stats: curated.stats,
write_stats,
})
}
#[cfg(test)]
#[path = "curate_macro_tests.rs"]
mod tests;

File diff suppressed because it is too large Load diff

View file

@ -10,9 +10,11 @@ pub mod bson_eod_intraday;
pub mod bson_eod_prices;
pub mod bson_qm_actions;
pub mod bson_qm_events;
pub mod bson_qm_financials;
pub mod bson_qm_intraday;
pub mod bson_qm_prices;
pub mod bson_stream;
pub mod bson_te_data;
pub mod bson_te_market_data;
pub mod cli;
pub mod corporate_actions;
@ -20,6 +22,7 @@ pub mod events;
pub mod fundamentals;
pub mod fx;
pub mod ilp;
pub mod macro_series;
pub mod mongo_safety;
pub mod mongo_stream;
pub mod parquet_adj;
@ -28,6 +31,7 @@ pub mod parquet_corporate_actions;
pub mod parquet_events;
pub mod parquet_fundamentals;
pub mod parquet_fx;
pub mod parquet_macro;
pub mod parquet_posts;
mod parquet_publish;
pub mod parquet_shorts;
@ -82,6 +86,13 @@ pub use bson_qm_events::{
DEFAULT_EARNINGS_KEY_FIELD, DEFAULT_EARNINGS_REPORT_DATE_FIELD, DEFAULT_FILINGS_KEY_FIELD,
DEFAULT_FILINGS_TIMEFILED_FIELD,
};
pub use bson_qm_financials::{
decode_qm_financials_buffer, decode_qm_financials_bytes, decode_qm_financials_doc,
BsonQmFinancialsDecodeStats, BsonQmFinancialsError, QmFinancialsFieldNames,
QmFinancialsFiscalPeriod, DEFAULT_QM_FINANCIALS_KEY_FIELD,
DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD, DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD,
DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD,
};
pub use bson_qm_prices::{
decode_qm_price_buffer, decode_qm_price_bytes, decode_qm_price_doc, BsonQmPriceDecodeStats,
BsonQmPriceError, RawQmPrice, FIELD_SHARE_VOLUME,
@ -91,12 +102,17 @@ pub use bson_stream::{
decode_ceo_shorts_stream, decode_eod_intraday_chunks, decode_eod_intraday_stream,
decode_eod_price_chunks, decode_eod_price_stream, decode_qm_dividend_chunks,
decode_qm_dividend_stream, decode_qm_earnings_chunks, decode_qm_earnings_stream,
decode_qm_filings_chunks, decode_qm_filings_stream, decode_qm_intraday_chunks,
decode_qm_intraday_stream, decode_qm_price_chunks, decode_qm_price_stream,
decode_qm_split_chunks, decode_qm_split_stream, decode_te_market_data_chunks,
decode_te_market_data_stream, BsonCeoPostsStreamError, BsonCeoShortsStreamError,
BsonQmEventsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunk, RawBsonChunkReader,
DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES,
decode_qm_filings_chunks, decode_qm_filings_stream, decode_qm_financials_chunks,
decode_qm_financials_stream, decode_qm_intraday_chunks, decode_qm_intraday_stream,
decode_qm_price_chunks, decode_qm_price_stream, decode_qm_split_chunks,
decode_qm_split_stream, decode_te_market_data_chunks, decode_te_market_data_stream,
BsonCeoPostsStreamError, BsonCeoShortsStreamError, BsonQmEventsStreamError,
BsonQmFinancialsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunk,
RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES,
};
pub use bson_te_data::{
decode_te_data_buffer, decode_te_data_bytes, decode_te_data_doc, BsonTeDataDecodeStats,
BsonTeDataError, TeDataPoint,
};
pub use bson_te_market_data::{
decode_te_market_data_buffer, decode_te_market_data_bytes, decode_te_market_data_doc,
@ -139,6 +155,11 @@ pub use ilp::{
DEFAULT_ILP_MAX_BATCH_BYTES, DEFAULT_ILP_MAX_BATCH_ROWS, FNV1A_64_OFFSET_BASIS,
FNV1A_64_PRIME, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M, TABLE_FX_1M,
};
pub use macro_series::{
build_macro_rows, MacroBuild, MacroBuildStats, MacroError, MacroLagClass, MacroObservation,
MacroRow, GDP65_LAG_DAYS, GDP90_LAG_DAYS, MACRO_KNOWN_AT_SOURCE, MONTHLY_RELEASE_LAG_DAYS,
POLICY_RATE_LAG_DAYS,
};
pub use mongo_safety::{
assert_read_only_mongo_uri, is_qa_mongo_target, parse_mongo_target, LocalHosts,
MongoSafetyError, MongoScheme, MongoTarget, MongoTargetHost, ReadOnlyPolicy,
@ -179,6 +200,10 @@ pub use parquet_fx::{
fx_1d_parquet_schema, write_fx_1d_dataset, Fx1dParquetRow, Fx1dWriteOptions, Fx1dWriteStats,
ParquetFxError,
};
pub use parquet_macro::{
macro_parquet_schema, write_macro_dataset, MacroParquetRow, MacroWriteOptions, MacroWriteStats,
ParquetMacroError,
};
pub use parquet_posts::{
posts_to_event_rows, EVENT_KIND_POST, KNOWN_AT_SOURCE_POST_EDITED,
KNOWN_AT_SOURCE_POST_TIMESTAMP, POST_SUBTYPE_NEWSWIRE, POST_SUBTYPE_RETAIL,
@ -237,6 +262,19 @@ pub use curate_posts::{
CuratePostsWriteError, CuratePostsWriteReport,
};
pub mod curate_fundamentals;
pub use curate_fundamentals::{
curate_and_write_fundamentals, curate_fundamentals, CurateFundamentalsError,
CurateFundamentalsOutput, CurateFundamentalsStats, CurateFundamentalsWriteError,
CurateFundamentalsWriteReport,
};
pub mod curate_macro;
pub use curate_macro::{
curate_and_write_macro, curate_macro, CurateMacroError, CurateMacroOutput, CurateMacroStats,
CurateMacroWriteError, CurateMacroWriteReport, MacroSeriesTarget,
};
pub mod curate_fx;
pub use curate_fx::{
curate_and_write_fx_1d, curate_fx_1d, fx_1d_utc_day_end_micros, CurateFx1dOutput,
@ -315,6 +353,13 @@ pub use run_curate_posts::{
CuratePostsRunReport, RunCuratePostsError,
};
pub mod run_curate_fundamentals;
pub use run_curate_fundamentals::{
format_curate_fundamentals_report, load_listing_venues_tsv, run_curate_fundamentals,
run_curate_fundamentals_with_readers, CurateFundamentalsArgs, CurateFundamentalsFiscalPeriod,
CurateFundamentalsRunReport, RunCurateFundamentalsError, DEFAULT_FUNDAMENTALS_MAPPING_SOURCE,
};
pub mod run_curate_shorts;
pub use run_curate_shorts::{
format_curate_shorts_report, run_curate_shorts, run_curate_shorts_with_reader,

View file

@ -0,0 +1,284 @@
//! Pure, in-memory `macro` builder for lagged `teData` regime series (`MacroObservation<K>` +
//! caller-supplied [`MacroLagClass`] → sorted, unique [`MacroRow<K>`]s matching
//! `macro/part.parquet` in `design/DATA-CONTRACTS.md` §1 and §3A).
//!
//! ## Governance & Provenance Assumptions
//! - **Regime-use policy owner:** Quant Research owns which macro indicators are admissible for
//! coarse regime filters and how estimated publication lags are stress-tested.
//! - **Lag-mapping owner:** The caller owns the explicit `(country_iso, indicator) -> Option<MacroLagClass>`
//! lookup. Indicator names are **not** hardcoded here because live TradingEconomics indicator
//! names in `teIndicators` / `teData` are unverified in this crate (unverified assumption).
//! - **Final-revised source data:** `teData` stores `{d, v}` final-revised values only, with no
//! verified release timestamps or historical revision vintages. Every emitted row carries
//! [`MACRO_KNOWN_AT_SOURCE`] (`"publication_lag_estimate"`) and becomes available strictly at
//! its estimated `known_at` (`00:00:00 UTC` on `period_date + lag_days`).
//!
//! ## Builder Rules
//! 1. **Fail-closed mapping & validation:** Each input observation is counted once in
//! [`MacroBuildStats::input`]. Unmapped `(country_iso, indicator)` pairs are skipped first
//! (`skipped_unmapped_indicator`) and never given a default lag. Mapped observations with
//! non-finite `value` (`NaN` / `±inf`) are skipped (`skipped_non_finite_value`).
//! 2. **Deterministic deduplication:** Surviving observations are sorted by
//! `(country_iso, indicator, period_date)`. Bitwise-identical duplicates (`f64::to_bits()`)
//! collapse to one row and count each extra copy in `skipped_duplicate`. Any conflicting value
//! for the same `(country_iso, indicator, period_date)`—including opposite signed zeros (`+0.0`
//! vs. `-0.0`)—fails the build with [`MacroError::ConflictingDuplicate`], independent of input
//! order.
//! 3. **Checked `known_at` arithmetic:** `known_at` is computed as
//! `00:00:00 UTC` on `period_date + lag_days` using checked `i32` date addition and checked
//! `i64` microsecond scaling (`86_400_000_000` µs/day). Overflow returns
//! [`MacroError::KnownAtOverflow`] rather than panicking.
//! 4. **Accounting invariant:**
//! `input == emitted + skipped_unmapped_indicator + skipped_non_finite_value + skipped_duplicate`.
use std::error::Error;
use std::fmt;
use crate::shorts::epoch_days_to_ymd;
/// Locked publication lag (calendar days) for central-bank policy rates (`design/DATA-CONTRACTS.md` §1).
pub const POLICY_RATE_LAG_DAYS: i32 = 1;
/// Locked publication lag (calendar days) for monthly releases such as CPI / NFP (`design/DATA-CONTRACTS.md` §1).
pub const MONTHLY_RELEASE_LAG_DAYS: i32 = 35;
/// Locked publication lag (calendar days) for 65-day GDP releases (`design/DATA-CONTRACTS.md` §1).
pub const GDP65_LAG_DAYS: i32 = 65;
/// Locked publication lag (calendar days) for 90-day GDP releases (`design/DATA-CONTRACTS.md` §1).
pub const GDP90_LAG_DAYS: i32 = 90;
/// Canonical provenance label written to [`MacroRow::known_at_source`].
pub const MACRO_KNOWN_AT_SOURCE: &str = "publication_lag_estimate";
const MICROS_PER_DAY: i64 = 86_400_000_000;
/// Caller-assigned publication lag class from `design/DATA-CONTRACTS.md` §1.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum MacroLagClass {
/// Central-bank policy rates (`+1` calendar day).
PolicyRate,
/// Monthly macro releases such as CPI / NFP (`+35` calendar days).
MonthlyRelease,
/// Faster GDP releases (`+65` calendar days).
Gdp65,
/// Conservative / slower GDP releases (`+90` calendar days).
Gdp90,
}
impl MacroLagClass {
/// Returns the locked publication lag in calendar days.
#[inline]
pub const fn lag_days(self) -> i32 {
match self {
Self::PolicyRate => POLICY_RATE_LAG_DAYS,
Self::MonthlyRelease => MONTHLY_RELEASE_LAG_DAYS,
Self::Gdp65 => GDP65_LAG_DAYS,
Self::Gdp90 => GDP90_LAG_DAYS,
}
}
}
/// A single raw `teData` macro observation input (BSON-free).
#[derive(Debug, Clone, PartialEq)]
pub struct MacroObservation<K = String> {
pub country_iso: K,
pub indicator: K,
/// Observation period date as days since `1970-01-01` (UTC Gregorian).
pub period_date: i32,
pub value: f64,
}
/// A single curated `macro` row matching `macro/part.parquet` in `design/DATA-CONTRACTS.md` §3A,
/// sorted and unique by `(country_iso, indicator, period_date)`.
#[derive(Debug, Clone, PartialEq)]
pub struct MacroRow<K = String> {
pub country_iso: K,
pub indicator: K,
/// Observation period date as days since `1970-01-01` (UTC Gregorian).
pub period_date: i32,
/// Estimated point-in-time availability timestamp (`00:00:00 UTC` of `period_date + lag_days`)
/// in UTC microseconds since `1970-01-01T00:00:00Z`.
pub known_at: i64,
pub known_at_source: &'static str,
pub value: f64,
}
/// Summary accounting counters produced alongside [`MacroBuild::rows`].
///
/// Conservation invariant:
/// `input == emitted + skipped_unmapped_indicator + skipped_non_finite_value + skipped_duplicate`
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct MacroBuildStats {
pub input: usize,
pub emitted: usize,
pub skipped_unmapped_indicator: usize,
pub skipped_non_finite_value: usize,
pub skipped_duplicate: usize,
}
/// Output of [`build_macro_rows`]: sorted, unique lagged macro rows and reconciling stats.
#[derive(Debug, Clone, PartialEq)]
pub struct MacroBuild<K = String> {
pub rows: Vec<MacroRow<K>>,
pub stats: MacroBuildStats,
}
/// Typed errors returned by [`build_macro_rows`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MacroError<K = String> {
/// Two or more mapped, finite observations shared `(country_iso, indicator, period_date)` with
/// non-identical `f64::to_bits()` values (including opposite signed zeros `+0.0` vs. `-0.0`).
ConflictingDuplicate {
country_iso: K,
indicator: K,
period_date: i32,
},
/// Computing `00:00:00 UTC` for `period_date + lag_class.lag_days()` overflowed `i32` day
/// addition or `i64` microsecond scaling.
KnownAtOverflow {
period_date: i32,
lag_class: MacroLagClass,
},
}
impl<K: fmt::Debug> fmt::Display for MacroError<K> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ConflictingDuplicate {
country_iso,
indicator,
period_date,
} => {
let (y, m, d) = epoch_days_to_ymd(*period_date);
write!(
f,
"conflicting duplicate macro observation for ({country_iso:?}, {indicator:?}, {y:04}-{m:02}-{d:02} [epoch_day={period_date}])"
)
}
Self::KnownAtOverflow {
period_date,
lag_class,
} => write!(
f,
"known_at timestamp overflow for period_date={period_date} with lag_class={lag_class:?} (+{} days)",
lag_class.lag_days()
),
}
}
}
impl<K: fmt::Debug> Error for MacroError<K> {}
struct MappedObservation<K> {
country_iso: K,
indicator: K,
period_date: i32,
lag_class: MacroLagClass,
value: f64,
}
/// Builds sorted, unique lagged `macro` rows from raw observations and a caller-supplied
/// `(country_iso, indicator) -> Option<MacroLagClass>` lookup.
///
/// The caller lookup `lag_for` must be deterministic/stable for each exact `(country_iso, indicator)`
/// pair. Any permutation of `observations` produces identical `rows` (including `f64` bit patterns)
/// and `stats`, or the same [`MacroError`].
pub fn build_macro_rows<K, I, F>(
observations: I,
lag_for: F,
) -> Result<MacroBuild<K>, MacroError<K>>
where
K: Ord,
I: IntoIterator<Item = MacroObservation<K>>,
F: Fn(&K, &K) -> Option<MacroLagClass>,
{
let iter = observations.into_iter();
let (lower, _) = iter.size_hint();
let mut stats = MacroBuildStats::default();
let mut mapped: Vec<MappedObservation<K>> = Vec::with_capacity(lower);
for obs in iter {
stats.input += 1;
let Some(lag_class) = lag_for(&obs.country_iso, &obs.indicator) else {
stats.skipped_unmapped_indicator += 1;
continue;
};
if !obs.value.is_finite() {
stats.skipped_non_finite_value += 1;
continue;
}
mapped.push(MappedObservation {
country_iso: obs.country_iso,
indicator: obs.indicator,
period_date: obs.period_date,
lag_class,
value: obs.value,
});
}
mapped.sort_unstable_by(|a, b| {
a.country_iso
.cmp(&b.country_iso)
.then_with(|| a.indicator.cmp(&b.indicator))
.then_with(|| a.period_date.cmp(&b.period_date))
});
let mut rows: Vec<MacroRow<K>> = Vec::with_capacity(mapped.len());
let mut sorted = mapped.into_iter().peekable();
while let Some(first) = sorted.next() {
while let Some(next) = sorted.peek() {
if next.country_iso == first.country_iso
&& next.indicator == first.indicator
&& next.period_date == first.period_date
{
if next.value.to_bits() != first.value.to_bits() {
return Err(MacroError::ConflictingDuplicate {
country_iso: first.country_iso,
indicator: first.indicator,
period_date: first.period_date,
});
}
stats.skipped_duplicate += 1;
sorted.next();
} else {
break;
}
}
let known_at_day = first
.period_date
.checked_add(first.lag_class.lag_days())
.ok_or(MacroError::KnownAtOverflow {
period_date: first.period_date,
lag_class: first.lag_class,
})?;
let known_at = i64::from(known_at_day)
.checked_mul(MICROS_PER_DAY)
.ok_or(MacroError::KnownAtOverflow {
period_date: first.period_date,
lag_class: first.lag_class,
})?;
rows.push(MacroRow {
country_iso: first.country_iso,
indicator: first.indicator,
period_date: first.period_date,
known_at,
known_at_source: MACRO_KNOWN_AT_SOURCE,
value: first.value,
});
}
stats.emitted = rows.len();
Ok(MacroBuild { rows, stats })
}
#[cfg(test)]
#[path = "macro_series_tests.rs"]
mod tests;

View file

@ -0,0 +1,601 @@
use super::*;
use crate::split::ymd_to_epoch_days;
fn day(y: i32, m: u32, d: u32) -> i32 {
ymd_to_epoch_days(y, m, d).expect("valid test date")
}
fn obs(
country_iso: &str,
indicator: &str,
period_date: i32,
value: f64,
) -> MacroObservation<String> {
MacroObservation {
country_iso: country_iso.to_string(),
indicator: indicator.to_string(),
period_date,
value,
}
}
fn assert_accounting_and_order<K: Ord>(build: &MacroBuild<K>) {
let s = &build.stats;
assert_eq!(s.emitted, build.rows.len());
assert_eq!(
s.input,
s.emitted + s.skipped_unmapped_indicator + s.skipped_non_finite_value + s.skipped_duplicate,
"accounting invariant failed: {s:?}"
);
for pair in build.rows.windows(2) {
assert!(
(
&pair[0].country_iso,
&pair[0].indicator,
pair[0].period_date
) < (
&pair[1].country_iso,
&pair[1].indicator,
pair[1].period_date
),
"rows must be strictly sorted and unique by (country_iso, indicator, period_date)"
);
}
for row in &build.rows {
assert_eq!(row.known_at_source, MACRO_KNOWN_AT_SOURCE);
let period_midnight = i64::from(row.period_date) * 86_400_000_000;
assert!(
row.known_at > period_midnight,
"look-ahead violation: known_at {} <= period midnight {}",
row.known_at,
period_midnight
);
}
}
fn assert_rows_bit_eq<K: PartialEq + std::fmt::Debug>(left: &[MacroRow<K>], right: &[MacroRow<K>]) {
assert_eq!(left.len(), right.len());
for (a, b) in left.iter().zip(right.iter()) {
assert_eq!(a.country_iso, b.country_iso);
assert_eq!(a.indicator, b.indicator);
assert_eq!(a.period_date, b.period_date);
assert_eq!(a.known_at, b.known_at);
assert_eq!(a.known_at_source, b.known_at_source);
assert_eq!(a.value.to_bits(), b.value.to_bits());
}
}
#[test]
fn lag_classes_produce_exact_utc_midnights() {
assert_eq!(POLICY_RATE_LAG_DAYS, 1);
assert_eq!(MONTHLY_RELEASE_LAG_DAYS, 35);
assert_eq!(GDP65_LAG_DAYS, 65);
assert_eq!(GDP90_LAG_DAYS, 90);
assert_eq!(MacroLagClass::PolicyRate.lag_days(), 1);
assert_eq!(MacroLagClass::MonthlyRelease.lag_days(), 35);
assert_eq!(MacroLagClass::Gdp65.lag_days(), 65);
assert_eq!(MacroLagClass::Gdp90.lag_days(), 90);
assert_eq!(MACRO_KNOWN_AT_SOURCE, "publication_lag_estimate");
let jan31 = day(2024, 1, 31);
let inputs = vec![
obs("US", "ind_policy", jan31, 5.50),
obs("US", "ind_monthly", jan31, 3.10),
obs("US", "ind_gdp65", jan31, 2.25),
obs("US", "ind_gdp90", jan31, 1.80),
];
let build = build_macro_rows(inputs, |country, indicator| {
match (country.as_str(), indicator.as_str()) {
("US", "ind_policy") => Some(MacroLagClass::PolicyRate),
("US", "ind_monthly") => Some(MacroLagClass::MonthlyRelease),
("US", "ind_gdp65") => Some(MacroLagClass::Gdp65),
("US", "ind_gdp90") => Some(MacroLagClass::Gdp90),
_ => None,
}
})
.expect("lag class fixture should succeed");
assert_accounting_and_order(&build);
assert_eq!(
build.stats,
MacroBuildStats {
input: 4,
emitted: 4,
skipped_unmapped_indicator: 0,
skipped_non_finite_value: 0,
skipped_duplicate: 0,
}
);
// Sorted alphabetically by indicator: ind_gdp65, ind_gdp90, ind_monthly, ind_policy
let expected: [(&str, i64, f64); 4] = [
("ind_gdp65", 1_712_275_200_000_000, 2.25), // 2024-04-05T00:00:00Z
("ind_gdp90", 1_714_435_200_000_000, 1.80), // 2024-04-30T00:00:00Z
("ind_monthly", 1_709_683_200_000_000, 3.10), // 2024-03-06T00:00:00Z (+35d across 2024-02-29)
("ind_policy", 1_706_745_600_000_000, 5.50), // 2024-02-01T00:00:00Z
];
assert_eq!(build.rows.len(), expected.len());
for (row, (indicator, known_at, value)) in build.rows.iter().zip(expected.iter()) {
assert_eq!(row.country_iso, "US");
assert_eq!(row.indicator, *indicator);
assert_eq!(row.period_date, jan31);
assert_eq!(row.known_at, *known_at);
assert_eq!(row.known_at_source, MACRO_KNOWN_AT_SOURCE);
assert_eq!(row.value.to_bits(), value.to_bits());
}
}
#[test]
fn skips_unmapped_and_non_finite_once() {
let d = day(2024, 6, 30);
let inputs = vec![
// Mapped indicator for US, valid value -> emitted
obs("US", "cpi_yoy", d, 3.0),
// Same indicator in unmapped country -> skipped_unmapped_indicator (pair-keyed lookup)
obs("CA", "cpi_yoy", d, 2.7),
// Unmapped indicator with NaN -> counted once as skipped_unmapped_indicator (precedence)
obs("CA", "cpi_yoy", day(2024, 7, 31), f64::NAN),
// Mapped pair with NaN, +inf, -inf -> skipped_non_finite_value
obs("US", "cpi_yoy", day(2024, 7, 31), f64::NAN),
obs("US", "cpi_yoy", day(2024, 8, 31), f64::INFINITY),
obs("US", "cpi_yoy", day(2024, 9, 30), f64::NEG_INFINITY),
];
let build = build_macro_rows(inputs, |country, indicator| {
if country == "US" && indicator == "cpi_yoy" {
Some(MacroLagClass::MonthlyRelease)
} else {
None
}
})
.expect("skips should not fail the build");
assert_accounting_and_order(&build);
assert_eq!(
build.stats,
MacroBuildStats {
input: 6,
emitted: 1,
skipped_unmapped_indicator: 2,
skipped_non_finite_value: 3,
skipped_duplicate: 0,
}
);
assert_eq!(build.rows[0].country_iso, "US");
assert_eq!(build.rows[0].indicator, "cpi_yoy");
assert_eq!(build.rows[0].period_date, d);
assert_eq!(build.rows[0].value.to_bits(), 3.0_f64.to_bits());
}
#[test]
fn sorts_deduplicates_and_accounts_for_all_inputs() {
let empty: Vec<MacroObservation<String>> = Vec::new();
let empty_build =
build_macro_rows(empty, |_, _| Some(MacroLagClass::PolicyRate)).expect("empty succeeds");
assert!(empty_build.rows.is_empty());
assert_eq!(empty_build.stats, MacroBuildStats::default());
assert_accounting_and_order(&empty_build);
let d1 = day(2024, 1, 31);
let d2 = day(2024, 2, 29);
let fixture_a = vec![
obs("US", "rate", d2, 5.25),
obs("CA", "gdp", d1, 1.50),
obs("US", "rate", d1, 5.50),
obs("CA", "gdp", d1, 1.50), // exact duplicate
obs("CA", "gdp", d1, 1.50), // second exact duplicate
obs("US", "unmapped_ind", d1, 42.0),
obs("US", "rate", day(2024, 3, 31), f64::NAN),
obs("CA", "rate", d1, -0.0), // signed zero preserved identically
obs("CA", "rate", d1, -0.0), // bitwise-identical -0.0 duplicate collapses
];
let fixture_b = vec![
obs("CA", "rate", d1, -0.0),
obs("US", "rate", day(2024, 3, 31), f64::NAN),
obs("CA", "gdp", d1, 1.50),
obs("US", "unmapped_ind", d1, 42.0),
obs("US", "rate", d1, 5.50),
obs("CA", "rate", d1, -0.0),
obs("CA", "gdp", d1, 1.50),
obs("US", "rate", d2, 5.25),
obs("CA", "gdp", d1, 1.50),
];
let lag_for =
|country: &String, indicator: &String| match (country.as_str(), indicator.as_str()) {
("CA", "gdp") => Some(MacroLagClass::Gdp65),
("CA", "rate") | ("US", "rate") => Some(MacroLagClass::PolicyRate),
_ => None,
};
let build_a = build_macro_rows(fixture_a, lag_for).expect("fixture_a succeeds");
let build_b = build_macro_rows(fixture_b, lag_for).expect("fixture_b succeeds");
assert_accounting_and_order(&build_a);
assert_accounting_and_order(&build_b);
assert_rows_bit_eq(&build_a.rows, &build_b.rows);
assert_eq!(build_a.stats, build_b.stats);
assert_eq!(
build_a.stats,
MacroBuildStats {
input: 9,
emitted: 4,
skipped_unmapped_indicator: 1,
skipped_non_finite_value: 1,
skipped_duplicate: 3,
}
);
let keys: Vec<(&str, &str, i32)> = build_a
.rows
.iter()
.map(|r| (r.country_iso.as_str(), r.indicator.as_str(), r.period_date))
.collect();
assert_eq!(
keys,
vec![
("CA", "gdp", d1),
("CA", "rate", d1),
("US", "rate", d1),
("US", "rate", d2),
]
);
assert_eq!(build_a.rows[1].value.to_bits(), (-0.0_f64).to_bits());
}
#[test]
fn rejects_conflicting_duplicates_in_either_order() {
let d = day(2024, 3, 31);
let lag_for = |_: &String, _: &String| Some(MacroLagClass::MonthlyRelease);
// Distinct finite values in both orders
let err_ab = build_macro_rows(
vec![obs("US", "cpi", d, 3.1), obs("US", "cpi", d, 3.2)],
lag_for,
)
.expect_err("distinct duplicate values must fail");
let err_ba = build_macro_rows(
vec![obs("US", "cpi", d, 3.2), obs("US", "cpi", d, 3.1)],
lag_for,
)
.expect_err("distinct duplicate values in reverse order must fail");
let expected = MacroError::ConflictingDuplicate {
country_iso: "US".to_string(),
indicator: "cpi".to_string(),
period_date: d,
};
assert_eq!(err_ab, expected);
assert_eq!(err_ba, expected);
assert!(err_ab.to_string().contains("2024-03-31"));
// Opposite signed zeros (+0.0 vs -0.0) in both orders
let err_pos_neg = build_macro_rows(
vec![obs("CA", "cpi", d, 0.0), obs("CA", "cpi", d, -0.0)],
lag_for,
)
.expect_err("+0.0 vs -0.0 must be treated as conflicting");
let err_neg_pos = build_macro_rows(
vec![obs("CA", "cpi", d, -0.0), obs("CA", "cpi", d, 0.0)],
lag_for,
)
.expect_err("-0.0 vs +0.0 must be treated as conflicting");
let expected_zero = MacroError::ConflictingDuplicate {
country_iso: "CA".to_string(),
indicator: "cpi".to_string(),
period_date: d,
};
assert_eq!(err_pos_neg, expected_zero);
assert_eq!(err_neg_pos, expected_zero);
}
#[test]
fn returns_typed_known_at_overflow() {
// 1. i32 day addition overflow: i32::MAX + 1
let err_add = build_macro_rows(vec![obs("US", "rate", i32::MAX, 5.0)], |_, _| {
Some(MacroLagClass::PolicyRate)
})
.expect_err("i32::MAX + PolicyRate must overflow");
assert_eq!(
err_add,
MacroError::KnownAtOverflow {
period_date: i32::MAX,
lag_class: MacroLagClass::PolicyRate,
}
);
assert!(err_add.to_string().contains("known_at timestamp overflow"));
// 2. i64 microsecond multiplication overflow after valid i32 addition:
// (106_751_991 + 1) * 86_400_000_000 > i64::MAX
let err_mul = build_macro_rows(vec![obs("US", "rate", 106_751_991, 5.0)], |_, _| {
Some(MacroLagClass::PolicyRate)
})
.expect_err("106_751_991 + PolicyRate must overflow microsecond scaling");
assert_eq!(
err_mul,
MacroError::KnownAtOverflow {
period_date: 106_751_991,
lag_class: MacroLagClass::PolicyRate,
}
);
// 3. Adjacent representable PolicyRate case succeeds:
// (106_751_990 + 1) * 86_400_000_000 == 9_223_372_020_000_000_000 <= i64::MAX
let ok = build_macro_rows(vec![obs("US", "rate", 106_751_990, 5.0)], |_, _| {
Some(MacroLagClass::PolicyRate)
})
.expect("adjacent representable policy-rate date must succeed");
assert_accounting_and_order(&ok);
assert_eq!(ok.rows.len(), 1);
assert_eq!(ok.rows[0].period_date, 106_751_990);
assert_eq!(ok.rows[0].known_at, 106_751_991_i64 * 86_400_000_000);
}
// ---- QA edge cases (T-172) ----
// `build_macro_rows` passes `&K`, so with `K = String` the lookup must take `&String`.
#[allow(clippy::ptr_arg)]
fn qa_lag(country: &String, indicator: &String) -> Option<MacroLagClass> {
match (country.as_str(), indicator.as_str()) {
("CA", "gdp") => Some(MacroLagClass::Gdp90),
("CA", "rate") => Some(MacroLagClass::PolicyRate),
("US", "cpi") => Some(MacroLagClass::MonthlyRelease),
("US", "gdp") => Some(MacroLagClass::Gdp65),
_ => None,
}
}
fn permutations<T: Clone>(items: &[T]) -> Vec<Vec<T>> {
if items.len() <= 1 {
return vec![items.to_vec()];
}
let mut out = Vec::new();
for i in 0..items.len() {
let mut rest = items.to_vec();
let head = rest.remove(i);
for mut tail in permutations(&rest) {
tail.insert(0, head.clone());
out.push(tail);
}
}
out
}
#[test]
fn every_permutation_of_mixed_fixture_yields_identical_build() {
let d1 = day(2023, 12, 31);
let d2 = day(2024, 3, 31);
let base = vec![
obs("US", "cpi", d2, 3.5),
obs("CA", "gdp", d1, -0.0),
obs("CA", "gdp", d1, -0.0),
obs("US", "cpi", d1, f64::NAN),
obs("XX", "cpi", d1, 1.0),
obs("CA", "rate", d2, 5.0),
obs("US", "gdp", d1, 2.1),
];
let reference = build_macro_rows(base.clone(), qa_lag).expect("reference build");
assert_accounting_and_order(&reference);
assert_eq!(
reference.stats,
MacroBuildStats {
input: 7,
emitted: 4,
skipped_unmapped_indicator: 1,
skipped_non_finite_value: 1,
skipped_duplicate: 1,
}
);
let perms = permutations(&base);
assert_eq!(perms.len(), 5040);
for perm in perms {
let build = build_macro_rows(perm, qa_lag).expect("permutation build");
assert_eq!(build.stats, reference.stats);
assert_rows_bit_eq(&build.rows, &reference.rows);
}
}
#[test]
fn conflict_anywhere_in_duplicate_group_fails_in_every_order() {
let d = day(2024, 1, 31);
let base = vec![
obs("US", "cpi", d, 3.1),
obs("US", "cpi", d, 3.1),
obs("US", "cpi", d, 3.2),
obs("CA", "rate", d, 5.0),
];
let expected = MacroError::ConflictingDuplicate {
country_iso: "US".to_string(),
indicator: "cpi".to_string(),
period_date: d,
};
for perm in permutations(&base) {
assert_eq!(build_macro_rows(perm, qa_lag), Err(expected.clone()));
}
}
#[test]
fn non_finite_copy_of_a_key_is_skipped_not_treated_as_conflict() {
let d = day(2024, 1, 31);
for inputs in [
vec![obs("US", "cpi", d, f64::NAN), obs("US", "cpi", d, 3.1)],
vec![obs("US", "cpi", d, 3.1), obs("US", "cpi", d, f64::INFINITY)],
] {
let build = build_macro_rows(inputs, qa_lag).expect("non-finite copy is skipped");
assert_accounting_and_order(&build);
assert_eq!(build.rows.len(), 1);
assert_eq!(build.rows[0].value.to_bits(), 3.1_f64.to_bits());
assert_eq!(build.stats.skipped_non_finite_value, 1);
assert_eq!(build.stats.skipped_duplicate, 0);
}
}
#[test]
fn unmapped_duplicates_and_conflicts_are_counted_as_unmapped_only() {
let d = day(2024, 1, 31);
let build = build_macro_rows(
vec![
obs("XX", "cpi", d, 1.0),
obs("XX", "cpi", d, 1.0),
obs("XX", "cpi", d, 2.0),
],
qa_lag,
)
.expect("unmapped conflicts must not error");
assert!(build.rows.is_empty());
assert_eq!(
build.stats,
MacroBuildStats {
input: 3,
emitted: 0,
skipped_unmapped_indicator: 3,
skipped_non_finite_value: 0,
skipped_duplicate: 0,
}
);
}
#[test]
fn lookup_receives_country_then_indicator() {
let d = day(2024, 1, 31);
let build = build_macro_rows(
vec![obs("US", "cpi", d, 3.0), obs("cpi", "US", d, 4.0)],
|country: &String, indicator: &String| {
(country == "US" && indicator == "cpi").then_some(MacroLagClass::MonthlyRelease)
},
)
.expect("build");
assert_eq!(build.rows.len(), 1);
assert_eq!(build.rows[0].country_iso, "US");
assert_eq!(build.rows[0].indicator, "cpi");
assert_eq!(build.stats.skipped_unmapped_indicator, 1);
}
#[test]
fn sorts_by_country_before_indicator_and_applies_per_pair_lag() {
let d = day(2024, 1, 31);
let build = build_macro_rows(
vec![
obs("US", "cpi", d, 3.0),
obs("CA", "rate", d, 5.0),
obs("US", "gdp", d, 2.0),
obs("CA", "gdp", d, 1.0),
],
qa_lag,
)
.expect("build");
assert_accounting_and_order(&build);
let got: Vec<(&str, &str, i64)> = build
.rows
.iter()
.map(|r| (r.country_iso.as_str(), r.indicator.as_str(), r.known_at))
.collect();
let micros = |days: i32| i64::from(days) * 86_400_000_000;
assert_eq!(
got,
vec![
("CA", "gdp", micros(day(2024, 4, 30))),
("CA", "rate", micros(day(2024, 2, 1))),
("US", "cpi", micros(day(2024, 3, 6))),
("US", "gdp", micros(day(2024, 4, 5))),
]
);
}
#[test]
fn pre_epoch_period_dates_produce_correct_known_at() {
let dec31_1969 = day(1969, 12, 31);
assert_eq!(dec31_1969, -1);
let build = build_macro_rows(
vec![
obs("CA", "rate", dec31_1969, 7.5),
obs("US", "cpi", day(1950, 1, 31), 1.2),
],
qa_lag,
)
.expect("pre-epoch dates are valid");
assert_accounting_and_order(&build);
// 1969-12-31 + 1d = 1970-01-01T00:00:00Z
assert_eq!(build.rows[0].known_at, 0);
// 1950-01-31 + 35d = 1950-03-07T00:00:00Z
assert_eq!(
build.rows[1].known_at,
i64::from(day(1950, 3, 7)) * 86_400_000_000
);
assert_eq!(build.rows[1].known_at, -625_536_000_000_000);
}
#[test]
fn negative_microsecond_overflow_is_typed_error() {
let err = build_macro_rows(vec![obs("US", "cpi", i32::MIN, 1.0)], qa_lag)
.expect_err("i32::MIN days scaled to micros underflows i64");
assert_eq!(
err,
MacroError::KnownAtOverflow {
period_date: i32::MIN,
lag_class: MacroLagClass::MonthlyRelease,
}
);
}
#[test]
fn overflow_boundary_for_each_lag_class() {
// Largest representable known_at day is i64::MAX / 86_400_000_000 = 106_751_991.
let max_day: i32 = 106_751_991;
for class in [
MacroLagClass::PolicyRate,
MacroLagClass::MonthlyRelease,
MacroLagClass::Gdp65,
MacroLagClass::Gdp90,
] {
let ok_date = max_day - class.lag_days();
let ok = build_macro_rows(vec![obs("US", "x", ok_date, 1.0)], |_, _| Some(class))
.expect("boundary date succeeds");
assert_eq!(ok.rows[0].known_at, i64::from(max_day) * 86_400_000_000);
let err = build_macro_rows(vec![obs("US", "x", ok_date + 1, 1.0)], |_, _| Some(class))
.expect_err("one day past boundary overflows");
assert_eq!(
err,
MacroError::KnownAtOverflow {
period_date: ok_date + 1,
lag_class: class,
}
);
}
}
#[test]
fn borrowed_str_keys_are_supported() {
let d = day(2024, 1, 31);
let inputs: Vec<MacroObservation<&str>> = vec![
MacroObservation {
country_iso: "US",
indicator: "cpi",
period_date: d,
value: 3.0,
},
MacroObservation {
country_iso: "CA",
indicator: "rate",
period_date: d,
value: 5.0,
},
];
let build = build_macro_rows(inputs, |c: &&str, i: &&str| match (*c, *i) {
("US", "cpi") => Some(MacroLagClass::MonthlyRelease),
("CA", "rate") => Some(MacroLagClass::PolicyRate),
_ => None,
})
.expect("build");
assert_accounting_and_order(&build);
assert_eq!(build.rows[0].country_iso, "CA");
assert_eq!(build.rows[1].country_iso, "US");
}

View file

@ -0,0 +1,776 @@
//! Streaming, atomic Zstd Parquet writer for `macro`.
//!
//! Writes `<out_dir>/macro/part.parquet` matching the 6-column contract schema in
//! `design/DATA-CONTRACTS.md` (§3A):
//!
//! 1. `country_iso` (`BYTE_ARRAY`, `REQUIRED`, `STRING`)
//! 2. `indicator` (`BYTE_ARRAY`, `REQUIRED`, `STRING`)
//! 3. `period_date` (`INT32`, `REQUIRED`, `DATE`)
//! 4. `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`)
//! 5. `known_at_source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`)
//! 6. `value` (`DOUBLE`, `REQUIRED`)
//!
//! ## Timestamp Units & Provenance
//! [`crate::macro_series::MacroRow::known_at`] is already in UTC microseconds since
//! `1970-01-01T00:00:00Z` (`00:00:00 UTC` of `period_date + lag_days`), so
//! `From<&MacroRow<K>>` copies it directly into [`MacroParquetRow::known_at_micros`]
//! without unit conversion and preserves `known_at_source` and `value` bit-for-bit.
use std::borrow::{Borrow, Cow};
use std::cmp::Ordering;
use std::error::Error;
use std::fmt;
use std::fs::{self, File};
use std::io::{self, BufWriter, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use parquet::basic::{Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel};
use parquet::data_type::ByteArray;
use parquet::errors::ParquetError;
use parquet::file::properties::{WriterProperties, WriterPropertiesPtr};
use parquet::file::writer::SerializedFileWriter;
use parquet::schema::types::{ColumnPath, Type, TypePtr};
use crate::macro_series::MacroRow;
use crate::parquet_publish::{
create_backup_preserving_live, create_exclusive_tmp_file, dataset_mutex, next_run_id,
write_f64_col, write_i32_col, write_i64_col, write_interned_str_col, DatasetFileLock,
PublishIoError, StagingFileGuard, StringInterner, DEFAULT_LOCK_TIMEOUT,
FILE_BUF_CAPACITY_BYTES, STRING_WRITE_BATCH_ROWS,
};
pub use crate::parquet_publish::{RollbackFailure, DEFAULT_ROW_GROUP_ROWS, DEFAULT_ZSTD_LEVEL};
/// Single `macro` row matching the `design/DATA-CONTRACTS.md` (§3A) Parquet schema.
#[derive(Debug, Clone, PartialEq)]
pub struct MacroParquetRow {
pub country_iso: Cow<'static, str>,
pub indicator: Cow<'static, str>,
/// Observation period date as days since `1970-01-01` (UTC Gregorian).
pub period_date: i32,
/// Estimated point-in-time availability timestamp in UTC microseconds since
/// `1970-01-01T00:00:00Z`.
pub known_at_micros: i64,
pub known_at_source: Cow<'static, str>,
pub value: f64,
}
impl<K: AsRef<str>> From<&MacroRow<K>> for MacroParquetRow {
#[inline]
fn from(row: &MacroRow<K>) -> Self {
Self {
country_iso: Cow::Owned(row.country_iso.as_ref().to_owned()),
indicator: Cow::Owned(row.indicator.as_ref().to_owned()),
period_date: row.period_date,
// MacroRow.known_at is already UTC epoch microseconds.
known_at_micros: row.known_at,
known_at_source: Cow::Borrowed(row.known_at_source),
value: row.value,
}
}
}
/// Configuration for [`write_macro_dataset`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MacroWriteOptions {
pub row_group_rows: usize,
pub zstd_level: i32,
}
impl Default for MacroWriteOptions {
fn default() -> Self {
Self {
row_group_rows: DEFAULT_ROW_GROUP_ROWS,
zstd_level: DEFAULT_ZSTD_LEVEL,
}
}
}
/// Accounting summary returned by [`write_macro_dataset`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct MacroWriteStats {
pub rows_written: usize,
pub files_written: usize,
pub row_groups_written: usize,
pub bytes_written: u64,
}
/// Typed error returned by [`write_macro_dataset`].
#[derive(Debug)]
pub enum ParquetMacroError {
InvalidRowGroupRows,
InvalidZstdLevel {
level: i32,
},
UnsortedInput {
prev_country_iso: String,
prev_indicator: String,
prev_period_date: i32,
country_iso: String,
indicator: String,
period_date: i32,
},
DuplicateKey {
country_iso: String,
indicator: String,
period_date: i32,
},
EmptyCountryIso {
indicator: String,
period_date: i32,
},
EmptyIndicator {
country_iso: String,
period_date: i32,
},
EmptyKnownAtSource {
country_iso: String,
indicator: String,
period_date: i32,
},
InvalidValue {
country_iso: String,
indicator: String,
period_date: i32,
value: f64,
},
LockTimeout {
path: PathBuf,
waited: Duration,
},
RollbackFailed {
cause: Box<ParquetMacroError>,
failures: Vec<RollbackFailure>,
},
Io {
path: PathBuf,
source: io::Error,
},
Parquet {
path: PathBuf,
source: ParquetError,
},
}
impl fmt::Display for ParquetMacroError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidRowGroupRows => {
write!(f, "invalid row_group_rows: must be greater than 0")
}
Self::InvalidZstdLevel { level } => {
write!(f, "invalid Zstd compression level: {level}")
}
Self::UnsortedInput {
prev_country_iso,
prev_indicator,
prev_period_date,
country_iso,
indicator,
period_date,
} => write!(
f,
"unsorted input: ({country_iso}, {indicator}, {period_date}) follows ({prev_country_iso}, {prev_indicator}, {prev_period_date})"
),
Self::DuplicateKey {
country_iso,
indicator,
period_date,
} => write!(
f,
"duplicate (country_iso, indicator, period_date) key: ({country_iso}, {indicator}, {period_date})"
),
Self::EmptyCountryIso {
indicator,
period_date,
} => write!(
f,
"empty country_iso for ({indicator}, {period_date}): must be non-empty"
),
Self::EmptyIndicator {
country_iso,
period_date,
} => write!(
f,
"empty indicator for ({country_iso}, {period_date}): must be non-empty"
),
Self::EmptyKnownAtSource {
country_iso,
indicator,
period_date,
} => write!(
f,
"empty known_at_source for ({country_iso}, {indicator}, {period_date}): must be non-empty"
),
Self::InvalidValue {
country_iso,
indicator,
period_date,
value,
} => write!(
f,
"invalid value ({value}) for ({country_iso}, {indicator}, {period_date}): must be finite"
),
Self::LockTimeout { path, waited } => write!(
f,
"timed out after {}ms waiting for dataset write lock '{}' (if no writer is active, remove the stale lock file and retry)",
waited.as_millis(),
path.display()
),
Self::RollbackFailed { cause, failures } => {
write!(
f,
"publication failed ({cause}) and rollback encountered {} error(s) requiring manual recovery:",
failures.len()
)?;
for failure in failures {
write!(f, " [{failure}]")?;
}
Ok(())
}
Self::Io { path, source } => {
write!(f, "I/O error at '{}': {source}", path.display())
}
Self::Parquet { path, source } => {
write!(f, "Parquet error at '{}': {source}", path.display())
}
}
}
}
impl Error for ParquetMacroError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::RollbackFailed { cause, .. } => Some(cause.as_ref()),
Self::Io { source, .. } => Some(source),
Self::Parquet { source, .. } => Some(source),
_ => None,
}
}
}
impl From<PublishIoError> for ParquetMacroError {
fn from(err: PublishIoError) -> Self {
match err {
PublishIoError::LockTimeout { path, waited } => Self::LockTimeout { path, waited },
PublishIoError::Io { path, source } => Self::Io { path, source },
}
}
}
/// Builds the exact 6-column Parquet schema for `macro` per `design/DATA-CONTRACTS.md` (§3A).
pub fn macro_parquet_schema() -> Result<TypePtr, ParquetError> {
let fields: Vec<TypePtr> = vec![
Arc::new(
Type::primitive_type_builder("country_iso", PhysicalType::BYTE_ARRAY)
.with_repetition(Repetition::REQUIRED)
.with_logical_type(Some(LogicalType::String))
.build()?,
),
Arc::new(
Type::primitive_type_builder("indicator", PhysicalType::BYTE_ARRAY)
.with_repetition(Repetition::REQUIRED)
.with_logical_type(Some(LogicalType::String))
.build()?,
),
Arc::new(
Type::primitive_type_builder("period_date", PhysicalType::INT32)
.with_repetition(Repetition::REQUIRED)
.with_logical_type(Some(LogicalType::Date))
.build()?,
),
Arc::new(
Type::primitive_type_builder("known_at", PhysicalType::INT64)
.with_repetition(Repetition::REQUIRED)
.with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS)))
.build()?,
),
Arc::new(
Type::primitive_type_builder("known_at_source", PhysicalType::BYTE_ARRAY)
.with_repetition(Repetition::REQUIRED)
.with_logical_type(Some(LogicalType::String))
.build()?,
),
Arc::new(
Type::primitive_type_builder("value", PhysicalType::DOUBLE)
.with_repetition(Repetition::REQUIRED)
.build()?,
),
];
Ok(Arc::new(
Type::group_type_builder("macro")
.with_fields(fields)
.build()?,
))
}
fn build_writer_properties(zstd_level: ZstdLevel) -> WriterPropertiesPtr {
Arc::new(
WriterProperties::builder()
.set_compression(Compression::ZSTD(zstd_level))
.set_column_dictionary_enabled(ColumnPath::from("country_iso"), true)
.set_column_dictionary_enabled(ColumnPath::from("indicator"), true)
.set_column_dictionary_enabled(ColumnPath::from("known_at_source"), true)
.set_created_by(format!("curate-etl {}", env!("CARGO_PKG_VERSION")))
.build(),
)
}
#[inline]
fn validate_row(row: &MacroParquetRow) -> Result<(), ParquetMacroError> {
if row.country_iso.trim().is_empty() {
return Err(ParquetMacroError::EmptyCountryIso {
indicator: row.indicator.as_ref().to_owned(),
period_date: row.period_date,
});
}
if row.indicator.trim().is_empty() {
return Err(ParquetMacroError::EmptyIndicator {
country_iso: row.country_iso.as_ref().to_owned(),
period_date: row.period_date,
});
}
if row.known_at_source.trim().is_empty() {
return Err(ParquetMacroError::EmptyKnownAtSource {
country_iso: row.country_iso.as_ref().to_owned(),
indicator: row.indicator.as_ref().to_owned(),
period_date: row.period_date,
});
}
if !row.value.is_finite() {
return Err(ParquetMacroError::InvalidValue {
country_iso: row.country_iso.as_ref().to_owned(),
indicator: row.indicator.as_ref().to_owned(),
period_date: row.period_date,
value: row.value,
});
}
Ok(())
}
#[derive(Default)]
struct RowGroupBuffer {
country_iso_ids: Vec<u32>,
country_iso_interner: StringInterner,
indicator_ids: Vec<u32>,
indicator_interner: StringInterner,
period_date: Vec<i32>,
known_at_micros: Vec<i64>,
known_at_source_ids: Vec<u32>,
known_at_source_interner: StringInterner,
value: Vec<f64>,
}
impl RowGroupBuffer {
#[inline]
fn len(&self) -> usize {
self.period_date.len()
}
fn push(&mut self, row: &MacroParquetRow) {
let country_iso_id = self.country_iso_interner.intern(row.country_iso.as_ref());
self.country_iso_ids.push(country_iso_id);
let indicator_id = self.indicator_interner.intern(row.indicator.as_ref());
self.indicator_ids.push(indicator_id);
self.period_date.push(row.period_date);
self.known_at_micros.push(row.known_at_micros);
let known_at_source_id = self
.known_at_source_interner
.intern(row.known_at_source.as_ref());
self.known_at_source_ids.push(known_at_source_id);
self.value.push(row.value);
}
fn clear(&mut self) {
self.country_iso_ids.clear();
self.country_iso_interner.clear();
self.indicator_ids.clear();
self.indicator_interner.clear();
self.period_date.clear();
self.known_at_micros.clear();
self.known_at_source_ids.clear();
self.known_at_source_interner.clear();
self.value.clear();
}
}
struct MacroFileWriter {
tmp_path: PathBuf,
final_path: PathBuf,
writer: SerializedFileWriter<BufWriter<File>>,
buf: RowGroupBuffer,
rows_written: usize,
row_groups_written: usize,
}
impl MacroFileWriter {
fn from_file(
tmp_path: PathBuf,
final_path: PathBuf,
file: File,
schema: &TypePtr,
props: &WriterPropertiesPtr,
) -> Result<Self, ParquetMacroError> {
let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file);
let writer = SerializedFileWriter::new(buf_writer, schema.clone(), props.clone()).map_err(
|source| ParquetMacroError::Parquet {
path: tmp_path.clone(),
source,
},
)?;
Ok(Self {
tmp_path,
final_path,
writer,
buf: RowGroupBuffer::default(),
rows_written: 0,
row_groups_written: 0,
})
}
fn flush_row_group(&mut self, scratch: &mut Vec<ByteArray>) -> Result<(), ParquetMacroError> {
let row_count = self.buf.len();
if row_count == 0 {
return Ok(());
}
let map_pq = |source: ParquetError| ParquetMacroError::Parquet {
path: self.tmp_path.clone(),
source,
};
let mut rg_writer = self.writer.next_row_group().map_err(map_pq)?;
// 1. country_iso (BYTE_ARRAY, REQUIRED, STRING)
write_interned_str_col(
&mut rg_writer,
&self.buf.country_iso_ids,
&self.buf.country_iso_interner,
scratch,
)
.map_err(map_pq)?;
// 2. indicator (BYTE_ARRAY, REQUIRED, STRING)
write_interned_str_col(
&mut rg_writer,
&self.buf.indicator_ids,
&self.buf.indicator_interner,
scratch,
)
.map_err(map_pq)?;
// 3. period_date (INT32, REQUIRED, DATE)
write_i32_col(&mut rg_writer, &self.buf.period_date).map_err(map_pq)?;
// 4. known_at (INT64, REQUIRED, TIMESTAMP MICROS UTC)
write_i64_col(&mut rg_writer, &self.buf.known_at_micros).map_err(map_pq)?;
// 5. known_at_source (BYTE_ARRAY, REQUIRED, STRING)
write_interned_str_col(
&mut rg_writer,
&self.buf.known_at_source_ids,
&self.buf.known_at_source_interner,
scratch,
)
.map_err(map_pq)?;
// 6. value (DOUBLE, REQUIRED)
write_f64_col(&mut rg_writer, &self.buf.value, None).map_err(map_pq)?;
rg_writer.close().map_err(map_pq)?;
self.rows_written += row_count;
self.row_groups_written += 1;
self.buf.clear();
Ok(())
}
fn finish_and_sync(
mut self,
scratch: &mut Vec<ByteArray>,
) -> Result<SyncedMacroFile, ParquetMacroError> {
self.flush_row_group(scratch)?;
let mut buf_writer =
self.writer
.into_inner()
.map_err(|source| ParquetMacroError::Parquet {
path: self.tmp_path.clone(),
source,
})?;
buf_writer.flush().map_err(|source| ParquetMacroError::Io {
path: self.tmp_path.clone(),
source,
})?;
let file = buf_writer
.into_inner()
.map_err(|err| ParquetMacroError::Io {
path: self.tmp_path.clone(),
source: err.into_error(),
})?;
file.sync_all().map_err(|source| ParquetMacroError::Io {
path: self.tmp_path.clone(),
source,
})?;
let bytes = file
.metadata()
.map_err(|source| ParquetMacroError::Io {
path: self.tmp_path.clone(),
source,
})?
.len();
drop(file);
Ok(SyncedMacroFile {
tmp_path: self.tmp_path,
final_path: self.final_path,
rows_written: self.rows_written,
row_groups_written: self.row_groups_written,
bytes,
})
}
}
struct SyncedMacroFile {
tmp_path: PathBuf,
final_path: PathBuf,
rows_written: usize,
row_groups_written: usize,
bytes: u64,
}
/// Streams strictly ascending `(country_iso, indicator, period_date)` rows into a single Zstd
/// Parquet file at `<out_dir>/macro/part.parquet`.
///
/// # Empty Input
/// Empty input (with valid options) returns `Ok(MacroWriteStats::default())` without creating
/// `<out_dir>/macro` and without modifying or removing any pre-existing `part.parquet`.
///
/// # Concurrency & Atomicity
/// Concurrent writers targeting the same `<out_dir>/macro` directory are serialized via an
/// in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file. The file is
/// written to an exclusively created per-run staging file (`part.parquet.<run>.tmp`), flushed,
/// and `sync_all`'d before publication. If a pre-existing `part.parquet` regular file exists,
/// a live-preserving backup (`part.parquet.<run>.bak`) is created via hard link (or exclusive
/// copy fallback) so readers never observe a missing `part.parquet` before replacement by a
/// single atomic `rename`. On any error, the writer is dropped, any backup created by this run
/// is cleaned up (reporting cleanup failures via [`ParquetMacroError::RollbackFailed`]), and
/// only staging files owned by this run are unlinked.
pub fn write_macro_dataset<P, I, R>(
out_dir: P,
rows: I,
options: MacroWriteOptions,
) -> Result<MacroWriteStats, ParquetMacroError>
where
P: AsRef<Path>,
I: IntoIterator<Item = R>,
R: Borrow<MacroParquetRow>,
{
write_macro_dataset_with_hooks(
out_dir,
rows,
options,
DEFAULT_LOCK_TIMEOUT,
|_, _| {},
|path| fs::remove_file(path),
)
}
fn write_macro_dataset_with_hooks<P, I, R, F, Rm>(
out_dir: P,
rows: I,
options: MacroWriteOptions,
lock_timeout: Duration,
mut on_after_backup: F,
mut remove_backup: Rm,
) -> Result<MacroWriteStats, ParquetMacroError>
where
P: AsRef<Path>,
I: IntoIterator<Item = R>,
R: Borrow<MacroParquetRow>,
F: FnMut(&Path, Option<&Path>),
Rm: FnMut(&Path) -> io::Result<()>,
{
if options.row_group_rows == 0 {
return Err(ParquetMacroError::InvalidRowGroupRows);
}
let zstd_level = ZstdLevel::try_new(options.zstd_level).map_err(|_| {
ParquetMacroError::InvalidZstdLevel {
level: options.zstd_level,
}
})?;
let mut row_iter = rows.into_iter();
let Some(first_item) = row_iter.next() else {
return Ok(MacroWriteStats::default());
};
validate_row(first_item.borrow())?;
let out_dir = out_dir.as_ref();
let macro_dir = out_dir.join("macro");
let schema = macro_parquet_schema().map_err(|source| ParquetMacroError::Parquet {
path: macro_dir.clone(),
source,
})?;
let props = build_writer_properties(zstd_level);
fs::create_dir_all(&macro_dir).map_err(|source| ParquetMacroError::Io {
path: macro_dir.clone(),
source,
})?;
// Serialize writers targeting the same dataset directory across threads and processes.
// Drop order guarantees `.write.lock` is removed while `_in_process_guard` is still held,
// and only after all staging/publication/rollback work has finished.
let dataset_mu = dataset_mutex(&macro_dir);
let _in_process_guard = dataset_mu.lock().unwrap_or_else(|err| err.into_inner());
let _file_lock = DatasetFileLock::acquire_with_timeout(&macro_dir, lock_timeout)?;
let run_id = next_run_id();
let (tmp_path, tmp_file) = create_exclusive_tmp_file(&macro_dir, &run_id)?;
// Declared before `file_writer` so Rust's reverse drop order closes the file handle
// before the guard unlinks the staging file on error or panic unwind, while `_file_lock`
// and `_in_process_guard` are still held.
let mut staging_guard = StagingFileGuard::new(tmp_path.clone());
let mut scratch: Vec<ByteArray> = Vec::with_capacity(STRING_WRITE_BATCH_ROWS);
let mut file_writer = Some(MacroFileWriter::from_file(
tmp_path,
macro_dir.join("part.parquet"),
tmp_file,
&schema,
&props,
)?);
let synced = {
let mut has_prev = false;
let mut prev_country_iso = String::new();
let mut prev_indicator = String::new();
let mut prev_period_date = 0i32;
let writer = file_writer.as_mut().expect("writer initialized");
for item in std::iter::once(first_item).chain(row_iter) {
let row = item.borrow();
// Validate row fields before checking sort order so e.g. an empty country_iso
// or indicator is reported as EmptyCountryIso/EmptyIndicator rather than UnsortedInput.
validate_row(row)?;
let country_iso = row.country_iso.as_ref();
let indicator = row.indicator.as_ref();
if has_prev {
match (country_iso, indicator, row.period_date).cmp(&(
prev_country_iso.as_str(),
prev_indicator.as_str(),
prev_period_date,
)) {
Ordering::Equal => {
return Err(ParquetMacroError::DuplicateKey {
country_iso: country_iso.to_owned(),
indicator: indicator.to_owned(),
period_date: row.period_date,
});
}
Ordering::Less => {
return Err(ParquetMacroError::UnsortedInput {
prev_country_iso,
prev_indicator,
prev_period_date,
country_iso: country_iso.to_owned(),
indicator: indicator.to_owned(),
period_date: row.period_date,
});
}
Ordering::Greater => {}
}
}
if !has_prev || country_iso != prev_country_iso.as_str() {
prev_country_iso.clear();
prev_country_iso.push_str(country_iso);
}
if !has_prev || indicator != prev_indicator.as_str() {
prev_indicator.clear();
prev_indicator.push_str(indicator);
}
prev_period_date = row.period_date;
has_prev = true;
writer.buf.push(row);
if writer.buf.len() == options.row_group_rows {
writer.flush_row_group(&mut scratch)?;
}
}
let writer = file_writer.take().expect("writer still present");
writer.finish_and_sync(&mut scratch)?
};
let backup_path = match fs::symlink_metadata(&synced.final_path) {
Ok(meta) if !meta.is_dir() => {
Some(create_backup_preserving_live(&synced.final_path, &run_id)?)
}
// Directory occupying final_path: leave it in place so the rename below fails cleanly.
Ok(_) => None,
Err(err) if err.kind() == io::ErrorKind::NotFound => None,
Err(source) => {
return Err(ParquetMacroError::Io {
path: synced.final_path,
source,
});
}
};
on_after_backup(&synced.final_path, backup_path.as_deref());
if let Err(source) = fs::rename(&synced.tmp_path, &synced.final_path) {
// `synced.final_path` was never moved during backup creation, so it remains intact;
// remove the backup created for this run. `staging_guard` unlinks our staging file on drop.
let backup_remove_failure = backup_path.and_then(|bak| {
fs::remove_file(&bak).err().map(|remove_err| RollbackFailure {
final_path: synced.final_path.clone(),
backup_path: Some(bak),
source: remove_err,
})
});
let cause = ParquetMacroError::Io {
path: synced.final_path,
source,
};
return match backup_remove_failure {
Some(failure) => Err(ParquetMacroError::RollbackFailed {
cause: Box::new(cause),
failures: vec![failure],
}),
None => Err(cause),
};
}
staging_guard.disarm();
if let Some(bak) = backup_path {
if let Err(remove_err) = remove_backup(&bak) {
let cause = ParquetMacroError::Io {
path: bak.clone(),
source: remove_err,
};
return match fs::rename(&bak, &synced.final_path) {
Ok(()) => Err(cause),
Err(restore_err) => Err(ParquetMacroError::RollbackFailed {
cause: Box::new(cause),
failures: vec![RollbackFailure {
final_path: synced.final_path,
backup_path: Some(bak),
source: restore_err,
}],
}),
};
}
}
Ok(MacroWriteStats {
rows_written: synced.rows_written,
files_written: 1,
row_groups_written: synced.row_groups_written,
bytes_written: synced.bytes,
})
}
#[cfg(test)]
#[path = "parquet_macro_tests.rs"]
mod tests;

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff