diff --git a/libs/research/README.md b/libs/research/README.md index cf49f406..f9cd428e 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -264,6 +264,25 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported - **`delistedAt` derivation:** Projects `delistedAt` as `listing.listed_to` (`YYYY-MM-DD`) when `delist_reason IS NOT NULL AND delist_reason <> 'active'`, else `null`. When `q.includeDelisted === false`, rows with non-null `delistedAt <= cutoff` are filtered out while future delistings (`delistedAt > cutoff`) remain eligible as of the cutoff. - **Port matching vs. MCP ranking:** The adapter matches on resolved as-of ticker (`ILIKE`), `listing.ticker_root` (`ILIKE`, gated by `NOT root_is_future`), `instrument.canonical_name` (`ILIKE`), or case-insensitive exact `instrument.primary_isin`, ignores `q.limit`, and returns all candidates ordered by `listing_id ASC`. When composed with `createSearchSymbolsTool`, the MCP tool applies Vault clamping/masking, ranks by exact ticker > ticker prefix > company name substring (tie-breaking by `listingId ASC`), and truncates to `limit` — so callers needing ticker-substring, root-only, or exact-ISIN lookups should call the port directly, while MCP tool callers should query by ticker or company name. +### PostgreSQL Findings & Provider Caveats Adapter + +- **`createPostgresFindingWritePort({ executor, schema? })`** and **`createPostgresKnowledgeReaders({ executor, schema? })`** (exported from `@stock-bot/research/mcp` alongside `PostgresFindingsExecutor`, `PostgresFindingsOptions`, `PostgresKnowledgeReaders`, `PostgresFindingsError`, and `PostgresFindingsErrorCode`) back `file_finding` (`FindingWritePort`) and the `findings` / `provider_caveats` halves of `read_knowledge` (`Pick`) over `37-research-findings.sql` with zero runtime `pg` dependency. +- **Inputs, schema & row validation:** Validates `executor.query` (`INVALID_EXECUTOR`) and optional `schema` against `^[a-z_][a-z0-9_]*$` (`INVALID_SCHEMA`; defaults to the executor's `search_path`), binds every caller value via `$n` parameters, issues zero `UPDATE`/`DELETE` statements, and fails closed (`INVALID_ROW`) on malformed result envelopes, non-1D/non-string ref arrays, unknown `kind`, or invalid timestamps (converting PostgreSQL `Date` values or strictly parsed timezone-qualified ISO-8601 strings to UTC ISO-8601 output). +- **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` over a configured read-only library root (`/library.yml` and `/cards//.md`) with zero new dependencies. +- **Read-only boundary, fresh reads & symlink safety:** Resolves `root` once at construction, reads `library.yml` and eligible cards fresh on every call (no cache), requires anchored directory operations (`LibraryCardFs.openDir`, backed by `/proc/self/fd/` in `createNodeLibraryCardFs()`) with no pathname fallback, enforces `O_NOFOLLOW` on every component below the configured root with `fstat` regular-file/directory verification, and fails closed if the adapter or runtime cannot enforce that boundary. +- **Exact-ID narrowing & unverified-card assumption:** Returns all eligible cards in manifest section order and code-unit slug order without pre-slicing or truncating text, narrowing only on exact case-sensitive `q.id` (malformed or unknown IDs return an empty frozen array without opening card files) so `createReadKnowledgeTool` owns `query`/`tags` filtering, ranking, truncation, and `limit`. All eligible cards are returned regardless of `verified` status, and callers must bind `root` to a research-visible corpus free of holdout or Vault-only observations. + ### Copilot Server - **`createResearchCopilotMcpServer(options)`** (exported from `@stock-bot/research/mcp` alongside `ResearchCopilotMcpServerOptions` and the frozen `RESEARCH_COPILOT_TOOL_NAMES` tuple) composes all six research tools into one transport-agnostic `McpServer` in the fixed registration order `search_symbols`, `query_data`, `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`. It accepts `name` and `version`, shared authoritative `store`, `vaultContext`, `ledger`, and `principalId`, plus the per-tool injected ports (`searchSymbols`, `eventStudy.resolveExchangeCalendars`, `fileFinding`, `readKnowledge`), fails closed on duplicate, missing, unexpected, or out-of-order tool names, and pairs directly with `runStdioServer(server, ...)` for headless newline-delimited JSON-RPC sessions. diff --git a/libs/research/src/mcp/adapters/exchange-calendars.ts b/libs/research/src/mcp/adapters/exchange-calendars.ts new file mode 100644 index 00000000..801230f6 --- /dev/null +++ b/libs/research/src/mcp/adapters/exchange-calendars.ts @@ -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>( + 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[]; +} + +/** 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[]; +} + +/** + * 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>>>; + +/** 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(target: Record, 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 { + 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(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 { + 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> { + const result = new Map>(); + 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(); + 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>; +} { + 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 { + 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(); + 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(); + 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(); + + 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 = {}; + 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 = {}; + for (let i = 0; i < sortedListingIds.length; i += 1) { + const id = sortedListingIds[i] as number; + defineDataProperty( + listingCalendarId as unknown as Record, + String(id), + listingToCalendar.get(id) as string + ); + } + + return { + calendars, + listingCalendarId, + }; + }; +} diff --git a/libs/research/src/mcp/adapters/library-cards.ts b/libs/research/src/mcp/adapters/library-cards.ts new file mode 100644 index 00000000..92935689 --- /dev/null +++ b/libs/research/src/mcp/adapters/library-cards.ts @@ -0,0 +1,883 @@ +/** + * Read-only filesystem adapter for the MCP copilot `read_knowledge` tool, + * implementing {@link KnowledgePort.listLibraryCards} over `/library.yml` + * and `/cards//.md`. + * + * Filesystem access is injected via {@link LibraryCardFs} for hermetic testing, + * with {@link createNodeLibraryCardFs} provided for Node/Bun composition. + */ + +import { constants as fsConstants } from 'node:fs'; +import { type FileHandle, open, readdir, stat } from 'node:fs/promises'; +import path from 'node:path'; +import type { KnowledgePort, LibraryCardQuery, LibraryCardRecord } from '../tools/read-knowledge'; + +const SAFE_IDENT_RE = /^[a-z0-9][a-z0-9-]*$/; +const LIBRARY_ID_RE = /^[a-z0-9][a-z0-9_-]*$/; +const PLAIN_YAML_KEY_RE = /^[^?:,[\]{}#&*!|>'"%@`\s](?:(?:[^,[\]{}#\s]| )*[^,[\]{}#\s])?$/; +const BLOCK_SCALAR_RE = /^[|>][+-]?$/; + +/** Error codes thrown by {@link LibraryCardError}. */ +export type LibraryCardErrorCode = + | 'INVALID_FS' + | 'INVALID_ROOT' + | 'INVALID_LIBRARY' + | 'INVALID_CARD'; + +/** Typed validation and I/O error thrown by the library card filesystem adapter. */ +export class LibraryCardError extends RangeError { + readonly code: LibraryCardErrorCode; + + constructor(code: LibraryCardErrorCode, message: string) { + super(message); + this.name = 'LibraryCardError'; + this.code = code; + Object.setPrototypeOf(this, new.target.prototype); + } +} + +/** Directory entry metadata returned by {@link LibraryCardFs.listDir}. */ +export interface LibraryCardDirEntry { + readonly name: string; + readonly isFile: boolean; + readonly isDirectory: boolean; +} + +/** Anchored read-only directory handle for symlink-safe traversal below a configured root. */ +export interface LibraryCardDirHandle { + listDir(): Promise; + openSubdir(name: string): Promise; + readTextFile(name: string): Promise; + close(): Promise; +} + +/** Minimal read-only filesystem port injected into {@link createLibraryCardReader}. */ +export interface LibraryCardFs { + readTextFile(filePath: string): Promise; + listDir(dirPath: string): Promise; + openDir(dirPath: string): Promise; +} + +/** Factory options for {@link createLibraryCardReader}. */ +export interface LibraryCardReaderOptions { + readonly root: string; + readonly fs: LibraryCardFs; +} + +/** Library-card subset of {@link KnowledgePort}. */ +export type LibraryCardReader = Pick; + +interface ParsedLibraryManifest { + readonly id: string; + readonly sections: readonly string[]; +} + +type FrontMatterValue = string | readonly string[]; + +function compareCodeUnits(a: string, b: string): number { + if (a < b) { + return -1; + } + if (a > b) { + return 1; + } + return 0; +} + +function isEnoentError(err: unknown): boolean { + return ( + typeof err === 'object' && + err !== null && + (err as { readonly code?: unknown }).code === 'ENOENT' + ); +} + +function invalidLibrary(reason: string): LibraryCardError { + return new LibraryCardError('INVALID_LIBRARY', `Invalid library.yml: ${reason}`); +} + +function invalidCard(relPath: string, reason: string): LibraryCardError { + return new LibraryCardError('INVALID_CARD', `Invalid card "${relPath}": ${reason}`); +} + +function validateFactoryOptions(options: LibraryCardReaderOptions): { + readonly resolvedRoot: string; + readonly fs: LibraryCardFs; +} { + if (typeof options !== 'object' || options === null) { + throw new LibraryCardError( + 'INVALID_ROOT', + 'Invalid options: expected an object with root and fs.' + ); + } + + const { root, fs } = options; + if (typeof root !== 'string' || root.trim().length === 0 || root.includes('\0')) { + throw new LibraryCardError( + 'INVALID_ROOT', + 'Invalid root: expected a non-empty filesystem path without null bytes.' + ); + } + + if ( + typeof fs !== 'object' || + fs === null || + typeof fs.readTextFile !== 'function' || + typeof fs.listDir !== 'function' || + typeof fs.openDir !== 'function' + ) { + throw new LibraryCardError( + 'INVALID_FS', + 'Invalid fs: expected a LibraryCardFs implementing readTextFile, listDir, and openDir.' + ); + } + + return { + resolvedRoot: path.resolve(root), + fs, + }; +} + +function parseLibraryScalar(rawValue: string): string { + if (rawValue.length === 0 || rawValue.startsWith('#')) { + throw invalidLibrary('"id" must not be empty.'); + } + if (rawValue.startsWith("'")) { + throw invalidLibrary('single-quoted "id" values are not supported.'); + } + if (rawValue.startsWith('"')) { + let parsed: unknown; + try { + parsed = JSON.parse(rawValue); + } catch { + throw invalidLibrary('invalid double-quoted "id" value.'); + } + if (typeof parsed !== 'string') { + throw invalidLibrary('invalid double-quoted "id" value.'); + } + return parsed; + } + if (rawValue.startsWith('[') || rawValue.startsWith('{') || BLOCK_SCALAR_RE.test(rawValue)) { + throw invalidLibrary('"id" must be a scalar string.'); + } + return rawValue; +} + +function parseLibraryManifest(content: string): ParsedLibraryManifest { + const lines = content.split(/\r?\n/); + + let libraryId: string | undefined; + let sawSections = false; + let sectionsIndent: number | null = null; + let currentTopLevelKey: string | null = null; + const seenSectionKeys = new Set(); + const validSections: string[] = []; + + for (let i = 0; i < lines.length; i += 1) { + const line = lines[i] as string; + const trimmed = line.trim(); + if (trimmed.length === 0 || trimmed.startsWith('#')) { + continue; + } + + let indent = 0; + while (indent < line.length && line[indent] === ' ') { + indent += 1; + } + if (line[indent] === '\t') { + throw invalidLibrary('tab indentation is not supported.'); + } + + if (indent === 0) { + const colonIdx = line.indexOf(':'); + if (colonIdx <= 0) { + throw invalidLibrary('malformed top-level entry.'); + } + const key = line.slice(0, colonIdx).trim(); + const rawValue = line.slice(colonIdx + 1).trim(); + if (key.length === 0 || /\s/.test(key)) { + throw invalidLibrary('invalid top-level key.'); + } + + currentTopLevelKey = key; + + if (key === 'id') { + if (libraryId !== undefined) { + throw invalidLibrary('duplicate "id" declaration.'); + } + const parsedId = parseLibraryScalar(rawValue); + if (!LIBRARY_ID_RE.test(parsedId)) { + throw invalidLibrary('"id" must match ^[a-z0-9][a-z0-9_-]*$.'); + } + libraryId = parsedId; + } else if (key === 'sections') { + if (sawSections) { + throw invalidLibrary('duplicate "sections" declaration.'); + } + if (rawValue.length > 0) { + throw invalidLibrary('"sections" must be an indented map.'); + } + sawSections = true; + sectionsIndent = null; + } + continue; + } + + if (currentTopLevelKey === null) { + throw invalidLibrary('indented entry before any top-level declaration.'); + } + if (currentTopLevelKey === 'id') { + throw invalidLibrary('"id" must be a single-line scalar.'); + } + if (currentTopLevelKey !== 'sections') { + continue; + } + + if (sectionsIndent === null) { + sectionsIndent = indent; + } else if (indent !== sectionsIndent) { + throw invalidLibrary('inconsistent indentation inside "sections" map.'); + } + + const body = line.slice(indent); + if (body === '-' || body.startsWith('- ') || body.startsWith('-\t')) { + throw invalidLibrary('sequence entries are not supported inside "sections" map.'); + } + const colonIdx = body.indexOf(':'); + if (colonIdx <= 0) { + throw invalidLibrary('malformed entry inside "sections" map.'); + } + const rawKey = body.slice(0, colonIdx); + const sectionKey = rawKey.trim(); + const afterColon = body.slice(colonIdx + 1); + if ( + rawKey !== sectionKey || + !PLAIN_YAML_KEY_RE.test(sectionKey) || + (afterColon.length > 0 && afterColon[0] !== ' ' && afterColon[0] !== '\t') + ) { + throw invalidLibrary('malformed entry inside "sections" map.'); + } + const sectionTitle = afterColon.trim(); + if (sectionTitle.length === 0 || sectionTitle.startsWith('#')) { + throw invalidLibrary('empty key or title inside "sections" map.'); + } + if (seenSectionKeys.has(sectionKey)) { + throw invalidLibrary('duplicate key inside "sections" map.'); + } + seenSectionKeys.add(sectionKey); + + if (SAFE_IDENT_RE.test(sectionKey)) { + validSections.push(sectionKey); + } + } + + if (libraryId === undefined) { + throw invalidLibrary('missing "id" declaration.'); + } + if (!sawSections || seenSectionKeys.size === 0) { + throw invalidLibrary('missing or empty "sections" map.'); + } + + return { + id: libraryId, + sections: validSections, + }; +} + +function parseFrontMatterValue(rawValue: string, relPath: string): FrontMatterValue { + if (rawValue.length === 0 || rawValue.startsWith('#')) { + throw invalidCard(relPath, 'empty or multiline front-matter value.'); + } + if (BLOCK_SCALAR_RE.test(rawValue)) { + throw invalidCard(relPath, 'multiline front-matter values are not supported.'); + } + if (rawValue.startsWith("'")) { + throw invalidCard(relPath, 'single-quoted front-matter values are not supported.'); + } + if (rawValue.startsWith('{')) { + throw invalidCard(relPath, 'object front-matter values are not supported.'); + } + + if (rawValue.startsWith('"')) { + let parsed: unknown; + try { + parsed = JSON.parse(rawValue); + } catch { + throw invalidCard(relPath, 'invalid double-quoted front-matter string.'); + } + if (typeof parsed !== 'string') { + throw invalidCard(relPath, 'invalid double-quoted front-matter string.'); + } + return parsed; + } + + if (rawValue.startsWith('[')) { + let parsed: unknown; + try { + parsed = JSON.parse(rawValue); + } catch { + throw invalidCard(relPath, 'invalid front-matter array.'); + } + if (!Array.isArray(parsed)) { + throw invalidCard(relPath, 'invalid front-matter array.'); + } + const items: string[] = []; + for (let i = 0; i < parsed.length; i += 1) { + const entry: unknown = parsed[i]; + if (typeof entry !== 'string') { + throw invalidCard(relPath, 'front-matter array entries must be strings.'); + } + items.push(entry); + } + return items; + } + + return rawValue; +} + +function parseCardDocument( + content: string, + libraryId: string, + sectionId: string, + slug: string +): LibraryCardRecord { + const relPath = `cards/${sectionId}/${slug}.md`; + const lines = content.split(/\r?\n/); + + if (lines[0] !== '---') { + throw invalidCard(relPath, 'missing opening front-matter delimiter.'); + } + + let closingIndex = -1; + for (let i = 1; i < lines.length; i += 1) { + if (lines[i] === '---') { + closingIndex = i; + break; + } + } + if (closingIndex === -1) { + throw invalidCard(relPath, 'missing closing front-matter delimiter.'); + } + + const fields = new Map(); + for (let i = 1; i < closingIndex; i += 1) { + const line = lines[i] as string; + const trimmed = line.trim(); + if (trimmed.length === 0 || trimmed.startsWith('#')) { + continue; + } + if (line[0] === ' ' || line[0] === '\t') { + throw invalidCard(relPath, 'multiline or indented front-matter values are not supported.'); + } + + const colonIdx = line.indexOf(':'); + if (colonIdx <= 0) { + throw invalidCard(relPath, 'malformed front-matter entry.'); + } + const key = line.slice(0, colonIdx).trim(); + if (key.length === 0 || /\s/.test(key)) { + throw invalidCard(relPath, 'invalid front-matter key.'); + } + if (fields.has(key)) { + throw invalidCard(relPath, 'duplicate front-matter key.'); + } + + const rawValue = line.slice(colonIdx + 1).trim(); + fields.set(key, parseFrontMatterValue(rawValue, relPath)); + } + + const rawTitle = fields.get('title'); + if (typeof rawTitle !== 'string' || rawTitle.trim().length === 0) { + throw invalidCard(relPath, 'missing or empty "title".'); + } + + const rawSummary = fields.get('summary'); + if (typeof rawSummary !== 'string' || rawSummary.trim().length === 0) { + throw invalidCard(relPath, 'missing or empty "summary".'); + } + + const rawMatches = fields.get('matches'); + if (rawMatches !== undefined && !Array.isArray(rawMatches)) { + throw invalidCard(relPath, '"matches" must be an array of strings.'); + } + + const tags: string[] = []; + const seenTags = new Set(); + const addTag = (raw: string): void => { + const normalized = raw.trim().toLowerCase(); + if (normalized.length > 0 && !seenTags.has(normalized)) { + seenTags.add(normalized); + tags.push(normalized); + } + }; + + addTag(sectionId); + if (rawMatches !== undefined) { + for (let i = 0; i < rawMatches.length; i += 1) { + addTag(rawMatches[i] as string); + } + } + + const body = lines + .slice(closingIndex + 1) + .join('\n') + .trim(); + + return Object.freeze({ + id: `${libraryId}:${sectionId}/${slug}`, + title: rawTitle, + tags: Object.freeze(tags), + summary: rawSummary, + body, + }); +} + +function parseExactCardId( + id: string, + libraryId: string, + declaredSections: ReadonlySet +): { readonly sectionId: string; readonly slug: string } | null { + const prefix = `${libraryId}:`; + if (!id.startsWith(prefix)) { + return null; + } + const rest = id.slice(prefix.length); + const slashIdx = rest.indexOf('/'); + if (slashIdx <= 0 || rest.indexOf('/', slashIdx + 1) !== -1) { + return null; + } + const sectionId = rest.slice(0, slashIdx); + const slug = rest.slice(slashIdx + 1); + if (!SAFE_IDENT_RE.test(sectionId) || !SAFE_IDENT_RE.test(slug)) { + return null; + } + if (!declaredSections.has(sectionId)) { + return null; + } + return { sectionId, slug }; +} + +function assertSafeChildName(name: string): void { + if ( + name.length === 0 || + name === '.' || + name === '..' || + name.includes('/') || + name.includes('\\') || + name.includes('\0') + ) { + throw new Error('Invalid directory child entry name.'); + } +} + +function isValidDirHandle(value: unknown): value is LibraryCardDirHandle { + return ( + typeof value === 'object' && + value !== null && + typeof (value as { readonly listDir?: unknown }).listDir === 'function' && + typeof (value as { readonly openSubdir?: unknown }).openSubdir === 'function' && + typeof (value as { readonly readTextFile?: unknown }).readTextFile === 'function' && + typeof (value as { readonly close?: unknown }).close === 'function' + ); +} + +async function safeOpenRootDir( + fs: LibraryCardFs, + resolvedRoot: string +): Promise { + let handle: unknown; + try { + handle = await fs.openDir(resolvedRoot); + } catch { + throw new LibraryCardError( + 'INVALID_LIBRARY', + 'Invalid library.yml: failed to open library root directory.' + ); + } + if (!isValidDirHandle(handle)) { + throw new LibraryCardError( + 'INVALID_LIBRARY', + 'Invalid library.yml: failed to open library root directory.' + ); + } + return handle; +} + +async function safeOpenSubdir( + parent: LibraryCardDirHandle, + name: string, + errorMessage: string, + allowMissing: boolean +): Promise { + let handle: unknown; + try { + handle = await parent.openSubdir(name); + } catch (err) { + if (allowMissing && isEnoentError(err)) { + return null; + } + throw new LibraryCardError('INVALID_LIBRARY', errorMessage); + } + if (!isValidDirHandle(handle)) { + throw new LibraryCardError('INVALID_LIBRARY', errorMessage); + } + return handle; +} + +async function safeReadTextFileFromDir( + dir: LibraryCardDirHandle, + name: string, + errorCode: 'INVALID_LIBRARY' | 'INVALID_CARD', + errorMessage: string +): Promise { + let content: unknown; + try { + content = await dir.readTextFile(name); + } catch { + throw new LibraryCardError(errorCode, errorMessage); + } + if (typeof content !== 'string') { + throw new LibraryCardError(errorCode, errorMessage); + } + return content; +} + +async function safeListDirHandle( + dir: LibraryCardDirHandle, + errorMessage: string, + allowMissing: boolean +): Promise { + let rawEntries: unknown; + try { + rawEntries = await dir.listDir(); + } catch (err) { + if (allowMissing && isEnoentError(err)) { + return []; + } + throw new LibraryCardError('INVALID_LIBRARY', errorMessage); + } + + if (!Array.isArray(rawEntries)) { + throw new LibraryCardError('INVALID_LIBRARY', errorMessage); + } + + const entries: LibraryCardDirEntry[] = []; + for (let i = 0; i < rawEntries.length; i += 1) { + const entry: unknown = rawEntries[i]; + if ( + typeof entry !== 'object' || + entry === null || + typeof (entry as { readonly name?: unknown }).name !== 'string' || + typeof (entry as { readonly isFile?: unknown }).isFile !== 'boolean' || + typeof (entry as { readonly isDirectory?: unknown }).isDirectory !== 'boolean' + ) { + throw new LibraryCardError('INVALID_LIBRARY', errorMessage); + } + entries.push(entry as LibraryCardDirEntry); + } + + return entries; +} + +interface AnchoredOpenFlags { + readonly dirOpenFlags: number; + readonly subdirOpenFlags: number; + readonly fileOpenFlags: number; +} + +function getAnchoredOpenFlags(): AnchoredOpenFlags { + if ( + process.platform !== 'linux' || + typeof fsConstants.O_NOFOLLOW !== 'number' || + typeof fsConstants.O_DIRECTORY !== 'number' + ) { + throw new Error('Anchored no-follow directory operations are not supported on this platform.'); + } + return { + dirOpenFlags: fsConstants.O_RDONLY | fsConstants.O_DIRECTORY, + subdirOpenFlags: fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW, + fileOpenFlags: fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW, + }; +} + +function createAnchoredNodeDirHandle( + handle: FileHandle, + flags: AnchoredOpenFlags +): LibraryCardDirHandle { + let closed = false; + + const getFdBase = (): string => { + if (closed) { + throw new Error('Directory handle is closed.'); + } + return `/proc/self/fd/${handle.fd}`; + }; + + return { + async listDir(): Promise { + const dirents = await readdir(getFdBase(), { withFileTypes: true }); + const entries: LibraryCardDirEntry[] = []; + for (let i = 0; i < dirents.length; i += 1) { + const dirent = dirents[i]; + if (dirent !== undefined) { + entries.push({ + name: dirent.name, + isFile: dirent.isFile(), + isDirectory: dirent.isDirectory(), + }); + } + } + return entries; + }, + + async openSubdir(name: string): Promise { + assertSafeChildName(name); + const childHandle = await open(`${getFdBase()}/${name}`, flags.subdirOpenFlags); + try { + const stats = await childHandle.stat(); + if (!stats.isDirectory()) { + throw new Error('Target path is not a directory.'); + } + } catch (err) { + await childHandle.close(); + throw err; + } + return createAnchoredNodeDirHandle(childHandle, flags); + }, + + async readTextFile(name: string): Promise { + assertSafeChildName(name); + const fileHandle = await open(`${getFdBase()}/${name}`, flags.fileOpenFlags); + try { + const stats = await fileHandle.stat(); + if (!stats.isFile()) { + throw new Error('Target path is not a regular file.'); + } + return await fileHandle.readFile({ encoding: 'utf8' }); + } finally { + await fileHandle.close(); + } + }, + + async close(): Promise { + if (closed) { + return; + } + closed = true; + await handle.close(); + }, + }; +} + +/** + * Creates a read-only {@link LibraryCardFs} backed by `node:fs/promises`. + * + * Anchors directory listings and file reads to opened directory file descriptors + * via `/proc/self/fd/`, enforces `O_NOFOLLOW` on every component below the + * configured root, verifies regular-file/directory types via `fstat`, and fails + * closed on platforms that cannot enforce this boundary. + */ +export function createNodeLibraryCardFs(): LibraryCardFs { + return { + async readTextFile(filePath: string): Promise { + const flags = getAnchoredOpenFlags(); + const handle = await open(filePath, flags.fileOpenFlags); + try { + const stats = await handle.stat(); + if (!stats.isFile()) { + throw new Error('Target path is not a regular file.'); + } + return await handle.readFile({ encoding: 'utf8' }); + } finally { + await handle.close(); + } + }, + + async listDir(dirPath: string): Promise { + const flags = getAnchoredOpenFlags(); + const handle = await open(dirPath, flags.subdirOpenFlags); + try { + const stats = await handle.stat(); + if (!stats.isDirectory()) { + throw new Error('Target path is not a directory.'); + } + const anchored = createAnchoredNodeDirHandle(handle, flags); + return await anchored.listDir(); + } finally { + await handle.close(); + } + }, + + async openDir(dirPath: string): Promise { + const flags = getAnchoredOpenFlags(); + const handle = await open(dirPath, flags.dirOpenFlags); + try { + const stats = await handle.stat(); + if (!stats.isDirectory()) { + throw new Error('Target path is not a directory.'); + } + const procStats = await stat(`/proc/self/fd/${handle.fd}`); + if (!procStats.isDirectory()) { + throw new Error('Anchored directory descriptor is not accessible.'); + } + } catch (err) { + await handle.close(); + throw err; + } + return createAnchoredNodeDirHandle(handle, flags); + }, + }; +} + +/** + * Creates a read-only filesystem reader implementing + * {@link KnowledgePort.listLibraryCards} over `/library.yml` and + * `/cards//.md`. + * + * Reads fresh from the injected {@link LibraryCardFs} on every call, narrows + * only by exact case-sensitive `q.id` (leaving `q.query`, `q.tags`, ranking, + * truncation, and `limit` to `createReadKnowledgeTool`), and returns all + * eligible cards regardless of `verified` status. + */ +export function createLibraryCardReader(options: LibraryCardReaderOptions): LibraryCardReader { + const { resolvedRoot, fs } = validateFactoryOptions(options); + + return { + async listLibraryCards(q: LibraryCardQuery): Promise { + const rootDir = await safeOpenRootDir(fs, resolvedRoot); + try { + const manifestText = await safeReadTextFileFromDir( + rootDir, + 'library.yml', + 'INVALID_LIBRARY', + 'Invalid library.yml: failed to read manifest.' + ); + const manifest = parseLibraryManifest(manifestText); + const declaredSections = new Set(manifest.sections); + + let target: { readonly sectionId: string; readonly slug: string } | null = null; + if (q.id !== undefined) { + target = parseExactCardId(q.id, manifest.id, declaredSections); + if (target === null) { + return Object.freeze([]); + } + } + + const rootEntries = await safeListDirHandle( + rootDir, + 'Invalid library.yml: failed to list library root directory.', + false + ); + const hasCardsDir = rootEntries.some( + entry => entry.name === 'cards' && entry.isDirectory && !entry.isFile + ); + if (!hasCardsDir) { + return Object.freeze([]); + } + + const cardsDir = await safeOpenSubdir( + rootDir, + 'cards', + 'Invalid library.yml: failed to open library cards directory.', + true + ); + if (cardsDir === null) { + return Object.freeze([]); + } + + try { + const cardDirEntries = await safeListDirHandle( + cardsDir, + 'Invalid library.yml: failed to list library cards directory.', + true + ); + const presentSectionDirs = new Set(); + for (let i = 0; i < cardDirEntries.length; i += 1) { + const entry = cardDirEntries[i] as LibraryCardDirEntry; + if (entry.isDirectory && !entry.isFile && SAFE_IDENT_RE.test(entry.name)) { + presentSectionDirs.add(entry.name); + } + } + + const sectionsToScan = target !== null ? [target.sectionId] : manifest.sections; + const cards: LibraryCardRecord[] = []; + const seenIds = new Set(); + + for (let s = 0; s < sectionsToScan.length; s += 1) { + const sectionId = sectionsToScan[s] as string; + if (!presentSectionDirs.has(sectionId)) { + continue; + } + + const sectionDir = await safeOpenSubdir( + cardsDir, + sectionId, + `Invalid library.yml: failed to open section directory "cards/${sectionId}".`, + true + ); + if (sectionDir === null) { + continue; + } + + try { + const sectionEntries = await safeListDirHandle( + sectionDir, + `Invalid library.yml: failed to list section directory "cards/${sectionId}".`, + true + ); + + const slugs: string[] = []; + const seenSectionSlugs = new Set(); + for (let i = 0; i < sectionEntries.length; i += 1) { + const entry = sectionEntries[i] as LibraryCardDirEntry; + if (!entry.isFile || entry.isDirectory || !entry.name.endsWith('.md')) { + continue; + } + const slug = entry.name.slice(0, -3); + if (!SAFE_IDENT_RE.test(slug)) { + continue; + } + if (target !== null && slug !== target.slug) { + continue; + } + if (seenSectionSlugs.has(slug)) { + throw invalidCard(`cards/${sectionId}/${slug}.md`, 'duplicate card id.'); + } + seenSectionSlugs.add(slug); + slugs.push(slug); + } + + slugs.sort(compareCodeUnits); + + for (let i = 0; i < slugs.length; i += 1) { + const slug = slugs[i] as string; + const relPath = `cards/${sectionId}/${slug}.md`; + const canonicalId = `${manifest.id}:${sectionId}/${slug}`; + if (seenIds.has(canonicalId)) { + throw invalidCard(relPath, 'duplicate card id.'); + } + seenIds.add(canonicalId); + + const cardText = await safeReadTextFileFromDir( + sectionDir, + `${slug}.md`, + 'INVALID_CARD', + `Invalid card "${relPath}": failed to read card file.` + ); + cards.push(parseCardDocument(cardText, manifest.id, sectionId, slug)); + } + } finally { + await sectionDir.close(); + } + } + + return Object.freeze(cards); + } finally { + await cardsDir.close(); + } + } finally { + await rootDir.close(); + } + }, + }; +} diff --git a/libs/research/src/mcp/adapters/postgres-findings.ts b/libs/research/src/mcp/adapters/postgres-findings.ts new file mode 100644 index 00000000..388aa8f3 --- /dev/null +++ b/libs/research/src/mcp/adapters/postgres-findings.ts @@ -0,0 +1,722 @@ +/** + * PostgreSQL adapter for the MCP copilot findings and provider caveats tables + * (`37-research-findings.sql`), implementing {@link FindingWritePort} for + * `file_finding` and the `listFindings` / `listProviderCaveats` readers of + * {@link KnowledgePort} for `read_knowledge`. + * + * Dependency-free (no `pg`, no `node:*`, no bare `process`): SQL execution is + * injected via {@link PostgresFindingsExecutor}. + */ + +import { + type AppendFindingResult, + FILE_FINDING_KINDS, + type FileFindingKind, + type FiledFindingComparablePayload, + type FiledFindingRecord, + type FindingWritePort, + areFiledFindingPayloadsEqual, +} from '../tools/file-finding'; +import type { + FindingQuery, + FindingRecord, + KnowledgePort, + ProviderCaveatQuery, + ProviderCaveatRecord, +} from '../tools/read-knowledge'; +import { MAX_ECMASCRIPT_EPOCH_MS } from '../tools/vault-fenced-input'; + +const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/; +const ISO_INSTANT_RE = + /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|([+-])(\d{2}):(\d{2}))$/; +const DAYS_IN_MONTH: readonly number[] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +const FILE_FINDING_KIND_SET: ReadonlySet = new Set(FILE_FINDING_KINDS); + +/** Error codes thrown by {@link PostgresFindingsError}. */ +export type PostgresFindingsErrorCode = 'INVALID_EXECUTOR' | 'INVALID_SCHEMA' | 'INVALID_ROW'; + +/** Typed validation error thrown by the PostgreSQL findings adapter. */ +export class PostgresFindingsError extends RangeError { + readonly code: PostgresFindingsErrorCode; + + constructor(code: PostgresFindingsErrorCode, message: string) { + super(message); + this.name = 'PostgresFindingsError'; + this.code = code; + 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. + * + * For {@link createPostgresFindingWritePort}, the executor must run each `query()` + * call in autocommit mode on a fresh `READ COMMITTED` snapshot (such as a `pg.Pool`) + * rather than inside a `REPEATABLE READ` / `SERIALIZABLE` or explicit `BEGIN` + * transaction (unless the executor wraps each statement in a `SAVEPOINT` and rolls + * it back before rethrowing errors). Autocommit ensures that `ON CONFLICT ... DO + * NOTHING` winner lookups observe the committed winner and that same-ID `23505` + * primary-key retry lookups do not fail with `25P02` (aborted transaction). + */ +export interface PostgresFindingsExecutor { + query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }>; +} + +/** Factory options for {@link createPostgresFindingWritePort} and {@link createPostgresKnowledgeReaders}. */ +export interface PostgresFindingsOptions { + readonly executor: PostgresFindingsExecutor; + /** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */ + readonly schema?: string; +} + +/** PostgreSQL-backed subset of {@link KnowledgePort} (`findings` and `provider_caveats`). */ +export type PostgresKnowledgeReaders = Pick; + +interface RawFindingReceiptRow { + readonly id: unknown; + readonly created_at: unknown; +} + +interface RawStoredFindingForReplayRow { + readonly id: unknown; + readonly kind: unknown; + readonly title: unknown; + readonly summary: unknown; + readonly created_at: unknown; + readonly trial_refs: unknown; + readonly evidence_refs: unknown; +} + +interface RawFindingRow { + readonly id: unknown; + readonly title: unknown; + readonly status: unknown; + readonly created_at: unknown; + readonly summary: unknown; + readonly trial_refs: unknown; + readonly evidence_refs: unknown; +} + +interface RawProviderCaveatRow { + readonly id: unknown; + readonly provider: unknown; + readonly dataset: unknown; + readonly caveat: unknown; + readonly created_at: unknown; +} + +function isLeapYear(year: number): boolean { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +function daysInUtcMonth(year: number, monthIndex: number): number { + if (monthIndex === 1 && isLeapYear(year)) { + return 29; + } + return DAYS_IN_MONTH[monthIndex] ?? 0; +} + +function utcDateMs( + year: number, + monthIndex: number, + day: number, + hours: number, + minutes: number, + seconds: number, + ms: number +): number { + const date = new Date(0); + date.setUTCFullYear(year, monthIndex, day); + date.setUTCHours(hours, minutes, seconds, ms); + return date.getTime(); +} + +function escapeLikePattern(value: string): string { + return value.replace(/[\\%_]/g, '\\$&'); +} + +/** + * PostgreSQL POSIX regex matching any non-ASCII character (`> 0x7F`). + * + * Used alongside ASCII SQL pushdown (`ILIKE` / `lower()`) so rows containing + * non-ASCII stored text (e.g. `BİST` under `C` collation or `K` U+212A) are + * kept as candidates and evaluated with JavaScript's `.toLowerCase()` rules. + */ +const PG_NON_ASCII_REGEX = "'[^\\x01-\\x7f]'"; + +/** + * Returns `true` when every UTF-16 code unit in `value` is ASCII (`<= 0x7F`). + * + * PostgreSQL `ILIKE` / `lower()` agrees with JavaScript `.toLowerCase()` only + * when both the selector and the stored text are pure ASCII. Non-ASCII + * selectors omit SQL casing filters, and ASCII selectors retain non-ASCII + * stored rows as candidates; all returned rows are then filtered with + * JavaScript's `.toLowerCase()` rules after validation. + */ +function isAsciiOnly(value: string): boolean { + for (let i = 0; i < value.length; i += 1) { + if (value.charCodeAt(i) > 0x7f) { + return false; + } + } + return true; +} + +function quoteTable(schemaPrefix: string, table: string): string { + return `${schemaPrefix}${table}`; +} + +function validateFactoryOptions(options: PostgresFindingsOptions): { + readonly executor: PostgresFindingsExecutor; + readonly schemaPrefix: string; +} { + if (typeof options !== 'object' || options === null) { + throw new PostgresFindingsError( + 'INVALID_EXECUTOR', + 'Invalid options: expected an object with a PostgresFindingsExecutor.' + ); + } + + const { executor, schema } = options; + if (typeof executor !== 'object' || executor === null || typeof executor.query !== 'function') { + throw new PostgresFindingsError( + '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 PostgresFindingsError( + 'INVALID_SCHEMA', + 'Invalid schema: expected an identifier matching ^[a-z_][a-z0-9_]*$.' + ); + } + + return { executor, schemaPrefix: `"${schema}".` }; +} + +function extractRows(result: unknown): readonly Row[] { + if ( + typeof result !== 'object' || + result === null || + !Array.isArray((result as { readonly rows?: unknown }).rows) + ) { + throw new PostgresFindingsError( + 'INVALID_ROW', + 'Invalid executor response: expected an object with a rows array.' + ); + } + return (result as { readonly rows: readonly Row[] }).rows; +} + +function parseNonEmptyString(value: unknown, field: string): string { + if (typeof value !== 'string' || value.trim().length === 0) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" must be a non-empty string.` + ); + } + return value; +} + +function parseFindingKind(value: unknown): FileFindingKind { + if (typeof value !== 'string' || !FILE_FINDING_KIND_SET.has(value)) { + throw new PostgresFindingsError( + 'INVALID_ROW', + 'Invalid findings row: "kind" must be "finding" or "dead_end".' + ); + } + return value as FileFindingKind; +} + +function parseStringArray(value: unknown, field: string): readonly string[] { + if (!Array.isArray(value)) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" must be a one-dimensional string array.` + ); + } + const result: string[] = []; + for (let i = 0; i < value.length; i += 1) { + const entry: unknown = value[i]; + if (typeof entry !== 'string') { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}[${i}]" must be a string.` + ); + } + result.push(entry); + } + return result; +} + +function parseTimestampIso(value: unknown, field: string): string { + if (value instanceof Date) { + const ms = value.getTime(); + if (!Number.isFinite(ms) || Math.abs(ms) >= MAX_ECMASCRIPT_EPOCH_MS) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" must be a finite Date.` + ); + } + return new Date(ms).toISOString(); + } + + if (typeof value !== 'string') { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" must be a Date or timezone-qualified ISO-8601 timestamp string.` + ); + } + + const match = ISO_INSTANT_RE.exec(value); + if (match === null) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" must be a timezone-qualified ISO-8601 timestamp string.` + ); + } + + const year = Number(match[1]); + const month = Number(match[2]); + const day = Number(match[3]); + const hours = Number(match[4]); + const minutes = Number(match[5]); + const seconds = Number(match[6]); + const fractional = match[7]; + const tzToken = match[8]; + const tzSign = match[9]; + const tzHoursRaw = match[10]; + const tzMinutesRaw = match[11]; + + if (month < 1 || month > 12) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" has an out-of-range calendar month.` + ); + } + const maxDay = daysInUtcMonth(year, month - 1); + if (day < 1 || day > maxDay) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" has an out-of-range calendar day.` + ); + } + if (hours > 23 || minutes > 59 || seconds > 59) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" has an out-of-range time of day.` + ); + } + + let ms = 0; + if (fractional !== undefined) { + ms = Number(fractional.slice(0, 3).padEnd(3, '0')); + } + + let offsetMs = 0; + if (tzToken !== 'Z') { + const offsetHours = Number(tzHoursRaw); + const offsetMinutes = Number(tzMinutesRaw); + if (offsetHours > 23 || offsetMinutes > 59) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" has an out-of-range timezone offset.` + ); + } + const sign = tzSign === '+' ? 1 : -1; + offsetMs = sign * (offsetHours * 60 + offsetMinutes) * 60_000; + } + + const epochMs = utcDateMs(year, month - 1, day, hours, minutes, seconds, ms) - offsetMs; + if (!Number.isFinite(epochMs) || Math.abs(epochMs) >= MAX_ECMASCRIPT_EPOCH_MS) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" is outside the valid ECMAScript timestamp range.` + ); + } + + return new Date(epochMs).toISOString(); +} + +function parseReceiptRow(raw: unknown): { readonly id: string; readonly createdAt: string } { + if (typeof raw !== 'object' || raw === null) { + throw new PostgresFindingsError( + 'INVALID_ROW', + 'Invalid findings receipt row: expected a non-null object.' + ); + } + const row = raw as RawFindingReceiptRow; + return { + id: parseNonEmptyString(row.id, 'id'), + createdAt: parseTimestampIso(row.created_at, 'created_at'), + }; +} + +function parseStoredFindingForReplayRow(raw: unknown): { + readonly id: string; + readonly createdAt: string; + readonly payload: FiledFindingComparablePayload; +} { + if (typeof raw !== 'object' || raw === null) { + throw new PostgresFindingsError( + 'INVALID_ROW', + 'Invalid findings replay row: expected a non-null object.' + ); + } + const row = raw as RawStoredFindingForReplayRow; + const id = parseNonEmptyString(row.id, 'id'); + const kind = parseFindingKind(row.kind); + const title = parseNonEmptyString(row.title, 'title'); + const summary = parseNonEmptyString(row.summary, 'summary'); + const createdAt = parseTimestampIso(row.created_at, 'created_at'); + const trialRefs = parseStringArray(row.trial_refs, 'trial_refs'); + const evidenceRefs = parseStringArray(row.evidence_refs, 'evidence_refs'); + + return { + id, + createdAt, + payload: { + kind, + title, + summary, + trialRefs, + evidenceRefs, + }, + }; +} + +function parseFindingRow(raw: unknown): FindingRecord { + if (typeof raw !== 'object' || raw === null) { + throw new PostgresFindingsError( + 'INVALID_ROW', + 'Invalid findings row: expected a non-null object.' + ); + } + const row = raw as RawFindingRow; + return { + id: parseNonEmptyString(row.id, 'id'), + title: parseNonEmptyString(row.title, 'title'), + status: parseNonEmptyString(row.status, 'status'), + createdAt: parseTimestampIso(row.created_at, 'created_at'), + summary: parseNonEmptyString(row.summary, 'summary'), + trialRefs: parseStringArray(row.trial_refs, 'trial_refs'), + evidenceRefs: parseStringArray(row.evidence_refs, 'evidence_refs'), + }; +} + +function parseProviderCaveatRow(raw: unknown): ProviderCaveatRecord { + if (typeof raw !== 'object' || raw === null) { + throw new PostgresFindingsError( + 'INVALID_ROW', + 'Invalid provider_caveats row: expected a non-null object.' + ); + } + const row = raw as RawProviderCaveatRow; + return { + id: parseNonEmptyString(row.id, 'id'), + provider: parseNonEmptyString(row.provider, 'provider'), + dataset: parseNonEmptyString(row.dataset, 'dataset'), + caveat: parseNonEmptyString(row.caveat, 'caveat'), + createdAt: parseTimestampIso(row.created_at, 'created_at'), + }; +} + +function isPostgresUniqueViolation(err: unknown): boolean { + return ( + typeof err === 'object' && + err !== null && + (err as { readonly code?: unknown }).code === '23505' + ); +} + +function buildInsertFindingSql(schemaPrefix: string, keyed: boolean): string { + const findingsTable = quoteTable(schemaPrefix, 'findings'); + const lines = [ + `INSERT INTO ${findingsTable} (`, + ' id,', + ' kind,', + ' title,', + ' summary,', + ' status,', + ' created_at,', + ' trial_refs,', + ' evidence_refs,', + ' idempotency_key', + ')', + 'VALUES ($1, $2, $3, $4, $5, $6::timestamptz, $7::text[], $8::text[], $9)', + ]; + if (keyed) { + lines.push('ON CONFLICT (idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING'); + } + lines.push('RETURNING id, created_at'); + return lines.join('\n'); +} + +function buildSelectByIdempotencyKeySql(schemaPrefix: string): string { + const findingsTable = quoteTable(schemaPrefix, 'findings'); + return [ + 'SELECT', + ' id,', + ' kind,', + ' title,', + ' summary,', + ' created_at,', + ' trial_refs,', + ' evidence_refs', + `FROM ${findingsTable}`, + 'WHERE idempotency_key = $1::text', + ].join('\n'); +} + +/** + * Creates an append-only PostgreSQL {@link FindingWritePort} backed by the + * `findings` table (`37-research-findings.sql`). + */ +export function createPostgresFindingWritePort(options: PostgresFindingsOptions): FindingWritePort { + const { executor, schemaPrefix } = validateFactoryOptions(options); + const unkeyedInsertSql = buildInsertFindingSql(schemaPrefix, false); + const keyedInsertSql = buildInsertFindingSql(schemaPrefix, true); + const selectByKeySql = buildSelectByIdempotencyKeySql(schemaPrefix); + + return { + async appendFinding( + record: FiledFindingRecord, + idempotencyKey?: string + ): Promise { + const insertParams: readonly unknown[] = [ + record.id, + record.kind, + record.title, + record.summary, + record.status, + record.createdAt, + [...record.trialRefs], + [...record.evidenceRefs], + idempotencyKey ?? null, + ]; + + if (idempotencyKey === undefined) { + const result = await executor.query(unkeyedInsertSql, insertParams); + const rows = extractRows(result); + if (rows.length !== 1) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Expected 1 inserted findings row, received ${rows.length}.` + ); + } + const receipt = parseReceiptRow(rows[0]); + return { + status: 'created', + id: receipt.id, + createdAt: receipt.createdAt, + }; + } + + let insertRows: readonly RawFindingReceiptRow[]; + try { + const result = await executor.query(keyedInsertSql, insertParams); + insertRows = extractRows(result); + } catch (err) { + if (!isPostgresUniqueViolation(err)) { + throw err; + } + // A concurrent same-ID retry can collide on the primary key before the + // partial idempotency_key index; resolve only if the stored row for this + // key has the exact same ID, otherwise propagate the primary-key error. + const lookupResult = await executor.query(selectByKeySql, [ + idempotencyKey, + ]); + const lookupRows = extractRows(lookupResult); + if (lookupRows.length === 0) { + throw err; + } + if (lookupRows.length > 1) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Expected at most 1 stored finding for idempotency_key, received ${lookupRows.length}.` + ); + } + const stored = parseStoredFindingForReplayRow(lookupRows[0]); + if (stored.id !== record.id) { + throw err; + } + return areFiledFindingPayloadsEqual(stored.payload, record) + ? { status: 'replayed', id: stored.id, createdAt: stored.createdAt } + : { status: 'conflict' }; + } + + if (insertRows.length === 1) { + const receipt = parseReceiptRow(insertRows[0]); + return { + status: 'created', + id: receipt.id, + createdAt: receipt.createdAt, + }; + } + + if (insertRows.length > 1) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Expected 0 or 1 inserted findings rows, received ${insertRows.length}.` + ); + } + + // Separate SELECT on a fresh READ COMMITTED snapshot so a concurrent winner + // committed during ON CONFLICT DO NOTHING is visible. + const winnerResult = await executor.query(selectByKeySql, [ + idempotencyKey, + ]); + const winnerRows = extractRows(winnerResult); + if (winnerRows.length !== 1) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Expected 1 stored finding for idempotency_key after conflict, received ${winnerRows.length}.` + ); + } + + const stored = parseStoredFindingForReplayRow(winnerRows[0]); + return areFiledFindingPayloadsEqual(stored.payload, record) + ? { status: 'replayed', id: stored.id, createdAt: stored.createdAt } + : { status: 'conflict' }; + }, + }; +} + +/** + * Creates read-only PostgreSQL readers (`listFindings` and `listProviderCaveats`) + * for composing {@link KnowledgePort} in `read_knowledge`. + */ +export function createPostgresKnowledgeReaders( + options: PostgresFindingsOptions +): PostgresKnowledgeReaders { + const { executor, schemaPrefix } = validateFactoryOptions(options); + const findingsTable = quoteTable(schemaPrefix, 'findings'); + const caveatsTable = quoteTable(schemaPrefix, 'provider_caveats'); + + return { + async listFindings(q: FindingQuery): Promise { + const lines = [ + 'SELECT', + ' id,', + ' title,', + ' status,', + ' created_at,', + ' summary,', + ' trial_refs,', + ' evidence_refs', + `FROM ${findingsTable}`, + ]; + const params: unknown[] = []; + let normalizedQuery: string | null = null; + + if (q.id !== undefined) { + params.push(q.id); + lines.push('WHERE id = $1::text'); + } else if (q.query !== undefined) { + normalizedQuery = q.query.toLowerCase(); + if (isAsciiOnly(q.query)) { + params.push(`%${escapeLikePattern(q.query)}%`); + lines.push( + `WHERE title ILIKE $1::text ESCAPE '\\' OR summary ILIKE $1::text ESCAPE '\\' OR title ~ ${PG_NON_ASCII_REGEX} OR summary ~ ${PG_NON_ASCII_REGEX}` + ); + } + } + + lines.push('ORDER BY id ASC'); + + const result = await executor.query(lines.join('\n'), params); + const rows = extractRows(result); + const mapped: FindingRecord[] = []; + for (let i = 0; i < rows.length; i += 1) { + const finding = parseFindingRow(rows[i]); + if ( + normalizedQuery !== null && + !finding.title.toLowerCase().includes(normalizedQuery) && + !finding.summary.toLowerCase().includes(normalizedQuery) + ) { + continue; + } + mapped.push(finding); + } + return mapped; + }, + + async listProviderCaveats(q: ProviderCaveatQuery): Promise { + const lines = [ + 'SELECT', + ' id,', + ' provider,', + ' dataset,', + ' caveat,', + ' created_at', + `FROM ${caveatsTable}`, + ]; + const conditions: string[] = []; + const params: unknown[] = []; + let normalizedProvider: string | null = null; + let normalizedQuery: string | null = null; + + if (q.provider !== undefined) { + normalizedProvider = q.provider.toLowerCase(); + if (isAsciiOnly(q.provider)) { + params.push(q.provider); + conditions.push( + `(lower(provider) = lower($${params.length}::text) OR provider ~ ${PG_NON_ASCII_REGEX})` + ); + } + } + + if (q.id !== undefined) { + params.push(q.id); + conditions.push(`id = $${params.length}::text`); + } else if (q.query !== undefined) { + normalizedQuery = q.query.toLowerCase(); + if (isAsciiOnly(q.query)) { + params.push(`%${escapeLikePattern(q.query)}%`); + const idx = params.length; + conditions.push( + `(provider ILIKE $${idx}::text ESCAPE '\\' OR dataset ILIKE $${idx}::text ESCAPE '\\' OR caveat ILIKE $${idx}::text ESCAPE '\\' OR provider ~ ${PG_NON_ASCII_REGEX} OR dataset ~ ${PG_NON_ASCII_REGEX} OR caveat ~ ${PG_NON_ASCII_REGEX})` + ); + } + } + + if (conditions.length > 0) { + lines.push(`WHERE ${conditions.join(' AND ')}`); + } + + lines.push('ORDER BY id ASC'); + + const result = await executor.query(lines.join('\n'), params); + const rows = extractRows(result); + const mapped: ProviderCaveatRecord[] = []; + for (let i = 0; i < rows.length; i += 1) { + const caveat = parseProviderCaveatRow(rows[i]); + if ( + normalizedProvider !== null && + caveat.provider.toLowerCase() !== normalizedProvider + ) { + continue; + } + if ( + normalizedQuery !== null && + !caveat.provider.toLowerCase().includes(normalizedQuery) && + !caveat.dataset.toLowerCase().includes(normalizedQuery) && + !caveat.caveat.toLowerCase().includes(normalizedQuery) + ) { + continue; + } + mapped.push(caveat); + } + return mapped; + }, + }; +} diff --git a/libs/research/src/mcp/adapters/postgres-trial-ref.ts b/libs/research/src/mcp/adapters/postgres-trial-ref.ts index 249227d0..bc6ac3f7 100644 --- a/libs/research/src/mcp/adapters/postgres-trial-ref.ts +++ b/libs/research/src/mcp/adapters/postgres-trial-ref.ts @@ -18,7 +18,8 @@ const MAX_SIGNED_BIGINT_STR = '9223372036854775807'; export type PostgresTrialRefErrorCode = | 'INVALID_EXECUTOR' | 'INVALID_SCHEMA' - | 'INVALID_VAULT_CUTOFF'; + | 'INVALID_VAULT_CUTOFF' + | 'INVALID_ROW'; /** Typed validation error thrown by the PostgreSQL trial-ref lookup adapter. */ export class PostgresTrialRefError extends RangeError { @@ -43,7 +44,7 @@ export interface TrialRefExecutor { ): Promise<{ readonly rows: readonly Row[] }>; } -/** Factory options for {@link createPostgresTrialRefLookupPort}. */ +/** Factory options for {@link createPostgresTrialRefLookupPort} / {@link createPostgresTrialRefPort}. */ export interface PostgresTrialRefLookupPortOptions { readonly executor: TrialRefExecutor; /** Authoritative UTC epoch-ms Vault cutoff; trials with `sample_end < cutoffDate` are research-visible. */ @@ -52,7 +53,10 @@ export interface PostgresTrialRefLookupPortOptions { readonly schema?: string; } -interface TrialVisibilityRow { +/** Alias for {@link PostgresTrialRefLookupPortOptions}. */ +export type PostgresTrialRefPortOptions = PostgresTrialRefLookupPortOptions; + +interface RawTrialRefVisibilityRow { readonly visible?: unknown; } @@ -123,7 +127,8 @@ function validateFactoryOptions(options: PostgresTrialRefLookupPortOptions): { } /** - * Creates a read-only PostgreSQL {@link TrialRefLookupPort} backed by `trial_ledger`. + * Creates a read-only PostgreSQL {@link TrialRefLookupPort} backed by `trial_ledger` + * (`36-trial-ledger.sql`). * * Only trials with `sample_end < cutoffDate` (exclusive UTC Vault cutoff date) are * research-visible. Unknown, malformed, and Vault-only references all return `false`. @@ -140,11 +145,37 @@ export function createPostgresTrialRefLookupPort( return false; } - const result = await executor.query(sql, [trialRef, cutoffDate]); + const result = await executor.query(sql, [trialRef, cutoffDate]); if (typeof result !== 'object' || result === null || !Array.isArray(result.rows)) { - throw new TypeError('Invalid executor response: expected an object with a rows array.'); + throw new PostgresTrialRefError( + 'INVALID_ROW', + 'Invalid executor response: expected an object with a rows array.' + ); } - return result.rows.length > 0; + + if (result.rows.length === 0) { + return false; + } + + if (result.rows.length !== 1) { + throw new PostgresTrialRefError( + 'INVALID_ROW', + `Invalid executor response: expected at most 1 trial_ledger row, received ${result.rows.length}.` + ); + } + + const raw = result.rows[0]; + if (typeof raw !== 'object' || raw === null || raw.visible !== 1) { + throw new PostgresTrialRefError( + 'INVALID_ROW', + 'Invalid trial_ledger visibility row: expected an object with visible === 1.' + ); + } + + return true; }, }; } + +/** Alias for {@link createPostgresTrialRefLookupPort}. */ +export const createPostgresTrialRefPort = createPostgresTrialRefLookupPort; diff --git a/libs/research/src/mcp/index.ts b/libs/research/src/mcp/index.ts index e598bcfa..910af37e 100644 --- a/libs/research/src/mcp/index.ts +++ b/libs/research/src/mcp/index.ts @@ -1,5 +1,8 @@ +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'; diff --git a/libs/research/test/mcp-exchange-calendars-qa.test.ts b/libs/research/test/mcp-exchange-calendars-qa.test.ts new file mode 100644 index 00000000..d35a216f --- /dev/null +++ b/libs/research/test/mcp-exchange-calendars-qa.test.ts @@ -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 { + 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; + + 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).XNYS!; + + const flipsByYear = new Map(); + 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 = [ + ['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)['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).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).XNYS!.push({ + date: '2024-01-03', + closeTs: 0, + }); + (first.listingCalendarId as Record)[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>(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 = { + 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 }, + ]); + }); +}); diff --git a/libs/research/test/mcp-exchange-calendars.test.ts b/libs/research/test/mcp-exchange-calendars.test.ts new file mode 100644 index 00000000..cb85f02c --- /dev/null +++ b/libs/research/test/mcp-exchange-calendars.test.ts @@ -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) + .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>(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>(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 + ).XNYS; + const xtseSessions = ( + overrideCal.calendars as Record + ).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; + xnysOverrides['2024-11-29'] = 780; + const earlyCloses = Object.create(null) as Record>; + 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) }, + ], + }); + }); +}); diff --git a/libs/research/test/mcp-library-cards.test.ts b/libs/research/test/mcp-library-cards.test.ts new file mode 100644 index 00000000..ac6a35eb --- /dev/null +++ b/libs/research/test/mcp-library-cards.test.ts @@ -0,0 +1,933 @@ +import { afterEach, describe, expect, test } from 'bun:test'; +import { mkdir, mkdtemp, rename, rm, symlink, unlink, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { + type KnowledgePort, + type LibraryCardDirEntry, + type LibraryCardDirHandle, + LibraryCardError, + type LibraryCardFs, + READ_KNOWLEDGE_MAX_TEXT_LENGTH, + type ReadKnowledgeResultPayload, + createLibraryCardReader, + createMcpServer, + createNodeLibraryCardFs, + createReadKnowledgeTool, +} from '../src/mcp/index'; + +const VIRTUAL_ROOT = '/virtual/quant-library'; + +const PIOTROSKI_CARD = `--- +verified: false +checked: 2026-03-15 +title: "Piotroski F-Score: Value, Quality (1976–2000)" +summary: "Nine-signal accounting screen: profitability, leverage, and operating efficiency." +excerpt: "Separates winners from value traps among high book-to-market equities." +matches: [" Value ", "Fundamental", "alphas", "value", "Quality"] +related: ["quant:alphas/novy-marx-gross-profitability"] +sources: ["https://doi.org/10.2307/2672906", "https://example.com/papers/f-score?year=2000&mode=full"] +confidence: high +topic: fundamental-value +--- + +# Piotroski F-Score + +Nine binary fundamental signals evaluated strictly point-in-time. +`; + +const MOMENTUM_CARD = `--- +verified: true +checked: 2026-03-10 +title: "Cross-Sectional Momentum (12-1)" +summary: "Twelve-month return skipping the most recent month." +--- + +Skipping the last month mitigates short-term reversal. +`; + +const LIVE_OPS_CARD = `--- +verified: false +checked: 2026-03-12 +title: "IBKR Margin & FX Rebalance Checklist" +summary: "Pre-trade checks for USD/CAD margin accounts." +matches: ["execution", "IBKR"] +--- + +Verify buying power and currency conversion buffers before routing. +`; + +const STANDARD_MANIFEST = `# Quant methodology library +id: quant +name: "Quant Research Library" +shelves: + - id: core + title: "Core reading" + nested: + ignored: true +sections: + live-ops: Live operations & execution + alphas: Signal & alpha research +`; + +interface FakeFsState { + readonly files: Map; + readonly dirs: Map; + readonly readPaths: string[]; + readonly listPaths: string[]; + readonly readErrors: Map; + readonly listErrors: Map; + readonly fs: LibraryCardFs; +} + +function makeEnoent(targetPath: string): NodeJS.ErrnoException { + const err = new Error(`ENOENT: no such file or directory, open '${targetPath}'`) as NodeJS.ErrnoException; + err.code = 'ENOENT'; + return err; +} + +function createFakeLibraryFs(init?: { + readonly files?: Readonly>; + readonly dirs?: Readonly>; +}): FakeFsState { + const files = new Map(); + const dirs = new Map(); + const readPaths: string[] = []; + const listPaths: string[] = []; + const readErrors = new Map(); + const listErrors = new Map(); + + if (init?.files !== undefined) { + for (const [relOrAbs, text] of Object.entries(init.files)) { + const full = path.isAbsolute(relOrAbs) ? relOrAbs : path.join(VIRTUAL_ROOT, relOrAbs); + files.set(full, text); + } + } + if (init?.dirs !== undefined) { + for (const [relOrAbs, entries] of Object.entries(init.dirs)) { + const full = relOrAbs === '' ? VIRTUAL_ROOT : path.isAbsolute(relOrAbs) ? relOrAbs : path.join(VIRTUAL_ROOT, relOrAbs); + dirs.set(full, [...entries]); + } + } + + const readFileByPath = async (filePath: string): Promise => { + readPaths.push(filePath); + const forcedErr = readErrors.get(filePath); + if (forcedErr !== undefined) { + throw forcedErr; + } + const text = files.get(filePath); + if (text === undefined) { + throw makeEnoent(filePath); + } + return text; + }; + + const listDirByPath = async (dirPath: string): Promise => { + listPaths.push(dirPath); + const forcedErr = listErrors.get(dirPath); + if (forcedErr !== undefined) { + throw forcedErr; + } + const entries = dirs.get(dirPath); + if (entries === undefined) { + throw makeEnoent(dirPath); + } + return [...entries]; + }; + + const createAnchoredFakeDirHandle = (dirPath: string): LibraryCardDirHandle => { + let closed = false; + const assertOpen = (): void => { + if (closed) { + throw new Error(`Directory handle already closed: ${dirPath}`); + } + }; + const assertChildName = (name: string): void => { + if ( + name.length === 0 || + name === '.' || + name === '..' || + name.includes('/') || + name.includes('\\') || + name.includes('\0') + ) { + throw new Error(`Invalid child name: ${name}`); + } + }; + return { + async listDir(): Promise { + assertOpen(); + return listDirByPath(dirPath); + }, + async openSubdir(name: string): Promise { + assertOpen(); + assertChildName(name); + const childPath = path.join(dirPath, name); + if (!dirs.has(childPath)) { + throw makeEnoent(childPath); + } + return createAnchoredFakeDirHandle(childPath); + }, + async readTextFile(name: string): Promise { + assertOpen(); + assertChildName(name); + return readFileByPath(path.join(dirPath, name)); + }, + async close(): Promise { + closed = true; + }, + }; + }; + + const fs: LibraryCardFs = { + readTextFile: readFileByPath, + listDir: listDirByPath, + async openDir(dirPath: string): Promise { + if (dirPath !== VIRTUAL_ROOT && !dirs.has(dirPath)) { + throw makeEnoent(dirPath); + } + return createAnchoredFakeDirHandle(dirPath); + }, + }; + + return { files, dirs, readPaths, listPaths, readErrors, listErrors, fs }; +} + +function createStandardFakeFs(): FakeFsState { + return createFakeLibraryFs({ + files: { + 'library.yml': STANDARD_MANIFEST, + 'cards/live-ops/ibkr-margin.md': LIVE_OPS_CARD, + 'cards/alphas/piotroski-f-score.md': PIOTROSKI_CARD, + 'cards/alphas/a-momentum.md': MOMENTUM_CARD, + }, + dirs: { + '': [ + { name: 'library.yml', isFile: true, isDirectory: false }, + { name: '_topics.yml', isFile: true, isDirectory: false }, + { name: 'rules', isFile: false, isDirectory: true }, + { name: 'cards', isFile: false, isDirectory: true }, + ], + cards: [ + { name: 'alphas', isFile: false, isDirectory: true }, + { name: 'live-ops', isFile: false, isDirectory: true }, + ], + 'cards/live-ops': [{ name: 'ibkr-margin.md', isFile: true, isDirectory: false }], + // Deliberately unsorted listing to verify code-unit slug sorting. + 'cards/alphas': [ + { name: 'piotroski-f-score.md', isFile: true, isDirectory: false }, + { name: 'a-momentum.md', isFile: true, isDirectory: false }, + ], + }, + }); +} + +async function expectLibraryCardError( + fn: () => Promise | unknown, + expectedCode: LibraryCardError['code'] +): Promise { + try { + await fn(); + } catch (err) { + expect(err).toBeInstanceOf(RangeError); + expect(err).toBeInstanceOf(LibraryCardError); + const typed = err as LibraryCardError; + expect(typed.code).toBe(expectedCode); + return typed; + } + throw new Error(`Expected LibraryCardError(${expectedCode}) to be thrown.`); +} + +const tempDirs: string[] = []; + +afterEach(async () => { + while (tempDirs.length > 0) { + const dir = tempDirs.pop(); + if (dir !== undefined) { + await rm(dir, { recursive: true, force: true }); + } + } +}); + +describe('MCP library-cards filesystem adapter', () => { + test('reads sections in manifest order, sorts slugs by code unit, normalizes tags, and preserves punctuation/Unicode and unverified cards', async () => { + const fake = createStandardFakeFs(); + const reader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: fake.fs }); + + const cards = await reader.listLibraryCards({}); + + expect(cards.map(c => c.id)).toEqual([ + 'quant:live-ops/ibkr-margin', + 'quant:alphas/a-momentum', + 'quant:alphas/piotroski-f-score', + ]); + + expect(cards[0]).toEqual({ + id: 'quant:live-ops/ibkr-margin', + title: 'IBKR Margin & FX Rebalance Checklist', + tags: ['live-ops', 'execution', 'ibkr'], + summary: 'Pre-trade checks for USD/CAD margin accounts.', + body: 'Verify buying power and currency conversion buffers before routing.', + }); + + // Missing matches falls back to [sectionId]. + expect(cards[1]).toEqual({ + id: 'quant:alphas/a-momentum', + title: 'Cross-Sectional Momentum (12-1)', + tags: ['alphas'], + summary: 'Twelve-month return skipping the most recent month.', + body: 'Skipping the last month mitigates short-term reversal.', + }); + + // Quoted punctuation (:, ,, (), en-dash), URL array, deduplicated tags in first-seen order, verified: false included. + expect(cards[2]).toEqual({ + id: 'quant:alphas/piotroski-f-score', + title: 'Piotroski F-Score: Value, Quality (1976–2000)', + tags: ['alphas', 'value', 'fundamental', 'quality'], + summary: 'Nine-signal accounting screen: profitability, leverage, and operating efficiency.', + body: '# Piotroski F-Score\n\nNine binary fundamental signals evaluated strictly point-in-time.', + }); + }); + + test('supports exact case-sensitive q.id narrowing and blocks traversal/unknown IDs with zero card reads', async () => { + const fake = createStandardFakeFs(); + const reader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: fake.fs }); + const manifestPath = path.join(VIRTUAL_ROOT, 'library.yml'); + const piotroskiPath = path.join(VIRTUAL_ROOT, 'cards/alphas/piotroski-f-score.md'); + + // Exact hit reads library.yml and only the target card. + const hit = await reader.listLibraryCards({ id: 'quant:alphas/piotroski-f-score' }); + expect(hit).toHaveLength(1); + expect(hit[0]?.id).toBe('quant:alphas/piotroski-f-score'); + expect(fake.readPaths).toEqual([manifestPath, piotroskiPath]); + + // Misses and traversal attempts must return frozen [] and read no card files. + const missIds = [ + 'QUANT:alphas/piotroski-f-score', + 'quant:Alphas/piotroski-f-score', + 'quant:alphas/Piotroski-f-score', + 'quant:unknown-section/piotroski-f-score', + 'quant:alphas/does-not-exist', + 'quant:../x', + 'quant:alphas/../../library', + '/etc/passwd', + 'quant:alphas/sub/nested', + '', + ]; + + for (const id of missIds) { + fake.readPaths.length = 0; + const result = await reader.listLibraryCards({ id }); + expect(result).toEqual([]); + expect(Object.isFrozen(result)).toBe(true); + expect(fake.readPaths).toEqual([manifestPath]); + for (const readPath of fake.readPaths) { + expect(readPath === manifestPath || readPath.startsWith(`${VIRTUAL_ROOT}/cards/`)).toBe( + true + ); + } + } + }); + + test('skips dotfiles, non-.md files, nested dirs, symlinks, undeclared sections, invalid slugs, invalid section IDs, and missing section dirs', async () => { + const fake = createFakeLibraryFs({ + files: { + 'library.yml': `id: quant +sections: + alphas: Alphas + -draft: Draft notes + .archived: Archived notes + old signals: Archived signals + Bad_Section: Invalid section name + empty-section: Declared section with no directory +`, + 'cards/alphas/valid-card.md': MOMENTUM_CARD, + 'cards/alphas/.hidden.md': MOMENTUM_CARD, + 'cards/alphas/README.txt': 'ignored', + 'cards/alphas/UpperCase.md': MOMENTUM_CARD, + 'cards/alphas/symlink-card.md': MOMENTUM_CARD, + 'cards/undeclared/secret.md': MOMENTUM_CARD, + 'cards/-draft/valid-card.md': MOMENTUM_CARD, + 'cards/old signals/valid-card.md': MOMENTUM_CARD, + 'cards/Bad_Section/valid-card.md': MOMENTUM_CARD, + }, + dirs: { + '': [ + { name: 'library.yml', isFile: true, isDirectory: false }, + { name: 'cards', isFile: false, isDirectory: true }, + ], + cards: [ + { name: 'alphas', isFile: false, isDirectory: true }, + { name: 'undeclared', isFile: false, isDirectory: true }, + { name: '-draft', isFile: false, isDirectory: true }, + { name: 'old signals', isFile: false, isDirectory: true }, + { name: 'Bad_Section', isFile: false, isDirectory: true }, + { name: 'symlink-section', isFile: false, isDirectory: false }, + ], + 'cards/alphas': [ + { name: '.hidden.md', isFile: true, isDirectory: false }, + { name: 'README.txt', isFile: true, isDirectory: false }, + { name: 'nested.md', isFile: false, isDirectory: true }, + { name: 'symlink-card.md', isFile: false, isDirectory: false }, + { name: 'UpperCase.md', isFile: true, isDirectory: false }, + { name: 'valid-card.md', isFile: true, isDirectory: false }, + ], + 'cards/old signals': [{ name: 'valid-card.md', isFile: true, isDirectory: false }], + }, + }); + + const reader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: fake.fs }); + const cards = await reader.listLibraryCards({}); + + expect(cards.map(c => c.id)).toEqual(['quant:alphas/valid-card']); + expect(fake.readPaths).toEqual([ + path.join(VIRTUAL_ROOT, 'library.yml'), + path.join(VIRTUAL_ROOT, 'cards/alphas/valid-card.md'), + ]); + }); + + test('validates constructor options synchronously and fails closed on invalid manifest and I/O errors', async () => { + const fake = createStandardFakeFs(); + + await expectLibraryCardError( + () => createLibraryCardReader(null as unknown as { root: string; fs: LibraryCardFs }), + 'INVALID_ROOT' + ); + await expectLibraryCardError( + () => createLibraryCardReader({ root: ' ', fs: fake.fs }), + 'INVALID_ROOT' + ); + await expectLibraryCardError( + () => createLibraryCardReader({ root: '/tmp/bad\0path', fs: fake.fs }), + 'INVALID_ROOT' + ); + await expectLibraryCardError( + () => createLibraryCardReader({ root: VIRTUAL_ROOT, fs: null as unknown as LibraryCardFs }), + 'INVALID_FS' + ); + await expectLibraryCardError( + () => + createLibraryCardReader({ + root: VIRTUAL_ROOT, + fs: { readTextFile: fake.fs.readTextFile } as unknown as LibraryCardFs, + }), + 'INVALID_FS' + ); + // A two-method wrapper omitting anchored openDir must fail closed at construction. + const nodeFs = createNodeLibraryCardFs(); + await expectLibraryCardError( + () => + createLibraryCardReader({ + root: VIRTUAL_ROOT, + fs: { + readTextFile: p => nodeFs.readTextFile(p), + listDir: p => nodeFs.listDir(p), + } as unknown as LibraryCardFs, + }), + 'INVALID_FS' + ); + + // Zero I/O happened during invalid option checks. + expect(fake.readPaths).toHaveLength(0); + expect(fake.listPaths).toHaveLength(0); + + // Missing library.yml + const missingManifestFs = createFakeLibraryFs({}); + const missingReader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: missingManifestFs.fs }); + await expectLibraryCardError(() => missingReader.listLibraryCards({}), 'INVALID_LIBRARY'); + + // Malformed library.yml variants + const badManifests: readonly string[] = [ + 'sections:\n alphas: Alphas\n', // missing id + 'id:\nsections:\n alphas: Alphas\n', // empty id + 'id: quant\nname: Only name\n', // missing sections + 'id: quant\nsections:\n', // empty sections + 'id: quant\nid: quant2\nsections:\n alphas: Alphas\n', // duplicate id + 'id: quant\nsections:\n alphas: A\nsections:\n beta: B\n', // duplicate sections + 'id: quant\nsections:\n alphas: A\n alphas: B\n', // duplicate section key + 'id: quant\nsections: []\n', // non-map sections + 'id: quant\nsections:\n - alphas: Alphas\n', // YAML sequence under sections + 'id: quant\nsections:\n - alphas\n', // YAML bare sequence under sections + 'id: quant\nsections:\n alphas: # comment-only title\n', // comment-only title + 'id: quant\nsections:\n alphas:NoSpace\n', // missing space after colon + ]; + + for (const manifest of badManifests) { + const f = createFakeLibraryFs({ files: { 'library.yml': manifest } }); + const r = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: f.fs }); + await expectLibraryCardError(() => r.listLibraryCards({}), 'INVALID_LIBRARY'); + } + + // Permission / generic I/O failure on listDir and card readTextFile + const ioFake = createStandardFakeFs(); + const eacces = Object.assign(new Error('EACCES: permission denied /secret/path'), { + code: 'EACCES', + }); + ioFake.listErrors.set(path.join(VIRTUAL_ROOT, 'cards/alphas'), eacces); + const ioReader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: ioFake.fs }); + const listErr = await expectLibraryCardError( + () => ioReader.listLibraryCards({}), + 'INVALID_LIBRARY' + ); + expect(listErr.message).not.toContain('/secret/path'); + + ioFake.listErrors.clear(); + ioFake.readErrors.set( + path.join(VIRTUAL_ROOT, 'cards/alphas/a-momentum.md'), + new Error('EIO: raw disk failure secret-bytes') + ); + const readErr = await expectLibraryCardError( + () => ioReader.listLibraryCards({}), + 'INVALID_CARD' + ); + expect(readErr.message).toContain('cards/alphas/a-momentum.md'); + expect(readErr.message).not.toContain('secret-bytes'); + }); + + test('fails closed on malformed cards and duplicate card IDs, naming relative path without leaking card content', async () => { + const SECRET_MARKER = 'CONFIDENTIAL_CARD_BODY_MARKER_99123'; + + const badCards: readonly { readonly label: string; readonly content: string }[] = [ + { + label: 'missing opening delimiter', + content: `title: "T"\nsummary: "S"\n---\n${SECRET_MARKER}`, + }, + { + label: 'missing closing delimiter', + content: `---\ntitle: "T"\nsummary: "S"\n${SECRET_MARKER}`, + }, + { + label: 'missing title', + content: `---\nsummary: "S"\n---\n${SECRET_MARKER}`, + }, + { + label: 'blank title', + content: `---\ntitle: " "\nsummary: "S"\n---\n${SECRET_MARKER}`, + }, + { + label: 'missing summary', + content: `---\ntitle: "T"\n---\n${SECRET_MARKER}`, + }, + { + label: 'blank summary', + content: `---\ntitle: "T"\nsummary: ""\n---\n${SECRET_MARKER}`, + }, + { + label: 'unterminated double quote', + content: `---\ntitle: "Unterminated ${SECRET_MARKER}\nsummary: "S"\n---\n${SECRET_MARKER}`, + }, + { + label: 'single-quoted value', + content: `---\ntitle: 'Single ${SECRET_MARKER}'\nsummary: "S"\n---\n${SECRET_MARKER}`, + }, + { + label: 'multiline block scalar', + content: `---\ntitle: "T"\nsummary: |\n ${SECRET_MARKER}\n---\n${SECRET_MARKER}`, + }, + { + label: 'indented continuation', + content: `---\ntitle: "T"\n ${SECRET_MARKER}\nsummary: "S"\n---\n${SECRET_MARKER}`, + }, + { + label: 'invalid matches non-array', + content: `---\ntitle: "T"\nsummary: "S"\nmatches: "${SECRET_MARKER}"\n---\n${SECRET_MARKER}`, + }, + { + label: 'invalid matches non-string item', + content: `---\ntitle: "T"\nsummary: "S"\nmatches: ["ok", 42]\n---\n${SECRET_MARKER}`, + }, + { + label: 'duplicate key', + content: `---\ntitle: "First"\ntitle: "Second ${SECRET_MARKER}"\nsummary: "S"\n---\n${SECRET_MARKER}`, + }, + { + label: 'comment-only summary', + content: `---\ntitle: "T"\nsummary: # Fill in after review ${SECRET_MARKER}\n---\n${SECRET_MARKER}`, + }, + { + label: 'comment-only title', + content: `---\ntitle: # Draft title ${SECRET_MARKER}\nsummary: "S"\n---\n${SECRET_MARKER}`, + }, + ]; + + for (const tc of badCards) { + const fake = createFakeLibraryFs({ + files: { + 'library.yml': STANDARD_MANIFEST, + 'cards/alphas/broken-card.md': tc.content, + }, + dirs: { + '': [{ name: 'cards', isFile: false, isDirectory: true }], + cards: [{ name: 'alphas', isFile: false, isDirectory: true }], + 'cards/alphas': [{ name: 'broken-card.md', isFile: true, isDirectory: false }], + }, + }); + const reader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: fake.fs }); + const err = await expectLibraryCardError(() => reader.listLibraryCards({}), 'INVALID_CARD'); + expect(err.message).toContain('cards/alphas/broken-card.md'); + expect(err.message).not.toContain(SECRET_MARKER); + } + + // Duplicate card ID via duplicate directory entries (both broad scan and exact ID lookup). + const dupFake = createFakeLibraryFs({ + files: { + 'library.yml': STANDARD_MANIFEST, + 'cards/alphas/dup-card.md': `---\ntitle: "Dup"\nsummary: "Summary"\n---\n${SECRET_MARKER}`, + }, + dirs: { + '': [{ name: 'cards', isFile: false, isDirectory: true }], + cards: [{ name: 'alphas', isFile: false, isDirectory: true }], + 'cards/alphas': [ + { name: 'dup-card.md', isFile: true, isDirectory: false }, + { name: 'dup-card.md', isFile: true, isDirectory: false }, + ], + }, + }); + const dupReader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: dupFake.fs }); + const broadDupErr = await expectLibraryCardError( + () => dupReader.listLibraryCards({}), + 'INVALID_CARD' + ); + expect(broadDupErr.message).toContain('cards/alphas/dup-card.md'); + expect(broadDupErr.message).not.toContain(SECRET_MARKER); + + const exactDupErr = await expectLibraryCardError( + () => dupReader.listLibraryCards({ id: 'quant:alphas/dup-card' }), + 'INVALID_CARD' + ); + expect(exactDupErr.message).toContain('cards/alphas/dup-card.md'); + expect(exactDupErr.message).not.toContain(SECRET_MARKER); + }); + + test('integrates end-to-end with createReadKnowledgeTool while adapter returns all candidates untruncated', async () => { + const longBody = 'A'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH + 250); + const fake = createStandardFakeFs(); + fake.files.set( + path.join(VIRTUAL_ROOT, 'cards/alphas/piotroski-f-score.md'), + `--- +verified: false +title: "Piotroski F-Score: Value, Quality (1976–2000)" +summary: "Nine-signal accounting screen: profitability, leverage, and operating efficiency." +matches: ["Value", "Quality"] +--- + +${longBody} +` + ); + + const libraryReader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: fake.fs }); + + // Adapter itself ignores query/tags and does not truncate body text. + const rawCandidates = await libraryReader.listLibraryCards({ + query: 'piotroski', + tags: ['VALUE'], + }); + expect(rawCandidates).toHaveLength(3); + const rawPiotroski = rawCandidates.find(c => c.id === 'quant:alphas/piotroski-f-score'); + expect(rawPiotroski?.body.length).toBe(READ_KNOWLEDGE_MAX_TEXT_LENGTH + 250); + + // Real read_knowledge tool filters by mixed-case tags + query and truncates long body. + const port: KnowledgePort = { + ...libraryReader, + async listFindings() { + return []; + }, + async listProviderCaveats() { + return []; + }, + }; + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [createReadKnowledgeTool({ port })], + }); + + const rawResponse = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'lib-e2e-1', + method: 'tools/call', + params: { + name: 'read_knowledge', + arguments: { + source: 'library', + tags: ['VALUE', 'Alphas'], + query: 'piotroski', + }, + }, + }) + ); + + expect(rawResponse).not.toBeNull(); + const parsed = JSON.parse(rawResponse as string) as { + result: { isError?: boolean; content: { type: string; text: string }[] }; + }; + expect(parsed.result.isError).toBeUndefined(); + const payload = JSON.parse(parsed.result.content[0]?.text ?? '') as ReadKnowledgeResultPayload; + expect(payload.rowCount).toBe(1); + expect(payload.sources).toEqual({ library: 1, findings: 0, provider_caveats: 0 }); + expect(payload.rows[0]).toEqual({ + source: 'library', + id: 'quant:alphas/piotroski-f-score', + title: 'Piotroski F-Score: Value, Quality (1976–2000)', + tags: ['alphas', 'value', 'quality'], + summary: 'Nine-signal accounting screen: profitability, leverage, and operating efficiency.', + body: 'A'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH), + truncated: true, + }); + }); + + test('reads fresh on every call and returns frozen result arrays, records, and tag arrays', async () => { + const fake = createStandardFakeFs(); + const reader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: fake.fs }); + + const first = await reader.listLibraryCards({}); + expect(Object.isFrozen(first)).toBe(true); + for (const card of first) { + expect(Object.isFrozen(card)).toBe(true); + expect(Object.isFrozen(card.tags)).toBe(true); + } + expect(first.find(c => c.id === 'quant:alphas/a-momentum')?.title).toBe( + 'Cross-Sectional Momentum (12-1)' + ); + + // Mutate card and manifest in the fake between calls. + fake.files.set( + path.join(VIRTUAL_ROOT, 'cards/alphas/a-momentum.md'), + `--- +title: "Updated Momentum Title" +summary: "Updated summary." +matches: ["updated-tag"] +--- + +Updated body. +` + ); + fake.files.set( + path.join(VIRTUAL_ROOT, 'library.yml'), + `id: quant-v2 +sections: + alphas: Alphas only +` + ); + + const second = await reader.listLibraryCards({}); + expect(second.map(c => c.id)).toEqual([ + 'quant-v2:alphas/a-momentum', + 'quant-v2:alphas/piotroski-f-score', + ]); + expect(second[0]).toEqual({ + id: 'quant-v2:alphas/a-momentum', + title: 'Updated Momentum Title', + tags: ['alphas', 'updated-tag'], + summary: 'Updated summary.', + body: 'Updated body.', + }); + expect(Object.isFrozen(second)).toBe(true); + expect(Object.isFrozen(second[0])).toBe(true); + expect(Object.isFrozen(second[0]?.tags)).toBe(true); + }); + + test('createNodeLibraryCardFs reads real temp fixtures and never follows symlinked files, sections, or manifests', async () => { + const tempBase = await mkdtemp(path.join(os.tmpdir(), 'stock-bot-library-cards-')); + tempDirs.push(tempBase); + + const libRoot = path.join(tempBase, 'library'); + const siblingDir = path.join(tempBase, 'sibling-outside-library'); + const siblingFile = path.join(siblingDir, 'leaked.md'); + + await mkdir(path.join(libRoot, 'cards', 'alphas'), { recursive: true }); + await mkdir(siblingDir, { recursive: true }); + + await writeFile( + path.join(libRoot, 'library.yml'), + `id: quant +sections: + alphas: Signal & alpha research + linked-section: Symlinked section +`, + 'utf8' + ); + await writeFile(path.join(libRoot, 'cards', 'alphas', 'piotroski-f-score.md'), PIOTROSKI_CARD, 'utf8'); + await writeFile( + siblingFile, + `--- +title: "Leaked Sibling Card" +summary: "Must never be read via symlink." +--- + +LEAKED_SIBLING_CONTENT +`, + 'utf8' + ); + + // Create symlinked file inside cards/alphas and symlinked section directory inside cards/. + await symlink(siblingFile, path.join(libRoot, 'cards', 'alphas', 'linked-card.md')); + await symlink(siblingDir, path.join(libRoot, 'cards', 'linked-section')); + + const nodeFs = createNodeLibraryCardFs(); + const reader = createLibraryCardReader({ root: libRoot, fs: nodeFs }); + + const cards = await reader.listLibraryCards({}); + expect(cards).toHaveLength(1); + expect(cards[0]?.id).toBe('quant:alphas/piotroski-f-score'); + + // Exact-ID lookups targeting symlinked file or symlinked section return empty without reading. + expect(await reader.listLibraryCards({ id: 'quant:alphas/linked-card' })).toEqual([]); + expect(await reader.listLibraryCards({ id: 'quant:linked-section/leaked' })).toEqual([]); + + // Direct symlinked library.yml must fail closed via O_NOFOLLOW. + const symlinkManifestRoot = path.join(tempBase, 'symlink-manifest-lib'); + await mkdir(symlinkManifestRoot, { recursive: true }); + await symlink(path.join(libRoot, 'library.yml'), path.join(symlinkManifestRoot, 'library.yml')); + const symlinkManifestReader = createLibraryCardReader({ + root: symlinkManifestRoot, + fs: nodeFs, + }); + await expectLibraryCardError( + () => symlinkManifestReader.listLibraryCards({}), + 'INVALID_LIBRARY' + ); + }); + + test('anchors directory listings and reads to open handles to block directory-symlink TOCTOU races', async () => { + const tempBase = await mkdtemp(path.join(os.tmpdir(), 'stock-bot-library-toctou-')); + tempDirs.push(tempBase); + + const libRoot = path.join(tempBase, 'library'); + const alphasDir = path.join(libRoot, 'cards', 'alphas'); + const outsideDir = path.join(tempBase, 'outside-corpus'); + const LEAK_MARKER = 'OUTSIDE_CORPUS_TOCTOU_LEAK_7741'; + + await mkdir(alphasDir, { recursive: true }); + await mkdir(outsideDir, { recursive: true }); + + await writeFile( + path.join(libRoot, 'library.yml'), + `id: quant\nsections:\n alphas: Signal & alpha research\n`, + 'utf8' + ); + await writeFile(path.join(alphasDir, 'piotroski-f-score.md'), PIOTROSKI_CARD, 'utf8'); + await writeFile( + path.join(outsideDir, 'piotroski-f-score.md'), + `---\ntitle: "Leaked Card"\nsummary: "Leaked summary"\n---\n\n${LEAK_MARKER}\n`, + 'utf8' + ); + + const baseNodeFs = createNodeLibraryCardFs(); + expect(typeof baseNodeFs.openDir).toBe('function'); + + // Race A: cards/alphas is replaced with a symlink after cards/ is listed, before opening alphas. + let raceATriggered = false; + const raceAFs: LibraryCardFs = { + readTextFile: p => baseNodeFs.readTextFile(p), + listDir: p => baseNodeFs.listDir(p), + async openDir(dirPath: string): Promise { + const rootHandle = await baseNodeFs.openDir(dirPath); + return { + listDir: () => rootHandle.listDir(), + readTextFile: name => rootHandle.readTextFile(name), + close: () => rootHandle.close(), + async openSubdir(name: string): Promise { + const sub = await rootHandle.openSubdir(name); + if (name !== 'cards') { + return sub; + } + return { + async listDir(): Promise { + const entries = await sub.listDir(); + if (!raceATriggered) { + raceATriggered = true; + await rename(alphasDir, path.join(libRoot, 'cards', 'alphas-moved-a')); + await symlink(outsideDir, alphasDir); + } + return entries; + }, + openSubdir: child => sub.openSubdir(child), + readTextFile: child => sub.readTextFile(child), + close: () => sub.close(), + }; + }, + }; + }, + }; + + const raceAReader = createLibraryCardReader({ root: libRoot, fs: raceAFs }); + const raceAErr = await expectLibraryCardError( + () => raceAReader.listLibraryCards({}), + 'INVALID_LIBRARY' + ); + expect(raceATriggered).toBe(true); + expect(raceAErr.message).not.toContain(LEAK_MARKER); + + // Restore alphas directory for Race B. + await unlink(alphasDir); + await rename(path.join(libRoot, 'cards', 'alphas-moved-a'), alphasDir); + + // Race B: cards/alphas is replaced with a symlink after alphas is opened and listed, before reading the card. + let raceBTriggered = false; + const raceBFs: LibraryCardFs = { + readTextFile: p => baseNodeFs.readTextFile(p), + listDir: p => baseNodeFs.listDir(p), + async openDir(dirPath: string): Promise { + const rootHandle = await baseNodeFs.openDir(dirPath); + return { + listDir: () => rootHandle.listDir(), + readTextFile: name => rootHandle.readTextFile(name), + close: () => rootHandle.close(), + async openSubdir(name: string): Promise { + const cardsHandle = await rootHandle.openSubdir(name); + if (name !== 'cards') { + return cardsHandle; + } + return { + listDir: () => cardsHandle.listDir(), + readTextFile: child => cardsHandle.readTextFile(child), + close: () => cardsHandle.close(), + async openSubdir(sectionName: string): Promise { + const sectionHandle = await cardsHandle.openSubdir(sectionName); + return { + async listDir(): Promise { + const entries = await sectionHandle.listDir(); + if (!raceBTriggered && sectionName === 'alphas') { + raceBTriggered = true; + await rename(alphasDir, path.join(libRoot, 'cards', 'alphas-moved-b')); + await symlink(outsideDir, alphasDir); + } + return entries; + }, + openSubdir: child => sectionHandle.openSubdir(child), + readTextFile: child => sectionHandle.readTextFile(child), + close: () => sectionHandle.close(), + }; + }, + }; + }, + }; + }, + }; + + const raceBReader = createLibraryCardReader({ root: libRoot, fs: raceBFs }); + const anchoredCards = await raceBReader.listLibraryCards({}); + expect(raceBTriggered).toBe(true); + expect(anchoredCards).toHaveLength(1); + expect(anchoredCards[0]?.id).toBe('quant:alphas/piotroski-f-score'); + expect(anchoredCards[0]?.body).not.toContain(LEAK_MARKER); + expect(anchoredCards[0]?.body).toContain('Piotroski F-Score'); + + // Unsupported boundary enforcement on openDir fails closed with INVALID_LIBRARY. + const unsupportedFs: LibraryCardFs = { + readTextFile: p => baseNodeFs.readTextFile(p), + listDir: p => baseNodeFs.listDir(p), + async openDir(): Promise { + throw new Error('Anchored no-follow directory operations are not supported.'); + }, + }; + const unsupportedReader = createLibraryCardReader({ root: libRoot, fs: unsupportedFs }); + await expectLibraryCardError( + () => unsupportedReader.listLibraryCards({}), + 'INVALID_LIBRARY' + ); + }); +}); diff --git a/libs/research/test/mcp-postgres-findings-qa.test.ts b/libs/research/test/mcp-postgres-findings-qa.test.ts new file mode 100644 index 00000000..249816fd --- /dev/null +++ b/libs/research/test/mcp-postgres-findings-qa.test.ts @@ -0,0 +1,268 @@ +import { describe, expect, test } from 'bun:test'; +import { + type FiledFindingRecord, + type PostgresFindingsExecutor, + createPostgresFindingWritePort, + createPostgresKnowledgeReaders, +} from '../src/mcp/index'; + +// QA edge cases for the PostgreSQL findings adapter (T-161), complementing +// mcp-postgres-findings.test.ts. All randomness is seeded; no wall clock. + +interface RecordedCall { + readonly text: string; + readonly params: readonly unknown[] | undefined; +} + +function createRowsExecutor(rows: readonly Record[]): { + readonly calls: RecordedCall[]; + readonly executor: PostgresFindingsExecutor; +} { + const calls: RecordedCall[] = []; + return { + calls, + executor: { + async query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + calls.push({ text, params }); + return { rows: rows as unknown as readonly Row[] }; + }, + }, + }; +} + +function mulberry32(seed: number): () => number { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +// Mix of ASCII (incl. LIKE wildcards / escape) and casing-hostile Unicode. +const ALPHABET = ['a', 'B', 'i', 'I', 's', 'S', 'k', '%', '_', '\\', ' ', 'İ', 'ı', 'Σ', 'ς', 'K', 'é', 'ß']; + +function randomText(rand: () => number, min: number, max: number): string { + const len = min + Math.floor(rand() * (max - min + 1)); + let out = ''; + for (let i = 0; i < len; i += 1) { + out += ALPHABET[Math.floor(rand() * ALPHABET.length)]; + } + return out; +} + +function randomQuery(rand: () => number, corpus: readonly string[]): string { + if (rand() < 0.5) { + const source = corpus[Math.floor(rand() * corpus.length)]!; + const start = Math.floor(rand() * source.length); + const end = Math.min(source.length, start + 1 + Math.floor(rand() * 3)); + let q = ''; + for (const ch of source.slice(start, end)) { + q += rand() < 0.5 ? ch.toUpperCase() : ch.toLowerCase(); + } + return q.length > 0 ? q : 'a'; + } + return randomText(rand, 1, 2); +} + +const TS = '2026-01-15T12:34:56.789Z'; + +describe('PostgreSQL findings readers QA: JS post-filter agrees with read_knowledge matching', () => { + test('seeded fuzz: listFindings returns exactly the read_knowledge-matching rows in SQL order', async () => { + const rand = mulberry32(161); + const rows = Array.from({ length: 40 }, (_, i) => ({ + id: `f-${String(i).padStart(3, '0')}`, + title: `T${randomText(rand, 2, 6)}`, + summary: `S${randomText(rand, 2, 6)}`, + status: 'pending_review', + created_at: new Date(TS), + trial_refs: [], + evidence_refs: [], + })); + const corpus = rows.flatMap(r => [r.title, r.summary]); + const { executor } = createRowsExecutor(rows); + const readers = createPostgresKnowledgeReaders({ executor }); + + for (let n = 0; n < 200; n += 1) { + const query = randomQuery(rand, corpus); + const lower = query.toLowerCase(); + const expected = rows + .filter(r => r.title.toLowerCase().includes(lower) || r.summary.toLowerCase().includes(lower)) + .map(r => r.id); + const actual = (await readers.listFindings({ query })).map(r => r.id); + expect({ query, ids: actual }).toEqual({ query, ids: expected }); + } + }); + + test('seeded fuzz: listProviderCaveats applies provider equality and query substring like read_knowledge', async () => { + const rand = mulberry32(2026); + const providers = ['EODHD', 'eodhd', 'K', 'kelvin', 'İBK', 'ibk', 'ΣΙΣ', 'σις']; + const rows = Array.from({ length: 40 }, (_, i) => ({ + id: `c-${String(i).padStart(3, '0')}`, + provider: providers[Math.floor(rand() * providers.length)]!, + dataset: `D${randomText(rand, 2, 5)}`, + caveat: `C${randomText(rand, 2, 6)}`, + created_at: new Date(TS), + })); + const corpus = rows.flatMap(r => [r.provider, r.dataset, r.caveat]); + const { executor } = createRowsExecutor(rows); + const readers = createPostgresKnowledgeReaders({ executor }); + + for (let n = 0; n < 200; n += 1) { + const provider = + rand() < 0.6 ? providers[Math.floor(rand() * providers.length)]!.toUpperCase() : undefined; + const query = rand() < 0.7 ? randomQuery(rand, corpus) : undefined; + const lowerProvider = provider?.toLowerCase(); + const lowerQuery = query?.toLowerCase(); + const expected = rows + .filter(r => lowerProvider === undefined || r.provider.toLowerCase() === lowerProvider) + .filter( + r => + lowerQuery === undefined || + r.provider.toLowerCase().includes(lowerQuery) || + r.dataset.toLowerCase().includes(lowerQuery) || + r.caveat.toLowerCase().includes(lowerQuery) + ) + .map(r => r.id); + const actual = ( + await readers.listProviderCaveats({ + ...(provider !== undefined ? { provider } : {}), + ...(query !== undefined ? { query } : {}), + }) + ).map(r => r.id); + expect({ provider, query, ids: actual }).toEqual({ provider, query, ids: expected }); + } + }); + + test('non-ASCII Kelvin-sign query omits SQL casing and still matches ASCII stored text via JS lowering', async () => { + const { calls, executor } = createRowsExecutor([ + { id: 'f-1', title: 'kelvin bars', summary: 'x', status: 's', created_at: new Date(TS), trial_refs: [], evidence_refs: [] }, + { id: 'f-2', title: 'other', summary: 'y', status: 's', created_at: new Date(TS), trial_refs: [], evidence_refs: [] }, + ]); + const readers = createPostgresKnowledgeReaders({ executor }); + + const result = await readers.listFindings({ query: 'Kelvin' }); + + expect(result.map(r => r.id)).toEqual(['f-1']); + expect(calls[0]!.text).not.toContain('WHERE'); + expect(calls[0]!.params).toEqual([]); + }); + + test('exact id ignores a non-ASCII query in the JS post-filter too', async () => { + const { calls, executor } = createRowsExecutor([ + { id: 'f-1', title: 'plain', summary: 'plain', status: 's', created_at: new Date(TS), trial_refs: [], evidence_refs: [] }, + ]); + const readers = createPostgresKnowledgeReaders({ executor }); + + const result = await readers.listFindings({ id: 'f-1', query: 'ΚΟΣΜΟΣ' }); + + expect(result.map(r => r.id)).toEqual(['f-1']); + expect(calls[0]!.params).toEqual(['f-1']); + }); + + test('ASCII provider selector excludes ASCII-different and Unicode-different providers after JS check', async () => { + const { executor } = createRowsExecutor([ + { id: 'c-1', provider: 'EODHD', dataset: 'd', caveat: 'c', created_at: new Date(TS) }, + { id: 'c-2', provider: 'EODHD2', dataset: 'd', caveat: 'c', created_at: new Date(TS) }, + { id: 'c-3', provider: 'ЕODHD', dataset: 'd', caveat: 'c', created_at: new Date(TS) }, // Cyrillic Е + ]); + const readers = createPostgresKnowledgeReaders({ executor }); + + expect((await readers.listProviderCaveats({ provider: 'eodhd' })).map(r => r.id)).toEqual(['c-1']); + }); +}); + +describe('PostgreSQL findings adapter QA: timestamps and write params', () => { + function readerForCreatedAt(createdAt: unknown) { + return createPostgresKnowledgeReaders({ + executor: createRowsExecutor([ + { id: 'c-1', provider: 'p', dataset: 'd', caveat: 'c', created_at: createdAt }, + ]).executor, + }); + } + + test.each([ + ['2024-02-29T00:00:00Z', '2024-02-29T00:00:00.000Z'], + ['2000-02-29T23:59:59.5+00:00', '2000-02-29T23:59:59.500Z'], + ['2026-01-01T01:30:00+02:00', '2025-12-31T23:30:00.000Z'], + ['2025-12-31T23:00:00-05:30', '2026-01-01T04:30:00.000Z'], + ['2026-01-15T12:34:56.123999+00:00', '2026-01-15T12:34:56.123Z'], + ['0099-06-01T00:00:00Z', '0099-06-01T00:00:00.000Z'], + ])('accepts valid timezone-qualified instant %s as UTC %s', async (raw, expectedIso) => { + const rows = await readerForCreatedAt(raw).listProviderCaveats({}); + expect(rows[0]!.createdAt).toBe(expectedIso); + }); + + test.each(['2025-02-29T00:00:00Z', '1900-02-29T00:00:00Z', '2026-04-31T00:00:00Z', '2026-00-10T00:00:00Z', '2026-01-15T12:60:00Z', '2026-01-15T12:00:00+05:60', '2026-01-15 12:00:00Z'])( + 'rejects invalid instant %s with INVALID_ROW', + async raw => { + await expect(readerForCreatedAt(raw).listProviderCaveats({})).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + } + ); + + test('appendFinding binds copies of ref arrays and does not mutate the caller record', async () => { + const { calls, executor } = createRowsExecutor([{ id: 'f-1', created_at: new Date(TS) }]); + const port = createPostgresFindingWritePort({ executor }); + const trialRefs = Object.freeze(['1', '2']); + const evidenceRefs = Object.freeze(['e']); + const record: FiledFindingRecord = Object.freeze({ + id: 'f-1', + kind: 'dead_end', + title: 't', + status: 'pending_review', + createdAt: TS, + summary: 's', + trialRefs, + evidenceRefs, + }); + + const outcome = await port.appendFinding(record, 'k-1'); + + expect(outcome).toEqual({ status: 'created', id: 'f-1', createdAt: TS }); + const params = calls[0]!.params!; + expect(params[6]).toEqual(['1', '2']); + expect(params[6]).not.toBe(trialRefs); + expect(params[7]).not.toBe(evidenceRefs); + expect(params[8]).toBe('k-1'); + }); + + test('replay with identical payload but different status/createdAt still replays the stored receipt', async () => { + let call = 0; + const executor: PostgresFindingsExecutor = { + async query>(): Promise<{ readonly rows: readonly Row[] }> { + call += 1; + const rows = + call === 1 + ? [] + : [ + { + id: 'f-orig', + kind: 'finding', + title: 't', + summary: 's', + created_at: '2026-01-01T00:00:00+01:00', + trial_refs: ['1'], + evidence_refs: [], + }, + ]; + return { rows: rows as unknown as readonly Row[] }; + }, + }; + const port = createPostgresFindingWritePort({ executor }); + + const outcome = await port.appendFinding( + { id: 'f-new', kind: 'finding', title: 't', summary: 's', status: 'other', createdAt: TS, trialRefs: ['1'], evidenceRefs: [] }, + 'k' + ); + + expect(outcome).toEqual({ status: 'replayed', id: 'f-orig', createdAt: '2025-12-31T23:00:00.000Z' }); + }); +}); diff --git a/libs/research/test/mcp-postgres-findings.test.ts b/libs/research/test/mcp-postgres-findings.test.ts new file mode 100644 index 00000000..6b5ddaf3 --- /dev/null +++ b/libs/research/test/mcp-postgres-findings.test.ts @@ -0,0 +1,772 @@ +import { describe, expect, test } from 'bun:test'; +import { + type FiledFindingRecord, + type PostgresFindingsExecutor, + PostgresFindingsError, + createPostgresFindingWritePort, + createPostgresKnowledgeReaders, +} from '../src/mcp/index'; + +interface RecordedCall { + readonly text: string; + readonly params: readonly unknown[] | undefined; +} + +type QueryHandler = ( + text: string, + params: readonly unknown[] | undefined, + callIndex: number +) => Promise<{ readonly rows: readonly Record[] }> | { readonly rows: readonly Record[] }; + +function createSequenceExecutor(handler: QueryHandler): { + readonly calls: RecordedCall[]; + readonly executor: PostgresFindingsExecutor; +} { + const calls: RecordedCall[] = []; + const executor: PostgresFindingsExecutor = { + async query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + const idx = calls.length; + calls.push({ text, params }); + const res = await handler(text, params, idx); + return res as unknown as { readonly rows: readonly Row[] }; + }, + }; + return { calls, executor }; +} + +function createFakeExecutor(rows: readonly Record[] = []): { + readonly calls: RecordedCall[]; + readonly executor: PostgresFindingsExecutor; +} { + return createSequenceExecutor(() => ({ rows })); +} + +const FIXED_TS = '2026-01-15T12:34:56.789Z'; + +function makeFiledRecord(overrides: Partial = {}): FiledFindingRecord { + return { + id: 'finding-001', + kind: 'finding', + title: 'Momentum decays after 5 sessions', + status: 'pending_review', + createdAt: FIXED_TS, + summary: 'Cross-sectional rank IC turns negative past day 5.', + trialRefs: ['101', '102'], + evidenceRefs: ['snap:2026-01-15:ic'], + ...overrides, + }; +} + +function makeRawFindingRow(overrides: Record = {}): Record { + return { + id: 'finding-001', + title: 'Momentum decays after 5 sessions', + status: 'pending_review', + created_at: new Date(FIXED_TS), + summary: 'Cross-sectional rank IC turns negative past day 5.', + trial_refs: ['101', '102'], + evidence_refs: ['snap:2026-01-15:ic'], + ...overrides, + }; +} + +function makeRawReplayRow(overrides: Record = {}): Record { + return { + id: 'finding-001', + kind: 'finding', + title: 'Momentum decays after 5 sessions', + summary: 'Cross-sectional rank IC turns negative past day 5.', + created_at: new Date(FIXED_TS), + trial_refs: ['101', '102'], + evidence_refs: ['snap:2026-01-15:ic'], + ...overrides, + }; +} + +function makeRawCaveatRow(overrides: Record = {}): Record { + return { + id: 'caveat-001', + provider: 'EODHD', + dataset: 'eodIntraday1M', + caveat: 'Intraday 1m OHLCV is retroactively split-adjusted.', + created_at: new Date(FIXED_TS), + ...overrides, + }; +} + +function assertNoMutationOrReaderLimitSql(calls: readonly RecordedCall[], checkNoLimit = false): void { + for (const call of calls) { + expect(call.text).not.toMatch(/\bUPDATE\b/i); + expect(call.text).not.toMatch(/\bDELETE\b/i); + expect(call.text).not.toMatch(/\bTRUNCATE\b/i); + if (checkNoLimit) { + expect(call.text).not.toMatch(/\bLIMIT\b/i); + } + } +} + +describe('createPostgresFindingWritePort (fake executor)', () => { + test('unkeyed append issues plain parameterized INSERT with NULL key and never interpolates values', async () => { + const injection = "'; DROP TABLE findings; --"; + const fake = createFakeExecutor([{ id: 'finding-inj', created_at: new Date(FIXED_TS) }]); + const port = createPostgresFindingWritePort({ executor: fake.executor }); + + const record = makeFiledRecord({ + id: 'finding-inj', + title: injection, + summary: `summary ${injection}`, + trialRefs: [injection], + evidenceRefs: [`ev:${injection}`], + }); + + const outcome = await port.appendFinding(record); + + expect(outcome).toEqual({ + status: 'created', + id: 'finding-inj', + createdAt: FIXED_TS, + }); + expect(fake.calls).toHaveLength(1); + const call = fake.calls[0]!; + expect(call.text).toContain('INSERT INTO findings'); + expect(call.text).not.toContain('ON CONFLICT'); + expect(call.text).toContain('RETURNING id, created_at'); + expect(call.text).not.toContain(injection); + expect(call.text).not.toContain(';'); + expect(call.params).toEqual([ + 'finding-inj', + 'finding', + injection, + `summary ${injection}`, + 'pending_review', + FIXED_TS, + [injection], + [`ev:${injection}`], + null, + ]); + assertNoMutationOrReaderLimitSql(fake.calls); + }); + + test('keyed append uses partial-index ON CONFLICT DO NOTHING and returns created on 1 returned row', async () => { + const fake = createFakeExecutor([ + { id: 'finding-001', created_at: '2026-01-15T14:34:56.789+02:00' }, + ]); + const port = createPostgresFindingWritePort({ executor: fake.executor }); + + const outcome = await port.appendFinding(makeFiledRecord(), 'idem-key-1'); + + expect(outcome).toEqual({ + status: 'created', + id: 'finding-001', + createdAt: FIXED_TS, + }); + expect(fake.calls).toHaveLength(1); + const call = fake.calls[0]!; + expect(call.text).toContain( + 'ON CONFLICT (idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING' + ); + expect(call.text).not.toContain('idem-key-1'); + expect(call.params).toEqual([ + 'finding-001', + 'finding', + 'Momentum decays after 5 sessions', + 'Cross-sectional rank IC turns negative past day 5.', + 'pending_review', + FIXED_TS, + ['101', '102'], + ['snap:2026-01-15:ic'], + 'idem-key-1', + ]); + assertNoMutationOrReaderLimitSql(fake.calls); + }); + + test('keyed append reads winner in separate SELECT on 0 rows and returns replayed with stored metadata', async () => { + const fake = createSequenceExecutor((_text, _params, idx) => { + if (idx === 0) { + return { rows: [] }; + } + return { + rows: [ + makeRawReplayRow({ + id: 'finding-original', + created_at: '2026-01-15T07:34:56.789999-05:00', + }), + ], + }; + }); + const port = createPostgresFindingWritePort({ executor: fake.executor }); + + // Incoming call has a new id and createdAt, but identical comparable payload + const outcome = await port.appendFinding( + makeFiledRecord({ + id: 'finding-retry-new-id', + createdAt: '2026-01-16T00:00:00.000Z', + }), + 'idem-replay' + ); + + expect(outcome).toEqual({ + status: 'replayed', + id: 'finding-original', + createdAt: FIXED_TS, + }); + expect(fake.calls).toHaveLength(2); + expect(fake.calls[1]!.text).toContain('SELECT'); + expect(fake.calls[1]!.text).toContain('WHERE idempotency_key = $1::text'); + expect(fake.calls[1]!.params).toEqual(['idem-replay']); + assertNoMutationOrReaderLimitSql(fake.calls); + }); + + test('keyed append returns conflict when stored payload differs on any comparable field', async () => { + const diffs: readonly Partial[] = [ + { kind: 'dead_end' }, + { title: 'Different title' }, + { summary: 'Different summary' }, + { trialRefs: ['101'] }, + { trialRefs: ['102', '101'] }, + { evidenceRefs: [] }, + ]; + + for (const diff of diffs) { + const fake = createSequenceExecutor((_text, _params, idx) => + idx === 0 ? { rows: [] } : { rows: [makeRawReplayRow()] } + ); + const port = createPostgresFindingWritePort({ executor: fake.executor }); + + const outcome = await port.appendFinding(makeFiledRecord(diff), 'idem-conflict'); + expect(outcome).toEqual({ status: 'conflict' }); + expect(fake.calls).toHaveLength(2); + assertNoMutationOrReaderLimitSql(fake.calls); + } + }); + + test('keyed append resolves same-ID 23505 retry as replayed or conflict, and propagates unrelated 23505 or other errors', async () => { + const pkErr = Object.assign(new Error('duplicate key value violates unique constraint'), { + code: '23505', + }); + + // Same ID + identical payload -> replayed + const fakeReplay = createSequenceExecutor((_text, _params, idx) => { + if (idx === 0) { + throw pkErr; + } + return { rows: [makeRawReplayRow({ id: 'finding-001' })] }; + }); + const replayPort = createPostgresFindingWritePort({ executor: fakeReplay.executor }); + expect(await replayPort.appendFinding(makeFiledRecord(), 'idem-same-id')).toEqual({ + status: 'replayed', + id: 'finding-001', + createdAt: FIXED_TS, + }); + expect(fakeReplay.calls).toHaveLength(2); + + // Same ID + different payload -> conflict + const fakeConflict = createSequenceExecutor((_text, _params, idx) => { + if (idx === 0) { + throw pkErr; + } + return { rows: [makeRawReplayRow({ id: 'finding-001', title: 'Other title' })] }; + }); + const conflictPort = createPostgresFindingWritePort({ executor: fakeConflict.executor }); + expect(await conflictPort.appendFinding(makeFiledRecord(), 'idem-same-id')).toEqual({ + status: 'conflict', + }); + + // Unrelated PK collision: no stored row for idempotency_key -> propagate pkErr + const fakeMissing = createSequenceExecutor((_text, _params, idx) => { + if (idx === 0) { + throw pkErr; + } + return { rows: [] }; + }); + const missingPort = createPostgresFindingWritePort({ executor: fakeMissing.executor }); + await expect(missingPort.appendFinding(makeFiledRecord(), 'idem-unrelated')).rejects.toBe( + pkErr + ); + + // Unrelated PK collision: stored row for idempotency_key has different ID -> propagate pkErr + const fakeDifferentId = createSequenceExecutor((_text, _params, idx) => { + if (idx === 0) { + throw pkErr; + } + return { rows: [makeRawReplayRow({ id: 'finding-other' })] }; + }); + const diffIdPort = createPostgresFindingWritePort({ executor: fakeDifferentId.executor }); + await expect(diffIdPort.appendFinding(makeFiledRecord(), 'idem-other-id')).rejects.toBe(pkErr); + + // Non-23505 error -> propagates immediately without SELECT + const checkErr = Object.assign(new Error('check violation'), { code: '23514' }); + const fakeOther = createSequenceExecutor(() => { + throw checkErr; + }); + const otherPort = createPostgresFindingWritePort({ executor: fakeOther.executor }); + await expect(otherPort.appendFinding(makeFiledRecord(), 'idem-check')).rejects.toBe(checkErr); + expect(fakeOther.calls).toHaveLength(1); + + // Unkeyed 23505 -> propagates immediately without SELECT + const fakeUnkeyed = createSequenceExecutor(() => { + throw pkErr; + }); + const unkeyedPort = createPostgresFindingWritePort({ executor: fakeUnkeyed.executor }); + await expect(unkeyedPort.appendFinding(makeFiledRecord())).rejects.toBe(pkErr); + expect(fakeUnkeyed.calls).toHaveLength(1); + }); + + test('quotes explicit schema on INSERT and replay SELECT, and omits prefix when unset', async () => { + const fakeScoped = createSequenceExecutor((_text, _params, idx) => + idx === 0 ? { rows: [] } : { rows: [makeRawReplayRow()] } + ); + const scopedPort = createPostgresFindingWritePort({ + executor: fakeScoped.executor, + schema: 'custom_research_1', + }); + await scopedPort.appendFinding(makeFiledRecord(), 'idem-schema'); + + expect(fakeScoped.calls[0]!.text).toContain('INSERT INTO "custom_research_1".findings'); + expect(fakeScoped.calls[1]!.text).toContain('FROM "custom_research_1".findings'); + assertNoMutationOrReaderLimitSql(fakeScoped.calls); + }); +}); + +describe('createPostgresKnowledgeReaders (fake executor)', () => { + test('listFindings binds exact id (taking precedence over query), escaped ILIKE query, and unfiltered queries with ORDER BY id ASC and no LIMIT', async () => { + const injection = "'; DELETE FROM findings; --"; + const fake = createFakeExecutor([makeRawFindingRow()]); + const readers = createPostgresKnowledgeReaders({ executor: fake.executor }); + + // Unfiltered + const allRows = await readers.listFindings({}); + expect(allRows).toEqual([ + { + id: 'finding-001', + title: 'Momentum decays after 5 sessions', + status: 'pending_review', + createdAt: FIXED_TS, + summary: 'Cross-sectional rank IC turns negative past day 5.', + trialRefs: ['101', '102'], + evidenceRefs: ['snap:2026-01-15:ic'], + }, + ]); + expect(fake.calls[0]!.text).not.toContain('WHERE'); + expect(fake.calls[0]!.text.trimEnd().endsWith('ORDER BY id ASC')).toBe(true); + expect(fake.calls[0]!.params).toEqual([]); + + // Exact id takes precedence over query + await readers.listFindings({ id: injection, query: 'ignored' }); + expect(fake.calls[1]!.text).toContain('WHERE id = $1::text'); + expect(fake.calls[1]!.text).not.toContain('ILIKE'); + expect(fake.calls[1]!.text).not.toContain(injection); + expect(fake.calls[1]!.params).toEqual([injection]); + + // Escaped ILIKE query on title and summary (retaining non-ASCII stored rows as candidates) + await readers.listFindings({ query: '100% pure_wild\\path' }); + expect(fake.calls[2]!.text).toContain( + "WHERE title ILIKE $1::text ESCAPE '\\' OR summary ILIKE $1::text ESCAPE '\\' OR title ~ '[^\\x01-\\x7f]' OR summary ~ '[^\\x01-\\x7f]'" + ); + expect(fake.calls[2]!.params).toEqual(['%100\\% pure\\_wild\\\\path%']); + + assertNoMutationOrReaderLimitSql(fake.calls, true); + }); + + test('listProviderCaveats combines case-insensitive provider with id or escaped ILIKE query and no LIMIT', async () => { + const fake = createFakeExecutor([ + makeRawCaveatRow({ created_at: '2026-01-15T12:34:56.789Z' }), + ]); + const readers = createPostgresKnowledgeReaders({ + executor: fake.executor, + schema: 'custom_research_2', + }); + + // Unfiltered + const rows = await readers.listProviderCaveats({}); + expect(rows).toEqual([ + { + id: 'caveat-001', + provider: 'EODHD', + dataset: 'eodIntraday1M', + caveat: 'Intraday 1m OHLCV is retroactively split-adjusted.', + createdAt: FIXED_TS, + }, + ]); + expect(fake.calls[0]!.text).toContain('FROM "custom_research_2".provider_caveats'); + expect(fake.calls[0]!.text).not.toContain('WHERE'); + expect(fake.calls[0]!.params).toEqual([]); + + // Provider + exact id (id takes precedence over query) + await readers.listProviderCaveats({ + provider: 'eodhd', + id: 'caveat-001', + query: 'ignored', + }); + expect(fake.calls[1]!.text).toContain( + "WHERE (lower(provider) = lower($1::text) OR provider ~ '[^\\x01-\\x7f]') AND id = $2::text" + ); + expect(fake.calls[1]!.text).not.toContain('ILIKE'); + expect(fake.calls[1]!.params).toEqual(['eodhd', 'caveat-001']); + + // Provider + query with wildcards + await readers.listProviderCaveats({ + provider: 'QuoteMedia', + query: '50%_ratio\\inv', + }); + expect(fake.calls[2]!.text).toContain( + "WHERE (lower(provider) = lower($1::text) OR provider ~ '[^\\x01-\\x7f]') AND (provider ILIKE $2::text ESCAPE '\\' OR dataset ILIKE $2::text ESCAPE '\\' OR caveat ILIKE $2::text ESCAPE '\\' OR provider ~ '[^\\x01-\\x7f]' OR dataset ~ '[^\\x01-\\x7f]' OR caveat ~ '[^\\x01-\\x7f]')" + ); + expect(fake.calls[2]!.params).toEqual(['QuoteMedia', '%50\\%\\_ratio\\\\inv%']); + + // Query only + await readers.listProviderCaveats({ query: 'split' }); + expect(fake.calls[3]!.text).toContain( + "WHERE (provider ILIKE $1::text ESCAPE '\\' OR dataset ILIKE $1::text ESCAPE '\\' OR caveat ILIKE $1::text ESCAPE '\\' OR provider ~ '[^\\x01-\\x7f]' OR dataset ~ '[^\\x01-\\x7f]' OR caveat ~ '[^\\x01-\\x7f]')" + ); + expect(fake.calls[3]!.params).toEqual(['%split%']); + + assertNoMutationOrReaderLimitSql(fake.calls, true); + }); + + test('falls back to JS Unicode lowercasing for non-ASCII query/provider while preserving ASCII SQL pushdown and row validation', async () => { + // Findings: non-ASCII query (Greek final sigma) omits SQL ILIKE and filters with JS .toLowerCase() + const findingFake = createFakeExecutor([ + makeRawFindingRow({ id: 'f-1', title: 'Αλφα κοσμος', summary: 'Greek cosmos finding.' }), + makeRawFindingRow({ id: 'f-2', title: 'Unrelated', summary: 'Does not match.' }), + makeRawFindingRow({ id: 'f-3', title: 'Other', summary: 'Summary has κοσμος too.' }), + ]); + const findingReaders = createPostgresKnowledgeReaders({ executor: findingFake.executor }); + const findingMatches = await findingReaders.listFindings({ query: 'ΚΟΣΜΟΣ' }); + expect(findingMatches.map(r => r.id)).toEqual(['f-1', 'f-3']); + expect(findingFake.calls[0]!.text).not.toContain('ILIKE'); + expect(findingFake.calls[0]!.text).not.toContain('WHERE'); + expect(findingFake.calls[0]!.params).toEqual([]); + + // Provider caveats: ASCII provider still pushes down SQL lower(provider), non-ASCII query filters in JS + const caveatFake = createFakeExecutor([ + makeRawCaveatRow({ id: 'c-1', provider: 'EODHD', caveat: 'Note on κοσμος regime.' }), + makeRawCaveatRow({ id: 'c-2', provider: 'EODHD', caveat: 'Unrelated note.' }), + ]); + const caveatReaders = createPostgresKnowledgeReaders({ executor: caveatFake.executor }); + const caveatMatches = await caveatReaders.listProviderCaveats({ + provider: 'eodhd', + query: 'ΚΟΣΜΟΣ', + }); + expect(caveatMatches.map(r => r.id)).toEqual(['c-1']); + expect(caveatFake.calls[0]!.text).toContain( + "WHERE (lower(provider) = lower($1::text) OR provider ~ '[^\\x01-\\x7f]')" + ); + expect(caveatFake.calls[0]!.text).not.toContain('ILIKE'); + expect(caveatFake.calls[0]!.params).toEqual(['eodhd']); + + // Provider caveats: non-ASCII provider falls back to JS exact case-insensitive match + const nonAsciiProvFake = createFakeExecutor([ + makeRawCaveatRow({ id: 'c-1', provider: 'κοσμος', dataset: 'ds', caveat: 'c' }), + makeRawCaveatRow({ id: 'c-2', provider: 'EODHD', dataset: 'ds', caveat: 'c' }), + ]); + const nonAsciiProvReaders = createPostgresKnowledgeReaders({ + executor: nonAsciiProvFake.executor, + }); + const provMatches = await nonAsciiProvReaders.listProviderCaveats({ provider: 'ΚΟΣΜΟΣ' }); + expect(provMatches.map(r => r.id)).toEqual(['c-1']); + expect(nonAsciiProvFake.calls[0]!.text).not.toContain('WHERE'); + expect(nonAsciiProvFake.calls[0]!.params).toEqual([]); + + // ASCII query / ASCII provider against Unicode stored rows (e.g. BİST and K under C collation): + // SQL retains non-ASCII stored rows as candidates and JS .toLowerCase() filters out non-matches. + const asciiAgainstUnicodeFindingFake = createFakeExecutor([ + makeRawFindingRow({ + id: 'f-bist', + title: 'BİST exchange coverage', + summary: 'Turkish equities.', + }), + makeRawFindingRow({ + id: 'f-other-unicode', + title: 'κόσμος', + summary: 'Unrelated Greek finding.', + }), + ]); + const asciiFindingReaders = createPostgresKnowledgeReaders({ + executor: asciiAgainstUnicodeFindingFake.executor, + }); + expect((await asciiFindingReaders.listFindings({ query: 'bi' })).map(r => r.id)).toEqual([ + 'f-bist', + ]); + + const asciiAgainstUnicodeCaveatFake = createFakeExecutor([ + makeRawCaveatRow({ + id: 'c-kelvin', + provider: 'K', + dataset: 'ds', + caveat: 'BİST feed note.', + }), + makeRawCaveatRow({ + id: 'c-other-unicode', + provider: 'κόσμος', + dataset: 'ds', + caveat: 'Unrelated.', + }), + ]); + const asciiCaveatReaders = createPostgresKnowledgeReaders({ + executor: asciiAgainstUnicodeCaveatFake.executor, + }); + expect( + (await asciiCaveatReaders.listProviderCaveats({ provider: 'k', query: 'bi' })).map(r => r.id) + ).toEqual(['c-kelvin']); + + assertNoMutationOrReaderLimitSql( + [ + ...findingFake.calls, + ...caveatFake.calls, + ...nonAsciiProvFake.calls, + ...asciiAgainstUnicodeFindingFake.calls, + ...asciiAgainstUnicodeCaveatFake.calls, + ], + true + ); + }); +}); + +describe('PostgreSQL findings adapter validation (fake executor)', () => { + test('rejects invalid executors and options with INVALID_EXECUTOR before any query', () => { + const invalidOptions: unknown[] = [ + null, + undefined, + {}, + { executor: null }, + { executor: {} }, + { executor: { query: 'not-a-fn' } }, + ]; + + for (const opts of invalidOptions) { + for (const factory of [createPostgresFindingWritePort, createPostgresKnowledgeReaders]) { + let caught: unknown; + try { + factory(opts as Parameters[0]); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresFindingsError); + expect((caught as PostgresFindingsError).code).toBe('INVALID_EXECUTOR'); + } + } + }); + + test('rejects invalid schema names with INVALID_SCHEMA before any query', () => { + const fake = createFakeExecutor([]); + const badSchemas: unknown[] = [ + '', + 'Public', + '1schema', + 'bad-name', + 'bad.name', + 'public"; DROP TABLE findings; --', + 'space name', + 123, + null, + ]; + + for (const schema of badSchemas) { + for (const factory of [createPostgresFindingWritePort, createPostgresKnowledgeReaders]) { + let caught: unknown; + try { + factory({ executor: fake.executor, schema: schema as string }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresFindingsError); + expect((caught as PostgresFindingsError).code).toBe('INVALID_SCHEMA'); + } + } + + expect(fake.calls).toHaveLength(0); + }); + + test('accepts prototype-method executors', async () => { + class ProtoExecutor { + async query>(): Promise<{ readonly rows: readonly Row[] }> { + return { rows: [makeRawFindingRow()] as unknown as readonly Row[] }; + } + } + const readers = createPostgresKnowledgeReaders({ executor: new ProtoExecutor() }); + const rows = await readers.listFindings({}); + expect(rows).toHaveLength(1); + expect(rows[0]!.id).toBe('finding-001'); + }); + + test('rejects invalid result envelopes and missing/duplicate receipt or winner rows with INVALID_ROW', async () => { + const badEnvelopeExecutor: PostgresFindingsExecutor = { + async query() { + return { rows: 'not-an-array' as unknown as readonly never[] }; + }, + }; + const badWritePort = createPostgresFindingWritePort({ executor: badEnvelopeExecutor }); + const badReaders = createPostgresKnowledgeReaders({ executor: badEnvelopeExecutor }); + + for (const op of [ + () => badWritePort.appendFinding(makeFiledRecord()), + () => badWritePort.appendFinding(makeFiledRecord(), 'k1'), + () => badReaders.listFindings({}), + () => badReaders.listProviderCaveats({}), + ]) { + let caught: unknown; + try { + await op(); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresFindingsError); + expect((caught as PostgresFindingsError).code).toBe('INVALID_ROW'); + } + + // Unkeyed insert returning 0 rows or 2 rows + for (const rows of [[], [{ id: 'a', created_at: FIXED_TS }, { id: 'b', created_at: FIXED_TS }]]) { + const port = createPostgresFindingWritePort({ executor: createFakeExecutor(rows).executor }); + await expect(port.appendFinding(makeFiledRecord())).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + } + + // Keyed insert returning 2 rows + const dupInsertPort = createPostgresFindingWritePort({ + executor: createFakeExecutor([ + { id: 'a', created_at: FIXED_TS }, + { id: 'b', created_at: FIXED_TS }, + ]).executor, + }); + await expect(dupInsertPort.appendFinding(makeFiledRecord(), 'k-dup')).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + + // Keyed conflict lookup returning 0 rows or 2 rows + for (const lookupRows of [[], [makeRawReplayRow(), makeRawReplayRow({ id: 'finding-002' })]]) { + const fake = createSequenceExecutor((_t, _p, idx) => + idx === 0 ? { rows: [] } : { rows: lookupRows } + ); + const port = createPostgresFindingWritePort({ executor: fake.executor }); + await expect(port.appendFinding(makeFiledRecord(), 'k-missing-or-dup')).rejects.toMatchObject( + { + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + } + ); + } + + // 23505 lookup returning 2 rows + const pkErr = Object.assign(new Error('dup'), { code: '23505' }); + const fakeDup23505 = createSequenceExecutor((_t, _p, idx) => { + if (idx === 0) { + throw pkErr; + } + return { rows: [makeRawReplayRow(), makeRawReplayRow({ id: 'finding-002' })] }; + }); + const dup23505Port = createPostgresFindingWritePort({ executor: fakeDup23505.executor }); + await expect(dup23505Port.appendFinding(makeFiledRecord(), 'k-dup-23505')).rejects.toMatchObject( + { + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + } + ); + }); + + test('rejects malformed timestamps, invalid kinds on replay, and non-string or nested arrays with INVALID_ROW', async () => { + const badTimestamps: readonly unknown[] = [ + null, + 1700000000000, + new Date(Number.NaN), + '', + '2026-01-15', + '2026-01-15T12:34:56', + '2026-02-30T00:00:00Z', + '2026-01-15T24:00:00Z', + '2026-01-15T12:00:00+25:00', + 'not-a-timestamp', + ]; + + for (const badTs of badTimestamps) { + const findingReaders = createPostgresKnowledgeReaders({ + executor: createFakeExecutor([makeRawFindingRow({ created_at: badTs })]).executor, + }); + await expect(findingReaders.listFindings({})).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + + const caveatReaders = createPostgresKnowledgeReaders({ + executor: createFakeExecutor([makeRawCaveatRow({ created_at: badTs })]).executor, + }); + await expect(caveatReaders.listProviderCaveats({})).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + } + + // Invalid kind on replay + for (const badKind of ['hypothesis', 'FINDING', '', null, 42]) { + const fake = createSequenceExecutor((_t, _p, idx) => + idx === 0 ? { rows: [] } : { rows: [makeRawReplayRow({ kind: badKind })] } + ); + const port = createPostgresFindingWritePort({ executor: fake.executor }); + await expect(port.appendFinding(makeFiledRecord(), 'k-bad-kind')).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + } + + // Invalid ref arrays (nested arrays, null elements, non-arrays) + const badArrays: readonly unknown[] = [null, '101', [101], ['101', null], [['101']]]; + for (const badArr of badArrays) { + const readers = createPostgresKnowledgeReaders({ + executor: createFakeExecutor([makeRawFindingRow({ trial_refs: badArr })]).executor, + }); + await expect(readers.listFindings({})).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + + const readersEv = createPostgresKnowledgeReaders({ + executor: createFakeExecutor([makeRawFindingRow({ evidence_refs: badArr })]).executor, + }); + await expect(readersEv.listFindings({})).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + } + + // Non-object rows & blank strings + const badFindingRows: readonly unknown[] = [ + null, + makeRawFindingRow({ id: ' ' }), + makeRawFindingRow({ title: '' }), + makeRawFindingRow({ status: null }), + makeRawFindingRow({ summary: '' }), + ]; + for (const badRow of badFindingRows) { + const readers = createPostgresKnowledgeReaders({ + executor: createFakeExecutor([badRow as Record]).executor, + }); + await expect(readers.listFindings({})).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + } + + const badCaveatRows: readonly unknown[] = [ + null, + makeRawCaveatRow({ id: '' }), + makeRawCaveatRow({ provider: ' ' }), + makeRawCaveatRow({ dataset: '' }), + makeRawCaveatRow({ caveat: null }), + ]; + for (const badRow of badCaveatRows) { + const readers = createPostgresKnowledgeReaders({ + executor: createFakeExecutor([badRow as Record]).executor, + }); + await expect(readers.listProviderCaveats({})).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + } + }); +}); diff --git a/libs/research/test/mcp-postgres-trial-ref-qa.test.ts b/libs/research/test/mcp-postgres-trial-ref-qa.test.ts new file mode 100644 index 00000000..f4cf1d66 --- /dev/null +++ b/libs/research/test/mcp-postgres-trial-ref-qa.test.ts @@ -0,0 +1,263 @@ +import { describe, expect, test } from 'bun:test'; +import { + createFileFindingTool, + createPostgresTrialRefPort, + FILE_FINDING_ERROR_FILING_FAILED, + FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, + PostgresTrialRefError, + type AppendFindingResult, + type FiledFindingRecord, + type FindingWritePort, + type PostgresTrialRefPortOptions, + type TrialRefExecutor, +} from '../src/mcp/index'; + +interface RecordedCall { + readonly text: string; + readonly params: readonly unknown[] | undefined; +} + +function scriptedExecutor(respond: (params: readonly unknown[] | undefined) => unknown): { + readonly calls: RecordedCall[]; + readonly executor: TrialRefExecutor; +} { + const calls: RecordedCall[] = []; + return { + calls, + executor: { + async query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + calls.push({ text, params }); + return respond(params) as { readonly rows: readonly Row[] }; + }, + }, + }; +} + +function recordingWritePort(): { + readonly appended: FiledFindingRecord[]; + readonly port: FindingWritePort; +} { + const appended: FiledFindingRecord[] = []; + return { + appended, + port: { + async appendFinding(record): Promise { + appended.push(record); + return { status: 'created', id: record.id, createdAt: record.createdAt }; + }, + }, + }; +} + +const CUTOFF_TS = Date.UTC(2025, 5, 30, 15, 45, 30, 500); // 2025-06-30T15:45:30.500Z +const CUTOFF_DATE = '2025-06-30'; +const FIXED_EPOCH_MS = Date.UTC(2026, 0, 15, 12, 0, 0); + +describe('createPostgresTrialRefPort QA edge cases', () => { + test('snapshots executor, schema and cutoff at construction so later option mutation has no effect', async () => { + const original = scriptedExecutor(() => ({ rows: [] })); + const replacement = scriptedExecutor(() => ({ rows: [{ visible: 1 }] })); + const options: { + -readonly [K in keyof PostgresTrialRefPortOptions]: PostgresTrialRefPortOptions[K]; + } = { + executor: original.executor, + vaultCutoffTs: CUTOFF_TS, + schema: 'research_a', + }; + const port = createPostgresTrialRefPort(options); + + options.executor = replacement.executor; + options.vaultCutoffTs = Date.UTC(2030, 0, 1); + options.schema = 'research_b'; + + expect(await port.hasResearchVisibleTrial('5')).toBe(false); + expect(replacement.calls).toHaveLength(0); + expect(original.calls).toEqual([ + { + text: 'SELECT 1 AS visible FROM "research_a".trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1', + params: ['5', CUTOFF_DATE], + }, + ]); + }); + + test('binds UTC dates for epoch, pre-1970 and four-digit-year extreme cutoffs', async () => { + const cases: [number, string][] = [ + [0, '1970-01-01'], + [-1, '1969-12-31'], + [Date.UTC(2025, 5, 30, 0, 0, 0, 0), '2025-06-30'], + [Date.UTC(2025, 5, 30, 23, 59, 59, 999), '2025-06-30'], + [new Date('0001-01-01T00:00:00.000Z').getTime(), '0001-01-01'], + [new Date('9999-12-31T23:59:59.999Z').getTime(), '9999-12-31'], + ]; + + for (const [vaultCutoffTs, expectedDate] of cases) { + const fake = scriptedExecutor(() => ({ rows: [] })); + const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs }); + expect(await port.hasResearchVisibleTrial('1')).toBe(false); + expect(fake.calls[0]?.params).toEqual(['1', expectedDate]); + } + }); + + test('reports INVALID_EXECUTOR before schema or cutoff errors when several options are invalid', () => { + let caught: unknown; + try { + createPostgresTrialRefPort({ + executor: {} as TrialRefExecutor, + vaultCutoffTs: Number.NaN, + schema: 'Bad-Schema', + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresTrialRefError); + expect(caught).toBeInstanceOf(RangeError); + expect((caught as PostgresTrialRefError).code).toBe('INVALID_EXECUTOR'); + expect((caught as PostgresTrialRefError).name).toBe('PostgresTrialRefError'); + }); + + test('queries every canonical id across the 1..19 digit range up to the PostgreSQL bigint max', async () => { + const fake = scriptedExecutor(() => ({ rows: [{ visible: 1 }] })); + const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_TS }); + const accepted = [ + '1', + '9', + '10', + '999999999999999999', + '1000000000000000000', + '9223372036854775799', + '9223372036854775806', + '9223372036854775807', + ]; + + for (const ref of accepted) { + expect(await port.hasResearchVisibleTrial(ref)).toBe(true); + } + expect(fake.calls.map(call => call.params?.[0])).toEqual(accepted); + }); + + test('returns false without querying for out-of-range, unicode-digit, control-char and boxed refs', async () => { + const fake = scriptedExecutor(() => ({ rows: [{ visible: 1 }] })); + const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_TS }); + const rejected: unknown[] = [ + '9223372036854775810', + '9300000000000000000', + '12345678901234567890', + '١', // Arabic-Indic digit one + '1', // full-width digit one + '1\u0000', + ' 1', + '1​', + new String('1'), + Number.MAX_SAFE_INTEGER, + ]; + + for (const ref of rejected) { + expect(await port.hasResearchVisibleTrial(ref as string)).toBe(false); + } + expect(fake.calls).toHaveLength(0); + }); + + test('concurrent lookups each issue their own query and keep their own answers', async () => { + const fake = scriptedExecutor(params => ({ + rows: params?.[0] === '2' ? [{ visible: 1 }] : [], + })); + const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_TS }); + + const results = await Promise.all( + ['1', '2', '3', '2'].map(ref => port.hasResearchVisibleTrial(ref)) + ); + + expect(results).toEqual([false, true, false, true]); + expect(fake.calls).toHaveLength(4); + for (const call of fake.calls) { + expect(call.text).toMatch(/^SELECT 1 AS visible FROM trial_ledger WHERE /); + expect(call.text).not.toMatch(/\b(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|TRUNCATE)\b/i); + expect(call.params?.[1]).toBe(CUTOFF_DATE); + } + }); + + test('exposes only the read-only hasResearchVisibleTrial method', () => { + const fake = scriptedExecutor(() => ({ rows: [] })); + const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_TS }); + expect(Object.keys(port)).toEqual(['hasResearchVisibleTrial']); + }); +}); + +describe('createPostgresTrialRefPort composed with file_finding (fake executor)', () => { + function composeTool(respond: (params: readonly unknown[] | undefined) => unknown) { + const fake = scriptedExecutor(respond); + const writes = recordingWritePort(); + const tool = createFileFindingTool({ + port: writes.port, + trialLookup: createPostgresTrialRefPort({ + executor: fake.executor, + vaultCutoffTs: CUTOFF_TS, + }), + newId: () => 'finding-qa-1', + now: () => FIXED_EPOCH_MS, + }); + return { fake, tool, writes }; + } + + const baseArgs = { kind: 'finding', title: 'QA filing', summary: 'Visible-only summary.' }; + + test('a visible ref files one finding with the original string ref', async () => { + const { fake, tool, writes } = composeTool(() => ({ rows: [{ visible: 1 }] })); + + const res = await tool.execute({ ...baseArgs, trialRefs: ['9223372036854775807'] }); + + expect(res.isError).toBeUndefined(); + expect(fake.calls).toHaveLength(1); + expect(writes.appended).toHaveLength(1); + expect(writes.appended[0]?.trialRefs).toEqual(['9223372036854775807']); + expect(writes.appended[0]?.status).toBe('pending_review'); + }); + + test('a non-canonical ref is reported unavailable without any query or append', async () => { + const { fake, tool, writes } = composeTool(() => ({ rows: [{ visible: 1 }] })); + + const res = await tool.execute({ ...baseArgs, trialRefs: ['1; DROP TABLE trial_ledger'] }); + + expect(res.isError).toBe(true); + expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); + expect(fake.calls).toHaveLength(0); + expect(writes.appended).toHaveLength(0); + }); + + test('one Vault-only ref among visible refs rejects the whole filing with zero appends', async () => { + const { tool, writes } = composeTool(params => ({ + rows: params?.[0] === '20' ? [] : [{ visible: 1 }], + })); + + const res = await tool.execute({ ...baseArgs, trialRefs: ['10', '20', '30'] }); + + expect(res.isError).toBe(true); + expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); + expect(writes.appended).toHaveLength(0); + }); + + test('a malformed multi-row response fails closed as filing_failed with zero appends', async () => { + const { tool, writes } = composeTool(() => ({ rows: [{ visible: 1 }, { visible: 1 }] })); + + const res = await tool.execute({ ...baseArgs, trialRefs: ['10'] }); + + expect(res.isError).toBe(true); + expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); + expect(writes.appended).toHaveLength(0); + }); + + test('an executor failure fails closed as filing_failed with zero appends', async () => { + const { tool, writes } = composeTool(() => { + throw new Error('connection terminated'); + }); + + const res = await tool.execute({ ...baseArgs, trialRefs: ['10'] }); + + expect(res.isError).toBe(true); + expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); + expect(writes.appended).toHaveLength(0); + }); +}); diff --git a/libs/research/test/mcp-postgres-trial-ref.test.ts b/libs/research/test/mcp-postgres-trial-ref.test.ts index 2f8f4868..f3f4186c 100644 --- a/libs/research/test/mcp-postgres-trial-ref.test.ts +++ b/libs/research/test/mcp-postgres-trial-ref.test.ts @@ -12,6 +12,7 @@ import { createFileFindingTool, createMcpServer, createPostgresTrialRefLookupPort, + createPostgresTrialRefPort, } from '../src/mcp/index'; import { utcDateOf } from '../src/mcp/tools/vault-fenced-input'; @@ -58,6 +59,10 @@ function createFakeWritePort(): { const CUTOFF_MIDNIGHT_TS = Date.UTC(2025, 5, 30, 0, 0, 0, 0); // 2025-06-30T00:00:00.000Z describe('createPostgresTrialRefLookupPort', () => { + test('exposes createPostgresTrialRefPort as an alias', () => { + expect(createPostgresTrialRefPort).toBe(createPostgresTrialRefLookupPort); + }); + test('rejects missing or non-callable executor with INVALID_EXECUTOR', () => { const invalidOptions: unknown[] = [ null, @@ -87,6 +92,7 @@ describe('createPostgresTrialRefLookupPort', () => { const fake = createFakeExecutor([]); const badSchemas: unknown[] = [ '', + 'Public', 'Bad-Schema', 'a;drop', '1schema', @@ -125,6 +131,9 @@ describe('createPostgresTrialRefLookupPort', () => { null, undefined, 123.45, + Number.MAX_SAFE_INTEGER + 1, + 8_640_000_000_000_000, + -8_640_000_000_000_000, Date.parse('+010000-01-01T00:00:00.000Z'), Date.parse('-000001-01-01T00:00:00.000Z'), Date.parse('0000-01-01T00:00:00.000Z'), @@ -162,10 +171,9 @@ describe('createPostgresTrialRefLookupPort', () => { expect(call.text.trimStart().startsWith('SELECT')).toBe(true); expect(call.text).not.toContain(';'); expect(call.text).not.toMatch(/\b(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|TRUNCATE)\b/i); - expect(call.text).toContain('FROM trial_ledger'); - expect(call.text).toContain('trial_id = $1::bigint'); - expect(call.text).toContain('sample_end < $2::date'); - expect(call.text).toContain('LIMIT 1'); + expect(call.text).toBe( + 'SELECT 1 AS visible FROM trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1' + ); expect(call.params).toEqual(['42', '2025-06-30']); expect(typeof call.params?.[0]).toBe('string'); }); @@ -224,6 +232,7 @@ describe('createPostgresTrialRefLookupPort', () => { '1.0', '1e3', '0x10', + '1_000', '42; DROP TABLE trial_ledger', '9223372036854775808', '10000000000000000000', @@ -232,6 +241,7 @@ describe('createPostgresTrialRefLookupPort', () => { null, undefined, {}, + [], ]; for (const ref of invalidRefs) { @@ -267,32 +277,93 @@ describe('createPostgresTrialRefLookupPort', () => { await defaultPort.hasResearchVisibleTrial('1'); expect(fakeDefault.calls[0]!.text).toContain('FROM trial_ledger '); - const fakeScoped = createFakeExecutor([]); - const scopedPort = createPostgresTrialRefLookupPort({ - executor: fakeScoped.executor, - vaultCutoffTs: CUTOFF_MIDNIGHT_TS, - schema: 'research_x', - }); - await scopedPort.hasResearchVisibleTrial('1'); - expect(fakeScoped.calls[0]!.text).toContain('FROM "research_x".trial_ledger '); + for (const schema of ['_', 'a', 'research_x', 'stock_bot_safety_0abc']) { + const fakeScoped = createFakeExecutor([]); + const scopedPort = createPostgresTrialRefLookupPort({ + executor: fakeScoped.executor, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, + schema, + }); + await scopedPort.hasResearchVisibleTrial('1'); + expect(fakeScoped.calls[0]!.text).toContain(`FROM "${schema}".trial_ledger `); + } }); - test('propagates executor rejections unchanged without retrying', async () => { - const failure = new Error('postgres connection lost'); - let attempts = 0; - const executor: TrialRefExecutor = { + test('throws INVALID_ROW for malformed envelopes, invalid singleton rows, and multiple rows (regression)', async () => { + const badResponses: unknown[] = [ + null, + undefined, + {}, + { rows: null }, + { rows: 'not-an-array' }, + { rows: {} }, + { rows: [null] }, + { rows: [undefined] }, + { rows: [1] }, + { rows: [{}] }, + { rows: [{ visible: '1' }] }, + { rows: [{ visible: true }] }, + { rows: [{ visible: 0 }] }, + { rows: [{ visible: 2 }] }, + { rows: [{ visible: null }] }, + // Regression: multiple rows must fail closed rather than returning true. + { rows: [{ visible: 1 }, { visible: 1 }] }, + ]; + + for (const response of badResponses) { + const executor: TrialRefExecutor = { + async query() { + return response as { readonly rows: readonly never[] }; + }, + }; + const port = createPostgresTrialRefLookupPort({ + executor, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, + }); + + let caught: unknown; + try { + await port.hasResearchVisibleTrial('101'); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresTrialRefError); + expect((caught as PostgresTrialRefError).code).toBe('INVALID_ROW'); + } + }); + + test('propagates rejected and synchronously thrown executor errors unchanged without retrying', async () => { + const asyncFailure = new Error('postgres connection lost'); + let asyncAttempts = 0; + const asyncExecutor: TrialRefExecutor = { async query() { - attempts += 1; - throw failure; + asyncAttempts += 1; + throw asyncFailure; }, }; - const port = createPostgresTrialRefLookupPort({ - executor, + const asyncPort = createPostgresTrialRefLookupPort({ + executor: asyncExecutor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS, }); - await expect(port.hasResearchVisibleTrial('42')).rejects.toBe(failure); - expect(attempts).toBe(1); + await expect(asyncPort.hasResearchVisibleTrial('42')).rejects.toBe(asyncFailure); + expect(asyncAttempts).toBe(1); + + const syncFailure = new Error('pool exhausted'); + let syncAttempts = 0; + const syncExecutor = { + query() { + syncAttempts += 1; + throw syncFailure; + }, + } as unknown as TrialRefExecutor; + const syncPort = createPostgresTrialRefLookupPort({ + executor: syncExecutor, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, + }); + + await expect(syncPort.hasResearchVisibleTrial('42')).rejects.toBe(syncFailure); + expect(syncAttempts).toBe(1); }); test('accepts a pg.Pool-shaped executor with query on its prototype', async () => { @@ -491,35 +562,4 @@ describe('createPostgresTrialRefLookupPort (QA edge cases)', () => { expect(fake.calls[0]!.text).toBe(fake.calls[1]!.text); expect(fake.calls[1]!.params).toEqual(['2', '2025-06-30']); }); - - test('returns true for multiple matching rows and rejects (not false) on a malformed executor response', async () => { - const many = createFakeExecutor([{ visible: 1 }, { visible: 1 }]); - const manyPort = createPostgresTrialRefLookupPort({ - executor: many.executor, - vaultCutoffTs: CUTOFF_MIDNIGHT_TS, - }); - expect(await manyPort.hasResearchVisibleTrial('3')).toBe(true); - - for (const response of [null, {}, { rows: 'x' }, { rows: null }]) { - const executor: TrialRefExecutor = { - async query() { - return response as unknown as { readonly rows: readonly never[] }; - }, - }; - const port = createPostgresTrialRefLookupPort({ executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS }); - await expect(port.hasResearchVisibleTrial('3')).rejects.toBeInstanceOf(TypeError); - } - }); - - test('propagates a synchronous executor throw as a rejection with the same error', async () => { - const failure = new Error('pool exhausted'); - const executor = { - query() { - throw failure; - }, - } as unknown as TrialRefExecutor; - const port = createPostgresTrialRefLookupPort({ executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS }); - - await expect(port.hasResearchVisibleTrial('42')).rejects.toBe(failure); - }); }); diff --git a/test/postgres/mcp-findings-adapter.test.ts b/test/postgres/mcp-findings-adapter.test.ts new file mode 100644 index 00000000..30857d7d --- /dev/null +++ b/test/postgres/mcp-findings-adapter.test.ts @@ -0,0 +1,934 @@ +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Client, Pool, type PoolClient, type PoolConfig } from 'pg'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; +import { + FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, + type FileFindingResultPayload, + type FiledFindingRecord, + type PostgresFindingsExecutor, + type ReadKnowledgeResultPayload, + createFileFindingTool, + createMcpServer, + createPostgresFindingWritePort, + createPostgresKnowledgeReaders, + createReadKnowledgeTool, +} from '../../libs/research/src/mcp/index'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('mcp-findings-adapter-pg-test'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; +const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); + +const FIXED_TS = '2026-01-15T12:34:56.789Z'; + +const cleanup: (() => Promise | void)[] = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); + +function assertSafetyDatabaseUrl(connectionString: string | undefined): string { + if (!connectionString) { + throw new Error('Dedicated stock_bot_safety database required'); + } + let parsed: URL; + try { + parsed = new URL(connectionString); + } catch { + throw new Error('Dedicated stock_bot_safety database required'); + } + if (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') { + throw new Error('Dedicated stock_bot_safety database required'); + } + const client = new Client({ connectionString }); + const effectiveDb = ( + client as unknown as { connectionParameters?: { database?: unknown } } + ).connectionParameters?.database; + if ( + typeof effectiveDb !== 'string' || + !effectiveDb.startsWith('stock_bot_safety') || + !parsed.pathname.startsWith('/stock_bot_safety') + ) { + throw new Error('Dedicated stock_bot_safety database required'); + } + return connectionString; +} + +function createPgExecutor(queryable: Pick | Pick): PostgresFindingsExecutor { + return { + query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + return queryable.query( + text, + params === undefined ? undefined : [...params] + ) as unknown as Promise<{ readonly rows: readonly Row[] }>; + }, + }; +} + +async function waitForBackendLockWait(pool: Pool, pid: number, timeoutMs = 2000): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const { rows } = await pool.query<{ wait_event_type: string | null }>( + 'SELECT wait_event_type FROM pg_stat_activity WHERE pid = $1', + [pid] + ); + if (rows[0]?.wait_event_type === 'Lock') { + return; + } + await new Promise(resolve => setTimeout(resolve, 10)); + } + throw new Error(`Timed out waiting for backend pid ${pid} to enter Lock wait`); +} + +function buildIsolatedPoolConfig(connectionString: string | undefined, schema: string): PoolConfig { + const safeUrl = assertSafetyDatabaseUrl(connectionString); + const parsed = new URL(safeUrl); + const existingOptions = parsed.searchParams + .getAll('options') + .map(value => value.trim()) + .filter(value => value.length > 0); + parsed.searchParams.delete('options'); + + const schemaOptions = `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`; + const options = [...existingOptions, schemaOptions].join(' '); + + return { + connectionString: parsed.toString(), + options, + }; +} + +async function createIsolatedFixture(connectionString: string | undefined = url) { + const safeUrl = assertSafetyDatabaseUrl(connectionString); + const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; + const admin = new Pool({ connectionString: safeUrl }); + await admin.query(`CREATE SCHEMA ${schema}`); + const pool = new Pool(buildIsolatedPoolConfig(safeUrl, schema)); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + + const { rows: schemaRows } = await pool.query<{ current_schema: string | null }>( + 'SELECT current_schema() AS current_schema' + ); + if (schemaRows[0]?.current_schema !== schema) { + throw new Error( + `Isolated fixture pool expected current_schema()=${schema}, got ${String(schemaRows[0]?.current_schema)}` + ); + } + + // Bootstrap pre-additive tables needed by the research migration track. + for (const filename of [ + '06-create-backtest-tables.sql', + '07-fix-execution-time-type.sql', + '08-create-runs-table.sql', + ]) { + await pool.query(readFileSync(`${initDir}${filename}`, 'utf8')); + } + + const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, + logger + ); + Object.defineProperty(postgres, 'connectionPool', { + get: () => ({ + connect: () => pool.connect(), + }), + }); + + await runPostgresMigrations(postgres, { track: 'research' }); + + return { admin, pool, schema }; +} + +function makeFinding(overrides: Partial = {}): FiledFindingRecord { + return { + id: `finding-${randomUUID()}`, + kind: 'finding', + title: 'Momentum factor decays after 5 sessions', + status: 'pending_review', + createdAt: FIXED_TS, + summary: 'Cross-sectional rank IC turns negative past day 5.', + trialRefs: ['101', '102'], + evidenceRefs: ['snap:2026-01-15:ic'], + ...overrides, + }; +} + +describe('PostgreSQL findings adapter safety guard', () => { + test('rejects unsafe database targets before connecting', () => { + expect(() => assertSafetyDatabaseUrl(undefined)).toThrow( + 'Dedicated stock_bot_safety database required' + ); + expect(() => + assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/trading_bot') + ).toThrow('Dedicated stock_bot_safety database required'); + expect(() => + assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5433/trading_bot_dev') + ).toThrow('Dedicated stock_bot_safety database required'); + expect(() => + assertSafetyDatabaseUrl('socket:/stock_bot_safety?db=trading_bot') + ).toThrow('Dedicated stock_bot_safety database required'); + expect(() => + assertSafetyDatabaseUrl('socket:///stock_bot_safety?db=trading_bot') + ).toThrow('Dedicated stock_bot_safety database required'); + expect(() => + assertSafetyDatabaseUrl('http://127.0.0.1:5432/stock_bot_safety_test') + ).toThrow('Dedicated stock_bot_safety database required'); + expect(() => assertSafetyDatabaseUrl('not-a-valid-url')).toThrow( + 'Dedicated stock_bot_safety database required' + ); + expect( + assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test') + ).toBe('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test'); + expect( + assertSafetyDatabaseUrl( + 'postgresql://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test' + ) + ).toBe('postgresql://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test'); + }); + + test('preserves isolated schema search_path precedence over URL startup options', () => { + const schema = 'stock_bot_safety_findings_options'; + const urlWithOptions = + 'postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test?options=-c%20statement_timeout%3D30000%20-c%20search_path%3Dpublic'; + const poolConfig = buildIsolatedPoolConfig(urlWithOptions, schema); + + expect(new URL(poolConfig.connectionString!).searchParams.has('options')).toBe(false); + + const client = new Client(poolConfig); + const resolvedOptions = (client as unknown as { connectionParameters: { options?: string } }) + .connectionParameters.options; + expect(resolvedOptions).toBe( + `-c statement_timeout=30000 -c search_path=public -c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000` + ); + }); +}); + +describe.skipIf(!url)('PostgreSQL MCP findings & provider caveats adapter', () => { + test('supports unkeyed inserts, keyed created -> replayed -> conflict, same-ID retries, and unrelated duplicate PK errors', async () => { + const f = await createIsolatedFixture(); + const writePort = createPostgresFindingWritePort({ executor: createPgExecutor(f.pool) }); + + // Two independent unkeyed inserts produce two distinct rows. + const u1 = await writePort.appendFinding(makeFinding({ id: 'f-unkeyed-1' })); + const u2 = await writePort.appendFinding(makeFinding({ id: 'f-unkeyed-2' })); + expect(u1).toEqual({ status: 'created', id: 'f-unkeyed-1', createdAt: FIXED_TS }); + expect(u2).toEqual({ status: 'created', id: 'f-unkeyed-2', createdAt: FIXED_TS }); + + // Keyed create -> replay -> conflict + const original = makeFinding({ + id: 'f-keyed-1', + createdAt: '2026-01-15T12:34:56.789Z', + }); + const created = await writePort.appendFinding(original, 'idem-roundtrip'); + expect(created).toEqual({ + status: 'created', + id: 'f-keyed-1', + createdAt: '2026-01-15T12:34:56.789Z', + }); + + // Replay with new generated ID and timestamp returns original stored ID and timestamp. + const replayed = await writePort.appendFinding( + { + ...original, + id: 'f-keyed-retry-new-id', + createdAt: '2026-01-16T00:00:00.000Z', + }, + 'idem-roundtrip' + ); + expect(replayed).toEqual({ + status: 'replayed', + id: 'f-keyed-1', + createdAt: '2026-01-15T12:34:56.789Z', + }); + + // Same-ID retry (triggers PK 23505) resolves cleanly as replayed / conflict. + const sameIdReplay = await writePort.appendFinding(original, 'idem-roundtrip'); + expect(sameIdReplay).toEqual({ + status: 'replayed', + id: 'f-keyed-1', + createdAt: '2026-01-15T12:34:56.789Z', + }); + const sameIdConflict = await writePort.appendFinding( + { ...original, title: 'Mutated title on same-ID retry' }, + 'idem-roundtrip' + ); + expect(sameIdConflict).toEqual({ status: 'conflict' }); + + // Different payload with new ID returns conflict and leaves row count unchanged. + const conflict = await writePort.appendFinding( + { ...original, id: 'f-keyed-conflict', summary: 'Different summary' }, + 'idem-roundtrip' + ); + expect(conflict).toEqual({ status: 'conflict' }); + + // Unrelated duplicate primary key (collides with unkeyed row f-unkeyed-1) propagates 23505. + let pkError: unknown; + try { + await writePort.appendFinding(makeFinding({ id: 'f-unkeyed-1' }), 'idem-fresh-unrelated'); + } catch (err) { + pkError = err; + } + expect((pkError as { code?: string } | null)?.code).toBe('23505'); + + const countRow = (await f.pool.query<{ c: number }>('SELECT count(*)::int AS c FROM findings')) + .rows[0]; + expect(countRow?.c).toBe(3); + }); + + test('concurrent same-key appends on pinned connections observe committed winner via fresh snapshot for identical and differing payloads', async () => { + const f = await createIsolatedFixture(); + + const runPinnedRace = async ( + key: string, + winnerRecord: FiledFindingRecord, + loserRecord: FiledFindingRecord + ) => { + const winnerClient = await f.pool.connect(); + let winnerOpen = false; + cleanup.push(async () => { + if (winnerOpen) { + await winnerClient.query('ROLLBACK').catch(() => {}); + } + winnerClient.release(); + }); + const loserClient = await f.pool.connect(); + cleanup.push(() => { + loserClient.release(); + }); + + const loserPid = ( + await loserClient.query<{ pid: number }>('SELECT pg_backend_pid() AS pid') + ).rows[0]!.pid; + + const winnerPort = createPostgresFindingWritePort({ + executor: createPgExecutor(winnerClient), + }); + const loserPort = createPostgresFindingWritePort({ + executor: createPgExecutor(loserClient), + }); + + await winnerClient.query('BEGIN'); + winnerOpen = true; + const winnerOutcome = await winnerPort.appendFinding(winnerRecord, key); + expect(winnerOutcome).toEqual({ + status: 'created', + id: winnerRecord.id, + createdAt: winnerRecord.createdAt, + }); + + // Start the competing append on the second connection and wait until PostgreSQL + // blocks its INSERT ... ON CONFLICT DO NOTHING on the winner's uncommitted tuple. + const loserPromise = loserPort.appendFinding(loserRecord, key); + await waitForBackendLockWait(f.pool, loserPid); + + await winnerClient.query('COMMIT'); + winnerOpen = false; + + const loserOutcome = await loserPromise; + return { winnerOutcome, loserOutcome }; + }; + + // Concurrent identical payloads: loser's separate READ COMMITTED lookup sees winner -> replayed + const recA = makeFinding({ id: 'f-race-same-a', createdAt: '2026-01-15T10:00:00.000Z' }); + const recB = { ...recA, id: 'f-race-same-b', createdAt: '2026-01-15T10:00:01.000Z' }; + const sameRace = await runPinnedRace('idem-race-same', recA, recB); + expect(sameRace.loserOutcome).toEqual({ + status: 'replayed', + id: recA.id, + createdAt: recA.createdAt, + }); + + const storedSame = ( + await f.pool.query<{ id: string }>( + 'SELECT id FROM findings WHERE idempotency_key = $1', + ['idem-race-same'] + ) + ).rows; + expect(storedSame).toEqual([{ id: recA.id }]); + + // Concurrent differing payloads: loser's separate READ COMMITTED lookup sees winner -> conflict + const diffA = makeFinding({ + id: 'f-race-diff-a', + title: 'Race title A', + createdAt: '2026-01-15T11:00:00.000Z', + }); + const diffB = makeFinding({ + id: 'f-race-diff-b', + title: 'Race title B', + createdAt: '2026-01-15T11:00:01.000Z', + }); + const diffRace = await runPinnedRace('idem-race-diff', diffA, diffB); + expect(diffRace.loserOutcome).toEqual({ status: 'conflict' }); + + const storedDiff = ( + await f.pool.query<{ id: string }>( + 'SELECT id FROM findings WHERE idempotency_key = $1', + ['idem-race-diff'] + ) + ).rows; + expect(storedDiff).toEqual([{ id: diffA.id }]); + }); + + test('readers return all eligible candidates in deterministic id order with mixed-case, provider, exact-id precedence, wildcard escaping, and explicit schema', async () => { + const f = await createIsolatedFixture(); + // Use admin pool (default search_path) with explicit schema option to verify quoting. + const writePort = createPostgresFindingWritePort({ + executor: createPgExecutor(f.admin), + schema: f.schema, + }); + const readers = createPostgresKnowledgeReaders({ + executor: createPgExecutor(f.admin), + schema: f.schema, + }); + + await writePort.appendFinding( + makeFinding({ + id: 'f-003', + title: '100% Pure_Wild\\Match', + summary: 'Literal wildcard finding.', + createdAt: '2026-01-15T03:00:00.000Z', + }) + ); + await writePort.appendFinding( + makeFinding({ + id: 'f-001', + title: '100X PureAWildXMatch', + summary: 'Near-match without literal wildcards.', + createdAt: '2026-01-15T01:00:00.000Z', + }) + ); + await writePort.appendFinding( + makeFinding({ + id: 'f-002', + title: 'Alpha Drift Signal', + summary: 'Observed on TSX equities.', + createdAt: '2026-01-15T02:00:00.000Z', + }) + ); + + await f.pool.query( + `INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at) + VALUES + ('c-003', 'EODHD', 'eodIntraday1M', '100% split_adjusted\\bars', '2026-01-15T03:00:00.000Z'), + ('c-001', 'QuoteMedia', 'qmSplits', '100X splitXadjustedYbars', '2026-01-15T01:00:00.000Z'), + ('c-002', 'EODHD', 'eodPrices', 'Daily raw OHLCV needs un-adjustment.', '2026-01-15T02:00:00.000Z')` + ); + + // Deterministic id ASC order for unfiltered reads + expect((await readers.listFindings({})).map(r => r.id)).toEqual(['f-001', 'f-002', 'f-003']); + expect((await readers.listProviderCaveats({})).map(r => r.id)).toEqual([ + 'c-001', + 'c-002', + 'c-003', + ]); + + // Mixed-case query matching + expect((await readers.listFindings({ query: 'tsx EQUITIES' })).map(r => r.id)).toEqual([ + 'f-002', + ]); + expect((await readers.listProviderCaveats({ query: 'DAILY RAW' })).map(r => r.id)).toEqual([ + 'c-002', + ]); + + // Case-insensitive provider filter + expect((await readers.listProviderCaveats({ provider: 'eodhd' })).map(r => r.id)).toEqual([ + 'c-002', + 'c-003', + ]); + + // Exact id is case-sensitive and takes precedence over query + expect( + (await readers.listFindings({ id: 'f-002', query: 'does-not-match' })).map(r => r.id) + ).toEqual(['f-002']); + expect(await readers.listFindings({ id: 'F-002' })).toEqual([]); + + // Provider condition still applies with exact id + expect( + (await readers.listProviderCaveats({ id: 'c-002', provider: 'eodhd', query: 'nope' })).map( + r => r.id + ) + ).toEqual(['c-002']); + expect( + await readers.listProviderCaveats({ id: 'c-002', provider: 'quotemedia' }) + ).toEqual([]); + + // Literal wildcard escaping: matches f-003 / c-003 and excludes near-matches f-001 / c-001 + expect((await readers.listFindings({ query: '100% Pure_Wild\\' })).map(r => r.id)).toEqual([ + 'f-003', + ]); + expect( + (await readers.listProviderCaveats({ query: '100% split_adjusted\\' })).map(r => r.id) + ).toEqual(['c-003']); + }); + + test('round-trips createFileFindingTool -> createReadKnowledgeTool through MCP server', async () => { + const f = await createIsolatedFixture(); + const executor = createPgExecutor(f.pool); + const writePort = createPostgresFindingWritePort({ executor }); + const readers = createPostgresKnowledgeReaders({ executor }); + + await f.pool.query( + `INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at) + VALUES ('caveat-eod-1', 'EODHD', 'eodIntraday1M', 'Retroactively split-adjusted.', $1::timestamptz)`, + [FIXED_TS] + ); + + let idSeq = 0; + const allowedTrials = new Set(['101', '102']); + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: writePort, + trialLookup: { + hasResearchVisibleTrial(ref) { + return allowedTrials.has(ref); + }, + }, + newId: () => { + idSeq += 1; + return `finding-mcp-${idSeq}`; + }, + now: () => new Date(FIXED_TS), + }), + createReadKnowledgeTool({ + port: { + listLibraryCards: async () => [], + ...readers, + }, + }), + ], + }); + + const callTool = async (name: string, args: Record) => { + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: `req-${name}`, + method: 'tools/call', + params: { name, arguments: args }, + }) + ); + expect(raw).not.toBeNull(); + const parsed = JSON.parse(raw!) as { + result: { isError?: boolean; content: Array<{ text: string }> }; + }; + return parsed.result; + }; + + // File a new finding through MCP + const fileRes = await callTool('file_finding', { + kind: 'finding', + title: 'Post-earnings drift persists 3 sessions', + summary: 'Positive rank IC across research-visible trials 101 and 102.', + trialRefs: ['102', '101'], + evidenceRefs: ['snap:b', 'snap:a'], + idempotencyKey: 'mcp-idem-1', + }); + expect(fileRes.isError).toBeUndefined(); + const receipt = JSON.parse(fileRes.content[0]!.text) as FileFindingResultPayload; + expect(receipt).toEqual({ + id: 'finding-mcp-1', + createdAt: FIXED_TS, + created: true, + }); + + // Retry with reordered & duplicate refs -> normalized replay with original receipt + const retryRes = await callTool('file_finding', { + kind: 'finding', + title: 'Post-earnings drift persists 3 sessions', + summary: 'Positive rank IC across research-visible trials 101 and 102.', + trialRefs: ['101', '102', '101'], + evidenceRefs: ['snap:a', 'snap:b', 'snap:a'], + idempotencyKey: 'mcp-idem-1', + }); + expect(retryRes.isError).toBeUndefined(); + const retryReceipt = JSON.parse(retryRes.content[0]!.text) as FileFindingResultPayload; + expect(retryReceipt).toEqual({ + id: 'finding-mcp-1', + createdAt: FIXED_TS, + created: false, + }); + + // Unavailable / Vault-only trial ref returns error and writes zero rows + const deniedRes = await callTool('file_finding', { + kind: 'dead_end', + title: 'Should not persist', + summary: 'References unavailable trial.', + trialRefs: ['999-vault'], + }); + expect(deniedRes.isError).toBe(true); + expect(deniedRes.content[0]!.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); + + // Read back the filed finding by receipt ID via read_knowledge + const readRes = await callTool('read_knowledge', { + source: 'findings', + id: receipt.id, + }); + expect(readRes.isError).toBeUndefined(); + const knowledge = JSON.parse(readRes.content[0]!.text) as ReadKnowledgeResultPayload; + expect(knowledge).toEqual({ + rowCount: 1, + sources: { library: 0, findings: 1, provider_caveats: 0 }, + rows: [ + { + source: 'findings', + id: 'finding-mcp-1', + title: 'Post-earnings drift persists 3 sessions', + status: 'pending_review', + createdAt: FIXED_TS, + summary: 'Positive rank IC across research-visible trials 101 and 102.', + trialRefs: ['101', '102'], + evidenceRefs: ['snap:a', 'snap:b'], + truncated: false, + }, + ], + }); + + // Verify provider_caveats case-insensitive filter through read_knowledge + const caveatRes = await callTool('read_knowledge', { + source: 'provider_caveats', + provider: 'eodhd', + }); + expect(caveatRes.isError).toBeUndefined(); + const caveatsPayload = JSON.parse(caveatRes.content[0]!.text) as ReadKnowledgeResultPayload; + expect(caveatsPayload.rowCount).toBe(1); + expect(caveatsPayload.sources).toEqual({ library: 0, findings: 0, provider_caveats: 1 }); + expect(caveatsPayload.rows[0]).toEqual({ + source: 'provider_caveats', + id: 'caveat-eod-1', + provider: 'EODHD', + dataset: 'eodIntraday1M', + caveat: 'Retroactively split-adjusted.', + createdAt: FIXED_TS, + truncated: false, + }); + + // Confirm only 1 finding row was persisted in total + const totalFindings = ( + await f.pool.query<{ c: number }>('SELECT count(*)::int AS c FROM findings') + ).rows[0]?.c; + expect(totalFindings).toBe(1); + + // Regression: Unicode final sigma (κοσμος vs ΚΟΣΜΟΣ) must not be dropped by libc ILIKE + const sigmaFileRes = await callTool('file_finding', { + kind: 'finding', + title: 'κοσμος', + summary: 'Greek final sigma regression finding.', + trialRefs: ['101'], + evidenceRefs: [], + }); + expect(sigmaFileRes.isError).toBeUndefined(); + const sigmaReceipt = JSON.parse(sigmaFileRes.content[0]!.text) as FileFindingResultPayload; + + const sigmaReadRes = await callTool('read_knowledge', { + source: 'findings', + query: 'ΚΟΣΜΟΣ', + }); + expect(sigmaReadRes.isError).toBeUndefined(); + const sigmaKnowledge = JSON.parse( + sigmaReadRes.content[0]!.text + ) as ReadKnowledgeResultPayload; + expect(sigmaKnowledge.rowCount).toBe(1); + expect(sigmaKnowledge.rows[0]?.id).toBe(sigmaReceipt.id); + + await f.pool.query( + `INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at) + VALUES ('caveat-sigma-1', 'EODHD', 'eodPrices', 'Caveat for κοσμος tickers.', $1::timestamptz)`, + [FIXED_TS] + ); + const sigmaCaveatRes = await callTool('read_knowledge', { + source: 'provider_caveats', + provider: 'eodhd', + query: 'ΚΟΣΜΟΣ', + }); + expect(sigmaCaveatRes.isError).toBeUndefined(); + const sigmaCaveats = JSON.parse( + sigmaCaveatRes.content[0]!.text + ) as ReadKnowledgeResultPayload; + expect(sigmaCaveats.rowCount).toBe(1); + expect(sigmaCaveats.rows[0]?.id).toBe('caveat-sigma-1'); + }); + + test('matches ASCII queries and providers against Unicode stored text under PostgreSQL C collation through MCP', async () => { + const f = await createIsolatedFixture(); + + // Force C collation on text columns to reproduce the C-collation casing mismatch + // regardless of the host test database's default collation. + await f.pool.query(` + ALTER TABLE findings + ALTER COLUMN title TYPE TEXT COLLATE "C", + ALTER COLUMN summary TYPE TEXT COLLATE "C"; + ALTER TABLE provider_caveats + ALTER COLUMN provider TYPE TEXT COLLATE "C", + ALTER COLUMN dataset TYPE TEXT COLLATE "C", + ALTER COLUMN caveat TYPE TEXT COLLATE "C"; + `); + + // Prove PostgreSQL C collation itself fails both direct SQL casing comparisons. + const pgCheck = ( + await f.pool.query<{ ilike_match: boolean; lower_match: boolean }>( + `SELECT + ('BİST exchange coverage' COLLATE "C" ILIKE '%bi%') AS ilike_match, + (lower('K' COLLATE "C") = lower('k' COLLATE "C")) AS lower_match` + ) + ).rows[0]!; + expect(pgCheck.ilike_match).toBe(false); + expect(pgCheck.lower_match).toBe(false); + + const executor = createPgExecutor(f.pool); + const writePort = createPostgresFindingWritePort({ executor }); + const readers = createPostgresKnowledgeReaders({ executor }); + + let idSeq = 0; + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: writePort, + trialLookup: { + hasResearchVisibleTrial(ref) { + return ref === '101'; + }, + }, + newId: () => { + idSeq += 1; + return `finding-c-coll-${idSeq}`; + }, + now: () => new Date(FIXED_TS), + }), + createReadKnowledgeTool({ + port: { + listLibraryCards: async () => [], + ...readers, + }, + }), + ], + }); + + const callTool = async (name: string, args: Record) => { + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: `req-c-coll-${name}`, + method: 'tools/call', + params: { name, arguments: args }, + }) + ); + expect(raw).not.toBeNull(); + const parsed = JSON.parse(raw!) as { + result: { isError?: boolean; content: Array<{ text: string }> }; + }; + return parsed.result; + }; + + // File Unicode finding 'BİST exchange coverage' and an unrelated Unicode finding 'κόσμος' + const bistFileRes = await callTool('file_finding', { + kind: 'finding', + title: 'BİST exchange coverage', + summary: 'Turkish equities universe check.', + trialRefs: ['101'], + evidenceRefs: [], + }); + expect(bistFileRes.isError).toBeUndefined(); + const bistReceipt = JSON.parse(bistFileRes.content[0]!.text) as FileFindingResultPayload; + + const unrelatedFileRes = await callTool('file_finding', { + kind: 'finding', + title: 'κόσμος', + summary: 'Unrelated Greek finding.', + trialRefs: ['101'], + evidenceRefs: [], + }); + expect(unrelatedFileRes.isError).toBeUndefined(); + + // ASCII query 'bi' must match 'BİST exchange coverage' and exclude 'κόσμος' + const bistReadRes = await callTool('read_knowledge', { + source: 'findings', + query: 'bi', + }); + expect(bistReadRes.isError).toBeUndefined(); + const bistKnowledge = JSON.parse( + bistReadRes.content[0]!.text + ) as ReadKnowledgeResultPayload; + expect(bistKnowledge.rowCount).toBe(1); + expect(bistKnowledge.rows[0]?.id).toBe(bistReceipt.id); + + // Provider caveats: ASCII query against 'BİST' text, and ASCII provider 'k' against 'K' (U+212A) + await f.pool.query( + `INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at) + VALUES + ('caveat-c-bist', 'EODHD', 'eodPrices', 'BİST intraday feed caveat.', $1::timestamptz), + ('caveat-c-kelvin', 'K', 'kelvinBars', 'Kelvin sign provider caveat.', $1::timestamptz), + ('caveat-c-greek', 'EODHD', 'eodPrices', 'Unrelated κόσμος caveat.', $1::timestamptz)`, + [FIXED_TS] + ); + + const bistCaveatRes = await callTool('read_knowledge', { + source: 'provider_caveats', + provider: 'eodhd', + query: 'bi', + }); + expect(bistCaveatRes.isError).toBeUndefined(); + const bistCaveats = JSON.parse( + bistCaveatRes.content[0]!.text + ) as ReadKnowledgeResultPayload; + expect(bistCaveats.rowCount).toBe(1); + expect(bistCaveats.rows[0]?.id).toBe('caveat-c-bist'); + + const kelvinCaveatRes = await callTool('read_knowledge', { + source: 'provider_caveats', + provider: 'k', + }); + expect(kelvinCaveatRes.isError).toBeUndefined(); + const kelvinCaveats = JSON.parse( + kelvinCaveatRes.content[0]!.text + ) as ReadKnowledgeResultPayload; + expect(kelvinCaveats.rowCount).toBe(1); + expect(kelvinCaveats.rows[0]?.id).toBe('caveat-c-kelvin'); + }); +}); + +// QA (T-161): seeded differential check that the adapter's SQL pushdown plus JS +// post-filter never drops or adds a row relative to read_knowledge's JS matching +// rules, against real PostgreSQL under both the database default and "C" collation. +function qaMulberry32(seed: number): () => number { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +const QA_ALPHABET = ['a', 'B', 'i', 'I', 's', 'S', 'k', '%', '_', '\\', ' ', 'İ', 'ı', 'Σ', 'ς', 'K', 'é', 'ß']; + +function qaText(rand: () => number, min: number, max: number): string { + const len = min + Math.floor(rand() * (max - min + 1)); + let out = ''; + for (let i = 0; i < len; i += 1) { + out += QA_ALPHABET[Math.floor(rand() * QA_ALPHABET.length)]; + } + return out; +} + +function qaQuery(rand: () => number, corpus: readonly string[]): string { + if (rand() < 0.5) { + const source = corpus[Math.floor(rand() * corpus.length)]!; + const start = Math.floor(rand() * source.length); + const end = Math.min(source.length, start + 1 + Math.floor(rand() * 3)); + let q = ''; + for (const ch of source.slice(start, end)) { + q += rand() < 0.5 ? ch.toUpperCase() : ch.toLowerCase(); + } + return q.length > 0 ? q : 'a'; + } + return qaText(rand, 1, 2); +} + +describe.skipIf(!url)('PostgreSQL findings readers QA differential vs read_knowledge matching', () => { + for (const forceCCollation of [false, true]) { + test(`seeded corpus/query fuzz agrees with JS matching (${forceCCollation ? 'C' : 'default'} collation)`, async () => { + const f = await createIsolatedFixture(); + if (forceCCollation) { + await f.pool.query(` + ALTER TABLE findings + ALTER COLUMN title TYPE TEXT COLLATE "C", + ALTER COLUMN summary TYPE TEXT COLLATE "C"; + ALTER TABLE provider_caveats + ALTER COLUMN provider TYPE TEXT COLLATE "C", + ALTER COLUMN dataset TYPE TEXT COLLATE "C", + ALTER COLUMN caveat TYPE TEXT COLLATE "C"; + `); + } + const executor = createPgExecutor(f.pool); + const writePort = createPostgresFindingWritePort({ executor }); + const readers = createPostgresKnowledgeReaders({ executor }); + const rand = qaMulberry32(forceCCollation ? 4242 : 161); + + const findings = Array.from({ length: 30 }, (_, i) => ({ + id: `qa-f-${String(i).padStart(3, '0')}`, + title: `T${qaText(rand, 2, 6)}`, + summary: `S${qaText(rand, 2, 6)}`, + })); + for (const row of findings) { + const outcome = await writePort.appendFinding( + makeFinding({ id: row.id, title: row.title, summary: row.summary }) + ); + expect(outcome.status).toBe('created'); + } + + const providers = ['EODHD', 'eodhd', 'K', 'kelvin', 'İBK', 'ibk', 'ΣΙΣ', 'σις']; + const caveats = Array.from({ length: 30 }, (_, i) => ({ + id: `qa-c-${String(i).padStart(3, '0')}`, + provider: providers[Math.floor(rand() * providers.length)]!, + dataset: `D${qaText(rand, 2, 5)}`, + caveat: `C${qaText(rand, 2, 6)}`, + })); + for (const row of caveats) { + await f.pool.query( + `INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at) + VALUES ($1, $2, $3, $4, $5::timestamptz)`, + [row.id, row.provider, row.dataset, row.caveat, FIXED_TS] + ); + } + + const findingCorpus = findings.flatMap(r => [r.title, r.summary]); + for (let n = 0; n < 60; n += 1) { + const query = qaQuery(rand, findingCorpus); + const lower = query.toLowerCase(); + const expected = findings + .filter( + r => r.title.toLowerCase().includes(lower) || r.summary.toLowerCase().includes(lower) + ) + .map(r => r.id); + const actual = (await readers.listFindings({ query })).map(r => r.id); + expect({ query, ids: actual }).toEqual({ query, ids: expected }); + } + + const caveatCorpus = caveats.flatMap(r => [r.provider, r.dataset, r.caveat]); + for (let n = 0; n < 60; n += 1) { + const provider = + rand() < 0.6 + ? providers[Math.floor(rand() * providers.length)]!.toUpperCase() + : undefined; + const query = rand() < 0.7 ? qaQuery(rand, caveatCorpus) : undefined; + const lowerProvider = provider?.toLowerCase(); + const lowerQuery = query?.toLowerCase(); + const expected = caveats + .filter(r => lowerProvider === undefined || r.provider.toLowerCase() === lowerProvider) + .filter( + r => + lowerQuery === undefined || + r.provider.toLowerCase().includes(lowerQuery) || + r.dataset.toLowerCase().includes(lowerQuery) || + r.caveat.toLowerCase().includes(lowerQuery) + ) + .map(r => r.id); + const actual = ( + await readers.listProviderCaveats({ + ...(provider !== undefined ? { provider } : {}), + ...(query !== undefined ? { query } : {}), + }) + ).map(r => r.id); + expect({ provider, query, ids: actual }).toEqual({ provider, query, ids: expected }); + } + }, 30_000); + } +}); diff --git a/test/postgres/mcp-trial-ref-adapter.test.ts b/test/postgres/mcp-trial-ref-adapter.test.ts index 7c78e11f..2a91334f 100644 --- a/test/postgres/mcp-trial-ref-adapter.test.ts +++ b/test/postgres/mcp-trial-ref-adapter.test.ts @@ -2,17 +2,19 @@ import { randomUUID } from 'node:crypto'; import { readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { afterEach, describe, expect, test } from 'bun:test'; -import { Pool, type PoolClient } from 'pg'; +import { Client, Pool, type PoolClient, type PoolConfig } from 'pg'; import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; import { type AppendFindingResult, FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, + type FileFindingResultPayload, type FiledFindingRecord, + type TrialRefExecutor, createFileFindingTool, createMcpServer, + createPostgresFindingWritePort, createPostgresTrialRefLookupPort, - type TrialRefExecutor, } from '../../libs/research/src/mcp/index'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); @@ -22,6 +24,7 @@ const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.me // Vault cutoff date 2025-06-30 (exclusive): sample_end must be < 2025-06-30 to be research-visible. const VAULT_CUTOFF_TS = Date.UTC(2025, 5, 30, 0, 0, 0, 0); +const FIXED_TS = '2026-01-15T12:34:56.789Z'; const MAX_BIGINT_REF = '9223372036854775807'; // 2^53 + 1 is not representable as a JS number; Number('9007199254740993') === 9007199254740992. const ABOVE_SAFE_INT_REF = '9007199254740993'; @@ -29,19 +32,50 @@ const ABOVE_SAFE_INT_NEIGHBOR_REF = '9007199254740992'; const cleanup: (() => Promise | void)[] = []; afterEach(async () => { + // Run every cleanup step even if an earlier one fails, then surface the first failure. + let firstError: unknown; for (const close of cleanup.splice(0).reverse()) { - await close(); + try { + await close(); + } catch (err) { + firstError ??= err; + } + } + if (firstError !== undefined) { + throw firstError; } }); function assertSafetyDatabaseUrl(connectionString: string | undefined): string { - if (!connectionString || !new URL(connectionString).pathname.startsWith('/stock_bot_safety')) { + if (!connectionString) { + throw new Error('Dedicated stock_bot_safety database required'); + } + let parsed: URL; + try { + parsed = new URL(connectionString); + } catch { + throw new Error('Dedicated stock_bot_safety database required'); + } + if (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') { + throw new Error('Dedicated stock_bot_safety database required'); + } + const client = new Client({ connectionString }); + const effectiveDb = ( + client as unknown as { connectionParameters?: { database?: unknown } } + ).connectionParameters?.database; + if ( + typeof effectiveDb !== 'string' || + !effectiveDb.startsWith('stock_bot_safety') || + !parsed.pathname.startsWith('/stock_bot_safety') + ) { throw new Error('Dedicated stock_bot_safety database required'); } return connectionString; } -function createPgExecutor(queryable: Pool | PoolClient): TrialRefExecutor { +function createPgExecutor( + queryable: Pick | Pick +): TrialRefExecutor { return { query>( text: string, @@ -55,25 +89,57 @@ function createPgExecutor(queryable: Pool | PoolClient): TrialRefExecutor { }; } -async function createIsolatedFixture() { - const safeUrl = assertSafetyDatabaseUrl(url); +function buildIsolatedPoolConfig( + connectionString: string | undefined, + schema: string, + extraOptions?: string +): PoolConfig { + const safeUrl = assertSafetyDatabaseUrl(connectionString); + const parsed = new URL(safeUrl); + const existingOptions = parsed.searchParams + .getAll('options') + .map(value => value.trim()) + .filter(value => value.length > 0); + parsed.searchParams.delete('options'); + + const schemaOptions = extraOptions + ? `-c search_path=${schema} ${extraOptions}` + : `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`; + const options = [...existingOptions, schemaOptions].join(' '); + + return { + connectionString: parsed.toString(), + options, + }; +} + +async function createIsolatedFixture(connectionString: string | undefined = url) { + const safeUrl = assertSafetyDatabaseUrl(connectionString); const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; const admin = new Pool({ connectionString: safeUrl }); + // Registered before CREATE SCHEMA so the admin pool closes even if creation or teardown fails. + cleanup.push(() => admin.end()); await admin.query(`CREATE SCHEMA ${schema}`); - const pool = new Pool({ - connectionString: safeUrl, - options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`, - }); - const readOnlyPool = new Pool({ - connectionString: safeUrl, - options: `-c search_path=${schema} -c default_transaction_read_only=on -c statement_timeout=5000`, - }); - cleanup.push(async () => { - await readOnlyPool.end(); - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); + cleanup.push(() => admin.query(`DROP SCHEMA ${schema} CASCADE`).then(() => undefined)); + const pool = new Pool(buildIsolatedPoolConfig(safeUrl, schema)); + cleanup.push(() => pool.end()); + const readOnlyPool = new Pool( + buildIsolatedPoolConfig( + safeUrl, + schema, + '-c default_transaction_read_only=on -c statement_timeout=5000' + ) + ); + cleanup.push(() => readOnlyPool.end()); + + const { rows: schemaRows } = await pool.query<{ current_schema: string | null }>( + 'SELECT current_schema() AS current_schema' + ); + if (schemaRows[0]?.current_schema !== schema) { + throw new Error( + `Isolated fixture pool expected current_schema()=${schema}, got ${String(schemaRows[0]?.current_schema)}` + ); + } // Bootstrap pre-additive tables needed by the research migration track. for (const filename of [ @@ -93,6 +159,7 @@ async function createIsolatedFixture() { connect: () => pool.connect(), }), }); + await runPostgresMigrations(postgres, { track: 'research' }); await seedTrials(pool); @@ -121,6 +188,48 @@ async function seedTrials(pool: Pool): Promise { } } +describe('PostgreSQL trial-ref adapter safety guard', () => { + test('rejects unsafe database targets before connecting', () => { + expect(() => assertSafetyDatabaseUrl(undefined)).toThrow( + 'Dedicated stock_bot_safety database required' + ); + expect(() => + assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/trading_bot') + ).toThrow('Dedicated stock_bot_safety database required'); + expect(() => + assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5433/trading_bot_dev') + ).toThrow('Dedicated stock_bot_safety database required'); + expect(() => + assertSafetyDatabaseUrl('socket:/stock_bot_safety?db=trading_bot') + ).toThrow('Dedicated stock_bot_safety database required'); + expect(() => + assertSafetyDatabaseUrl('http://127.0.0.1:5432/stock_bot_safety_test') + ).toThrow('Dedicated stock_bot_safety database required'); + expect(() => assertSafetyDatabaseUrl('not-a-valid-url')).toThrow( + 'Dedicated stock_bot_safety database required' + ); + expect( + assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test') + ).toBe('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test'); + }); + + test('preserves isolated schema search_path precedence over URL startup options', () => { + const schema = 'stock_bot_safety_trial_ref_options'; + const urlWithOptions = + 'postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test?options=-c%20statement_timeout%3D30000%20-c%20search_path%3Dpublic'; + const poolConfig = buildIsolatedPoolConfig(urlWithOptions, schema); + + expect(new URL(poolConfig.connectionString!).searchParams.has('options')).toBe(false); + + const client = new Client(poolConfig); + const resolvedOptions = (client as unknown as { connectionParameters: { options?: string } }) + .connectionParameters.options; + expect(resolvedOptions).toBe( + `-c statement_timeout=30000 -c search_path=public -c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000` + ); + }); +}); + describe.skipIf(!url)('PostgreSQL MCP trial-ref lookup adapter', () => { test('exposes only trials with sample_end strictly before the UTC Vault cutoff date', async () => { const f = await createIsolatedFixture(); @@ -280,4 +389,96 @@ describe.skipIf(!url)('PostgreSQL MCP trial-ref lookup adapter', () => { expect(appended).toHaveLength(1); expect(appended[0]!.trialRefs).toEqual(['1', MAX_BIGINT_REF]); }); + + test('composes with createFileFindingTool and createPostgresFindingWritePort through MCP', async () => { + const f = await createIsolatedFixture(); + const executor = createPgExecutor(f.pool); + const trialLookup = createPostgresTrialRefLookupPort({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + const writePort = createPostgresFindingWritePort({ executor }); + + let idSeq = 0; + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: writePort, + trialLookup, + newId: () => { + idSeq += 1; + return `finding-trial-ref-${idSeq}`; + }, + now: () => new Date(FIXED_TS), + }), + ], + }); + + const callFileFinding = async (args: Record) => { + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'req-file-finding', + method: 'tools/call', + params: { + name: 'file_finding', + arguments: args, + }, + }) + ); + expect(raw).not.toBeNull(); + const parsed = JSON.parse(raw!) as { + result: { isError?: boolean; content: Array<{ text: string }> }; + }; + return parsed.result; + }; + + // Visible trial (sample_end = 2025-06-29 < 2025-06-30) succeeds and persists pending_review row. + const okRes = await callFileFinding({ + kind: 'finding', + title: 'Pre-cutoff signal holds across US equities', + summary: 'Positive IC verified strictly before the Vault cutoff.', + trialRefs: ['1'], + evidenceRefs: ['snap:2025-06-29:ic'], + }); + expect(okRes.isError).toBeUndefined(); + const receipt = JSON.parse(okRes.content[0]!.text) as FileFindingResultPayload; + expect(receipt).toEqual({ + id: 'finding-trial-ref-1', + createdAt: FIXED_TS, + created: true, + }); + + const storedRows = ( + await f.pool.query<{ id: string; status: string; trial_refs: string[] }>( + 'SELECT id, status, trial_refs FROM findings ORDER BY id ASC' + ) + ).rows; + expect(storedRows).toEqual([ + { + id: 'finding-trial-ref-1', + status: 'pending_review', + trial_refs: ['1'], + }, + ]); + + // Vault-only (equal to cutoff, after cutoff) and unknown citations all return the same error with zero rows added. + for (const deniedRef of ['2', '3', '999999999']) { + const deniedRes = await callFileFinding({ + kind: 'dead_end', + title: 'Should be rejected by Vault fence', + summary: 'References non-visible trial.', + trialRefs: [deniedRef], + }); + expect(deniedRes.isError).toBe(true); + expect(deniedRes.content[0]!.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); + } + + const totalFindings = ( + await f.pool.query<{ c: number }>('SELECT count(*)::int AS c FROM findings') + ).rows[0]?.c; + expect(totalFindings).toBe(1); + }); }); diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index d47f9e02..8c2221aa 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -142,7 +142,16 @@ Rules: 4. **Global `spiel_id` deduplication & deterministic tie-break:** Deduplicates globally on `spiel_id` before splitting into `newswire` and `retail`. Within each `spiel_id` group, the survivor is the row with the greatest `known_at`, breaking ties by the maximum lexicographic tuple `(posted_at, is_edited, is_bot, key, user_id, text)` (`None < Some` for `user_id`), with zero dependence on input order. The remaining `group_len - 1` rows are counted in `stats.duplicates_dropped`. 5. **Sort order & invariants:** Both `newswire` and `retail` are sorted strictly ascending by `(key, known_at, spiel_id)`. Any input permutation yields identical `newswire`, `retail`, and `stats`, and `input == newswire + retail + duplicates_dropped + rejected_invalid`. -Deferred out of `src/posts.rs`: `ceoPosts` raw-BSON decoding (pending live `edited` BSON type verification), `provider_mapping` resolution, Parquet writing, CLI subcommand, and benchmarks. +Deferred out of `src/posts.rs`: benchmark, live `ceoPosts` verification (including live `edited` BSON type verification), `--from-mongo` streaming, and co-publishing with `curate-events` output (offline raw-BSON decoding lives in `src/bson_ceo_posts.rs`, chunked streaming in `src/bson_stream.rs`, `events` Parquet row mapping in `src/parquet_posts.rs`, `provider_mapping` listing resolution + Parquet writing in `src/curate_posts.rs`, the file-to-file runner in `src/run_curate_posts.rs`, and the file-mode `curate-posts` CLI command in `src/cli.rs` + `src/main.rs`). + +### `run_curate_posts` File-to-File Runner (`M2.2i`) + +`run_curate_posts` / `run_curate_posts_with_reader` (`src/run_curate_posts.rs`) connects a concatenated raw BSON `ceoPosts` dump file and a headerless 5-column `provider_mapping.tsv` (`load_provider_mapping_tsv`) through `decode_ceo_posts_chunks` (`src/bson_stream.rs`) and `curate_and_write_posts` into `/events/year=YYYY/part.parquet` (Zstd Parquet): + +- **Explicit timestamp unit (no default):** `CuratePostsArgs::timestamp_unit` requires callers to pass `CeoPostsTimestampUnit::Seconds` or `CeoPostsTimestampUnit::Millis` explicitly (the live MongoDB numeric unit is unverified in the repo; BSON `DateTime` values are always epoch milliseconds). +- **Dedicated output directory & clobber guard:** Because `write_events_dataset` replaces whole `events/year=YYYY/part.parquet` files and `run_curate_events` (filings + earnings) writes to the same `/events` path, `run_curate_posts` requires a dedicated `--out` directory and fails closed with `RunCuratePostsError::EventsDatasetExists` before any write whenever `/events` already contains any `year=*` entry. Combining filings, earnings, and posts into a single `events` dataset is a separate follow-up. +- **Zero-row & fail-closed behavior:** Empty or all-unmapped inputs return `Ok` with `rows_written == 0` without creating `/events`. Validation, clobber checks, TSV loading, full BSON decoding, and curation complete before `out_dir` is touched. +- **In-memory accumulation:** `RawBsonChunkReader` bounds only the raw BSON chunk buffer (`peak_chunk_bytes`); decoded posts and their text accumulate in memory before `curate_and_write_posts` runs (as `curate_posts` requires). ## `events` Builder (`M1.2g`) @@ -890,6 +899,30 @@ Command (`2026-11-28`, two back-to-back runs with identical checksum `0x0a1b7ace - Parquet write: `elapsed=682.82 ms`, `throughput=709419 rows/s` - Combined (stage → Parquet): `elapsed=1272.06 ms`, `throughput=393065 rows/s` +## `posts` Curation Stage (`M2.2h`) + +`curate_posts` and `curate_and_write_posts` (`src/curate_posts.rs`) join `build_posts`, `ProviderMappingTable`, `parquet_posts`, and `write_events_dataset` into contract `EventsParquetRow` records strictly ascending in the 7-field writer sort key `(listing_id, ts_micros, kind, subtype, payload_json, known_at_micros, known_at_source)`. + +1. **Contract & Eastern-posting-date mapping rules:** + - Validates that `mapping_source` is non-blank before consuming the input iterator (`CuratePostsError::EmptyMappingSource`), then runs `build_posts` unchanged on source keys so global `spiel_id` deduplication, `bot == "1"` newswire vs. retail splitting, and the `edited` text `known_at` guard execute before listing resolution. + - **Mapping date (`posted_at` in `America/Toronto`):** resolves `(mapping_source, key, et_date) -> listing_id` where `et_date` is the Eastern local calendar date of `posted_at` computed via `session_close::utc_micros_to_et_local` (supported Eastern calendar range `1976-01-01..=2030-12-31`, i.e. `1976-01-01T05:00:00Z..=2031-01-01T04:59:59.999999Z`). Never uses the UTC date and never uses the `known_at` date, so a post edited days later stays on the listing active when it was posted while its text remains guarded by `known_at`. + - Uses one `ProviderMappingTable::cursor_for` per contiguous `key` run in each builder stream (`newswire`, then `retail`); because `build_posts` sorts by `(key, known_at, spiel_id)` rather than `posted_at`, backward `et_date` steps use `ProviderMappingCursor::resolve`'s binary-search fallback automatically. + - Converts each mapped `PostRow` via `EventsParquetRow::from` (reusing `parquet_posts` labels `kind = "post"`, `subtype = "newswire" | "retail"`, `known_at_source = "post_timestamp" | "post_edited"`, and its RFC 8259 `payload_json` encoder), then sorts in place by the 7-field writer key and collapses exact 7-field duplicates into `listing_duplicate_collapsed`. + - `curate_and_write_posts` publishes Zstd Parquet partitions to `/events/year=YYYY/part.parquet` (partitioned by UTC calendar year of `ts_micros`). Any `CuratePostsError` returns before `write_events_dataset` is called, leaving `out_dir` untouched. +2. **Drop policy & stats conservation invariants (`CuratePostsStats`):** + - Posts whose `posted_at` falls outside `utc_micros_to_et_local`'s supported range are dropped and counted in `dropped_unsupported_date` (checked before mapping coverage) without aborting or panicking. + - Posts whose `(mapping_source, key, et_date)` has no covering `provider_mapping` range are dropped into `dropped_unmapped`. + - Exact conservation invariants: + - `rows_in == builder.newswire + builder.retail` + - `rows_in == rows_out + dropped_unmapped + dropped_unsupported_date + listing_duplicate_collapsed` + - `rows_out == newswire_out + retail_out` + - Typed errors: `CuratePostsError` (`Posts(PostsError)`, `EmptyMappingSource`) and `CuratePostsWriteError` (`Curate(CuratePostsError)`, `Parquet(ParquetEventsError)`). +3. **Known limits & deferred work:** + - **Global `spiel_id` deduplication & `listing_duplicate_collapsed`:** because `build_posts` deduplicates globally on `spiel_id` (keeping the greatest `known_at` and breaking ties by the maximum `(posted_at, is_edited, is_bot, key, user_id, text)` tuple) and `payload_json` carries `spiel_id`, `listing_duplicate_collapsed` is expected to be `0` for real input and exists only as a defensive writer-key uniqueness guard; when the same `spiel_id` appears under two source keys, the surviving key is chosen by `build_posts`'s existing tie-break. + - **In-memory buffering:** both `build_posts` and the final 7-field sort buffer all rows in RAM; full-corpus memory and throughput over the 14.8M-row `ceoPosts` dataset remain unverified. + - **Separate output root (no co-publishing with `curate-events`):** `write_events_dataset` writes and replaces `/events/year=YYYY/part.parquet` partitions, so publishing curated posts alongside `curate-events` filings/earnings in the same `events/` directory is not handled here; pass a dedicated `out_dir` until a unified publisher exists. + - **Not done / deferred:** benchmark, `--from-mongo` / live `ceoPosts` run and schema verification, and co-publishing posts with `curate-events` output remain deferred to follow-up tasks. + ## `fx_1d` Curation Stage (`M1.2t`) `curate_fx_1d` and `curate_and_write_fx_1d` (`src/curate_fx.rs`) join `build_fx_1d` and `write_fx_1d_dataset` into contract `Fx1dParquetRow` records sorted and unique by `session_date` (no `provider_mapping` lookup is needed because FX rows are keyed by `pair = "USDCAD"`, not `listing_id`). @@ -1506,6 +1539,37 @@ Measured locally (`2026-11-29`, default `500,000` rows; two back-to-back runs wi - **Key-namespace alignment between `qmFilings` and `qmEarnings`:** `qmFilings` defaults to `symbol` while `qmEarnings` defaults to `qmSearchCode`. Both exports must carry an unambiguous key in the `provider_mapping` namespace (for example, the QuoteMedia security ID, not a bare ticker — the security master records distinct QuoteMedia IDs such as `VOY:CNX` and `VOY:CC` for the same symbol and exchange, so switching earnings to bare `symbol` can merge distinct identities or drop rows). If a live `qmFilings` export lacks that unambiguous key, prepare the export with verified QuoteMedia IDs and exclude unresolved rows rather than downgrading `qmEarnings` to bare tickers. - **In-RAM buffering & single-threaded execution:** decoded filings and earnings are buffered in RAM (with shared `Arc` key interning) before sorting/curation; `rayon` key-sharded streaming, direct MongoDB/PostgreSQL connections, and M2 `fundamentals_pit` joins remain out of scope. +## `curate-posts` Command (`M2.2j`) + +End-to-end file-to-Parquet CLI command (`src/run_curate_posts.rs`, wired in `src/cli.rs` and `src/main.rs`) streaming a concatenated raw BSON `ceoPosts` dump alongside `provider_mapping.tsv` into atomically published `/events/year=YYYY/part.parquet` partitions with zero extra crates and no database connections (`--from-mongo` is not supported yet and is rejected as an unknown flag). + +### Invocation + +```bash +curate-etl curate-posts \ + --ceo-posts ceoPosts.bson \ + --provider-mapping provider_mapping.tsv \ + --out ./out-posts \ + --timestamp-unit seconds +``` + +Inputs, defaults, and output rules: +- `--ceo-posts ` *(required)*: concatenated raw BSON (`mongodump` `ceoPosts.bson`). +- `--provider-mapping ` *(required)*: headerless 5-column TSV (same format as `curate-bars-1d`). +- `--out ` *(required, dedicated output directory)*: dataset root where `/events/year=YYYY/part.parquet` is atomically published. Because `curate-events` (filings + earnings) writes to the same `/events` directory layout, `curate-posts` requires a dedicated `--out` directory and fails closed before any write if `/events` already contains any `year=*` entry (leaving existing partitions byte-identical). +- `--timestamp-unit ` *(required, **no default**)*: explicit numeric epoch unit (`seconds` or `millis`) for numeric `timestamp` and `edited` fields. There is intentionally no default because the live MongoDB `ceoPosts` numeric timestamp unit is unverified in the repository; BSON `DateTime` values are always epoch milliseconds regardless of unit. +- Optional field-name overrides (defaults from `src/bson_ceo_posts.rs` / `get-posts.action.ts`): + - `--key-field` (default `ceoId`) + - `--spiel-id-field` (default `spielId`) + - `--timestamp-field` (default `timestamp`) + - `--edited-field` (default `edited`) + - `--bot-field` (default `bot`) + - `--user-id-field` (default `userId`) + - `--text-field` (default `spiel`) +- `--mapping-source ` *(optional, default `ceo`)*: `provider_mapping` source name used to resolve `(mapping_source, key, et_date) -> listing_id` on the Eastern local posting date of `posted_at`. + +Both `--flag value` and `--flag=value` forms are accepted. Missing required flags, invalid `--timestamp-unit`, duplicate flags, unknown flags (including `--from-mongo`), positional arguments, blank field names or `--mapping-source`, and colliding field-name roles (checked after applying defaults) exit non-zero with usage on stderr. + ## Read-Only MongoDB URI Safety Guard (`M1.2ak`) Pure, offline, `std`-only MongoDB URI safety guard (`src/mongo_safety.rs`, zero new crates, no sockets, no DNS resolution, no subprocesses) that ports the QA MongoDB target-classification rules from `apps/stock/config/src/env-safety.ts` before any Rust code may open a MongoDB connection. @@ -1616,3 +1680,43 @@ All `curate-*` commands read local TSV and concatenated raw-BSON files produced - **MongoDB concatenated raw-BSON files (`.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 `/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` 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_idvenue`, 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 `/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` inputs and a caller-supplied `(country_iso, indicator) -> Option` lookup into sorted, unique `MacroRow` 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>`) atomically to `/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 `/macro/part.parquet`: + +- **Explicit caller-supplied series map:** Maps verbatim `(te_symbol, country, category)` triples to `Option`; 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 `/macro/part.parquet` untouched on empty/all-unmapped input or any curation error. diff --git a/tools/curate-etl/src/bson_ceo_posts.rs b/tools/curate-etl/src/bson_ceo_posts.rs new file mode 100644 index 00000000..046ec0f9 --- /dev/null +++ b/tools/curate-etl/src/bson_ceo_posts.rs @@ -0,0 +1,860 @@ +//! Zero-copy raw BSON decoder for MongoDB `ceoPosts` documents (`M2.2g`). +//! +//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` without +//! allocating a `bson::Document`, emitting [`CeoPost<&str>`] rows (borrowing `key` directly from +//! the input buffer and allocating owned `String`s only for rows that will be emitted) via a +//! caller-supplied callback. +//! +//! # Unverified Live Schema & Explicit Timestamp Unit +//! +//! `apps/stock/data-ingestion/src/handlers/ceo/actions/get-posts.action.ts` establishes the +//! default stored field names (`ceoId`, `spielId`, `timestamp`, `edited`, `bot`, `userId`, +//! `spiel`), but the live MongoDB BSON types and whether `timestamp` / `edited` are stored in +//! epoch seconds or epoch milliseconds are **not verified** in the repository. Callers must +//! therefore supply [`CeoPostsTimestampUnit`] explicitly (there is intentionally no default). +//! +//! # Decoding & Validation Rules +//! - Every element and nested subdocument/array/JS-with-scope (up to depth `128`) of each +//! [`RawDocument`] is scanned and structurally validated to completion before applying semantic +//! skip rules, so structural BSON corruption always returns +//! `Err(BsonCeoPostsError::CorruptBson)` rather than being masked by an earlier semantic skip. +//! - `key` (`ceoId`): required non-blank UTF-8 BSON `String`, passed through verbatim (no +//! trimming). Missing, wrong type, or empty/whitespace-only strings skip the row under +//! `skipped_missing_key`, `skipped_wrong_key_type`, or `skipped_empty_key`. +//! - `spiel_id` (`spielId`): required UTF-8 BSON `String` (verbatim, non-blank) or `Int32` / +//! `Int64` rendered as decimal. Missing, wrong type, or empty/whitespace-only strings skip the +//! row under `skipped_missing_spiel_id`, `skipped_wrong_spiel_id_type`, or +//! `skipped_empty_spiel_id`. +//! - `timestamp` (`timestamp`): required `Int32`, `Int64`, finite integral `Double` in the +//! half-open `[-2^63, 2^63)` range, or BSON `DateTime` (already epoch milliseconds; unit +//! ignored). Under [`CeoPostsTimestampUnit::Seconds`], numeric values are multiplied by `1_000` +//! using `checked_mul`; overflow or out-of-range doubles skip under +//! `skipped_timestamp_out_of_range`. Non-finite or fractional doubles skip under +//! `skipped_invalid_timestamp`. Missing or other BSON types skip under +//! `skipped_missing_timestamp` or `skipped_wrong_timestamp_type`. Values `<= 0` are passed +//! through so [`crate::posts::build_posts`] remains the single place rejecting non-positive +//! creation timestamps. +//! - `edited` (`edited`, **point-in-time guard, fail closed**): +//! - Absent or BSON `Null` yields `edited_ms = None`. +//! - Numeric `0` (`Int32(0)`, `Int64(0)`, `Double(0.0)`, `Double(-0.0)`) or `Boolean(false)` +//! yields `edited_ms = None` and increments `edited_zero_or_false` (on emitted rows). +//! - Positive integral numeric values (`Int32`, `Int64`, finite integral `Double` in +//! `[-2^63, 2^63)`) converted with `unit` (checked multiply for seconds), or non-negative BSON +//! `DateTime` (including epoch-zero `DateTime(0)` -> `Some(0)` because the zero sentinel is +//! numeric), yield `edited_ms = Some(ms)`. +//! - Anything else — negative values, fractional or non-finite doubles, `Boolean(true)`, +//! `String`, other BSON types, seconds overflow, or repeated `edited` fields in the same +//! document — skips the row under `skipped_invalid_edited`. A row with a present but +//! unreadable `edited` field is never emitted as unedited. +//! - `text` (`spiel`): UTF-8 BSON `String` (verbatim); absent or BSON `Null` emits `String::new()` +//! and increments `empty_text` (on emitted rows); any other BSON type skips under +//! `skipped_wrong_text_type`. +//! - `bot` (`bot`): normalized only for emitted rows. UTF-8 `String` (verbatim), `Int32`/`Int64` +//! rendered as decimal, `Boolean` mapped to `"1"` / `"0"`, absent or `Null` -> `None`; any +//! other BSON type -> `None` and increments `nulled_wrong_type_bot`. +//! - `user_id` (`userId`): normalized only for emitted rows. UTF-8 `String` (verbatim), +//! `Int32`/`Int64` rendered as decimal, absent or `Null` -> `None`; any other BSON type -> +//! `None` and increments `nulled_wrong_type_user_id`. +//! - Deterministic semantic skip priority: `key` → `spiel_id` → `timestamp` → `edited` → `text`. +//! - Emitted-row counters (`edited_zero_or_false`, `nulled_wrong_type_bot`, +//! `nulled_wrong_type_user_id`, `empty_text`) are incremented only on rows that pass all skip +//! checks and are emitted to `on_row`. +//! - Conservation invariant: `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, BsonEodPriceError}; +use crate::posts::CeoPost; + +/// Default BSON field name for the `ceoPosts` channel / security key (`get-posts.action.ts`). +pub const DEFAULT_KEY_FIELD: &str = "ceoId"; +/// Default BSON field name for the `ceoPosts` post identifier (`get-posts.action.ts`). +pub const DEFAULT_SPIEL_ID_FIELD: &str = "spielId"; +/// Default BSON field name for the `ceoPosts` creation timestamp (`get-posts.action.ts`). +pub const DEFAULT_TIMESTAMP_FIELD: &str = "timestamp"; +/// Default BSON field name for the `ceoPosts` last-edit timestamp (`get-posts.action.ts`). +pub const DEFAULT_EDITED_FIELD: &str = "edited"; +/// Default BSON field name for the `ceoPosts` bot/newswire flag (`get-posts.action.ts`). +pub const DEFAULT_BOT_FIELD: &str = "bot"; +/// Default BSON field name for the `ceoPosts` author identifier (`get-posts.action.ts`). +pub const DEFAULT_USER_ID_FIELD: &str = "userId"; +/// Default BSON field name for the `ceoPosts` post body (`get-posts.action.ts`). +pub const DEFAULT_TEXT_FIELD: &str = "spiel"; + +/// Explicit numeric timestamp unit for `ceoPosts` `timestamp` and `edited` fields. +/// +/// Intentionally has no `Default`: the live MongoDB unit is unverified in the repository, so +/// callers must choose explicitly. BSON `DateTime` values are always epoch milliseconds and ignore +/// this setting. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CeoPostsTimestampUnit { + /// Numeric `timestamp` / `edited` values are Unix epoch seconds (multiplied by `1_000`). + Seconds, + /// Numeric `timestamp` / `edited` values are Unix epoch milliseconds. + Millis, +} + +/// Borrowed BSON field-name configuration for decoding `ceoPosts` documents. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CeoPostsFieldNames<'a> { + pub key: &'a str, + pub spiel_id: &'a str, + pub timestamp: &'a str, + pub edited: &'a str, + pub bot: &'a str, + pub user_id: &'a str, + pub text: &'a str, +} + +impl Default for CeoPostsFieldNames<'static> { + fn default() -> Self { + Self { + key: DEFAULT_KEY_FIELD, + spiel_id: DEFAULT_SPIEL_ID_FIELD, + timestamp: DEFAULT_TIMESTAMP_FIELD, + edited: DEFAULT_EDITED_FIELD, + bot: DEFAULT_BOT_FIELD, + user_id: DEFAULT_USER_ID_FIELD, + text: DEFAULT_TEXT_FIELD, + } + } +} + +impl<'a> CeoPostsFieldNames<'a> { + /// Validates that every configured field name is non-empty/non-blank and that no two + /// configured roles point to the same BSON field name. + pub fn validate(&self) -> Result<(), BsonCeoPostsError> { + let roles: [(&'static str, &str); 7] = [ + ("key", self.key), + ("spiel_id", self.spiel_id), + ("timestamp", self.timestamp), + ("edited", self.edited), + ("bot", self.bot), + ("user_id", self.user_id), + ("text", self.text), + ]; + + for &(role, name) in &roles { + if name.trim().is_empty() { + return Err(BsonCeoPostsError::InvalidFieldNames { + detail: format!("field name for '{role}' must not be empty or blank"), + }); + } + } + + for i in 0..roles.len() { + let (role_a, name_a) = roles[i]; + for &(role_b, name_b) in &roles[i + 1..] { + if name_a == name_b { + return Err(BsonCeoPostsError::InvalidFieldNames { + detail: format!( + "roles '{role_a}' and '{role_b}' cannot share BSON field '{name_a}'" + ), + }); + } + } + } + + Ok(()) + } +} + +/// Typed errors returned while validating field configuration or decoding raw `ceoPosts` 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 BsonCeoPostsError { + /// Invalid [`CeoPostsFieldNames`] configuration (empty/blank name or duplicate role mapping). + InvalidFieldNames { detail: String }, + /// Buffer ended before a complete 4-byte length prefix or declared document body. + TruncatedDocument { + offset: u64, + remaining: usize, + declared_len: Option, + }, + /// 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 BsonCeoPostsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidFieldNames { detail } => { + write!(f, "invalid ceoPosts field 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 BsonCeoPostsError {} + +#[inline] +fn map_framing_error(err: BsonEodPriceError) -> BsonCeoPostsError { + match err { + BsonEodPriceError::TruncatedDocument { + offset, + remaining, + declared_len, + } => BsonCeoPostsError::TruncatedDocument { + offset: offset as u64, + remaining, + declared_len, + }, + BsonEodPriceError::CorruptDocumentLength { + offset, + declared_len, + } => BsonCeoPostsError::CorruptDocumentLength { + offset: offset as u64, + declared_len, + }, + BsonEodPriceError::CorruptBson { offset, detail } => BsonCeoPostsError::CorruptBson { + offset: offset as u64, + detail, + }, + other => BsonCeoPostsError::CorruptBson { + offset: 0, + detail: other.to_string(), + }, + } +} + +/// Per-batch decode accounting for `ceoPosts`. +/// +/// Conservation invariant: +/// `docs_in == rows_out + skipped_total()` +/// +/// Emitted-row counters (`edited_zero_or_false`, `nulled_wrong_type_bot`, +/// `nulled_wrong_type_user_id`, `empty_text`) are incremented only for emitted rows and are +/// excluded from [`Self::skipped_total`]. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BsonCeoPostsDecodeStats { + 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_spiel_id: usize, + pub skipped_wrong_spiel_id_type: usize, + pub skipped_empty_spiel_id: usize, + pub skipped_missing_timestamp: usize, + pub skipped_wrong_timestamp_type: usize, + pub skipped_invalid_timestamp: usize, + pub skipped_timestamp_out_of_range: usize, + pub skipped_invalid_edited: usize, + pub skipped_wrong_text_type: usize, + pub edited_zero_or_false: usize, + pub nulled_wrong_type_bot: usize, + pub nulled_wrong_type_user_id: usize, + pub empty_text: usize, +} + +impl BsonCeoPostsDecodeStats { + /// Total number of semantically skipped 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_spiel_id + + self.skipped_wrong_spiel_id_type + + self.skipped_empty_spiel_id + + self.skipped_missing_timestamp + + self.skipped_wrong_timestamp_type + + self.skipped_invalid_timestamp + + self.skipped_timestamp_out_of_range + + self.skipped_invalid_edited + + self.skipped_wrong_text_type + } + + /// 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_spiel_id += other.skipped_missing_spiel_id; + self.skipped_wrong_spiel_id_type += other.skipped_wrong_spiel_id_type; + self.skipped_empty_spiel_id += other.skipped_empty_spiel_id; + self.skipped_missing_timestamp += other.skipped_missing_timestamp; + self.skipped_wrong_timestamp_type += other.skipped_wrong_timestamp_type; + self.skipped_invalid_timestamp += other.skipped_invalid_timestamp; + self.skipped_timestamp_out_of_range += other.skipped_timestamp_out_of_range; + self.skipped_invalid_edited += other.skipped_invalid_edited; + self.skipped_wrong_text_type += other.skipped_wrong_text_type; + self.edited_zero_or_false += other.edited_zero_or_false; + self.nulled_wrong_type_bot += other.nulled_wrong_type_bot; + self.nulled_wrong_type_user_id += other.nulled_wrong_type_user_id; + self.empty_text += other.empty_text; + } +} + +impl std::ops::AddAssign for BsonCeoPostsDecodeStats { + #[inline] + fn add_assign(&mut self, rhs: Self) { + self.merge(&rhs); + } +} + +enum KeyState<'a> { + Missing, + WrongType, + Empty, + Valid(&'a str), +} + +enum SpielIdState<'a> { + Missing, + WrongType, + Empty, + Str(&'a str), + Int32(i32), + Int64(i64), +} + +enum TimestampState { + Missing, + WrongType, + Invalid, + OutOfRange, + Valid(i64), +} + +enum EditedState { + Absent, + Null, + ZeroOrFalse, + Valid(i64), + Invalid, +} + +enum TextState<'a> { + MissingOrNull, + WrongType, + Str(&'a str), +} + +enum BotState<'a> { + None, + WrongType, + Str(&'a str), + Int32(i32), + Int64(i64), + Bool(bool), +} + +enum UserIdState<'a> { + None, + WrongType, + Str(&'a str), + Int32(i32), + Int64(i64), +} + +#[inline] +fn scale_numeric_timestamp(raw: i64, unit: CeoPostsTimestampUnit) -> TimestampState { + match unit { + CeoPostsTimestampUnit::Millis => TimestampState::Valid(raw), + CeoPostsTimestampUnit::Seconds => match raw.checked_mul(1_000) { + Some(ms) => TimestampState::Valid(ms), + None => TimestampState::OutOfRange, + }, + } +} + +#[inline] +fn decode_timestamp_val(val: RawBsonRef<'_>, unit: CeoPostsTimestampUnit) -> TimestampState { + match val { + RawBsonRef::DateTime(dt) => TimestampState::Valid(dt.timestamp_millis()), + RawBsonRef::Int32(v) => scale_numeric_timestamp(i64::from(v), unit), + RawBsonRef::Int64(v) => scale_numeric_timestamp(v, unit), + RawBsonRef::Double(v) => { + if !v.is_finite() || v.fract() != 0.0 { + return TimestampState::Invalid; + } + // Exact half-open range of `f64` values representable as `i64` (`[-2^63, 2^63)`). + if !(-9_223_372_036_854_775_808.0..9_223_372_036_854_775_808.0).contains(&v) { + return TimestampState::OutOfRange; + } + scale_numeric_timestamp(v as i64, unit) + } + _ => TimestampState::WrongType, + } +} + +#[inline] +fn decode_edited_val(val: RawBsonRef<'_>, unit: CeoPostsTimestampUnit) -> EditedState { + match val { + RawBsonRef::Null => EditedState::Null, + RawBsonRef::Boolean(false) => EditedState::ZeroOrFalse, + RawBsonRef::Boolean(true) => EditedState::Invalid, + RawBsonRef::DateTime(dt) => { + let ms = dt.timestamp_millis(); + if ms < 0 { + EditedState::Invalid + } else { + // Epoch-zero BSON DateTime is a timestamp, not the numeric `0` sentinel. + EditedState::Valid(ms) + } + } + RawBsonRef::Int32(_) | RawBsonRef::Int64(_) | RawBsonRef::Double(_) => { + match decode_timestamp_val(val, unit) { + TimestampState::Valid(0) => EditedState::ZeroOrFalse, + TimestampState::Valid(ms) if ms > 0 => EditedState::Valid(ms), + TimestampState::Valid(_) + | TimestampState::Invalid + | TimestampState::OutOfRange + | TimestampState::WrongType + | TimestampState::Missing => EditedState::Invalid, + } + } + _ => EditedState::Invalid, + } +} + +#[inline] +fn decode_spiel_id_val(val: RawBsonRef<'_>) -> SpielIdState<'_> { + match val { + RawBsonRef::String(s) => { + if s.trim().is_empty() { + SpielIdState::Empty + } else { + SpielIdState::Str(s) + } + } + RawBsonRef::Int32(v) => SpielIdState::Int32(v), + RawBsonRef::Int64(v) => SpielIdState::Int64(v), + _ => SpielIdState::WrongType, + } +} + +#[inline] +fn decode_bot_val(val: RawBsonRef<'_>) -> BotState<'_> { + match val { + RawBsonRef::Null => BotState::None, + RawBsonRef::String(s) => BotState::Str(s), + RawBsonRef::Int32(v) => BotState::Int32(v), + RawBsonRef::Int64(v) => BotState::Int64(v), + RawBsonRef::Boolean(b) => BotState::Bool(b), + _ => BotState::WrongType, + } +} + +#[inline] +fn decode_user_id_val(val: RawBsonRef<'_>) -> UserIdState<'_> { + match val { + RawBsonRef::Null => UserIdState::None, + RawBsonRef::String(s) => UserIdState::Str(s), + RawBsonRef::Int32(v) => UserIdState::Int32(v), + RawBsonRef::Int64(v) => UserIdState::Int64(v), + _ => UserIdState::WrongType, + } +} + +#[inline] +fn decode_text_val(val: RawBsonRef<'_>) -> TextState<'_> { + match val { + RawBsonRef::Null => TextState::MissingOrNull, + RawBsonRef::String(s) => TextState::Str(s), + _ => TextState::WrongType, + } +} + +/// 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<(), BsonCeoPostsError> { + 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(BsonCeoPostsError::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| BsonCeoPostsError::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(BsonCeoPostsError::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| BsonCeoPostsError::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<(), BsonCeoPostsError> { + if depth > MAX_BSON_VALIDATION_DEPTH { + return Err(BsonCeoPostsError::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| BsonCeoPostsError::CorruptBson { + offset: doc_offset, + detail: format!("field '{field_name}': {err}"), + })?; + let val = elem.value().map_err(|err| BsonCeoPostsError::CorruptBson { + offset: doc_offset, + detail: format!("field '{field_name}': {err}"), + })?; + validate_raw_bson_value(val, doc_offset, field_name, depth)?; + } + Ok(()) +} + +fn decode_ceo_posts_doc_at<'a, F>( + doc: &'a RawDocument, + doc_offset: u64, + fields: &CeoPostsFieldNames<'_>, + unit: CeoPostsTimestampUnit, + mut on_row: F, +) -> Result +where + F: FnMut(CeoPost<&'a str>), +{ + let mut stats = BsonCeoPostsDecodeStats { + docs_in: 1, + ..BsonCeoPostsDecodeStats::default() + }; + + let mut key_state = KeyState::Missing; + let mut spiel_id_state = SpielIdState::Missing; + let mut timestamp_state = TimestampState::Missing; + let mut edited_state = EditedState::Absent; + let mut bot_state = BotState::None; + let mut user_id_state = UserIdState::None; + let mut text_state = TextState::MissingOrNull; + + // Scan and validate every element and nested raw value to completion so structural BSON + // corruption (including invalid UTF-8 in unused fields or malformed nested documents/arrays) + // always fails closed and is never masked by an earlier semantic skip. + for elem_res in doc.iter_elements() { + let elem = elem_res.map_err(|err| BsonCeoPostsError::CorruptBson { + offset: doc_offset, + detail: err.to_string(), + })?; + let name = elem.key().as_str(); + let val = elem.value().map_err(|err| BsonCeoPostsError::CorruptBson { + offset: doc_offset, + detail: format!("field '{name}': {err}"), + })?; + validate_raw_bson_value(val, doc_offset, name, 0)?; + + if name == fields.key { + key_state = match val { + RawBsonRef::String(s) => { + if s.trim().is_empty() { + KeyState::Empty + } else { + KeyState::Valid(s) + } + } + _ => KeyState::WrongType, + }; + } else if name == fields.spiel_id { + spiel_id_state = decode_spiel_id_val(val); + } else if name == fields.timestamp { + timestamp_state = decode_timestamp_val(val, unit); + } else if name == fields.edited { + // Fail closed on repeated `edited` fields so a later value (e.g. Null) can never + // mask an earlier unreadable or later edit timestamp. + edited_state = if matches!(edited_state, EditedState::Absent) { + decode_edited_val(val, unit) + } else { + EditedState::Invalid + }; + } else if name == fields.bot { + bot_state = decode_bot_val(val); + } else if name == fields.user_id { + user_id_state = decode_user_id_val(val); + } else if name == fields.text { + text_state = decode_text_val(val); + } + } + + // Apply deterministic semantic skip priority: key -> spiel_id -> timestamp -> edited -> text. + let key = match key_state { + KeyState::Valid(s) => s, + KeyState::Missing => { + stats.skipped_missing_key += 1; + return Ok(stats); + } + KeyState::WrongType => { + stats.skipped_wrong_key_type += 1; + return Ok(stats); + } + KeyState::Empty => { + stats.skipped_empty_key += 1; + return Ok(stats); + } + }; + + match spiel_id_state { + SpielIdState::Str(_) | SpielIdState::Int32(_) | SpielIdState::Int64(_) => {} + SpielIdState::Missing => { + stats.skipped_missing_spiel_id += 1; + return Ok(stats); + } + SpielIdState::WrongType => { + stats.skipped_wrong_spiel_id_type += 1; + return Ok(stats); + } + SpielIdState::Empty => { + stats.skipped_empty_spiel_id += 1; + return Ok(stats); + } + } + + let timestamp_ms = match timestamp_state { + TimestampState::Valid(ms) => ms, + TimestampState::Missing => { + stats.skipped_missing_timestamp += 1; + return Ok(stats); + } + TimestampState::WrongType => { + stats.skipped_wrong_timestamp_type += 1; + return Ok(stats); + } + TimestampState::Invalid => { + stats.skipped_invalid_timestamp += 1; + return Ok(stats); + } + TimestampState::OutOfRange => { + stats.skipped_timestamp_out_of_range += 1; + return Ok(stats); + } + }; + + let (edited_ms, edited_is_zero_or_false) = match edited_state { + EditedState::Absent | EditedState::Null => (None, false), + EditedState::ZeroOrFalse => (None, true), + EditedState::Valid(ms) => (Some(ms), false), + EditedState::Invalid => { + stats.skipped_invalid_edited += 1; + return Ok(stats); + } + }; + + let (text, text_is_empty) = match text_state { + TextState::Str(s) => (s.to_owned(), false), + TextState::MissingOrNull => (String::new(), true), + TextState::WrongType => { + stats.skipped_wrong_text_type += 1; + return Ok(stats); + } + }; + + // Row passed all skip checks: record emitted-row counters and allocate owned fields. + if edited_is_zero_or_false { + stats.edited_zero_or_false += 1; + } + if text_is_empty { + stats.empty_text += 1; + } + + let spiel_id = match spiel_id_state { + SpielIdState::Str(s) => s.to_owned(), + SpielIdState::Int32(v) => v.to_string(), + SpielIdState::Int64(v) => v.to_string(), + SpielIdState::Missing | SpielIdState::WrongType | SpielIdState::Empty => { + unreachable!("validated above") + } + }; + + let bot = match bot_state { + BotState::None => None, + BotState::Str(s) => Some(s.to_owned()), + BotState::Int32(v) => Some(v.to_string()), + BotState::Int64(v) => Some(v.to_string()), + BotState::Bool(true) => Some("1".to_owned()), + BotState::Bool(false) => Some("0".to_owned()), + BotState::WrongType => { + stats.nulled_wrong_type_bot += 1; + None + } + }; + + let user_id = match user_id_state { + UserIdState::None => None, + UserIdState::Str(s) => Some(s.to_owned()), + UserIdState::Int32(v) => Some(v.to_string()), + UserIdState::Int64(v) => Some(v.to_string()), + UserIdState::WrongType => { + stats.nulled_wrong_type_user_id += 1; + None + } + }; + + stats.rows_out += 1; + on_row(CeoPost { + key, + spiel_id, + timestamp_ms, + edited_ms, + bot, + user_id, + text, + }); + Ok(stats) +} + +/// Decodes a single `&RawDocument` representing a `ceoPosts` MongoDB document in one forward pass +/// without allocating a `bson::Document`. +/// +/// Validates `fields` before inspecting the document. +pub fn decode_ceo_posts_doc<'a, F>( + doc: &'a RawDocument, + fields: &CeoPostsFieldNames<'_>, + unit: CeoPostsTimestampUnit, + on_row: F, +) -> Result +where + F: FnMut(CeoPost<&'a str>), +{ + fields.validate()?; + decode_ceo_posts_doc_at(doc, 0, fields, unit, on_row) +} + +/// Decodes a single length-prefixed raw BSON document byte slice representing a `ceoPosts` +/// document. +/// +/// Validates `fields` before inspecting the bytes. +pub fn decode_ceo_posts_bytes<'a, F>( + bytes: &'a [u8], + fields: &CeoPostsFieldNames<'_>, + unit: CeoPostsTimestampUnit, + on_row: F, +) -> Result +where + F: FnMut(CeoPost<&'a str>), +{ + fields.validate()?; + let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?; + decode_ceo_posts_doc_at(doc, 0, fields, unit, on_row) +} + +/// Streams a concatenated length-prefixed BSON buffer through [`decode_ceo_posts_doc`], +/// emitting every valid [`CeoPost<&str>`] to `on_row` and failing closed on the first structural +/// BSON framing or element corruption. +/// +/// Validates `fields` 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. +/// +/// Always maintains `stats.docs_in == stats.rows_out + stats.skipped_total()`. +pub fn decode_ceo_posts_buffer<'a, F>( + buf: &'a [u8], + fields: &CeoPostsFieldNames<'_>, + unit: CeoPostsTimestampUnit, + mut on_row: F, +) -> Result +where + F: FnMut(CeoPost<&'a str>), +{ + fields.validate()?; + let mut total = BsonCeoPostsDecodeStats::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_ceo_posts_doc_at(doc, offset as u64, fields, unit, &mut on_row)?; + total += doc_stats; + } + Err((_, err)) => return Err(map_framing_error(err)), + } + } + Ok(total) +} + +#[cfg(test)] +#[path = "bson_ceo_posts_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/bson_ceo_posts_tests.rs b/tools/curate-etl/src/bson_ceo_posts_tests.rs new file mode 100644 index 00000000..abd8a6cd --- /dev/null +++ b/tools/curate-etl/src/bson_ceo_posts_tests.rs @@ -0,0 +1,1453 @@ +use bson::raw::{cstr, RawArrayBuf, RawBson, RawDocument, RawDocumentBuf}; +use bson::DateTime as BsonDateTime; + +use super::*; +use crate::posts::build_posts; + +fn assert_conservation(stats: &BsonCeoPostsDecodeStats) { + assert_eq!( + stats.docs_in, + stats.rows_out + stats.skipped_total(), + "conservation invariant failed: {stats:?}" + ); +} + +fn make_base_doc(key: &str, spiel_id: &str, ts_secs: i64) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("ceoId"), key); + doc.append(cstr!("spielId"), spiel_id); + doc.append(cstr!("timestamp"), ts_secs); + doc.append(cstr!("spiel"), "hello world"); + doc +} + +#[test] +fn validates_field_names_rejecting_empty_blank_and_duplicates() { + let defaults = CeoPostsFieldNames::default(); + assert_eq!(defaults.key, DEFAULT_KEY_FIELD); + assert_eq!(defaults.spiel_id, DEFAULT_SPIEL_ID_FIELD); + assert_eq!(defaults.timestamp, DEFAULT_TIMESTAMP_FIELD); + assert_eq!(defaults.edited, DEFAULT_EDITED_FIELD); + assert_eq!(defaults.bot, DEFAULT_BOT_FIELD); + assert_eq!(defaults.user_id, DEFAULT_USER_ID_FIELD); + assert_eq!(defaults.text, DEFAULT_TEXT_FIELD); + assert!(defaults.validate().is_ok()); + + let custom = CeoPostsFieldNames { + key: "channel", + spiel_id: "postId", + timestamp: "createdAt", + edited: "updatedAt", + bot: "isBot", + user_id: "authorId", + text: "body", + }; + assert!(custom.validate().is_ok()); + + let bad_configs = [ + CeoPostsFieldNames { + key: "", + ..defaults + }, + CeoPostsFieldNames { + key: " \t ", + ..defaults + }, + CeoPostsFieldNames { + spiel_id: "", + ..defaults + }, + CeoPostsFieldNames { + timestamp: " ", + ..defaults + }, + CeoPostsFieldNames { + edited: "", + ..defaults + }, + CeoPostsFieldNames { + bot: " ", + ..defaults + }, + CeoPostsFieldNames { + user_id: "", + ..defaults + }, + CeoPostsFieldNames { + text: "\t", + ..defaults + }, + // Duplicate role mappings + CeoPostsFieldNames { + key: "dup", + spiel_id: "dup", + ..defaults + }, + CeoPostsFieldNames { + timestamp: "edited", + ..defaults + }, + CeoPostsFieldNames { + bot: "userId", + ..defaults + }, + CeoPostsFieldNames { + text: "ceoId", + ..defaults + }, + ]; + + let empty_doc = RawDocumentBuf::new(); + + for cfg in bad_configs { + let err = cfg.validate().unwrap_err(); + assert!( + matches!(err, BsonCeoPostsError::InvalidFieldNames { .. }), + "expected InvalidFieldNames for {cfg:?}, got {err:?}" + ); + let msg = err.to_string(); + assert!(!msg.contains('\n'), "single-line display expected: {msg}"); + + // All three entry points validate config before touching bytes/docs. + assert!(matches!( + decode_ceo_posts_buffer(&[], &cfg, CeoPostsTimestampUnit::Seconds, |_| {}), + Err(BsonCeoPostsError::InvalidFieldNames { .. }) + )); + assert!(matches!( + decode_ceo_posts_bytes(&[], &cfg, CeoPostsTimestampUnit::Millis, |_| {}), + Err(BsonCeoPostsError::InvalidFieldNames { .. }) + )); + assert!(matches!( + decode_ceo_posts_doc( + empty_doc.as_ref(), + &cfg, + CeoPostsTimestampUnit::Seconds, + |_| {} + ), + Err(BsonCeoPostsError::InvalidFieldNames { .. }) + )); + } +} + +#[test] +fn decodes_timestamp_and_edited_across_types_under_seconds_and_millis() { + let fields = CeoPostsFieldNames::default(); + let ts_sec_i32: i32 = 1_710_460_800; // 2024-03-15T00:00:00Z + let ed_sec_i32: i32 = 1_710_461_400; // +600s + let ts_sec_i64: i64 = 1_710_460_900; + let ed_sec_i64: i64 = 1_710_461_900; + let ts_dt_ms: i64 = 1_710_460_800_123; + let ed_dt_ms: i64 = 1_710_461_400_456; + + // --- Seconds unit --- + let mut sec_buf = Vec::new(); + + // 1. Int32 timestamp + Int32 edited + let mut d1 = RawDocumentBuf::new(); + d1.append(cstr!("ceoId"), " CH-1 "); // verbatim + d1.append(cstr!("spielId"), "s1"); + d1.append(cstr!("timestamp"), ts_sec_i32); + d1.append(cstr!("edited"), ed_sec_i32); + d1.append(cstr!("spiel"), "int32"); + sec_buf.extend_from_slice(d1.as_bytes()); + + // 2. Int64 timestamp + Int64 edited + let mut d2 = RawDocumentBuf::new(); + d2.append(cstr!("ceoId"), "CH-2"); + d2.append(cstr!("spielId"), 200_i32); + d2.append(cstr!("timestamp"), ts_sec_i64); + d2.append(cstr!("edited"), ed_sec_i64); + d2.append(cstr!("spiel"), "int64"); + sec_buf.extend_from_slice(d2.as_bytes()); + + // 3. Integral Double timestamp + integral Double edited + let mut d3 = RawDocumentBuf::new(); + d3.append(cstr!("ceoId"), "CH-3"); + d3.append(cstr!("spielId"), 300_i64); + d3.append(cstr!("timestamp"), ts_sec_i64 as f64); + d3.append(cstr!("edited"), ed_sec_i64 as f64); + d3.append(cstr!("spiel"), "double"); + sec_buf.extend_from_slice(d3.as_bytes()); + + // 4. BSON DateTime (already ms; unit ignored) + let mut d4 = RawDocumentBuf::new(); + d4.append(cstr!("ceoId"), "CH-4"); + d4.append(cstr!("spielId"), "s4"); + d4.append(cstr!("timestamp"), BsonDateTime::from_millis(ts_dt_ms)); + d4.append(cstr!("edited"), BsonDateTime::from_millis(ed_dt_ms)); + d4.append(cstr!("spiel"), "datetime"); + sec_buf.extend_from_slice(d4.as_bytes()); + + // 5. Non-positive creation times (<= 0) passed through verbatim (build_posts rejects them) + let mut d5 = RawDocumentBuf::new(); + d5.append(cstr!("ceoId"), "CH-5"); + d5.append(cstr!("spielId"), "s5"); + d5.append(cstr!("timestamp"), 0_i32); + d5.append(cstr!("spiel"), "zero"); + sec_buf.extend_from_slice(d5.as_bytes()); + + let mut d6 = RawDocumentBuf::new(); + d6.append(cstr!("ceoId"), "CH-6"); + d6.append(cstr!("spielId"), "s6"); + d6.append(cstr!("timestamp"), -10_i64); + d6.append(cstr!("spiel"), "neg"); + sec_buf.extend_from_slice(d6.as_bytes()); + + let mut d7 = RawDocumentBuf::new(); + d7.append(cstr!("ceoId"), "CH-7"); + d7.append(cstr!("spielId"), "s7"); + d7.append(cstr!("timestamp"), -0.0_f64); + d7.append(cstr!("spiel"), "negzero"); + sec_buf.extend_from_slice(d7.as_bytes()); + + let buf_start = sec_buf.as_ptr() as usize; + let buf_end = buf_start + sec_buf.len(); + + let mut sec_rows = Vec::new(); + let stats = decode_ceo_posts_buffer(&sec_buf, &fields, CeoPostsTimestampUnit::Seconds, |r| { + // Verify zero-copy borrow: `key` points directly into `sec_buf`. + let key_ptr = r.key.as_ptr() as usize; + assert!( + key_ptr >= buf_start && key_ptr + r.key.len() <= buf_end, + "decoded key must borrow directly from input buffer" + ); + sec_rows.push(( + r.key.to_owned(), + r.spiel_id, + r.timestamp_ms, + r.edited_ms, + r.text, + )); + }) + .expect("decode seconds buffer"); + + assert_conservation(&stats); + assert_eq!(stats.docs_in, 7); + assert_eq!(stats.rows_out, 7); + assert_eq!( + sec_rows, + vec![ + ( + " CH-1 ".to_string(), + "s1".to_string(), + i64::from(ts_sec_i32) * 1_000, + Some(i64::from(ed_sec_i32) * 1_000), + "int32".to_string() + ), + ( + "CH-2".to_string(), + "200".to_string(), + ts_sec_i64 * 1_000, + Some(ed_sec_i64 * 1_000), + "int64".to_string() + ), + ( + "CH-3".to_string(), + "300".to_string(), + ts_sec_i64 * 1_000, + Some(ed_sec_i64 * 1_000), + "double".to_string() + ), + ( + "CH-4".to_string(), + "s4".to_string(), + ts_dt_ms, + Some(ed_dt_ms), + "datetime".to_string() + ), + ( + "CH-5".to_string(), + "s5".to_string(), + 0, + None, + "zero".to_string() + ), + ( + "CH-6".to_string(), + "s6".to_string(), + -10_000, + None, + "neg".to_string() + ), + ( + "CH-7".to_string(), + "s7".to_string(), + 0, + None, + "negzero".to_string() + ), + ] + ); + + // --- Millis unit --- + let mut ms_buf = Vec::new(); + + // Int32 millis + let mut m1 = RawDocumentBuf::new(); + m1.append(cstr!("ceoId"), "M1"); + m1.append(cstr!("spielId"), "m1"); + m1.append(cstr!("timestamp"), 1_000_000_i32); + m1.append(cstr!("edited"), 1_000_500_i32); + m1.append(cstr!("spiel"), "m1"); + ms_buf.extend_from_slice(m1.as_bytes()); + + // Int64 millis + let mut m2 = RawDocumentBuf::new(); + m2.append(cstr!("ceoId"), "M2"); + m2.append(cstr!("spielId"), "m2"); + m2.append(cstr!("timestamp"), ts_dt_ms); + m2.append(cstr!("edited"), ed_dt_ms); + m2.append(cstr!("spiel"), "m2"); + ms_buf.extend_from_slice(m2.as_bytes()); + + // Integral Double millis (including exact -2^63 and 2^63 - 1024 boundaries) + let mut m3 = RawDocumentBuf::new(); + m3.append(cstr!("ceoId"), "M3"); + m3.append(cstr!("spielId"), "m3"); + m3.append(cstr!("timestamp"), -9_223_372_036_854_775_808.0_f64); + m3.append(cstr!("edited"), 9_223_372_036_854_774_784.0_f64); + m3.append(cstr!("spiel"), "m3"); + ms_buf.extend_from_slice(m3.as_bytes()); + + // BSON DateTime under Millis (unchanged) + let mut m4 = RawDocumentBuf::new(); + m4.append(cstr!("ceoId"), "M4"); + m4.append(cstr!("spielId"), "m4"); + m4.append(cstr!("timestamp"), BsonDateTime::from_millis(ts_dt_ms)); + m4.append(cstr!("edited"), BsonDateTime::from_millis(ed_dt_ms)); + m4.append(cstr!("spiel"), "m4"); + ms_buf.extend_from_slice(m4.as_bytes()); + + let mut ms_rows = Vec::new(); + let ms_stats = decode_ceo_posts_buffer(&ms_buf, &fields, CeoPostsTimestampUnit::Millis, |r| { + ms_rows.push((r.spiel_id, r.timestamp_ms, r.edited_ms)); + }) + .expect("decode millis buffer"); + + assert_conservation(&ms_stats); + assert_eq!(ms_stats.docs_in, 4); + assert_eq!(ms_stats.rows_out, 4); + assert_eq!( + ms_rows, + vec![ + ("m1".to_string(), 1_000_000, Some(1_000_500)), + ("m2".to_string(), ts_dt_ms, Some(ed_dt_ms)), + ( + "m3".to_string(), + i64::MIN, + Some(9_223_372_036_854_774_784_i64) + ), + ("m4".to_string(), ts_dt_ms, Some(ed_dt_ms)), + ] + ); +} + +#[test] +fn skips_timestamp_seconds_overflow_and_double_range_boundaries() { + let fields = CeoPostsFieldNames::default(); + let mut buf = Vec::new(); + + // 1. Positive Int64 seconds overflow (i64::MAX / 1_000 + 1) + let mut d1 = RawDocumentBuf::new(); + d1.append(cstr!("ceoId"), "CH"); + d1.append(cstr!("spielId"), "ovf_pos"); + d1.append(cstr!("timestamp"), (i64::MAX / 1_000) + 1); + buf.extend_from_slice(d1.as_bytes()); + + // 2. Negative Int64 seconds overflow (i64::MIN / 1_000 - 1) + let mut d2 = RawDocumentBuf::new(); + d2.append(cstr!("ceoId"), "CH"); + d2.append(cstr!("spielId"), "ovf_neg"); + d2.append(cstr!("timestamp"), (i64::MIN / 1_000) - 1); + buf.extend_from_slice(d2.as_bytes()); + + // 3. Double exactly at 2^63 (outside half-open [-2^63, 2^63)) + let mut d3 = RawDocumentBuf::new(); + d3.append(cstr!("ceoId"), "CH"); + d3.append(cstr!("spielId"), "dbl_2p63"); + d3.append(cstr!("timestamp"), 9_223_372_036_854_775_808.0_f64); + buf.extend_from_slice(d3.as_bytes()); + + // 4. Double below -2^63 + let mut d4 = RawDocumentBuf::new(); + d4.append(cstr!("ceoId"), "CH"); + d4.append(cstr!("spielId"), "dbl_neg_oob"); + d4.append(cstr!("timestamp"), -1e20_f64); + buf.extend_from_slice(d4.as_bytes()); + + // 5. Double in i64 range but overflows when multiplied by 1_000 + let mut d5 = RawDocumentBuf::new(); + d5.append(cstr!("ceoId"), "CH"); + d5.append(cstr!("spielId"), "dbl_sec_ovf"); + d5.append(cstr!("timestamp"), 9_223_372_036_854_774_784.0_f64); + buf.extend_from_slice(d5.as_bytes()); + + let mut emitted = 0usize; + let stats = decode_ceo_posts_buffer(&buf, &fields, CeoPostsTimestampUnit::Seconds, |_| { + emitted += 1; + }) + .expect("decode overflow buffer"); + + assert_conservation(&stats); + assert_eq!(emitted, 0); + assert_eq!(stats.docs_in, 5); + assert_eq!(stats.skipped_timestamp_out_of_range, 5); + + // Under Millis, 2^63 is still out of range. + let stats_2p63 = decode_ceo_posts_bytes( + d3.as_bytes(), + &fields, + CeoPostsTimestampUnit::Millis, + |_| panic!("2^63 double must not emit"), + ) + .expect("decode 2^63 under millis"); + assert_eq!(stats_2p63.skipped_timestamp_out_of_range, 1); +} + +#[test] +fn edited_fail_closed_rule_and_sentinel_accounting() { + let fields = CeoPostsFieldNames::default(); + let ts_sec: i64 = 1_710_460_800; + + // --- Unedited & valid cases --- + let mut valid_buf = Vec::new(); + + // 1. Absent edited -> None (not counted in edited_zero_or_false) + valid_buf.extend_from_slice(make_base_doc("CH", "e_absent", ts_sec).as_bytes()); + + // 2. Null edited -> None (not counted in edited_zero_or_false) + let mut d = make_base_doc("CH", "e_null", ts_sec); + d.append(cstr!("edited"), RawBson::Null); + valid_buf.extend_from_slice(d.as_bytes()); + + // 3. Int32(0) -> None + edited_zero_or_false + let mut d = make_base_doc("CH", "e_i32_zero", ts_sec); + d.append(cstr!("edited"), 0_i32); + valid_buf.extend_from_slice(d.as_bytes()); + + // 4. Int64(0) -> None + edited_zero_or_false + let mut d = make_base_doc("CH", "e_i64_zero", ts_sec); + d.append(cstr!("edited"), 0_i64); + valid_buf.extend_from_slice(d.as_bytes()); + + // 5. Double(0.0) -> None + edited_zero_or_false + let mut d = make_base_doc("CH", "e_f64_zero", ts_sec); + d.append(cstr!("edited"), 0.0_f64); + valid_buf.extend_from_slice(d.as_bytes()); + + // 6. Double(-0.0) -> None + edited_zero_or_false + let mut d = make_base_doc("CH", "e_f64_neg_zero", ts_sec); + d.append(cstr!("edited"), -0.0_f64); + valid_buf.extend_from_slice(d.as_bytes()); + + // 7. Boolean(false) -> None + edited_zero_or_false + let mut d = make_base_doc("CH", "e_bool_false", ts_sec); + d.append(cstr!("edited"), false); + valid_buf.extend_from_slice(d.as_bytes()); + + // 8. Epoch-zero BSON DateTime -> Some(0) (not numeric zero sentinel) + let mut d = make_base_doc("CH", "e_dt_zero", ts_sec); + d.append(cstr!("edited"), BsonDateTime::from_millis(0)); + valid_buf.extend_from_slice(d.as_bytes()); + + let mut valid_out = Vec::new(); + let valid_stats = + decode_ceo_posts_buffer(&valid_buf, &fields, CeoPostsTimestampUnit::Seconds, |r| { + valid_out.push((r.spiel_id, r.edited_ms)); + }) + .expect("decode valid edited buffer"); + + assert_conservation(&valid_stats); + assert_eq!(valid_stats.docs_in, 8); + assert_eq!(valid_stats.rows_out, 8); + assert_eq!(valid_stats.skipped_invalid_edited, 0); + assert_eq!(valid_stats.edited_zero_or_false, 5); + assert_eq!( + valid_out, + vec![ + ("e_absent".to_string(), None), + ("e_null".to_string(), None), + ("e_i32_zero".to_string(), None), + ("e_i64_zero".to_string(), None), + ("e_f64_zero".to_string(), None), + ("e_f64_neg_zero".to_string(), None), + ("e_bool_false".to_string(), None), + ("e_dt_zero".to_string(), Some(0)), + ] + ); + + // --- Fail-closed rejected cases (must NEVER invoke on_row) --- + let mut bad_buf = Vec::new(); + + // 1. Negative Int32 + let mut d = make_base_doc("CH", "bad_neg_i32", ts_sec); + d.append(cstr!("edited"), -1_i32); + bad_buf.extend_from_slice(d.as_bytes()); + + // 2. Negative Int64 + let mut d = make_base_doc("CH", "bad_neg_i64", ts_sec); + d.append(cstr!("edited"), -5_000_i64); + bad_buf.extend_from_slice(d.as_bytes()); + + // 3. Negative Double + let mut d = make_base_doc("CH", "bad_neg_f64", ts_sec); + d.append(cstr!("edited"), -1.0_f64); + bad_buf.extend_from_slice(d.as_bytes()); + + // 4. Negative DateTime + let mut d = make_base_doc("CH", "bad_neg_dt", ts_sec); + d.append(cstr!("edited"), BsonDateTime::from_millis(-1)); + bad_buf.extend_from_slice(d.as_bytes()); + + // 5. Fractional Double + let mut d = make_base_doc("CH", "bad_frac", ts_sec); + d.append(cstr!("edited"), 1_710_461_400.5_f64); + bad_buf.extend_from_slice(d.as_bytes()); + + // 6. NaN Double + let mut d = make_base_doc("CH", "bad_nan", ts_sec); + d.append(cstr!("edited"), f64::NAN); + bad_buf.extend_from_slice(d.as_bytes()); + + // 7. +Inf Double + let mut d = make_base_doc("CH", "bad_inf", ts_sec); + d.append(cstr!("edited"), f64::INFINITY); + bad_buf.extend_from_slice(d.as_bytes()); + + // 8. Boolean(true) + let mut d = make_base_doc("CH", "bad_true", ts_sec); + d.append(cstr!("edited"), true); + bad_buf.extend_from_slice(d.as_bytes()); + + // 9. String + let mut d = make_base_doc("CH", "bad_str", ts_sec); + d.append(cstr!("edited"), "1710461400"); + bad_buf.extend_from_slice(d.as_bytes()); + + // 10. Unsupported type (embedded document) + let mut d = make_base_doc("CH", "bad_doc", ts_sec); + d.append(cstr!("edited"), RawDocumentBuf::new()); + bad_buf.extend_from_slice(d.as_bytes()); + + // 11. Seconds overflow + let mut d = make_base_doc("CH", "bad_ovf", ts_sec); + d.append(cstr!("edited"), (i64::MAX / 1_000) + 1); + bad_buf.extend_from_slice(d.as_bytes()); + + // 12. Repeated `edited` with unreadable value followed by Null (must fail closed!) + let mut d = make_base_doc("CH", "bad_dup_unreadable_then_null", ts_sec); + d.append(cstr!("edited"), "unreadable"); + d.append(cstr!("edited"), RawBson::Null); + bad_buf.extend_from_slice(d.as_bytes()); + + // 13. Repeated `edited` with valid timestamp followed by Null + let mut d = make_base_doc("CH", "bad_dup_valid_then_null", ts_sec); + d.append(cstr!("edited"), ts_sec + 60); + d.append(cstr!("edited"), RawBson::Null); + bad_buf.extend_from_slice(d.as_bytes()); + + // 14. Repeated `edited` with Null followed by valid timestamp + let mut d = make_base_doc("CH", "bad_dup_null_then_valid", ts_sec); + d.append(cstr!("edited"), RawBson::Null); + d.append(cstr!("edited"), ts_sec + 60); + bad_buf.extend_from_slice(d.as_bytes()); + + let mut bad_emitted = 0usize; + let bad_stats = + decode_ceo_posts_buffer(&bad_buf, &fields, CeoPostsTimestampUnit::Seconds, |_| { + bad_emitted += 1; + }) + .expect("decode bad edited buffer"); + + assert_conservation(&bad_stats); + assert_eq!(bad_emitted, 0); + assert_eq!(bad_stats.docs_in, 14); + assert_eq!(bad_stats.rows_out, 0); + assert_eq!(bad_stats.skipped_invalid_edited, 14); + assert_eq!(bad_stats.edited_zero_or_false, 0); +} + +#[test] +fn skips_every_counter_respects_priority_and_matches_single_doc_sum() { + let fields = CeoPostsFieldNames::default(); + let ts_sec: i64 = 1_710_460_800; + + let mut docs: Vec = Vec::new(); + + // 1. skipped_missing_key (also missing spiel_id, timestamp, bad edited, bad text -> key wins) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("spiel"), 123_i32); + d.append(cstr!("edited"), true); + docs.push(d); + + // 2. skipped_wrong_key_type (fields in reverse priority order -> key still wins) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("spiel"), 123_i32); + d.append(cstr!("edited"), "bad"); + d.append(cstr!("timestamp"), "bad"); + d.append(cstr!("spielId"), true); + d.append(cstr!("ceoId"), 42_i32); + docs.push(d); + + // 3. skipped_empty_key (with wrong-type optionals & zero edited -> emitted-row counters stay 0) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), " "); + d.append(cstr!("spielId"), "s3"); + d.append(cstr!("timestamp"), ts_sec); + d.append(cstr!("edited"), 0_i32); + d.append(cstr!("bot"), 1.5_f64); + d.append(cstr!("userId"), true); + docs.push(d); + + // 4. skipped_missing_spiel_id (also bad timestamp, edited, text -> spiel_id wins) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("spiel"), false); + d.append(cstr!("edited"), true); + d.append(cstr!("timestamp"), f64::NAN); + d.append(cstr!("ceoId"), "CH"); + docs.push(d); + + // 5. skipped_wrong_spiel_id_type + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), true); + d.append(cstr!("timestamp"), ts_sec); + docs.push(d); + + // 6. skipped_empty_spiel_id + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), " "); + d.append(cstr!("timestamp"), ts_sec); + docs.push(d); + + // 7. skipped_missing_timestamp (also bad edited & bad text -> timestamp wins) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("spiel"), 99_i32); + d.append(cstr!("edited"), "bad"); + d.append(cstr!("spielId"), "s7"); + d.append(cstr!("ceoId"), "CH"); + docs.push(d); + + // 8. skipped_wrong_timestamp_type + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), "s8"); + d.append(cstr!("timestamp"), "2024-03-15"); + docs.push(d); + + // 9. skipped_invalid_timestamp (fractional Double) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), "s9"); + d.append(cstr!("timestamp"), 1_710_460_800.25_f64); + docs.push(d); + + // 10. skipped_timestamp_out_of_range (Seconds overflow) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), "s10"); + d.append(cstr!("timestamp"), i64::MAX); + docs.push(d); + + // 11. skipped_invalid_edited (also bad text -> edited wins over text) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("spiel"), 99_i32); + d.append(cstr!("edited"), true); + d.append(cstr!("timestamp"), ts_sec); + d.append(cstr!("spielId"), "s11"); + d.append(cstr!("ceoId"), "CH"); + docs.push(d); + + // 12. skipped_wrong_text_type (with valid edited=0 and wrong-type bot/userId -> emitted counters stay 0) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), "s12"); + d.append(cstr!("timestamp"), ts_sec); + d.append(cstr!("edited"), false); + d.append(cstr!("bot"), 2.5_f64); + d.append(cstr!("userId"), true); + d.append(cstr!("spiel"), 123_i32); + docs.push(d); + + // 13. Valid emitted row with missing text, wrong-type bot & userId, edited=false + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), "ok1"); + d.append(cstr!("timestamp"), ts_sec); + d.append(cstr!("edited"), false); + d.append(cstr!("bot"), 2.5_f64); + d.append(cstr!("userId"), false); + docs.push(d); + + // 14. Valid emitted row with Null text, Int32 userId, String bot + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), "ok2"); + d.append(cstr!("timestamp"), ts_sec); + d.append(cstr!("bot"), "1"); + d.append(cstr!("userId"), 777_i32); + d.append(cstr!("spiel"), RawBson::Null); + docs.push(d); + + // 15. Valid emitted row with explicit empty string text (not counted in empty_text) and Int64 userId + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), "ok3"); + d.append(cstr!("timestamp"), ts_sec); + d.append(cstr!("bot"), 0_i64); + d.append(cstr!("userId"), 9_000_000_000_i64); + d.append(cstr!("spiel"), ""); + docs.push(d); + + let mut combined = Vec::new(); + let mut summed = BsonCeoPostsDecodeStats::default(); + for doc in &docs { + combined.extend_from_slice(doc.as_bytes()); + let single = decode_ceo_posts_doc( + doc.as_ref(), + &fields, + CeoPostsTimestampUnit::Seconds, + |_| {}, + ) + .expect("decode single doc"); + assert_conservation(&single); + summed += single; + } + + let mut emitted = Vec::new(); + let buf_stats = + decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { + emitted.push((r.spiel_id, r.bot, r.user_id, r.text)) + }) + .expect("decode combined buffer"); + + assert_conservation(&buf_stats); + assert_eq!(buf_stats, summed); + assert_eq!(buf_stats.docs_in, 15); + assert_eq!(buf_stats.rows_out, 3); + assert_eq!(buf_stats.skipped_total(), 12); + assert_eq!(buf_stats.skipped_missing_key, 1); + assert_eq!(buf_stats.skipped_wrong_key_type, 1); + assert_eq!(buf_stats.skipped_empty_key, 1); + assert_eq!(buf_stats.skipped_missing_spiel_id, 1); + assert_eq!(buf_stats.skipped_wrong_spiel_id_type, 1); + assert_eq!(buf_stats.skipped_empty_spiel_id, 1); + assert_eq!(buf_stats.skipped_missing_timestamp, 1); + assert_eq!(buf_stats.skipped_wrong_timestamp_type, 1); + assert_eq!(buf_stats.skipped_invalid_timestamp, 1); + assert_eq!(buf_stats.skipped_timestamp_out_of_range, 1); + assert_eq!(buf_stats.skipped_invalid_edited, 1); + assert_eq!(buf_stats.skipped_wrong_text_type, 1); + assert_eq!(buf_stats.edited_zero_or_false, 1); + assert_eq!(buf_stats.nulled_wrong_type_bot, 1); + assert_eq!(buf_stats.nulled_wrong_type_user_id, 1); + assert_eq!(buf_stats.empty_text, 2); + + assert_eq!( + emitted, + vec![ + ("ok1".to_string(), None, None, String::new()), + ( + "ok2".to_string(), + Some("1".to_string()), + Some("777".to_string()), + String::new() + ), + ( + "ok3".to_string(), + Some("0".to_string()), + Some("9000000000".to_string()), + String::new() + ), + ] + ); +} + +#[test] +fn decodes_custom_field_names_and_feeds_build_posts_deterministically() { + let fields = CeoPostsFieldNames { + key: "channelId", + spiel_id: "postId", + timestamp: "postedSec", + edited: "editedSec", + bot: "botFlag", + user_id: "author", + text: "body", + }; + + let t0_sec: i64 = 1_710_460_800; // 2024-03-15T00:00:00Z + let t_edit_sec: i64 = t0_sec + 900; // +15m + + let mut raw_docs: Vec = Vec::new(); + + // 1. bot = "1" (newswire, unedited baseline) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("channelId"), "CH-A"); + d.append(cstr!("postId"), "nw_str_1"); + d.append(cstr!("postedSec"), t0_sec); + d.append(cstr!("botFlag"), "1"); + d.append(cstr!("author"), "wire"); + d.append(cstr!("body"), "Press release"); + raw_docs.push(d); + + // 2. bot = Int32(1) (newswire, edited later -> known_at == edited_ms * 1_000) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("channelId"), "CH-A"); + d.append(cstr!("postId"), "nw_i32_1"); + d.append(cstr!("postedSec"), t0_sec + 10); + d.append(cstr!("editedSec"), t_edit_sec); + d.append(cstr!("botFlag"), 1_i32); + d.append(cstr!("author"), 42_i32); + d.append(cstr!("body"), "Corrected release"); + raw_docs.push(d); + + // 3. bot = Boolean(true) (newswire) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("channelId"), "CH-A"); + d.append(cstr!("postId"), "nw_bool_true"); + d.append(cstr!("postedSec"), t0_sec + 20); + d.append(cstr!("botFlag"), true); + d.append(cstr!("body"), "Auto alert"); + raw_docs.push(d); + + // 4. bot = "0" (retail) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("channelId"), "CH-A"); + d.append(cstr!("postId"), "ret_str_0"); + d.append(cstr!("postedSec"), t0_sec + 30); + d.append(cstr!("botFlag"), "0"); + d.append(cstr!("body"), "Retail chatter"); + raw_docs.push(d); + + // 5. bot absent (retail) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("channelId"), "CH-A"); + d.append(cstr!("postId"), "ret_absent"); + d.append(cstr!("postedSec"), t0_sec + 40); + d.append(cstr!("body"), "No bot field"); + raw_docs.push(d); + + // 6. bot wrong type (Double -> nulled -> retail) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("channelId"), "CH-A"); + d.append(cstr!("postId"), "ret_wrong_type"); + d.append(cstr!("postedSec"), t0_sec + 50); + d.append(cstr!("botFlag"), 1.0_f64); + d.append(cstr!("body"), "Wrong type bot"); + raw_docs.push(d); + + // 7. Non-positive creation time passed through by decoder, rejected by build_posts + let mut d = RawDocumentBuf::new(); + d.append(cstr!("channelId"), "CH-A"); + d.append(cstr!("postId"), "zero_ts"); + d.append(cstr!("postedSec"), 0_i64); + d.append(cstr!("body"), "Zero ts"); + raw_docs.push(d); + + let mut buf = Vec::new(); + for d in &raw_docs { + buf.extend_from_slice(d.as_bytes()); + } + + // Run through all three entry points and confirm identical decoded rows. + let mut rows_from_buffer = Vec::new(); + let stats_buf = decode_ceo_posts_buffer(&buf, &fields, CeoPostsTimestampUnit::Seconds, |r| { + rows_from_buffer.push(r); + }) + .expect("decode buffer"); + + let mut rows_from_bytes = Vec::new(); + let mut stats_bytes = BsonCeoPostsDecodeStats::default(); + for d in &raw_docs { + stats_bytes += + decode_ceo_posts_bytes(d.as_bytes(), &fields, CeoPostsTimestampUnit::Seconds, |r| { + rows_from_bytes.push(r) + }) + .expect("decode bytes"); + } + + let mut rows_from_doc = Vec::new(); + let mut stats_doc = BsonCeoPostsDecodeStats::default(); + for d in &raw_docs { + let raw_doc = RawDocument::from_bytes(d.as_bytes()).expect("valid raw doc"); + stats_doc += decode_ceo_posts_doc(raw_doc, &fields, CeoPostsTimestampUnit::Seconds, |r| { + rows_from_doc.push(r) + }) + .expect("decode doc"); + } + + assert_eq!(stats_buf, stats_bytes); + assert_eq!(stats_buf, stats_doc); + assert_eq!(stats_buf.nulled_wrong_type_bot, 1); + assert_eq!(rows_from_buffer, rows_from_bytes); + assert_eq!(rows_from_buffer, rows_from_doc); + + // Feed into `build_posts` twice and verify exact classification, known_at, and determinism. + let build1 = build_posts(rows_from_buffer.clone()).expect("build_posts run 1"); + let build2 = build_posts(rows_from_buffer).expect("build_posts run 2"); + assert_eq!(build1, build2); + + let newswire_ids: Vec<&str> = build1 + .newswire + .iter() + .map(|r| r.spiel_id.as_str()) + .collect(); + let retail_ids: Vec<&str> = build1.retail.iter().map(|r| r.spiel_id.as_str()).collect(); + assert_eq!(newswire_ids, vec!["nw_str_1", "nw_bool_true", "nw_i32_1"]); + assert_eq!( + retail_ids, + vec!["ret_str_0", "ret_absent", "ret_wrong_type"] + ); + assert_eq!(build1.stats.rejected_invalid, 1); + + // Baseline unedited post: known_at == posted_at. + let baseline = build1 + .newswire + .iter() + .find(|r| r.spiel_id == "nw_str_1") + .expect("baseline row"); + assert_eq!(baseline.posted_at, t0_sec * 1_000_000); + assert_eq!(baseline.known_at, baseline.posted_at); + assert!(!baseline.is_edited); + + // Edited post: known_at == edited_ms * 1_000 (UTC microseconds). + let edited = build1 + .newswire + .iter() + .find(|r| r.spiel_id == "nw_i32_1") + .expect("edited row"); + assert_eq!(edited.posted_at, (t0_sec + 10) * 1_000_000); + assert_eq!(edited.known_at, (t_edit_sec * 1_000) * 1_000); + assert!(edited.is_edited); + assert_eq!(edited.user_id.as_deref(), Some("42")); +} + +#[test] +fn framing_and_structural_corruption_fail_closed_with_exact_offsets() { + let fields = CeoPostsFieldNames::default(); + let ts_sec: i64 = 1_710_460_800; + + let good = make_base_doc("CH-OK", "ok_first", ts_sec); + let good_len = good.as_bytes().len() as u64; + + // 1. Truncated header (< 4 bytes) after one valid doc + let mut combined = good.as_bytes().to_vec(); + combined.extend_from_slice(&[0x10, 0x00]); + let mut emitted = Vec::new(); + let err = decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { + emitted.push(r.spiel_id); + }) + .unwrap_err(); + assert_eq!(emitted, vec!["ok_first".to_string()]); + assert_eq!( + err, + BsonCeoPostsError::TruncatedDocument { + offset: good_len, + remaining: 2, + declared_len: None, + } + ); + assert!(!err.to_string().contains('\n')); + + // 2. Truncated body after one valid doc + let mut combined = good.as_bytes().to_vec(); + combined.extend_from_slice(&[20, 0, 0, 0, 0, 0]); + let mut emitted = Vec::new(); + let err = decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { + emitted.push(r.spiel_id); + }) + .unwrap_err(); + assert_eq!(emitted, vec!["ok_first".to_string()]); + assert_eq!( + err, + BsonCeoPostsError::TruncatedDocument { + offset: good_len, + remaining: 6, + declared_len: Some(20), + } + ); + assert!(!err.to_string().contains('\n')); + + // 3. Declared length < 5 after one valid doc + let mut combined = good.as_bytes().to_vec(); + combined.extend_from_slice(&[3, 0, 0, 0, 0]); + let mut emitted = Vec::new(); + let err = decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { + emitted.push(r.spiel_id); + }) + .unwrap_err(); + assert_eq!(emitted, vec!["ok_first".to_string()]); + assert_eq!( + err, + BsonCeoPostsError::CorruptDocumentLength { + offset: good_len, + declared_len: 3, + } + ); + assert!(!err.to_string().contains('\n')); + + // 4. Malformed element AFTER a semantically invalid field (must not be masked by skip) + let mut bad_after_skip = RawDocumentBuf::new(); + bad_after_skip.append(cstr!("ceoId"), ""); // would be skipped_empty_key + bad_after_skip.append(cstr!("z"), 1_i32); + let mut bad_bytes = bad_after_skip.into_bytes(); + let z_pos = bad_bytes + .windows(3) + .position(|w| w == [0x10, b'z', 0x00]) + .expect("locate z element"); + bad_bytes[z_pos] = 0x7e; + + let mut combined = good.as_bytes().to_vec(); + combined.extend_from_slice(&bad_bytes); + let mut emitted = Vec::new(); + let err = decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { + emitted.push(r.spiel_id); + }) + .unwrap_err(); + assert_eq!(emitted, vec!["ok_first".to_string()]); + assert!( + matches!(err, BsonCeoPostsError::CorruptBson { offset, .. } if offset == good_len), + "expected CorruptBson at offset {good_len}, got {err:?}" + ); + assert!(!err.to_string().contains('\n')); + + // 5. Corruption inside an unused nested embedded document after one valid doc + let mut inner = RawDocumentBuf::new(); + inner.append(cstr!("nestedText"), "INNER!"); + let mut nested_bad = make_base_doc("CH-2", "nested_bad", ts_sec); + nested_bad.append(cstr!("poll"), inner); + let mut nested_bytes = nested_bad.into_bytes(); + let pos = nested_bytes + .windows(6) + .position(|w| w == b"INNER!") + .expect("locate INNER!"); + nested_bytes[pos] = 0xff; + + let mut combined = good.as_bytes().to_vec(); + combined.extend_from_slice(&nested_bytes); + let mut emitted = Vec::new(); + let err = decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { + emitted.push(r.spiel_id); + }) + .unwrap_err(); + assert_eq!(emitted, vec!["ok_first".to_string()]); + assert!( + matches!(err, BsonCeoPostsError::CorruptBson { offset, .. } if offset == good_len), + "expected CorruptBson for nested embedded doc at offset {good_len}, got {err:?}" + ); + + // 6. Corrupt array index inside an unused array after one valid doc + let mut arr = RawArrayBuf::new(); + arr.push(10_i32); + arr.push(20_i32); + let mut arr_bad = make_base_doc("CH-3", "arr_bad", ts_sec); + arr_bad.append(cstr!("votes"), arr); + let mut arr_bytes = arr_bad.into_bytes(); + let idx1 = arr_bytes + .windows(3) + .position(|w| w == [0x10, b'1', 0x00]) + .expect("locate index 1"); + arr_bytes[idx1 + 1] = b'2'; + + let mut combined = good.as_bytes().to_vec(); + combined.extend_from_slice(&arr_bytes); + let mut emitted = Vec::new(); + let err = decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { + emitted.push(r.spiel_id); + }) + .unwrap_err(); + assert_eq!(emitted, vec!["ok_first".to_string()]); + assert!( + matches!(err, BsonCeoPostsError::CorruptBson { offset, .. } if offset == good_len), + "expected CorruptBson for corrupt array index at offset {good_len}, got {err:?}" + ); + + // 7. Trailing bytes on decode_ceo_posts_bytes -> CorruptDocumentLength + let mut extra = good.as_bytes().to_vec(); + extra.push(0x00); + let err = decode_ceo_posts_bytes(&extra, &fields, CeoPostsTimestampUnit::Seconds, |_| {}) + .unwrap_err(); + assert!(matches!( + err, + BsonCeoPostsError::CorruptDocumentLength { .. } + )); +} + +// --------------------------------------------------------------------------- +// QA edge cases (T-160) +// --------------------------------------------------------------------------- + +fn decode_one_seconds_and_millis( + doc: &RawDocumentBuf, +) -> [(BsonCeoPostsDecodeStats, Vec>); 2] { + let fields = CeoPostsFieldNames::default(); + [ + CeoPostsTimestampUnit::Seconds, + CeoPostsTimestampUnit::Millis, + ] + .map(|unit| { + let mut rows = Vec::new(); + let stats = decode_ceo_posts_bytes(doc.as_bytes(), &fields, unit, |r| { + rows.push(CeoPost { + key: r.key.to_owned(), + spiel_id: r.spiel_id, + timestamp_ms: r.timestamp_ms, + edited_ms: r.edited_ms, + bot: r.bot, + user_id: r.user_id, + text: r.text, + }) + }) + .expect("decode single doc"); + assert_conservation(&stats); + (stats, rows) + }) +} + +#[test] +fn same_numeric_bytes_scale_by_unit_but_datetime_ignores_unit() { + // Arrange: numeric Int64 timestamp/edited and a DateTime doc. + let mut numeric = make_base_doc("CH", "n", 1_710_460_800); + numeric.append(cstr!("edited"), 1_710_461_400_i64); + let mut dt_doc = RawDocumentBuf::new(); + dt_doc.append(cstr!("ceoId"), "CH"); + dt_doc.append(cstr!("spielId"), "d"); + dt_doc.append( + cstr!("timestamp"), + BsonDateTime::from_millis(1_710_460_800_000), + ); + dt_doc.append( + cstr!("edited"), + BsonDateTime::from_millis(1_710_461_400_000), + ); + + // Act + let [(_, n_sec), (_, n_ms)] = decode_one_seconds_and_millis(&numeric); + let [(_, d_sec), (_, d_ms)] = decode_one_seconds_and_millis(&dt_doc); + + // Assert: numeric values differ by exactly 1000x; DateTime is identical under both units. + assert_eq!(n_sec[0].timestamp_ms, 1_710_460_800_000); + assert_eq!(n_sec[0].edited_ms, Some(1_710_461_400_000)); + assert_eq!(n_ms[0].timestamp_ms, 1_710_460_800); + assert_eq!(n_ms[0].edited_ms, Some(1_710_461_400)); + assert_eq!(d_sec, d_ms); + assert_eq!(d_sec[0].timestamp_ms, 1_710_460_800_000); + assert_eq!(d_sec[0].edited_ms, Some(1_710_461_400_000)); +} + +#[test] +fn edited_rejections_hold_under_millis_and_large_millis_values_do_not_overflow() { + // Negative/fractional/true/string edits must also fail closed under Millis. + let bad: Vec = vec![ + RawBson::Int32(-1), + RawBson::Int64(i64::MIN), + RawBson::Double(-0.5), + RawBson::Double(0.5), + RawBson::Double(f64::NEG_INFINITY), + RawBson::Boolean(true), + RawBson::String(String::new()), + RawBson::Double(9_223_372_036_854_775_808.0), + ]; + for value in bad { + let mut d = make_base_doc("CH", "x", 1_710_460_800_000); + d.append(cstr!("edited"), value.clone()); + let [_, (stats, rows)] = decode_one_seconds_and_millis(&d); + assert!( + rows.is_empty(), + "edited {value:?} must not emit under Millis" + ); + assert_eq!(stats.skipped_invalid_edited, 1, "edited {value:?}"); + } + + // A value that overflows under Seconds is valid under Millis. + let mut d = make_base_doc("CH", "big", 1); + d.append(cstr!("edited"), i64::MAX); + let [(sec_stats, sec_rows), (ms_stats, ms_rows)] = decode_one_seconds_and_millis(&d); + assert!(sec_rows.is_empty()); + assert_eq!(sec_stats.skipped_invalid_edited, 1); + assert_eq!(ms_stats.rows_out, 1); + assert_eq!(ms_rows[0].edited_ms, Some(i64::MAX)); +} + +#[test] +fn bot_and_user_id_normalization_covers_int64_false_null_and_verbatim_strings() { + let cases: Vec<(RawBson, Option<&str>, usize)> = vec![ + (RawBson::Int64(1), Some("1"), 0), + (RawBson::Int32(-7), Some("-7"), 0), + (RawBson::Boolean(false), Some("0"), 0), + (RawBson::Null, None, 0), + (RawBson::String(" 1 ".into()), Some(" 1 "), 0), + (RawBson::Document(RawDocumentBuf::new()), None, 1), + ]; + for (value, expected, nulled) in cases { + let mut d = make_base_doc("CH", "b", 1_710_460_800); + d.append(cstr!("bot"), value.clone()); + d.append(cstr!("userId"), value.clone()); + let [(stats, rows), _] = decode_one_seconds_and_millis(&d); + assert_eq!(stats.rows_out, 1, "bot {value:?}"); + assert_eq!(rows[0].bot.as_deref(), expected, "bot {value:?}"); + assert_eq!(stats.nulled_wrong_type_bot, nulled, "bot {value:?}"); + let expected_user = match value { + // Boolean is not an accepted user_id type. + RawBson::Boolean(_) => None, + _ => expected, + }; + let expected_user_nulled = usize::from(matches!(value, RawBson::Boolean(_))) + nulled; + assert_eq!( + rows[0].user_id.as_deref(), + expected_user, + "userId {value:?}" + ); + assert_eq!( + stats.nulled_wrong_type_user_id, expected_user_nulled, + "userId {value:?}" + ); + } +} + +#[test] +fn preserves_unicode_text_and_key_verbatim_and_key_borrows_from_single_doc_bytes() { + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "Ünïcødé-CH 📈"); + d.append(cstr!("spielId"), " s 1 "); + d.append(cstr!("timestamp"), 1_710_460_800_i64); + d.append(cstr!("spiel"), " $XYZ to the 🌕\nline2\t "); + let bytes = d.as_bytes(); + let (start, end) = ( + bytes.as_ptr() as usize, + bytes.as_ptr() as usize + bytes.len(), + ); + + let mut seen = Vec::new(); + decode_ceo_posts_bytes( + bytes, + &CeoPostsFieldNames::default(), + CeoPostsTimestampUnit::Seconds, + |r| { + let p = r.key.as_ptr() as usize; + assert!( + p >= start && p + r.key.len() <= end, + "key must borrow from input bytes" + ); + seen.push((r.key, r.spiel_id, r.text)); + }, + ) + .expect("decode"); + + assert_eq!( + seen, + vec![( + "Ünïcødé-CH 📈", + " s 1 ".to_string(), + " $XYZ to the 🌕\nline2\t ".to_string() + )] + ); +} + +#[test] +fn spiel_id_int64_extremes_render_as_decimal() { + for (value, expected) in [ + (RawBson::Int64(i64::MIN), i64::MIN.to_string()), + (RawBson::Int64(i64::MAX), i64::MAX.to_string()), + (RawBson::Int32(0), "0".to_string()), + ] { + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), value); + d.append(cstr!("timestamp"), 1_i64); + let [(_, rows), _] = decode_one_seconds_and_millis(&d); + assert_eq!(rows[0].spiel_id, expected); + } +} + +#[test] +fn invalid_utf8_in_unused_or_key_field_is_corrupt_bson_not_a_skip() { + let fields = CeoPostsFieldNames::default(); + for marker in ["ceoId", "extra"] { + let mut d = make_base_doc("KEYVAL", "s", 1_710_460_800); + d.append(cstr!("extra"), "EXTRAV"); + let mut bytes = d.into_bytes(); + let needle: &[u8] = if marker == "ceoId" { + b"KEYVAL" + } else { + b"EXTRAV" + }; + let pos = bytes.windows(6).position(|w| w == needle).expect("needle"); + bytes[pos] = 0xff; + + let mut emitted = 0; + let err = decode_ceo_posts_buffer(&bytes, &fields, CeoPostsTimestampUnit::Seconds, |_| { + emitted += 1 + }) + .unwrap_err(); + assert_eq!(emitted, 0, "{marker}"); + assert!( + matches!(err, BsonCeoPostsError::CorruptBson { offset: 0, .. }), + "{marker}: {err:?}" + ); + } +} + +#[test] +fn corruption_in_first_document_reports_offset_zero_and_emits_nothing() { + let fields = CeoPostsFieldNames::default(); + let good = make_base_doc("CH", "after", 1_710_460_800); + let mut buf = vec![3, 0, 0, 0, 0]; + buf.extend_from_slice(good.as_bytes()); + let mut emitted = 0; + let err = decode_ceo_posts_buffer(&buf, &fields, CeoPostsTimestampUnit::Seconds, |_| { + emitted += 1 + }) + .unwrap_err(); + assert_eq!(emitted, 0); + assert_eq!( + err, + BsonCeoPostsError::CorruptDocumentLength { + offset: 0, + declared_len: 3 + } + ); +} + +#[test] +fn excessive_nesting_fails_closed_without_stack_overflow_and_moderate_nesting_decodes() { + fn nested(depth: usize) -> RawDocumentBuf { + let mut inner = RawDocumentBuf::new(); + inner.append(cstr!("leaf"), 1_i32); + for _ in 0..depth { + let mut outer = RawDocumentBuf::new(); + outer.append(cstr!("n"), inner); + inner = outer; + } + inner + } + let fields = CeoPostsFieldNames::default(); + + let mut ok = make_base_doc("CH", "shallow", 1_710_460_800); + ok.append(cstr!("meta"), nested(10)); + let stats = decode_ceo_posts_bytes( + ok.as_bytes(), + &fields, + CeoPostsTimestampUnit::Seconds, + |_| {}, + ) + .expect("moderate nesting decodes"); + assert_eq!(stats.rows_out, 1); + + let mut deep = make_base_doc("CH", "deep", 1_710_460_800); + deep.append(cstr!("meta"), nested(400)); + let err = decode_ceo_posts_bytes( + deep.as_bytes(), + &fields, + CeoPostsTimestampUnit::Seconds, + |_| panic!("deep nesting must not emit"), + ) + .unwrap_err(); + assert!( + matches!(err, BsonCeoPostsError::CorruptBson { offset: 0, .. }), + "{err:?}" + ); +} + +#[test] +fn empty_buffer_yields_zero_stats() { + let stats = decode_ceo_posts_buffer( + &[], + &CeoPostsFieldNames::default(), + CeoPostsTimestampUnit::Millis, + |_| panic!("no rows"), + ) + .expect("empty buffer ok"); + assert_eq!(stats, BsonCeoPostsDecodeStats::default()); +} + +#[test] +fn add_assign_sums_every_counter() { + let a = BsonCeoPostsDecodeStats { + docs_in: 1, + rows_out: 2, + skipped_missing_key: 3, + skipped_wrong_key_type: 4, + skipped_empty_key: 5, + skipped_missing_spiel_id: 6, + skipped_wrong_spiel_id_type: 7, + skipped_empty_spiel_id: 8, + skipped_missing_timestamp: 9, + skipped_wrong_timestamp_type: 10, + skipped_invalid_timestamp: 11, + skipped_timestamp_out_of_range: 12, + skipped_invalid_edited: 13, + skipped_wrong_text_type: 14, + edited_zero_or_false: 15, + nulled_wrong_type_bot: 16, + nulled_wrong_type_user_id: 17, + empty_text: 18, + }; + let mut sum = a; + sum += a; + let doubled = BsonCeoPostsDecodeStats { + docs_in: 2, + rows_out: 4, + skipped_missing_key: 6, + skipped_wrong_key_type: 8, + skipped_empty_key: 10, + skipped_missing_spiel_id: 12, + skipped_wrong_spiel_id_type: 14, + skipped_empty_spiel_id: 16, + skipped_missing_timestamp: 18, + skipped_wrong_timestamp_type: 20, + skipped_invalid_timestamp: 22, + skipped_timestamp_out_of_range: 24, + skipped_invalid_edited: 26, + skipped_wrong_text_type: 28, + edited_zero_or_false: 30, + nulled_wrong_type_bot: 32, + nulled_wrong_type_user_id: 34, + empty_text: 36, + }; + assert_eq!(sum, doubled); + // skipped_total excludes docs_in, rows_out and emitted-row counters: 3+..+14 = 102. + assert_eq!(a.skipped_total(), 102); +} + +#[test] +fn edited_text_is_excluded_at_a_cutoff_between_post_and_edit() { + // Point-in-time check: a consumer filtering `known_at < cutoff` must not see edited text + // whose edit happened after the cutoff, while an unedited post at the same time is visible. + let posted = 1_710_460_800_i64; // seconds + let edit = posted + 600; + let cutoff_us = (posted + 300) * 1_000_000; + + let mut unedited = make_base_doc("CH", "plain", posted); + unedited.append(cstr!("edited"), 0_i32); + let mut edited = make_base_doc("CH", "edited", posted); + edited.append(cstr!("edited"), edit); + let mut buf = unedited.into_bytes(); + buf.extend_from_slice(edited.as_bytes()); + + let mut rows = Vec::new(); + decode_ceo_posts_buffer( + &buf, + &CeoPostsFieldNames::default(), + CeoPostsTimestampUnit::Seconds, + |r| rows.push(r), + ) + .expect("decode"); + let built = build_posts(rows).expect("build"); + + let visible: Vec<&str> = built + .retail + .iter() + .filter(|r| r.known_at < cutoff_us) + .map(|r| r.spiel_id.as_str()) + .collect(); + assert_eq!(visible, vec!["plain"]); + let late = built + .retail + .iter() + .find(|r| r.spiel_id == "edited") + .expect("edited row"); + assert_eq!(late.known_at, edit * 1_000_000); + assert_eq!(late.posted_at, posted * 1_000_000); +} diff --git a/tools/curate-etl/src/bson_qm_financials.rs b/tools/curate-etl/src/bson_qm_financials.rs new file mode 100644 index 00000000..8627c843 --- /dev/null +++ b/tools/curate-etl/src/bson_qm_financials.rs @@ -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, + }, + /// 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, 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> = 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, 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::() { + 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 +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 +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 +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 +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; diff --git a/tools/curate-etl/src/bson_qm_financials_tests.rs b/tools/curate-etl/src/bson_qm_financials_tests.rs new file mode 100644 index 00000000..b563060a --- /dev/null +++ b/tools/curate-etl/src/bson_qm_financials_tests.rs @@ -0,0 +1,1007 @@ +use std::collections::BTreeMap; + +use bson::raw::{cstr, RawArrayBuf, RawBson, RawDocument, RawDocumentBuf}; +use bson::DateTime as BsonDateTime; + +use super::*; +use crate::events::{QmFiling, KNOWN_AT_SOURCE_FILING_TIMESTAMP}; +use crate::fundamentals::{ + as_of, build_fundamentals_rows, build_fundamentals_snapshots, StatutoryLagVenue, +}; +use crate::shorts::epoch_days_to_ymd; +use crate::split::ymd_to_epoch_days; + +fn assert_conservation(stats: &BsonQmFinancialsDecodeStats) { + assert_eq!( + stats.docs_in, + stats.rows_out + stats.skipped_total(), + "conservation invariant failed: {stats:?}" + ); +} + +fn full_test_fields() -> QmFinancialsFieldNames<'static> { + QmFinancialsFieldNames::with_verified_defaults( + "currency", + Some("IncomeStatement.totalRevenue"), + Some("IncomeStatement.netIncome"), + Some("CashFlow.operatingCashFlow"), + Some("BalanceSheet.totalAssets"), + Some("BalanceSheet.totalEquity"), + Some("BalanceSheet.commonSharesOutstanding"), + ) +} + +const QUARTERLY_TOKENS: &[&str] = &["Q", "Q1", "Q2", "Q3", "Q4"]; +const ANNUAL_TOKENS: &[&str] = &["A", "FY"]; + +fn token_period_cfg() -> QmFinancialsFiscalPeriod<'static> { + QmFinancialsFiscalPeriod::ByTokens { + quarterly: QUARTERLY_TOKENS, + annual: ANNUAL_TOKENS, + } +} + +fn make_nested_doc( + key: &str, + period_end: RawBson, + report_period: &str, + report_date: Option, + currency: &str, + statements: (RawDocumentBuf, RawDocumentBuf, RawDocumentBuf), +) -> RawDocumentBuf { + let (income, balance, cash_flow) = statements; + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), key); + doc.append(cstr!("periodEndDate"), period_end); + doc.append(cstr!("reportPeriod"), report_period); + if let Some(rd) = report_date { + doc.append(cstr!("reportDate"), rd); + } + doc.append(cstr!("currency"), currency); + doc.append(cstr!("IncomeStatement"), income); + doc.append(cstr!("BalanceSheet"), balance); + doc.append(cstr!("CashFlow"), cash_flow); + doc +} + +fn make_valid_doc(key: &str) -> RawDocumentBuf { + let mut income = RawDocumentBuf::new(); + income.append(cstr!("totalRevenue"), 1_250_000.5_f64); + income.append(cstr!("netIncome"), 125_000_i32); + + let mut balance = RawDocumentBuf::new(); + balance.append(cstr!("totalAssets"), 9_000_000_000_i64); + balance.append(cstr!("totalEquity"), "4500000.25"); + balance.append(cstr!("commonSharesOutstanding"), " 100000000 "); + + let mut cash_flow = RawDocumentBuf::new(); + cash_flow.append(cstr!("operatingCashFlow"), 300_000.75_f64); + + make_nested_doc( + key, + RawBson::String("2024-06-30".to_string()), + "Q2", + Some(RawBson::String("2024-08-02".to_string())), + "USD", + (income, balance, cash_flow), + ) +} + +#[test] +fn decodes_nested_statements_all_entry_points_date_and_numeric_types() { + let fields = full_test_fields(); + let period_cfg = token_period_cfg(); + + // Doc 1: String dates + Double, Int32, Int64, numeric String (with spaces). + let doc1 = make_valid_doc("AAPL:US"); + + // Doc 2: BSON DateTime dates (mid-day UTC) + Annual token + negative numeric string. + let pe_day = ymd_to_epoch_days(2024, 12, 31).unwrap(); + let rd_day = ymd_to_epoch_days(2025, 2, 14).unwrap(); + let mut income2 = RawDocumentBuf::new(); + income2.append(cstr!("totalRevenue"), 5_000_000_i64); + income2.append(cstr!("netIncome"), "-42500.5"); + let mut balance2 = RawDocumentBuf::new(); + balance2.append(cstr!("totalAssets"), 20_000_000_i32); + balance2.append(cstr!("totalEquity"), 12_500_000.0_f64); + balance2.append(cstr!("commonSharesOutstanding"), 50_000_000_i64); + let mut cash2 = RawDocumentBuf::new(); + cash2.append(cstr!("operatingCashFlow"), -10_000_i32); + + let doc2 = make_nested_doc( + "SHOP:CA", + RawBson::DateTime(BsonDateTime::from_millis( + i64::from(pe_day) * MILLIS_PER_DAY + 43_200_000, + )), + "FY", + Some(RawBson::DateTime(BsonDateTime::from_millis( + i64::from(rd_day) * MILLIS_PER_DAY + 3_600_000, + ))), + "CAD", + (income2, balance2, cash2), + ); + + // 1. decode_qm_financials_doc (zero-copy check on borrowed key) + let raw_doc1: &RawDocument = doc1.as_ref(); + let raw_bytes1 = raw_doc1.as_bytes(); + let range1 = raw_bytes1.as_ptr() as usize..raw_bytes1.as_ptr() as usize + raw_bytes1.len(); + let mut rows_doc = Vec::new(); + let stats_doc = decode_qm_financials_doc(raw_doc1, &fields, period_cfg, |obs| { + let key_ptr = obs.key.as_ptr() as usize; + assert!( + range1.contains(&key_ptr), + "expected key to borrow directly from input RawDocument slice" + ); + rows_doc.push(obs); + }) + .unwrap(); + assert_conservation(&stats_doc); + assert_eq!(stats_doc.docs_in, 1); + assert_eq!(stats_doc.rows_out, 1); + assert_eq!(rows_doc.len(), 1); + assert_eq!( + rows_doc[0], + FinancialObservation { + key: "AAPL:US", + period_end: ymd_to_epoch_days(2024, 6, 30).unwrap(), + fiscal_period: FiscalPeriod::Quarterly, + currency: "USD".to_string(), + report_date: Some(ymd_to_epoch_days(2024, 8, 2).unwrap()), + fields: FundamentalsFields { + revenue: Some(1_250_000.5), + net_income: Some(125_000.0), + operating_cash_flow: Some(300_000.75), + total_assets: Some(9_000_000_000.0), + total_equity: Some(4_500_000.25), + shares_outstanding: Some(100_000_000.0), + }, + } + ); + + // 2. decode_qm_financials_bytes + let bytes2 = doc2.as_bytes(); + let mut rows_bytes = Vec::new(); + let stats_bytes = decode_qm_financials_bytes(bytes2, &fields, period_cfg, |obs| { + rows_bytes.push(obs); + }) + .unwrap(); + assert_conservation(&stats_bytes); + assert_eq!(stats_bytes.docs_in, 1); + assert_eq!(stats_bytes.rows_out, 1); + assert_eq!( + rows_bytes[0], + FinancialObservation { + key: "SHOP:CA", + period_end: pe_day, + fiscal_period: FiscalPeriod::Annual, + currency: "CAD".to_string(), + report_date: Some(rd_day), + fields: FundamentalsFields { + revenue: Some(5_000_000.0), + net_income: Some(-42_500.5), + operating_cash_flow: Some(-10_000.0), + total_assets: Some(20_000_000.0), + total_equity: Some(12_500_000.0), + shares_outstanding: Some(50_000_000.0), + }, + } + ); + + // 3. decode_qm_financials_buffer + let mut buf = Vec::new(); + buf.extend_from_slice(doc1.as_bytes()); + buf.extend_from_slice(doc2.as_bytes()); + let mut rows_buf = Vec::new(); + let stats_buf = decode_qm_financials_buffer(&buf, &fields, period_cfg, |obs| { + rows_buf.push(obs); + }) + .unwrap(); + assert_conservation(&stats_buf); + assert_eq!(stats_buf.docs_in, 2); + assert_eq!(stats_buf.rows_out, 2); + assert_eq!(rows_buf, vec![rows_doc[0].clone(), rows_bytes[0].clone()]); +} + +#[test] +fn rejects_invalid_field_paths_and_fiscal_period_configs_before_decoding() { + let base = full_test_fields(); + let bad_field_configs = [ + QmFinancialsFieldNames { key: "", ..base }, + QmFinancialsFieldNames { key: " ", ..base }, + QmFinancialsFieldNames { + period_end: ".periodEndDate", + ..base + }, + QmFinancialsFieldNames { + report_date: "reportDate.", + ..base + }, + QmFinancialsFieldNames { + report_period: "a..b", + ..base + }, + QmFinancialsFieldNames { + currency: "", + ..base + }, + QmFinancialsFieldNames { + currency: "meta. .currency", + ..base + }, + QmFinancialsFieldNames { + revenue: Some(""), + ..base + }, + QmFinancialsFieldNames { + net_income: Some(".netIncome"), + ..base + }, + QmFinancialsFieldNames { + operating_cash_flow: Some("CashFlow."), + ..base + }, + QmFinancialsFieldNames { + total_assets: Some("BalanceSheet..totalAssets"), + ..base + }, + QmFinancialsFieldNames { + total_equity: Some("BalanceSheet. \t .totalEquity"), + ..base + }, + QmFinancialsFieldNames { + shares_outstanding: Some("."), + ..base + }, + ]; + + let doc = make_valid_doc("AAPL:US"); + + for cfg in bad_field_configs { + let err = cfg.validate().unwrap_err(); + assert!( + matches!(err, BsonQmFinancialsError::InvalidFieldNames { .. }), + "expected InvalidFieldNames for {cfg:?}, got {err:?}" + ); + assert!(!err.to_string().contains('\n')); + + let mut called = false; + assert!(matches!( + decode_qm_financials_doc(doc.as_ref(), &cfg, token_period_cfg(), |_| called = true), + Err(BsonQmFinancialsError::InvalidFieldNames { .. }) + )); + assert!(matches!( + decode_qm_financials_bytes(doc.as_bytes(), &cfg, token_period_cfg(), |_| called = true), + Err(BsonQmFinancialsError::InvalidFieldNames { .. }) + )); + assert!(matches!( + decode_qm_financials_buffer(doc.as_bytes(), &cfg, token_period_cfg(), |_| called = + true), + Err(BsonQmFinancialsError::InvalidFieldNames { .. }) + )); + assert!(!called); + } + + let bad_period_configs = [ + QmFinancialsFiscalPeriod::ByTokens { + quarterly: &["Q", "BOTH"], + annual: &["FY", "BOTH"], + }, + QmFinancialsFiscalPeriod::ByTokens { + quarterly: &[""], + annual: &["FY"], + }, + QmFinancialsFiscalPeriod::ByTokens { + quarterly: &["Q"], + annual: &[" "], + }, + ]; + + for pcfg in bad_period_configs { + let err = pcfg.validate().unwrap_err(); + assert!( + matches!(err, BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. }), + "expected InvalidFiscalPeriodConfig for {pcfg:?}, got {err:?}" + ); + assert!(!err.to_string().contains('\n')); + + let mut called = false; + assert!(matches!( + decode_qm_financials_doc(doc.as_ref(), &base, pcfg, |_| called = true), + Err(BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. }) + )); + assert!(matches!( + decode_qm_financials_bytes(doc.as_bytes(), &base, pcfg, |_| called = true), + Err(BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. }) + )); + assert!(matches!( + decode_qm_financials_buffer(doc.as_bytes(), &base, pcfg, |_| called = true), + Err(BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. }) + )); + assert!(!called); + } +} + +#[test] +fn covers_each_skip_counter_and_inclusive_date_bounds() { + let fields = full_test_fields(); + let pcfg = token_period_cfg(); + + // Helper to decode a single doc and assert zero rows emitted. + let decode_skipped = |doc: &RawDocumentBuf| -> BsonQmFinancialsDecodeStats { + let mut count = 0usize; + let stats = decode_qm_financials_doc(doc.as_ref(), &fields, pcfg, |_| count += 1).unwrap(); + assert_eq!(count, 0); + assert_eq!(stats.rows_out, 0); + assert_conservation(&stats); + stats + }; + + // --- Key skips --- + let mut missing_key = RawDocumentBuf::new(); + missing_key.append(cstr!("periodEndDate"), "2024-06-30"); + missing_key.append(cstr!("reportPeriod"), "Q"); + missing_key.append(cstr!("currency"), "USD"); + assert_eq!(decode_skipped(&missing_key).skipped_missing_key, 1); + + let mut wrong_key = RawDocumentBuf::new(); + wrong_key.append(cstr!("qmSearchCode"), 12345_i32); + wrong_key.append(cstr!("periodEndDate"), "2024-06-30"); + wrong_key.append(cstr!("reportPeriod"), "Q"); + wrong_key.append(cstr!("currency"), "USD"); + assert_eq!(decode_skipped(&wrong_key).skipped_wrong_key_type, 1); + + let mut empty_key = RawDocumentBuf::new(); + empty_key.append(cstr!("qmSearchCode"), " \t "); + empty_key.append(cstr!("periodEndDate"), "2024-06-30"); + empty_key.append(cstr!("reportPeriod"), "Q"); + empty_key.append(cstr!("currency"), "USD"); + assert_eq!(decode_skipped(&empty_key).skipped_empty_key, 1); + + // --- periodEndDate skips --- + let mut missing_pe = RawDocumentBuf::new(); + missing_pe.append(cstr!("qmSearchCode"), "AAPL:US"); + missing_pe.append(cstr!("reportPeriod"), "Q"); + missing_pe.append(cstr!("currency"), "USD"); + assert_eq!(decode_skipped(&missing_pe).skipped_missing_period_end, 1); + + let mut wrong_pe = RawDocumentBuf::new(); + wrong_pe.append(cstr!("qmSearchCode"), "AAPL:US"); + wrong_pe.append(cstr!("periodEndDate"), 20240630_i32); + wrong_pe.append(cstr!("reportPeriod"), "Q"); + wrong_pe.append(cstr!("currency"), "USD"); + assert_eq!(decode_skipped(&wrong_pe).skipped_wrong_period_end_type, 1); + + let mut invalid_pe = RawDocumentBuf::new(); + invalid_pe.append(cstr!("qmSearchCode"), "AAPL:US"); + invalid_pe.append(cstr!("periodEndDate"), "2024-02-30"); + invalid_pe.append(cstr!("reportPeriod"), "Q"); + invalid_pe.append(cstr!("currency"), "USD"); + assert_eq!(decode_skipped(&invalid_pe).skipped_invalid_period_end, 1); + + let mut oor_pe_low = RawDocumentBuf::new(); + oor_pe_low.append(cstr!("qmSearchCode"), "AAPL:US"); + oor_pe_low.append(cstr!("periodEndDate"), "2007-12-31"); + oor_pe_low.append(cstr!("reportPeriod"), "Q"); + oor_pe_low.append(cstr!("currency"), "USD"); + assert_eq!( + decode_skipped(&oor_pe_low).skipped_period_end_out_of_range, + 1 + ); + + let mut oor_pe_high_dt = RawDocumentBuf::new(); + oor_pe_high_dt.append(cstr!("qmSearchCode"), "AAPL:US"); + oor_pe_high_dt.append( + cstr!("periodEndDate"), + BsonDateTime::from_millis(i64::from(MAX_SUPPORTED_DATE + 1) * MILLIS_PER_DAY), + ); + oor_pe_high_dt.append(cstr!("reportPeriod"), "Q"); + oor_pe_high_dt.append(cstr!("currency"), "USD"); + assert_eq!( + decode_skipped(&oor_pe_high_dt).skipped_period_end_out_of_range, + 1 + ); + + // --- reportPeriod skips --- + let mut missing_rp = RawDocumentBuf::new(); + missing_rp.append(cstr!("qmSearchCode"), "AAPL:US"); + missing_rp.append(cstr!("periodEndDate"), "2024-06-30"); + missing_rp.append(cstr!("currency"), "USD"); + assert_eq!(decode_skipped(&missing_rp).skipped_missing_report_period, 1); + + let mut wrong_rp = RawDocumentBuf::new(); + wrong_rp.append(cstr!("qmSearchCode"), "AAPL:US"); + wrong_rp.append(cstr!("periodEndDate"), "2024-06-30"); + wrong_rp.append(cstr!("reportPeriod"), 4_i32); + wrong_rp.append(cstr!("currency"), "USD"); + assert_eq!( + decode_skipped(&wrong_rp).skipped_wrong_report_period_type, + 1 + ); + + let mut unmapped_rp = RawDocumentBuf::new(); + unmapped_rp.append(cstr!("qmSearchCode"), "AAPL:US"); + unmapped_rp.append(cstr!("periodEndDate"), "2024-06-30"); + unmapped_rp.append(cstr!("reportPeriod"), "TTM"); + unmapped_rp.append(cstr!("currency"), "USD"); + assert_eq!( + decode_skipped(&unmapped_rp).skipped_unmapped_report_period, + 1 + ); + + // --- reportDate skips (present-but-invalid fails closed) --- + let mut wrong_rd = RawDocumentBuf::new(); + wrong_rd.append(cstr!("qmSearchCode"), "AAPL:US"); + wrong_rd.append(cstr!("periodEndDate"), "2024-06-30"); + wrong_rd.append(cstr!("reportPeriod"), "Q"); + wrong_rd.append(cstr!("reportDate"), true); + wrong_rd.append(cstr!("currency"), "USD"); + assert_eq!(decode_skipped(&wrong_rd).skipped_wrong_report_date_type, 1); + + let mut invalid_rd = RawDocumentBuf::new(); + invalid_rd.append(cstr!("qmSearchCode"), "AAPL:US"); + invalid_rd.append(cstr!("periodEndDate"), "2024-06-30"); + invalid_rd.append(cstr!("reportPeriod"), "Q"); + invalid_rd.append(cstr!("reportDate"), "08/02/2024"); + invalid_rd.append(cstr!("currency"), "USD"); + assert_eq!(decode_skipped(&invalid_rd).skipped_invalid_report_date, 1); + + let mut blank_rd = RawDocumentBuf::new(); + blank_rd.append(cstr!("qmSearchCode"), "AAPL:US"); + blank_rd.append(cstr!("periodEndDate"), "2024-06-30"); + blank_rd.append(cstr!("reportPeriod"), "Q"); + blank_rd.append(cstr!("reportDate"), " "); + blank_rd.append(cstr!("currency"), "USD"); + assert_eq!(decode_skipped(&blank_rd).skipped_invalid_report_date, 1); + + let mut oor_rd = RawDocumentBuf::new(); + oor_rd.append(cstr!("qmSearchCode"), "AAPL:US"); + oor_rd.append(cstr!("periodEndDate"), "2024-06-30"); + oor_rd.append(cstr!("reportPeriod"), "Q"); + oor_rd.append(cstr!("reportDate"), "2031-01-01"); + oor_rd.append(cstr!("currency"), "USD"); + assert_eq!(decode_skipped(&oor_rd).skipped_report_date_out_of_range, 1); + + // --- currency skips --- + let mut missing_ccy = RawDocumentBuf::new(); + missing_ccy.append(cstr!("qmSearchCode"), "AAPL:US"); + missing_ccy.append(cstr!("periodEndDate"), "2024-06-30"); + missing_ccy.append(cstr!("reportPeriod"), "Q"); + assert_eq!(decode_skipped(&missing_ccy).skipped_missing_currency, 1); + + let mut wrong_ccy = RawDocumentBuf::new(); + wrong_ccy.append(cstr!("qmSearchCode"), "AAPL:US"); + wrong_ccy.append(cstr!("periodEndDate"), "2024-06-30"); + wrong_ccy.append(cstr!("reportPeriod"), "Q"); + wrong_ccy.append(cstr!("currency"), 840_i32); + assert_eq!(decode_skipped(&wrong_ccy).skipped_wrong_currency_type, 1); + + let mut empty_ccy = RawDocumentBuf::new(); + empty_ccy.append(cstr!("qmSearchCode"), "AAPL:US"); + empty_ccy.append(cstr!("periodEndDate"), "2024-06-30"); + empty_ccy.append(cstr!("reportPeriod"), "Q"); + empty_ccy.append(cstr!("currency"), " "); + assert_eq!(decode_skipped(&empty_ccy).skipped_empty_currency, 1); + + // --- Inclusive date bounds + absent/Null reportDate --- + let (min_y, min_m, min_d) = epoch_days_to_ymd(MIN_SUPPORTED_DATE); + let (max_y, max_m, max_d) = epoch_days_to_ymd(MAX_SUPPORTED_DATE); + let min_str = format!("{min_y:04}-{min_m:02}-{min_d:02}"); + let max_str = format!("{max_y:04}-{max_m:02}-{max_d:02}"); + + let mut min_bound_absent_rd = RawDocumentBuf::new(); + min_bound_absent_rd.append(cstr!("qmSearchCode"), "AAPL:US"); + min_bound_absent_rd.append(cstr!("periodEndDate"), min_str.as_str()); + min_bound_absent_rd.append(cstr!("reportPeriod"), "Q"); + min_bound_absent_rd.append(cstr!("currency"), "USD"); + + let mut max_bound_null_rd = RawDocumentBuf::new(); + max_bound_null_rd.append(cstr!("qmSearchCode"), "AAPL:US"); + max_bound_null_rd.append(cstr!("periodEndDate"), max_str.as_str()); + max_bound_null_rd.append(cstr!("reportPeriod"), "FY"); + max_bound_null_rd.append(cstr!("reportDate"), RawBson::Null); + max_bound_null_rd.append(cstr!("currency"), "USD"); + + let minimal_fields = + QmFinancialsFieldNames::with_verified_defaults("currency", None, None, None, None, None, None); + let mut emitted = Vec::new(); + let mut buf = Vec::new(); + buf.extend_from_slice(min_bound_absent_rd.as_bytes()); + buf.extend_from_slice(max_bound_null_rd.as_bytes()); + let stats = decode_qm_financials_buffer(&buf, &minimal_fields, pcfg, |obs| { + emitted.push(obs); + }) + .unwrap(); + assert_conservation(&stats); + assert_eq!(stats.rows_out, 2); + assert_eq!(emitted[0].period_end, MIN_SUPPORTED_DATE); + assert_eq!(emitted[0].report_date, None); + assert_eq!(emitted[1].period_end, MAX_SUPPORTED_DATE); + assert_eq!(emitted[1].report_date, None); +} + +#[test] +fn fixed_fiscal_period_override_ignores_report_period_field() { + let fields = + QmFinancialsFieldNames::with_verified_defaults("currency", None, None, None, None, None, None); + + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "MSFT:US"); + doc.append(cstr!("periodEndDate"), "2024-09-30"); + // Wrong-typed reportPeriod would fail in ByTokens mode, but Fixed mode ignores it. + doc.append(cstr!("reportPeriod"), 999_i32); + doc.append(cstr!("currency"), "USD"); + + let mut rows = Vec::new(); + let stats = decode_qm_financials_doc( + doc.as_ref(), + &fields, + QmFinancialsFiscalPeriod::Fixed(FiscalPeriod::Annual), + |obs| rows.push(obs), + ) + .unwrap(); + assert_conservation(&stats); + assert_eq!(stats.rows_out, 1); + assert_eq!(rows[0].fiscal_period, FiscalPeriod::Annual); +} + +#[test] +fn numeric_null_counters_and_unconfigured_paths() { + // Configure 5 of 6 paths; leave `shares_outstanding` explicitly unconfigured (`None`). + let fields = QmFinancialsFieldNames::with_verified_defaults( + "meta.currency", + Some("IncomeStatement.totalRevenue"), // missing sub-document + Some("BalanceSheet.netIncome"), // wrong type (boolean) + Some("CashFlow.ocf"), // unparsable string + Some("BalanceSheet.assets"), // non-finite double (NaN) + Some("BalanceSheet.equity"), // non-finite string ("inf") + None, // unconfigured -> no null counter + ); + + let mut meta = RawDocumentBuf::new(); + meta.append(cstr!("currency"), "CAD"); + + let mut balance = RawDocumentBuf::new(); + balance.append(cstr!("netIncome"), true); + balance.append(cstr!("assets"), f64::NAN); + balance.append(cstr!("equity"), "inf"); + + let mut cash = RawDocumentBuf::new(); + cash.append(cstr!("ocf"), "N/A"); + + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "RY:CA"); + doc.append(cstr!("periodEndDate"), "2024-10-31"); + doc.append(cstr!("reportPeriod"), "FY"); + doc.append(cstr!("meta"), meta); + // IncomeStatement intentionally omitted -> nulled_missing_path + doc.append(cstr!("BalanceSheet"), balance); + doc.append(cstr!("CashFlow"), cash); + + let mut rows = Vec::new(); + let stats = decode_qm_financials_doc(doc.as_ref(), &fields, token_period_cfg(), |obs| { + rows.push(obs); + }) + .unwrap(); + assert_conservation(&stats); + assert_eq!(stats.rows_out, 1); + assert_eq!(stats.nulled_missing_path, 1); + assert_eq!(stats.nulled_wrong_type, 1); + assert_eq!(stats.nulled_unparsable_string, 1); + assert_eq!(stats.nulled_non_finite, 2); + assert_eq!(rows[0].currency, "CAD"); + assert_eq!(rows[0].fields, FundamentalsFields::default()); + + // BSON Null on a configured numeric leaf emits None cleanly without incrementing null counters. + let mut income_null = RawDocumentBuf::new(); + income_null.append(cstr!("totalRevenue"), RawBson::Null); + let mut doc_null = RawDocumentBuf::new(); + doc_null.append(cstr!("qmSearchCode"), "RY:CA"); + doc_null.append(cstr!("periodEndDate"), "2024-10-31"); + doc_null.append(cstr!("reportPeriod"), "FY"); + doc_null.append(cstr!("currency"), "CAD"); + doc_null.append(cstr!("IncomeStatement"), income_null); + + let single_field = QmFinancialsFieldNames::with_verified_defaults( + "currency", + Some("IncomeStatement.totalRevenue"), + None, + None, + None, + None, + None, + ); + let mut rows_null = Vec::new(); + let stats_null = + decode_qm_financials_doc(doc_null.as_ref(), &single_field, token_period_cfg(), |obs| { + rows_null.push(obs); + }) + .unwrap(); + assert_eq!(stats_null.rows_out, 1); + assert_eq!(stats_null.nulled_missing_path, 0); + assert_eq!(stats_null.nulled_wrong_type, 0); + assert_eq!(stats_null.nulled_unparsable_string, 0); + assert_eq!(stats_null.nulled_non_finite, 0); + assert_eq!(rows_null[0].fields.revenue, None); +} + +#[test] +fn mixed_buffer_reconciles_stats_and_framing_errors_fail_closed_with_offset() { + let fields = full_test_fields(); + let pcfg = token_period_cfg(); + + let good = make_valid_doc("AAPL:US"); + + let mut bad_key = RawDocumentBuf::new(); + bad_key.append(cstr!("periodEndDate"), "2024-06-30"); + bad_key.append(cstr!("reportPeriod"), "Q"); + bad_key.append(cstr!("currency"), "USD"); + + let mut bad_period = RawDocumentBuf::new(); + bad_period.append(cstr!("qmSearchCode"), "AAPL:US"); + bad_period.append(cstr!("periodEndDate"), "2024-06-30"); + bad_period.append(cstr!("reportPeriod"), "UNKNOWN"); + bad_period.append(cstr!("currency"), "USD"); + + let mut bad_rd = RawDocumentBuf::new(); + bad_rd.append(cstr!("qmSearchCode"), "AAPL:US"); + bad_rd.append(cstr!("periodEndDate"), "2024-06-30"); + bad_rd.append(cstr!("reportPeriod"), "Q"); + bad_rd.append(cstr!("reportDate"), "not-a-date"); + bad_rd.append(cstr!("currency"), "USD"); + + let mut mixed = Vec::new(); + mixed.extend_from_slice(good.as_bytes()); + mixed.extend_from_slice(bad_key.as_bytes()); + mixed.extend_from_slice(bad_period.as_bytes()); + mixed.extend_from_slice(bad_rd.as_bytes()); + + let mut emitted = Vec::new(); + let stats = decode_qm_financials_buffer(&mixed, &fields, pcfg, |obs| emitted.push(obs)).unwrap(); + assert_eq!(stats.docs_in, 4); + assert_eq!(stats.rows_out, 1); + assert_eq!(stats.skipped_missing_key, 1); + assert_eq!(stats.skipped_unmapped_report_period, 1); + assert_eq!(stats.skipped_invalid_report_date, 1); + assert_eq!(stats.skipped_total(), 3); + assert_conservation(&stats); + assert_eq!(emitted.len(), 1); + + // 1. Truncated length prefix after a valid document. + let prefix_len = good.as_bytes().len() as u64; + let mut truncated_hdr = good.as_bytes().to_vec(); + truncated_hdr.extend_from_slice(&[0x10, 0x00]); + let mut seen = 0usize; + let err = decode_qm_financials_buffer(&truncated_hdr, &fields, pcfg, |_| seen += 1).unwrap_err(); + assert_eq!(seen, 1); + assert_eq!( + err, + BsonQmFinancialsError::TruncatedDocument { + offset: prefix_len, + remaining: 2, + declared_len: None, + } + ); + + // 2. Truncated document body after a valid document. + let mut truncated_body = good.as_bytes().to_vec(); + truncated_body.extend_from_slice(&good.as_bytes()[..10]); + let err = decode_qm_financials_buffer(&truncated_body, &fields, pcfg, |_| {}).unwrap_err(); + assert!(matches!( + err, + BsonQmFinancialsError::TruncatedDocument { + offset, + remaining: 10, + declared_len: Some(_), + } if offset == prefix_len + )); + + // 3. Invalid declared document length (< 5). + let mut bad_len = good.as_bytes().to_vec(); + bad_len.extend_from_slice(&3_i32.to_le_bytes()); + bad_len.push(0x00); + let err = decode_qm_financials_buffer(&bad_len, &fields, pcfg, |_| {}).unwrap_err(); + assert_eq!( + err, + BsonQmFinancialsError::CorruptDocumentLength { + offset: prefix_len, + declared_len: 3, + } + ); + + // 4. Malformed nested BSON (invalid UTF-8 inside an unused nested subdocument) in a document + // that ALSO lacks a key: must return CorruptBson rather than silently skipping! + let mut nested = RawDocumentBuf::new(); + nested.append(cstr!("note"), "AAAA"); + let mut nested_bytes = nested.into_bytes(); + // Corrupt the 4-byte ASCII payload "AAAA" into invalid UTF-8 bytes. + let pos = nested_bytes + .windows(4) + .position(|w| w == b"AAAA") + .expect("marker present"); + nested_bytes[pos] = 0xFF; + nested_bytes[pos + 1] = 0xFE; + + // Build outer doc containing no key (would skip) + the corrupt nested subdoc. + let mut outer = Vec::new(); + let placeholder_len = 0_i32; + outer.extend_from_slice(&placeholder_len.to_le_bytes()); + outer.push(0x03); // Embedded Document element type + outer.extend_from_slice(b"extra\0"); + outer.extend_from_slice(&nested_bytes); + outer.push(0x00); // Document terminator + let total_len = i32::try_from(outer.len()).unwrap(); + outer[..4].copy_from_slice(&total_len.to_le_bytes()); + + let mut with_prefix = good.as_bytes().to_vec(); + with_prefix.extend_from_slice(&outer); + let err = decode_qm_financials_buffer(&with_prefix, &fields, pcfg, |_| {}).unwrap_err(); + assert!( + matches!(err, BsonQmFinancialsError::CorruptBson { offset, .. } if offset == prefix_len), + "expected CorruptBson at offset {prefix_len}, got {err:?}" + ); + + // 5. Corrupt array index inside a nested array fails closed. + let mut bad_arr = RawArrayBuf::new(); + bad_arr.push(1_i32); + let mut arr_bytes = bad_arr.as_bytes().to_vec(); + // Replace key "0" with "1" so array index validation rejects it. + let zero_pos = arr_bytes + .windows(2) + .position(|w| w == b"0\0") + .expect("index 0 key present"); + arr_bytes[zero_pos] = b'1'; + let mut outer_arr = Vec::new(); + outer_arr.extend_from_slice(&0_i32.to_le_bytes()); + outer_arr.push(0x04); // Array element type + outer_arr.extend_from_slice(b"arr\0"); + outer_arr.extend_from_slice(&arr_bytes); + outer_arr.push(0x00); + let arr_total_len = i32::try_from(outer_arr.len()).unwrap(); + outer_arr[..4].copy_from_slice(&arr_total_len.to_le_bytes()); + + let err = decode_qm_financials_bytes(&outer_arr, &fields, pcfg, |_| {}).unwrap_err(); + assert!(matches!(err, BsonQmFinancialsError::CorruptBson { offset: 0, .. })); +} + +#[test] +fn decoded_observation_feeds_build_fundamentals_rows_with_filing_timestamp() { + let fields = full_test_fields(); + let doc = make_valid_doc("AAPL:US"); + + let mut observations: Vec> = Vec::new(); + let decode_stats = + decode_qm_financials_bytes(doc.as_bytes(), &fields, token_period_cfg(), |obs| { + observations.push(obs); + }) + .unwrap(); + assert_conservation(&decode_stats); + assert_eq!(observations.len(), 1); + + let timefiled = "2024-08-02T16:30:15 EDT"; + // 2024-08-02T16:30:15 EDT == 2024-08-02T20:30:15Z (1,722,630,615 seconds since Unix epoch). + let expected_micros: i64 = 1_722_630_615_000_000; + + let filings = vec![QmFiling { + key: "AAPL:US", + timefiled: timefiled.to_string(), + form_type: "10-Q".to_string(), + filing_id: Some("0000320193-24-000081".to_string()), + url: None, + }]; + + let mut venues = BTreeMap::new(); + venues.insert("AAPL:US", StatutoryLagVenue::UsTsx); + + let build = build_fundamentals_rows(observations, filings, &venues); + assert_eq!(build.stats.observations_in, 1); + assert_eq!(build.stats.rows_out, 1); + assert_eq!(build.stats.rows_linked_to_filing, 1); + assert_eq!(build.stats.rows_statutory_lag_estimate, 0); + assert_eq!(build.rows.len(), 1); + + let row = &build.rows[0]; + assert_eq!(row.key, "AAPL:US"); + assert_eq!(row.period_end, ymd_to_epoch_days(2024, 6, 30).unwrap()); + assert_eq!(row.fiscal_period, FiscalPeriod::Quarterly); + assert_eq!(row.currency, "USD"); + assert_eq!(row.known_at_utc_micros, expected_micros); + assert_eq!(row.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert_eq!(row.fields.revenue, Some(1_250_000.5)); + assert_eq!(row.fields.net_income, Some(125_000.0)); + assert_eq!(row.fields.operating_cash_flow, Some(300_000.75)); + assert_eq!(row.fields.total_assets, Some(9_000_000_000.0)); + assert_eq!(row.fields.total_equity, Some(4_500_000.25)); + assert_eq!(row.fields.shares_outstanding, Some(100_000_000.0)); +} + +#[test] +fn nested_vintages_preserve_the_earlier_snapshot_until_the_amended_filing() { + let fields = QmFinancialsFieldNames { + key: "metadata.identity.code", + period_end: "metadata.period.end", + report_period: "metadata.period.token", + report_date: "metadata.period.vintage", + ..QmFinancialsFieldNames::with_verified_defaults( + "metadata.identity.currency", + Some("IncomeStatement.values.revenue"), + None, + None, + None, + None, + None, + ) + }; + let statement = |vintage: RawBson, revenue: i32| { + let mut identity = RawDocumentBuf::new(); + identity.append(cstr!("code"), "FIXTURE:CA"); + identity.append(cstr!("currency"), "CAD"); + let mut period = RawDocumentBuf::new(); + period.append(cstr!("end"), "2024-06-30"); + period.append(cstr!("token"), "Q2"); + period.append(cstr!("vintage"), vintage); + let mut metadata = RawDocumentBuf::new(); + metadata.append(cstr!("identity"), identity); + metadata.append(cstr!("period"), period); + let mut values = RawDocumentBuf::new(); + values.append(cstr!("revenue"), revenue); + let mut income = RawDocumentBuf::new(); + income.append(cstr!("values"), values); + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("metadata"), metadata); + doc.append(cstr!("IncomeStatement"), income); + doc + }; + let original = statement(RawBson::String("2024-08-02".to_owned()), 2_100_000); + let amendment = statement(RawBson::String("2024-09-06".to_owned()), 900_000); + let invalid = statement(RawBson::DateTime(BsonDateTime::from_millis(i64::MAX)), 1); + let filing = |timefiled: &str, form_type: &str, id: &str| QmFiling { + key: "FIXTURE:CA", + timefiled: timefiled.to_owned(), + form_type: form_type.to_owned(), + filing_id: Some(id.to_owned()), + url: None, + }; + let original_filing = filing("2024-08-02T16:30:15 EDT", "10-Q", "fixture-original"); + let amended_filing = filing("2024-09-06T16:30:15 EDT", "10-Q/A", "fixture-amended"); + let original_micros = 1_722_630_615_000_000; + let amended_micros = 1_725_654_615_000_000; + let venues = BTreeMap::from([("FIXTURE:CA", StatutoryLagVenue::UsTsx)]); + let decode = |bytes| { + let mut observations = Vec::new(); + let stats = decode_qm_financials_buffer(bytes, &fields, token_period_cfg(), |obs| { + observations.push(obs); + }) + .unwrap(); + assert_conservation(&stats); + (observations, stats) + }; + + let (baseline, _) = decode(original.as_bytes()); + let baseline = build_fundamentals_rows(baseline, [original_filing.clone()], &venues); + let baseline = build_fundamentals_snapshots(&baseline.rows, 1).unwrap(); + let input = [ + amendment.as_bytes(), + invalid.as_bytes(), + original.as_bytes(), + ] + .concat(); + let (observations, stats) = decode(&input); + let full = build_fundamentals_rows(observations, [amended_filing, original_filing], &venues); + let snapshots = build_fundamentals_snapshots(&full.rows, 1).unwrap(); + + assert_eq!( + stats, + BsonQmFinancialsDecodeStats { + docs_in: 3, + rows_out: 2, + skipped_report_date_out_of_range: 1, + ..Default::default() + } + ); + assert_eq!(full.stats.rows_linked_to_filing, 2); + assert_eq!(full.stats.rows_statutory_lag_estimate, 0); + assert_eq!(snapshots.len(), 2); + assert_eq!(as_of(&snapshots, "FIXTURE:CA", original_micros - 1), None); + let prior = as_of(&snapshots, "FIXTURE:CA", amended_micros - 1).unwrap(); + assert_eq!(prior, &baseline[0]); + assert_eq!(prior.effective_known_at_utc_micros, original_micros); + assert_eq!(prior.periods[0].fields.revenue, Some(2_100_000.0)); + let revised = as_of(&snapshots, "FIXTURE:CA", amended_micros).unwrap(); + assert_eq!(revised.effective_known_at_utc_micros, amended_micros); + assert_eq!(revised.periods[0].fields.revenue, Some(900_000.0)); +} + +#[test] +fn distinguishes_null_and_scalar_intermediates_and_matches_period_tokens_verbatim() { + let fields = QmFinancialsFieldNames { + report_date: "disclosure.vintage", + ..QmFinancialsFieldNames::with_verified_defaults( + "currency", + Some("IncomeStatement.revenue"), + None, + None, + None, + None, + None, + ) + }; + let fixture = |token: &str, disclosure: RawBson, income: RawBson| { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), " FIXTURE:CA "); + doc.append(cstr!("periodEndDate"), "2024-06-30"); + doc.append(cstr!("reportPeriod"), token); + doc.append(cstr!("currency"), "CAD"); + doc.append(cstr!("disclosure"), disclosure); + doc.append(cstr!("IncomeStatement"), income); + doc + }; + let docs = [ + fixture("Q2", RawBson::Null, RawBson::Null), + fixture("Q2", RawBson::Null, RawBson::Int32(1)), + fixture("Q2", RawBson::Int32(1), RawBson::Null), + fixture(" Q2 ", RawBson::Int32(1), RawBson::Int32(1)), + fixture("q2", RawBson::Null, RawBson::Null), + ]; + let input: Vec = docs + .iter() + .flat_map(|doc| doc.as_bytes().iter().copied()) + .collect(); + let mut rows = Vec::new(); + + let stats = decode_qm_financials_buffer(&input, &fields, token_period_cfg(), |row| { + rows.push(row); + }) + .unwrap(); + + assert_conservation(&stats); + assert_eq!( + stats, + BsonQmFinancialsDecodeStats { + docs_in: 5, + rows_out: 2, + skipped_unmapped_report_period: 2, + skipped_wrong_report_date_type: 1, + nulled_missing_path: 1, + nulled_wrong_type: 1, + ..Default::default() + } + ); + assert_eq!(rows.len(), 2); + for row in rows { + assert_eq!(row.key, " FIXTURE:CA "); + assert_eq!(row.report_date, None); + assert_eq!(row.fields.revenue, None); + } +} + +#[test] +fn validates_unused_nested_documents_at_the_depth_boundary() { + let nest = |levels| { + let mut inner = RawDocumentBuf::new(); + for _ in 1..levels { + let mut parent = RawDocumentBuf::new(); + parent.append(cstr!("nested"), inner); + inner = parent; + } + inner + }; + let mut good = make_valid_doc("AAPL:US"); + good.append(cstr!("extra"), nest(128)); + let mut bad = make_valid_doc("SHOP:CA"); + bad.append(cstr!("extra"), nest(129)); + let input = [good.as_bytes(), bad.as_bytes(), good.as_bytes()].concat(); + let mut seen = Vec::new(); + + let error = + decode_qm_financials_buffer(&input, &full_test_fields(), token_period_cfg(), |row| { + seen.push(row.key); + }) + .unwrap_err(); + + assert_eq!(seen, ["AAPL:US"]); + assert!(matches!( + error, + BsonQmFinancialsError::CorruptBson { offset, .. } + if offset == good.as_bytes().len() as u64 + )); +} diff --git a/tools/curate-etl/src/bson_stream.rs b/tools/curate-etl/src/bson_stream.rs index be7c201a..f797bf80 100644 --- a/tools/curate-etl/src/bson_stream.rs +++ b/tools/curate-etl/src/bson_stream.rs @@ -21,6 +21,10 @@ use std::error::Error; use std::fmt; use std::io; +use crate::bson_ceo_posts::{ + decode_ceo_posts_buffer, BsonCeoPostsDecodeStats, BsonCeoPostsError, CeoPostsFieldNames, + CeoPostsTimestampUnit, +}; use crate::bson_ceo_shorts::{ decode_ceo_shorts_buffer, BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames, }; @@ -40,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, }; @@ -49,7 +57,9 @@ 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; /// Default chunk buffer capacity: 8 MiB. @@ -973,6 +983,112 @@ where decode_te_market_data_chunks(&mut chunk_reader, target_symbol, on_bar, on_error) } +/// Terminal error returned by [`decode_ceo_posts_chunks`] and [`decode_ceo_posts_stream`]. +#[derive(Debug)] +pub enum BsonCeoPostsStreamError { + Stream(BsonStreamError), + Decode(BsonCeoPostsError), +} + +impl fmt::Display for BsonCeoPostsStreamError { + 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 BsonCeoPostsStreamError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Stream(err) => Some(err), + Self::Decode(err) => Some(err), + } + } +} + +impl From for BsonCeoPostsStreamError { + fn from(err: BsonStreamError) -> Self { + Self::Stream(err) + } +} + +impl From for BsonCeoPostsStreamError { + fn from(err: BsonCeoPostsError) -> Self { + Self::Decode(err) + } +} + +#[inline] +fn rebase_ceo_posts_error(base: u64, err: BsonCeoPostsError) -> BsonCeoPostsError { + match err { + BsonCeoPostsError::TruncatedDocument { + offset, + remaining, + declared_len, + } => BsonCeoPostsError::TruncatedDocument { + offset: base.saturating_add(offset), + remaining, + declared_len, + }, + BsonCeoPostsError::CorruptDocumentLength { + offset, + declared_len, + } => BsonCeoPostsError::CorruptDocumentLength { + offset: base.saturating_add(offset), + declared_len, + }, + BsonCeoPostsError::CorruptBson { offset, detail } => BsonCeoPostsError::CorruptBson { + offset: base.saturating_add(offset), + detail, + }, + other => other, + } +} + +/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_ceo_posts_buffer`], +/// accumulating [`BsonCeoPostsDecodeStats`] and rebasing structural BSON error offsets to +/// absolute stream byte offsets. +pub fn decode_ceo_posts_chunks( + reader: &mut RawBsonChunkReader, + fields: &CeoPostsFieldNames<'_>, + unit: CeoPostsTimestampUnit, + mut on_row: F, +) -> Result +where + R: io::Read, + F: for<'a> FnMut(CeoPost<&'a str>), +{ + fields.validate()?; + let mut total = BsonCeoPostsDecodeStats::default(); + while let Some(chunk) = reader.next_chunk()? { + let base = chunk.start_offset; + let chunk_stats = decode_ceo_posts_buffer(chunk.bytes, fields, unit, &mut on_row) + .map_err(|err| BsonCeoPostsStreamError::Decode(rebase_ceo_posts_error(base, err)))?; + total += chunk_stats; + } + Ok(total) +} + +/// Streams a concatenated raw BSON `ceoPosts` [`std::io::Read`] source through +/// [`decode_ceo_posts_buffer`] with bounded memory. +pub fn decode_ceo_posts_stream( + reader: R, + options: BsonStreamOptions, + fields: &CeoPostsFieldNames<'_>, + unit: CeoPostsTimestampUnit, + on_row: F, +) -> Result +where + R: io::Read, + F: for<'a> FnMut(CeoPost<&'a str>), +{ + fields.validate()?; + let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; + decode_ceo_posts_chunks(&mut chunk_reader, fields, unit, on_row) +} + /// Terminal error returned by [`decode_ceo_shorts_chunks`] and [`decode_ceo_shorts_stream`]. #[derive(Debug)] pub enum BsonCeoShortsStreamError { @@ -1222,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 for BsonQmFinancialsStreamError { + fn from(err: BsonStreamError) -> Self { + Self::Stream(err) + } +} + +impl From 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( + reader: &mut RawBsonChunkReader, + fields: &QmFinancialsFieldNames<'_>, + fiscal_period: QmFinancialsFiscalPeriod<'_>, + mut on_row: F, +) -> Result +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( + reader: R, + options: BsonStreamOptions, + fields: &QmFinancialsFieldNames<'_>, + fiscal_period: QmFinancialsFiscalPeriod<'_>, + on_row: F, +) -> Result +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; diff --git a/tools/curate-etl/src/bson_stream_tests.rs b/tools/curate-etl/src/bson_stream_tests.rs index 1ca61802..12c563fa 100644 --- a/tools/curate-etl/src/bson_stream_tests.rs +++ b/tools/curate-etl/src/bson_stream_tests.rs @@ -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); @@ -1731,6 +1737,268 @@ fn randomized_buffer_and_read_size_sweep_matches_buffer_decoder() { } } +#[test] +fn ceo_posts_chunks_match_buffer_across_small_chunks_and_respect_timestamp_unit() { + use super::{decode_ceo_posts_chunks, BsonStreamOptions, RawBsonChunkReader}; + use crate::bson_ceo_posts::{ + decode_ceo_posts_buffer, CeoPostsFieldNames, CeoPostsTimestampUnit, + }; + use crate::posts::CeoPost; + + let fields = CeoPostsFieldNames::default(); + + let mut fixture = Vec::new(); + for i in 0..40_i32 { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("ceoId"), format!("CEO{i}")); + doc.append(cstr!("spielId"), format!("sp-{i}")); + let ts_secs = 1_710_000_000_i64 + i64::from(i) * 60; + if i % 4 == 0 { + // BSON DateTime (always epoch milliseconds regardless of unit) + doc.append( + cstr!("timestamp"), + bson::DateTime::from_millis(ts_secs * 1_000), + ); + } else if i % 4 == 1 { + doc.append(cstr!("timestamp"), ts_secs); + } else if i % 4 == 2 { + doc.append(cstr!("timestamp"), ts_secs as f64); + } else { + doc.append(cstr!("timestamp"), ts_secs as i32); + } + + if i % 6 == 0 { + // Edited with numeric timestamp + doc.append(cstr!("edited"), ts_secs + 120); + } else if i % 6 == 1 { + // Edited with BSON DateTime + doc.append( + cstr!("edited"), + bson::DateTime::from_millis((ts_secs + 180) * 1_000), + ); + } else if i % 6 == 2 { + // Zero sentinel -> unedited + doc.append(cstr!("edited"), 0_i32); + } else if i % 6 == 3 { + // Semantic skip: invalid edited value (boolean true) + doc.append(cstr!("edited"), true); + } + + if i % 5 == 0 { + doc.append(cstr!("bot"), "1"); + } else if i % 5 == 1 { + doc.append(cstr!("bot"), false); + } + doc.append(cstr!("userId"), format!("user-{i}")); + if i % 9 == 0 { + // Semantic skip: wrong text type + doc.append(cstr!("spiel"), 123_i32); + } else { + doc.append(cstr!("spiel"), format!("post body #{i}")); + } + fixture.extend_from_slice(doc.as_bytes()); + } + + let to_owned = |p: CeoPost<&str>| CeoPost { + key: p.key.to_owned(), + spiel_id: p.spiel_id, + timestamp_ms: p.timestamp_ms, + edited_ms: p.edited_ms, + bot: p.bot, + user_id: p.user_id, + text: p.text, + }; + + for unit in [CeoPostsTimestampUnit::Seconds, CeoPostsTimestampUnit::Millis] { + let mut expected_rows = Vec::new(); + let expected_stats = decode_ceo_posts_buffer(&fixture, &fields, unit, |p| { + expected_rows.push(to_owned(p)); + }) + .expect("buffer decode"); + assert!(expected_stats.rows_out > 0); + assert!(expected_stats.skipped_total() > 0); + + // Tiny capacities and small read steps splitting reads within documents, plus single-chunk. + for (cap, step) in [(17, 7), (64, 19), (128, 37), (fixture.len() + 64, fixture.len())] { + let opts = BsonStreamOptions { + chunk_capacity_bytes: cap, + max_doc_bytes: 4096, + }; + let mut reader = + RawBsonChunkReader::with_options(FixedStepReader::new(&fixture, step), opts) + .unwrap(); + let mut got_rows = Vec::new(); + let got_stats = decode_ceo_posts_chunks(&mut reader, &fields, unit, |p| { + got_rows.push(to_owned(p)); + }) + .expect("chunk decode"); + + assert_eq!(got_stats, expected_stats, "unit={unit:?} cap={cap}"); + assert_eq!(got_rows, expected_rows, "unit={unit:?} cap={cap}"); + assert_eq!(reader.docs_framed() as usize, expected_stats.docs_in); + assert!( + reader.buffer_capacity() <= 4096.max(fixture.len() + 64), + "capacity {} exceeded expected bound", + reader.buffer_capacity() + ); + } + } + + // Explicitly verify 1,000x difference for numeric posting & edit timestamps and unit + // independence for BSON DateTime. + let mut unit_fixture = Vec::new(); + let numeric_ts = 1_710_000_123_i64; + let numeric_ed = 1_710_000_456_i64; + let dt_ts_ms = 1_710_000_789_000_i64; + let dt_ed_ms = 1_710_000_999_000_i64; + { + let mut d_num = RawDocumentBuf::new(); + d_num.append(cstr!("ceoId"), "NUM"); + d_num.append(cstr!("spielId"), "sp-num"); + d_num.append(cstr!("timestamp"), numeric_ts); + d_num.append(cstr!("edited"), numeric_ed); + d_num.append(cstr!("spiel"), "numeric"); + unit_fixture.extend_from_slice(d_num.as_bytes()); + + let mut d_dt = RawDocumentBuf::new(); + d_dt.append(cstr!("ceoId"), "DT"); + d_dt.append(cstr!("spielId"), "sp-dt"); + d_dt.append(cstr!("timestamp"), bson::DateTime::from_millis(dt_ts_ms)); + d_dt.append(cstr!("edited"), bson::DateTime::from_millis(dt_ed_ms)); + d_dt.append(cstr!("spiel"), "datetime"); + unit_fixture.extend_from_slice(d_dt.as_bytes()); + } + + let decode_unit = |unit: CeoPostsTimestampUnit| -> Vec> { + let mut rows = Vec::new(); + let mut reader = RawBsonChunkReader::with_options( + FixedStepReader::new(&unit_fixture, 11), + BsonStreamOptions { + chunk_capacity_bytes: 32, + max_doc_bytes: 4096, + }, + ) + .unwrap(); + decode_ceo_posts_chunks(&mut reader, &fields, unit, |p| rows.push(to_owned(p))) + .expect("decode unit fixture"); + rows + }; + + let rows_sec = decode_unit(CeoPostsTimestampUnit::Seconds); + let rows_ms = decode_unit(CeoPostsTimestampUnit::Millis); + assert_eq!(rows_sec.len(), 2); + assert_eq!(rows_ms.len(), 2); + + // Numeric doc: Seconds is 1,000x Millis for both timestamp and edited. + assert_eq!(rows_ms[0].timestamp_ms, numeric_ts); + assert_eq!(rows_sec[0].timestamp_ms, numeric_ts * 1_000); + assert_eq!(rows_ms[0].edited_ms, Some(numeric_ed)); + assert_eq!(rows_sec[0].edited_ms, Some(numeric_ed * 1_000)); + + // DateTime doc: identical under both Seconds and Millis. + assert_eq!(rows_ms[1].timestamp_ms, dt_ts_ms); + assert_eq!(rows_sec[1].timestamp_ms, dt_ts_ms); + assert_eq!(rows_ms[1].edited_ms, Some(dt_ed_ms)); + assert_eq!(rows_sec[1].edited_ms, Some(dt_ed_ms)); +} + +#[test] +fn ceo_posts_stream_rebases_corrupt_bson_offset_and_rejects_invalid_fields() { + use super::{ + decode_ceo_posts_chunks, decode_ceo_posts_stream, BsonCeoPostsStreamError, + BsonStreamError, BsonStreamOptions, RawBsonChunkReader, + }; + use crate::bson_ceo_posts::{BsonCeoPostsError, CeoPostsFieldNames, CeoPostsTimestampUnit}; + + // Duplicate field role rejected before reading. + let bad_fields = CeoPostsFieldNames { + key: "ceoId", + spiel_id: "ceoId", + ..CeoPostsFieldNames::default() + }; + assert!(matches!( + decode_ceo_posts_stream( + Cursor::new(Vec::::new()), + BsonStreamOptions::default(), + &bad_fields, + CeoPostsTimestampUnit::Millis, + |_| {}, + ), + Err(BsonCeoPostsStreamError::Decode( + BsonCeoPostsError::InvalidFieldNames { .. } + )) + )); + + let fields = CeoPostsFieldNames::default(); + let mut good = RawDocumentBuf::new(); + good.append(cstr!("ceoId"), "RY"); + good.append(cstr!("spielId"), "sp-1"); + good.append(cstr!("timestamp"), 1_710_460_800_000_i64); + good.append(cstr!("spiel"), "ok"); + let good_bytes = good.into_bytes(); + + let mut corrupt = RawDocumentBuf::new(); + corrupt.append(cstr!("ceoId"), "TD"); + corrupt.append(cstr!("z"), 1_i32); + let mut corrupt_bytes = corrupt.into_bytes(); + let z_pos = corrupt_bytes + .windows(3) + .position(|w| w == [0x10, b'z', 0x00]) + .expect("locate z"); + corrupt_bytes[z_pos] = 0x7e; + + let mut combined = Vec::new(); + combined.extend_from_slice(&good_bytes); + combined.extend_from_slice(&good_bytes); + let expected_offset = combined.len() as u64; + combined.extend_from_slice(&corrupt_bytes); + + // Chunk capacity == one doc forces the corrupt doc into a subsequent chunk. + let opts = BsonStreamOptions { + chunk_capacity_bytes: good_bytes.len(), + max_doc_bytes: 4096, + }; + let mut reader = RawBsonChunkReader::with_options(Cursor::new(combined), opts).unwrap(); + let err = decode_ceo_posts_chunks( + &mut reader, + &fields, + CeoPostsTimestampUnit::Millis, + |_| {}, + ) + .unwrap_err(); + assert!( + matches!( + err, + BsonCeoPostsStreamError::Decode(BsonCeoPostsError::CorruptBson { offset, .. }) + if offset == expected_offset + ), + "expected rebased CorruptBson at {expected_offset}, got {err:?}" + ); + + // Truncated trailing document preserves RawBsonChunkReader's absolute offset. + let mut truncated = Vec::new(); + truncated.extend_from_slice(&good_bytes); + let trunc_offset = truncated.len() as u64; + truncated.extend_from_slice(&64_i32.to_le_bytes()); + truncated.extend_from_slice(&[0x02, b'a', 0x00]); + let err = decode_ceo_posts_stream( + Cursor::new(truncated), + opts, + &fields, + CeoPostsTimestampUnit::Millis, + |_| {}, + ) + .unwrap_err(); + assert!( + matches!( + err, + BsonCeoPostsStreamError::Stream(BsonStreamError::TruncatedDocument { offset, .. }) + if offset == trunc_offset + ), + "expected TruncatedDocument at {trunc_offset}, got {err:?}" + ); +} + #[test] fn ceo_shorts_stream_matches_buffer_across_small_chunks_and_preserves_bounded_capacity() { use super::{decode_ceo_shorts_chunks, BsonStreamOptions, RawBsonChunkReader}; @@ -2462,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, + net_income_str: Option<&str>, + total_assets: Option, +) -> Vec { + 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 { + 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::::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 { + 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 { .. }) + )); +} diff --git a/tools/curate-etl/src/bson_te_data.rs b/tools/curate-etl/src/bson_te_data.rs new file mode 100644 index 00000000..b82b1509 --- /dev/null +++ b/tools/curate-etl/src/bson_te_data.rs @@ -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, + }, + /// 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 { + 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 { + 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 = None; + let mut value: Option = None; + let mut d_err: Option = None; + let mut v_err: Option = 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 = None; + let mut country: Option<&'a str> = None; + let mut country_err: Option = None; + let mut category: Option<&'a str> = None; + let mut category_err: Option = None; + let mut data_elem: Option> = 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; diff --git a/tools/curate-etl/src/bson_te_data_tests.rs b/tools/curate-etl/src/bson_te_data_tests.rs new file mode 100644 index 00000000..88218964 --- /dev/null +++ b/tools/curate-etl/src/bson_te_data_tests.rs @@ -0,0 +1,1282 @@ +use bson::raw::{cstr, RawArrayBuf, RawBson, RawDocumentBuf}; +use bson::spec::ElementType; +use bson::DateTime; + +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 date") +} + +fn assert_stats_conserved(stats: &BsonTeDataDecodeStats) { + assert_eq!( + stats.docs_in, + stats.docs_accepted + stats.docs_rejected_total(), + "doc conservation failed: {stats:?}" + ); + assert_eq!( + stats.points_in, + stats.points_decoded + stats.rejected_total(), + "point conservation failed: {stats:?}" + ); +} + +#[derive(Debug, PartialEq)] +struct OwnedPoint { + te_symbol: String, + country: String, + category: String, + period_date: i32, + value_bits: u64, +} + +impl From> for OwnedPoint { + fn from(p: TeDataPoint<'_>) -> Self { + Self { + te_symbol: p.te_symbol.to_owned(), + country: p.country.to_owned(), + category: p.category.to_owned(), + period_date: p.period_date, + value_bits: p.value.to_bits(), + } + } +} + +fn make_point_f64(d: &str, v: f64) -> RawDocumentBuf { + let mut pt = RawDocumentBuf::new(); + pt.append(cstr!("d"), d); + pt.append(cstr!("v"), v); + pt +} + +fn make_writer_order_doc( + te_symbol: &str, + country: &str, + category: &str, + data: RawArrayBuf, + forecast: Option, +) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + // Exact field order from `apps/stock/data-ingestion/src/handlers/te/actions/data-fetch.action.ts:93-105` + doc.append(cstr!("teSymbol"), te_symbol); + doc.append(cstr!("name"), "United States Fed Funds Interest Rate"); + doc.append(cstr!("unit"), "percent"); + doc.append(cstr!("source"), "Federal Reserve"); + doc.append(cstr!("frequency"), "Daily"); + doc.append(cstr!("country"), country); + doc.append(cstr!("category"), category); + doc.append(cstr!("data"), data); + if let Some(fc) = forecast { + doc.append(cstr!("forecast"), fc); + } + doc.append( + cstr!("lastUpdated"), + DateTime::from_millis(1_710_000_000_000), + ); + doc.append(cstr!("createdAt"), DateTime::from_millis(1_700_000_000_000)); + doc +} + +#[test] +fn decodes_writer_order_document_across_all_three_entry_points() { + let mut data = RawArrayBuf::new(); + data.push(make_point_f64("2024-02-29", 5.5_f64)); + data.push(make_point_f64("2024-03-31", -0.25_f64)); + data.push(make_point_f64("1970-01-01", 0.0_f64)); + + let doc = make_writer_order_doc("FDTR", "United States", "Interest Rate", data, None); + + let expected = vec![ + OwnedPoint { + te_symbol: "FDTR".to_owned(), + country: "United States".to_owned(), + category: "Interest Rate".to_owned(), + period_date: 19_782, // 2024-02-29 + value_bits: 5.5_f64.to_bits(), + }, + OwnedPoint { + te_symbol: "FDTR".to_owned(), + country: "United States".to_owned(), + category: "Interest Rate".to_owned(), + period_date: day(2024, 3, 31), + value_bits: (-0.25_f64).to_bits(), + }, + OwnedPoint { + te_symbol: "FDTR".to_owned(), + country: "United States".to_owned(), + category: "Interest Rate".to_owned(), + period_date: 0, + value_bits: 0.0_f64.to_bits(), + }, + ]; + + // 1. decode_te_data_doc (verify zero-copy borrowed slices directly) + let mut doc_points: Vec> = Vec::new(); + let mut doc_errs = Vec::new(); + let doc_stats = decode_te_data_doc(&doc, |p| doc_points.push(p), |e| doc_errs.push(e)); + assert_stats_conserved(&doc_stats); + assert!(doc_errs.is_empty(), "unexpected errors: {doc_errs:?}"); + assert_eq!(doc_stats.docs_in, 1); + assert_eq!(doc_stats.docs_accepted, 1); + assert_eq!(doc_stats.points_in, 3); + assert_eq!(doc_stats.points_decoded, 3); + let doc_owned: Vec = doc_points.into_iter().map(OwnedPoint::from).collect(); + assert_eq!(doc_owned, expected); + + // 2. decode_te_data_bytes + let mut bytes_points = Vec::new(); + let mut bytes_errs = Vec::new(); + let bytes_stats = decode_te_data_bytes( + doc.as_bytes(), + |p| bytes_points.push(OwnedPoint::from(p)), + |e| bytes_errs.push(e), + ); + assert_stats_conserved(&bytes_stats); + assert!(bytes_errs.is_empty(), "unexpected errors: {bytes_errs:?}"); + assert_eq!(bytes_stats, doc_stats); + assert_eq!(bytes_points, expected); + + // 3. decode_te_data_buffer + let mut buf_points = Vec::new(); + let mut buf_errs = Vec::new(); + let buf_stats = decode_te_data_buffer( + doc.as_bytes(), + |p| buf_points.push(OwnedPoint::from(p)), + |off, e| buf_errs.push((off, e)), + ); + assert_stats_conserved(&buf_stats); + assert!(buf_errs.is_empty(), "unexpected errors: {buf_errs:?}"); + assert_eq!(buf_stats, doc_stats); + assert_eq!(buf_points, expected); +} + +#[test] +fn empty_data_array_accepts_document_and_emits_zero_points() { + let doc = make_writer_order_doc( + "CACPI", + "Canada", + "Inflation Rate", + RawArrayBuf::new(), + None, + ); + let mut points = Vec::new(); + let mut errs = Vec::new(); + let stats = decode_te_data_doc(&doc, |p| points.push(p), |e| errs.push(e)); + + assert_stats_conserved(&stats); + assert!(errs.is_empty(), "unexpected errors: {errs:?}"); + assert!(points.is_empty()); + assert_eq!(stats.docs_in, 1); + assert_eq!(stats.docs_accepted, 1); + assert_eq!(stats.points_in, 0); + assert_eq!(stats.points_decoded, 0); +} + +#[test] +fn data_before_metadata_decodes_identically_to_writer_order() { + let make_data = || { + let mut data = RawArrayBuf::new(); + data.push(make_point_f64("2024-02-29", 4.75_f64)); + data.push(make_point_f64("2025-01-15", 3.25_f64)); + data + }; + + let writer_doc = make_writer_order_doc("CABOC", "Canada", "Interest Rate", make_data(), None); + + let mut reordered_doc = RawDocumentBuf::new(); + reordered_doc.append(cstr!("data"), make_data()); + reordered_doc.append(cstr!("category"), "Interest Rate"); + reordered_doc.append(cstr!("country"), "Canada"); + reordered_doc.append(cstr!("teSymbol"), "CABOC"); + + let mut writer_points = Vec::new(); + let mut writer_errs = Vec::new(); + let writer_stats = decode_te_data_doc( + &writer_doc, + |p| writer_points.push(OwnedPoint::from(p)), + |e| writer_errs.push(e), + ); + + let mut reordered_points = Vec::new(); + let mut reordered_errs = Vec::new(); + let reordered_stats = decode_te_data_doc( + &reordered_doc, + |p| reordered_points.push(OwnedPoint::from(p)), + |e| reordered_errs.push(e), + ); + + assert_stats_conserved(&writer_stats); + assert_stats_conserved(&reordered_stats); + assert!(writer_errs.is_empty()); + assert!(reordered_errs.is_empty()); + assert_eq!(reordered_stats, writer_stats); + assert_eq!(reordered_points, writer_points); +} + +#[test] +fn forecast_is_never_read_or_emitted_before_after_or_when_corrupted() { + let make_data = || { + let mut data = RawArrayBuf::new(); + data.push(make_point_f64("2024-02-29", 3.1_f64)); + data.push(make_point_f64("2024-03-31", 3.2_f64)); + data + }; + + let make_forecast = || { + let mut fc = RawArrayBuf::new(); + fc.push(make_point_f64("2026-06-30", 2.0_f64)); + fc.push("not-even-a-document"); + let mut bad_pt = RawDocumentBuf::new(); + bad_pt.append(cstr!("d"), "invalid-date"); + bad_pt.append(cstr!("v"), RawBson::Null); + fc.push(bad_pt); + fc + }; + + // Baseline: data-only + let baseline_doc = make_writer_order_doc( + "USCPI", + "United States", + "Inflation Rate", + make_data(), + None, + ); + let mut base_points = Vec::new(); + let mut base_errs = Vec::new(); + let base_stats = decode_te_data_doc( + &baseline_doc, + |p| base_points.push(OwnedPoint::from(p)), + |e| base_errs.push(e), + ); + assert_stats_conserved(&base_stats); + assert!(base_errs.is_empty()); + assert_eq!(base_points.len(), 2); + + // Variant 1: populated forecast AFTER data (writer order) + let after_doc = make_writer_order_doc( + "USCPI", + "United States", + "Inflation Rate", + make_data(), + Some(make_forecast()), + ); + let mut after_points = Vec::new(); + let mut after_errs = Vec::new(); + let after_stats = decode_te_data_doc( + &after_doc, + |p| after_points.push(OwnedPoint::from(p)), + |e| after_errs.push(e), + ); + assert_eq!(after_stats, base_stats); + assert_eq!(after_points, base_points); + assert!(after_errs.is_empty()); + + // Variant 2: populated forecast BEFORE data + let mut before_doc = RawDocumentBuf::new(); + before_doc.append(cstr!("forecast"), make_forecast()); + before_doc.append(cstr!("teSymbol"), "USCPI"); + before_doc.append(cstr!("country"), "United States"); + before_doc.append(cstr!("category"), "Inflation Rate"); + before_doc.append(cstr!("data"), make_data()); + + let mut before_points = Vec::new(); + let mut before_errs = Vec::new(); + let before_stats = decode_te_data_doc( + &before_doc, + |p| before_points.push(OwnedPoint::from(p)), + |e| before_errs.push(e), + ); + assert_eq!(before_stats, base_stats); + assert_eq!(before_points, base_points); + assert!(before_errs.is_empty()); + + // Variant 3: corrupt a byte inside the `forecast` array payload while preserving the + // enclosing array length and document terminator. If `elem.value()` or array iteration ever + // inspected `forecast`, this would fail with a corrupt BSON error. + let mut corrupt_fc_bytes = before_doc.as_bytes().to_vec(); + // Locate the array element `\x04forecast\0`, then advance past its 4-byte length prefix + // into the first inner array element's type byte (`0x03` EmbeddedDocument) and corrupt it + // to `0xFF`. + let fc_header = b"\x04forecast\0"; + let fc_pos = corrupt_fc_bytes + .windows(fc_header.len()) + .position(|w| w == fc_header) + .expect("find forecast array element"); + let first_inner_elem_type_pos = fc_pos + fc_header.len() + 4; + assert_eq!( + corrupt_fc_bytes[first_inner_elem_type_pos], 0x03, + "expected EmbeddedDocument type byte for forecast[0]" + ); + corrupt_fc_bytes[first_inner_elem_type_pos] = 0xFF; + + let mut corrupt_fc_points = Vec::new(); + let mut corrupt_fc_errs = Vec::new(); + let corrupt_fc_stats = decode_te_data_bytes( + &corrupt_fc_bytes, + |p| corrupt_fc_points.push(OwnedPoint::from(p)), + |e| corrupt_fc_errs.push(e), + ); + assert_stats_conserved(&corrupt_fc_stats); + assert_eq!(corrupt_fc_stats, base_stats); + assert_eq!(corrupt_fc_points, base_points); + assert!( + corrupt_fc_errs.is_empty(), + "corrupt forecast payload must never be read, got: {corrupt_fc_errs:?}" + ); +} + +#[test] +fn rejects_missing_empty_and_wrong_type_required_top_level_fields() { + let valid_data = || { + let mut data = RawArrayBuf::new(); + data.push(make_point_f64("2024-02-29", 1.0_f64)); + data + }; + + // Helper to assert a single rejected doc emits zero points and exact error + counter. + let check_reject = |doc: RawDocumentBuf, + expected_err: BsonTeDataError, + check_counter: fn(&BsonTeDataDecodeStats) -> usize| { + let mut points = Vec::new(); + let mut errs = Vec::new(); + let stats = decode_te_data_doc(&doc, |p| points.push(p), |e| errs.push(e)); + assert_stats_conserved(&stats); + assert!(points.is_empty(), "rejected doc must emit zero points"); + assert_eq!(stats.docs_in, 1); + assert_eq!(stats.docs_accepted, 0); + assert_eq!(stats.docs_rejected_total(), 1); + assert_eq!( + check_counter(&stats), + 1, + "wrong counter for {expected_err:?}: {stats:?}" + ); + assert_eq!(errs, vec![expected_err]); + let msg = errs[0].to_string(); + assert!(!msg.contains('\n'), "multiline error display: {msg}"); + }; + + // --- teSymbol --- + // Missing + let mut d = RawDocumentBuf::new(); + d.append(cstr!("country"), "Canada"); + d.append(cstr!("category"), "GDP"); + d.append(cstr!("data"), valid_data()); + check_reject(d, BsonTeDataError::MissingSymbol, |s| { + s.rejected_missing_symbol + }); + + // Empty ("") + let mut d = RawDocumentBuf::new(); + d.append(cstr!("teSymbol"), ""); + d.append(cstr!("country"), "Canada"); + d.append(cstr!("category"), "GDP"); + d.append(cstr!("data"), valid_data()); + check_reject(d, BsonTeDataError::EmptySymbol, |s| s.rejected_empty_symbol); + + // Whitespace-only (" \t ") + let mut d = RawDocumentBuf::new(); + d.append(cstr!("teSymbol"), " \t "); + d.append(cstr!("country"), "Canada"); + d.append(cstr!("category"), "GDP"); + d.append(cstr!("data"), valid_data()); + check_reject(d, BsonTeDataError::EmptySymbol, |s| s.rejected_empty_symbol); + + // Non-string + let mut d = RawDocumentBuf::new(); + d.append(cstr!("teSymbol"), 42_i32); + d.append(cstr!("country"), "Canada"); + d.append(cstr!("category"), "GDP"); + d.append(cstr!("data"), valid_data()); + check_reject( + d, + BsonTeDataError::WrongSymbolType { + actual: ElementType::Int32, + }, + |s| s.rejected_wrong_symbol_type, + ); + + // --- country --- + // Missing + let mut d = RawDocumentBuf::new(); + d.append(cstr!("teSymbol"), "CAGDP"); + d.append(cstr!("category"), "GDP"); + d.append(cstr!("data"), valid_data()); + check_reject(d, BsonTeDataError::MissingCountry, |s| { + s.rejected_missing_country + }); + + // Empty ("") + let mut d = RawDocumentBuf::new(); + d.append(cstr!("teSymbol"), "CAGDP"); + d.append(cstr!("country"), ""); + d.append(cstr!("category"), "GDP"); + d.append(cstr!("data"), valid_data()); + check_reject(d, BsonTeDataError::EmptyCountry, |s| { + s.rejected_empty_country + }); + + // Whitespace-only + let mut d = RawDocumentBuf::new(); + d.append(cstr!("teSymbol"), "CAGDP"); + d.append(cstr!("country"), " "); + d.append(cstr!("category"), "GDP"); + d.append(cstr!("data"), valid_data()); + check_reject(d, BsonTeDataError::EmptyCountry, |s| { + s.rejected_empty_country + }); + + // Non-string + let mut d = RawDocumentBuf::new(); + d.append(cstr!("teSymbol"), "CAGDP"); + d.append(cstr!("country"), RawBson::Null); + d.append(cstr!("category"), "GDP"); + d.append(cstr!("data"), valid_data()); + check_reject( + d, + BsonTeDataError::WrongCountryType { + actual: ElementType::Null, + }, + |s| s.rejected_wrong_country_type, + ); + + // --- category --- + // Missing + let mut d = RawDocumentBuf::new(); + d.append(cstr!("teSymbol"), "CAGDP"); + d.append(cstr!("country"), "Canada"); + d.append(cstr!("data"), valid_data()); + check_reject(d, BsonTeDataError::MissingCategory, |s| { + s.rejected_missing_category + }); + + // Empty ("") + let mut d = RawDocumentBuf::new(); + d.append(cstr!("teSymbol"), "CAGDP"); + d.append(cstr!("country"), "Canada"); + d.append(cstr!("category"), ""); + d.append(cstr!("data"), valid_data()); + check_reject(d, BsonTeDataError::EmptyCategory, |s| { + s.rejected_empty_category + }); + + // Non-string + let mut d = RawDocumentBuf::new(); + d.append(cstr!("teSymbol"), "CAGDP"); + d.append(cstr!("country"), "Canada"); + d.append(cstr!("category"), true); + d.append(cstr!("data"), valid_data()); + check_reject( + d, + BsonTeDataError::WrongCategoryType { + actual: ElementType::Boolean, + }, + |s| s.rejected_wrong_category_type, + ); + + // --- data --- + // Missing + let mut d = RawDocumentBuf::new(); + d.append(cstr!("teSymbol"), "CAGDP"); + d.append(cstr!("country"), "Canada"); + d.append(cstr!("category"), "GDP"); + check_reject(d, BsonTeDataError::MissingData, |s| s.rejected_data_missing); + + // Document-valued `data` + let mut d = RawDocumentBuf::new(); + d.append(cstr!("teSymbol"), "CAGDP"); + d.append(cstr!("country"), "Canada"); + d.append(cstr!("category"), "GDP"); + d.append(cstr!("data"), RawDocumentBuf::new()); + check_reject( + d, + BsonTeDataError::DataNotArray { + actual: ElementType::EmbeddedDocument, + }, + |s| s.rejected_data_not_array, + ); + + // Scalar `data` + let mut d = RawDocumentBuf::new(); + d.append(cstr!("teSymbol"), "CAGDP"); + d.append(cstr!("country"), "Canada"); + d.append(cstr!("category"), "GDP"); + d.append(cstr!("data"), "not-an-array"); + check_reject( + d, + BsonTeDataError::DataNotArray { + actual: ElementType::String, + }, + |s| s.rejected_data_not_array, + ); +} + +#[test] +fn point_level_validation_numeric_types_and_non_finite_passthrough() { + let mut data = RawArrayBuf::new(); + + // [0] Valid Double + data.push(make_point_f64("2024-02-29", 5.25_f64)); + + // [1] Invalid date: non-existent Feb 30 + data.push(make_point_f64("2024-02-30", 1.0_f64)); + // [2] Invalid date: non-leap year Feb 29 + data.push(make_point_f64("2023-02-29", 1.0_f64)); + // [3] Invalid date: non-padded month/day + data.push(make_point_f64("2024-2-1", 1.0_f64)); + // [4] Invalid date: leading whitespace (no trimming) + data.push(make_point_f64(" 2024-01-01", 1.0_f64)); + // [5] Invalid date: compact YYYYMMDD + data.push(make_point_f64("20240101", 1.0_f64)); + // [6] Invalid date: non-string (`Int32`) + let mut pt_int_d = RawDocumentBuf::new(); + pt_int_d.append(cstr!("d"), 20240101_i32); + pt_int_d.append(cstr!("v"), 1.0_f64); + data.push(pt_int_d); + // [7] Missing `d` + let mut pt_no_d = RawDocumentBuf::new(); + pt_no_d.append(cstr!("v"), 1.0_f64); + data.push(pt_no_d); + + // [8] Valid Int32 `v` (interleaved after bad dates to prove continuation) + let mut pt_i32 = RawDocumentBuf::new(); + pt_i32.append(cstr!("d"), "2024-03-01"); + pt_i32.append(cstr!("v"), -7_i32); + data.push(pt_i32); + + // [9] Invalid `v`: Null + let mut pt_null_v = RawDocumentBuf::new(); + pt_null_v.append(cstr!("d"), "2024-03-02"); + pt_null_v.append(cstr!("v"), RawBson::Null); + data.push(pt_null_v); + // [10] Invalid `v`: String + let mut pt_str_v = RawDocumentBuf::new(); + pt_str_v.append(cstr!("d"), "2024-03-03"); + pt_str_v.append(cstr!("v"), "5.25"); + data.push(pt_str_v); + // [11] Invalid `v`: Bool + let mut pt_bool_v = RawDocumentBuf::new(); + pt_bool_v.append(cstr!("d"), "2024-03-04"); + pt_bool_v.append(cstr!("v"), false); + data.push(pt_bool_v); + // [12] Missing `v` + let mut pt_no_v = RawDocumentBuf::new(); + pt_no_v.append(cstr!("d"), "2024-03-05"); + data.push(pt_no_v); + + // [13] Non-document array element + data.push("scalar-item"); + + // [14] Valid Int64 `v` + let mut pt_i64 = RawDocumentBuf::new(); + pt_i64.append(cstr!("d"), "2024-03-06"); + pt_i64.append(cstr!("v"), 1_000_000_000_000_i64); + data.push(pt_i64); + + // [15] Signed zero (-0.0) passed through bit-identically + data.push(make_point_f64("2024-03-07", -0.0_f64)); + // [16] Payload-bearing NaN passed through bit-identically + let payload_nan = f64::from_bits(0x7ff8_0000_0000_1234); + assert!(payload_nan.is_nan()); + data.push(make_point_f64("2024-03-08", payload_nan)); + // [17] +Infinity passed through bit-identically + data.push(make_point_f64("2024-03-09", f64::INFINITY)); + // [18] -Infinity passed through bit-identically + data.push(make_point_f64("2024-03-10", f64::NEG_INFINITY)); + + let doc = make_writer_order_doc("TEST", "United States", "CPI", data, None); + + let mut points = Vec::new(); + let mut errs = Vec::new(); + let stats = decode_te_data_doc(&doc, |p| points.push(p), |e| errs.push(e)); + + assert_stats_conserved(&stats); + assert_eq!(stats.docs_in, 1); + assert_eq!(stats.docs_accepted, 1); + assert_eq!(stats.points_in, 19); + assert_eq!(stats.points_decoded, 7); + assert_eq!(stats.rejected_invalid_date, 7); + assert_eq!(stats.rejected_invalid_value, 4); + assert_eq!(stats.rejected_point_not_document, 1); + assert_eq!(stats.rejected_corrupt_point, 0); + assert_eq!(errs.len(), 12); + + assert_eq!(points.len(), 7); + assert_eq!(points[0].period_date, 19_782); + assert_eq!(points[0].value.to_bits(), 5.25_f64.to_bits()); + + assert_eq!(points[1].period_date, day(2024, 3, 1)); + assert_eq!(points[1].value.to_bits(), (-7.0_f64).to_bits()); + + assert_eq!(points[2].period_date, day(2024, 3, 6)); + assert_eq!(points[2].value.to_bits(), 1_000_000_000_000.0_f64.to_bits()); + + assert_eq!(points[3].period_date, day(2024, 3, 7)); + assert_eq!(points[3].value.to_bits(), (-0.0_f64).to_bits()); + + assert_eq!(points[4].period_date, day(2024, 3, 8)); + assert_eq!(points[4].value.to_bits(), payload_nan.to_bits()); + + assert_eq!(points[5].period_date, day(2024, 3, 9)); + assert_eq!(points[5].value.to_bits(), f64::INFINITY.to_bits()); + + assert_eq!(points[6].period_date, day(2024, 3, 10)); + assert_eq!(points[6].value.to_bits(), f64::NEG_INFINITY.to_bits()); + + // Spot-check error variants and single-line Display + assert!(errs + .iter() + .any(|e| matches!(e, BsonTeDataError::InvalidPointDate { point_index: 1 }))); + assert!(errs.iter().any(|e| matches!( + e, + BsonTeDataError::WrongPointFieldType { + point_index: 6, + field: FIELD_POINT_D, + actual: ElementType::Int32 + } + ))); + assert!(errs.iter().any(|e| matches!( + e, + BsonTeDataError::MissingPointField { + point_index: 7, + field: FIELD_POINT_D + } + ))); + assert!(errs.iter().any(|e| matches!( + e, + BsonTeDataError::WrongPointFieldType { + point_index: 9, + field: FIELD_POINT_V, + actual: ElementType::Null + } + ))); + assert!(errs.iter().any(|e| matches!( + e, + BsonTeDataError::MissingPointField { + point_index: 12, + field: FIELD_POINT_V + } + ))); + assert!(errs.iter().any(|e| matches!( + e, + BsonTeDataError::PointNotDocument { + point_index: 13, + actual: ElementType::String + } + ))); + + for err in &errs { + let msg = err.to_string(); + assert!(!msg.contains('\n'), "multiline error display: {msg}"); + } +} + +#[test] +fn multi_doc_buffer_conservation_and_chunk_merge_parity() { + // Chunk 1: good doc + rejected doc (missing country) + mixed valid/invalid points doc + let mut chunk1 = Vec::new(); + + let mut d1_data = RawArrayBuf::new(); + d1_data.push(make_point_f64("2024-01-31", 4.5_f64)); + d1_data.push(make_point_f64("2024-02-29", 4.5_f64)); + let doc1 = make_writer_order_doc("FDTR", "United States", "Interest Rate", d1_data, None); + chunk1.extend_from_slice(doc1.as_bytes()); + + let mut doc2_missing_country = RawDocumentBuf::new(); + doc2_missing_country.append(cstr!("teSymbol"), "BAD1"); + doc2_missing_country.append(cstr!("category"), "GDP"); + doc2_missing_country.append(cstr!("data"), RawArrayBuf::new()); + chunk1.extend_from_slice(doc2_missing_country.as_bytes()); + + let mut d3_data = RawArrayBuf::new(); + d3_data.push(make_point_f64("2023-02-29", 1.0_f64)); // invalid date + d3_data.push(make_point_f64("2024-03-31", 2.9_f64)); // valid + let doc3 = make_writer_order_doc("CACPI", "Canada", "Inflation Rate", d3_data, None); + chunk1.extend_from_slice(doc3.as_bytes()); + + // Chunk 2: rejected doc (data not array) + empty-data doc + valid doc with bad v + let mut chunk2 = Vec::new(); + + let mut doc4_bad_data = RawDocumentBuf::new(); + doc4_bad_data.append(cstr!("teSymbol"), "BAD2"); + doc4_bad_data.append(cstr!("country"), "Canada"); + doc4_bad_data.append(cstr!("category"), "GDP"); + doc4_bad_data.append(cstr!("data"), 99_i32); + chunk2.extend_from_slice(doc4_bad_data.as_bytes()); + + let doc5_empty = make_writer_order_doc("EMPTY", "Canada", "GDP", RawArrayBuf::new(), None); + chunk2.extend_from_slice(doc5_empty.as_bytes()); + + let mut d6_data = RawArrayBuf::new(); + d6_data.push(123_i32); // PointNotDocument + let mut bad_v = RawDocumentBuf::new(); + bad_v.append(cstr!("d"), "2024-04-30"); + bad_v.append(cstr!("v"), "NaN"); + d6_data.push(bad_v); + d6_data.push(make_point_f64("2024-05-31", 1.75_f64)); + let doc6 = make_writer_order_doc("CAGDP", "Canada", "GDP Growth Rate", d6_data, None); + chunk2.extend_from_slice(doc6.as_bytes()); + + let mut full_buf = Vec::with_capacity(chunk1.len() + chunk2.len()); + full_buf.extend_from_slice(&chunk1); + full_buf.extend_from_slice(&chunk2); + + // Decode concatenated buffer + let mut full_points = Vec::new(); + let mut full_errs = Vec::new(); + let full_stats = decode_te_data_buffer( + &full_buf, + |p| full_points.push(OwnedPoint::from(p)), + |off, e| full_errs.push((off, e)), + ); + assert_stats_conserved(&full_stats); + + // Decode chunk 1 and chunk 2 separately and merge + let mut split_points = Vec::new(); + let stats1 = decode_te_data_buffer( + &chunk1, + |p| split_points.push(OwnedPoint::from(p)), + |_, _| {}, + ); + assert_stats_conserved(&stats1); + + let stats2 = decode_te_data_buffer( + &chunk2, + |p| split_points.push(OwnedPoint::from(p)), + |_, _| {}, + ); + assert_stats_conserved(&stats2); + + let mut merged = stats1; + merged.merge(&stats2); + assert_stats_conserved(&merged); + + assert_eq!(merged, full_stats); + assert_eq!(split_points, full_points); + assert_eq!(full_stats.docs_in, 6); + assert_eq!(full_stats.docs_accepted, 4); + assert_eq!(full_stats.docs_rejected_total(), 2); + assert_eq!(full_stats.points_in, 7); + assert_eq!(full_stats.points_decoded, 4); + assert_eq!(full_stats.rejected_total(), 3); + assert_eq!(full_errs.len(), 5); +} + +#[test] +fn framed_corrupt_doc_recovery_and_truncated_tail_offsets() { + // 1. decode_te_data_bytes on truncated input + let mut trunc_errs = Vec::new(); + let trunc_stats = decode_te_data_bytes(&[10, 0, 0, 0, 1], |_| {}, |e| trunc_errs.push(e)); + assert_stats_conserved(&trunc_stats); + assert_eq!(trunc_stats.docs_in, 1); + assert_eq!(trunc_stats.rejected_corrupt_document, 1); + assert!(matches!( + trunc_errs.as_slice(), + [BsonTeDataError::TruncatedDocument { + offset: 0, + remaining: 5, + declared_len: Some(10) + }] + )); + + // 2. Buffer: [recoverably corrupt framed doc] + [valid doc] + [truncated tail] + // Valid 4-byte length prefix (12 bytes) with invalid element type byte 0xFF and trailing NUL + let bad_framed_doc: [u8; 12] = [12, 0, 0, 0, 0xFF, b'a', 0, 0, 0, 0, 0, 0]; + + let mut good_data = RawArrayBuf::new(); + good_data.push(make_point_f64("2024-02-29", 3.5_f64)); + let good_doc = make_writer_order_doc("FDTR", "United States", "Interest Rate", good_data, None); + + let truncated_tail: [u8; 3] = [20, 0, 0]; + + let mut buf = Vec::new(); + buf.extend_from_slice(&bad_framed_doc); + let good_offset = buf.len(); + buf.extend_from_slice(good_doc.as_bytes()); + let tail_offset = buf.len(); + buf.extend_from_slice(&truncated_tail); + + let mut points = Vec::new(); + let mut errs = Vec::new(); + let stats = decode_te_data_buffer( + &buf, + |p| points.push(OwnedPoint::from(p)), + |off, e| errs.push((off, e)), + ); + + assert_stats_conserved(&stats); + assert_eq!(good_offset, 12); + assert_eq!(stats.docs_in, 3); + assert_eq!(stats.docs_accepted, 1); + assert_eq!(stats.rejected_corrupt_document, 2); + assert_eq!(stats.points_in, 1); + assert_eq!(stats.points_decoded, 1); + assert_eq!(points.len(), 1); + assert_eq!(points[0].te_symbol, "FDTR"); + assert_eq!(points[0].period_date, 19_782); + assert_eq!(points[0].value_bits, 3.5_f64.to_bits()); + + assert_eq!(errs.len(), 2); + assert_eq!(errs[0].0, 0); + assert!(matches!( + errs[0].1, + BsonTeDataError::CorruptBson { offset: 0, .. } + )); + assert_eq!(errs[1].0, tail_offset); + assert!(matches!( + errs[1].1, + BsonTeDataError::TruncatedDocument { + offset, + remaining: 3, + declared_len: None + } if offset == tail_offset + )); + + // 3. CorruptDocumentLength (< 5) terminates cleanly + let bad_len_buf: [u8; 8] = [4, 0, 0, 0, 0, 0, 0, 0]; + let mut bad_len_errs = Vec::new(); + let bad_len_stats = decode_te_data_buffer( + &bad_len_buf, + |_| panic!("no points expected"), + |off, e| bad_len_errs.push((off, e)), + ); + assert_stats_conserved(&bad_len_stats); + assert_eq!(bad_len_stats.docs_in, 1); + assert_eq!(bad_len_stats.rejected_corrupt_document, 1); + assert_eq!( + bad_len_errs, + vec![( + 0, + BsonTeDataError::CorruptDocumentLength { + offset: 0, + declared_len: 4 + } + )] + ); +} + +#[test] +fn structural_corruption_after_semantic_reject_takes_precedence() { + // 1. Point with invalid `d` followed by corrupt element type byte on `v`. + let mut pt = RawDocumentBuf::new(); + pt.append(cstr!("d"), "2024-02-30"); + pt.append(cstr!("v"), 1.25_f64); + + let mut data = RawArrayBuf::new(); + data.push(pt); + let doc = make_writer_order_doc("FDTR", "United States", "Interest Rate", data, None); + let mut bytes = doc.as_bytes().to_vec(); + let v_elem_pos = bytes + .windows(3) + .position(|w| w == b"\x01v\0") + .expect("find double element 'v'"); + bytes[v_elem_pos] = 0xFF; + + let mut points = Vec::new(); + let mut errs = Vec::new(); + let stats = decode_te_data_bytes(&bytes, |p| points.push(p), |e| errs.push(e)); + assert_stats_conserved(&stats); + assert!(points.is_empty()); + assert_eq!(stats.points_in, 1); + assert_eq!(stats.rejected_corrupt_point, 1); + assert_eq!(stats.rejected_invalid_date, 0); + assert!( + matches!( + errs.as_slice(), + [BsonTeDataError::CorruptPointBson { point_index: 0, .. }] + ), + "expected CorruptPointBson to take precedence over InvalidPointDate, got {errs:?}" + ); + + // 2. Top-level doc with empty `teSymbol` followed by corrupt element type byte on `data`. + let mut bad_top = RawDocumentBuf::new(); + bad_top.append(cstr!("teSymbol"), ""); + bad_top.append(cstr!("country"), "Canada"); + bad_top.append(cstr!("category"), "GDP"); + bad_top.append(cstr!("data"), RawArrayBuf::new()); + let mut doc_bytes = bad_top.as_bytes().to_vec(); + let data_elem_pos = doc_bytes + .windows(6) + .position(|w| w == b"\x04data\0") + .expect("find array element 'data'"); + doc_bytes[data_elem_pos] = 0xFF; + + let mut top_errs = Vec::new(); + let top_stats = decode_te_data_bytes(&doc_bytes, |_| {}, |e| top_errs.push(e)); + assert_stats_conserved(&top_stats); + assert_eq!(top_stats.rejected_corrupt_document, 1); + assert_eq!(top_stats.rejected_empty_symbol, 0); + assert!( + matches!(top_errs.as_slice(), [BsonTeDataError::CorruptBson { .. }]), + "expected CorruptBson to take precedence over EmptySymbol, got {top_errs:?}" + ); +} + +// --------------------------------------------------------------------------- +// QA (T-174) edge cases +// --------------------------------------------------------------------------- + +/// Replaces the first occurrence of `needle` in `bytes` with `replacement` (same length), so +/// BSON length prefixes and terminators stay intact. +fn patch_bytes(bytes: &mut [u8], needle: &[u8], replacement: &[u8]) { + assert_eq!(needle.len(), replacement.len()); + let pos = bytes + .windows(needle.len()) + .position(|w| w == needle) + .expect("needle present in fixture"); + bytes[pos..pos + needle.len()].copy_from_slice(replacement); +} + +fn decode_bytes_owned( + bytes: &[u8], +) -> (Vec, Vec, BsonTeDataDecodeStats) { + let mut points = Vec::new(); + let mut errs = Vec::new(); + let stats = decode_te_data_bytes( + bytes, + |p| points.push(OwnedPoint::from(p)), + |e| errs.push(e), + ); + assert_stats_conserved(&stats); + (points, errs, stats) +} + +fn two_point_data() -> RawArrayBuf { + let mut data = RawArrayBuf::new(); + data.push(make_point_f64("2024-01-31", 5.33_f64)); + data.push(make_point_f64("2024-02-29", 5.33_f64)); + data +} + +#[test] +fn qa_forecast_and_metadata_with_value_level_corruption_are_skipped_unread() { + let baseline = make_writer_order_doc( + "FDTR", + "United States", + "Interest Rate", + two_point_data(), + None, + ); + let (base_points, base_errs, base_stats) = decode_bytes_owned(baseline.as_bytes()); + assert!(base_errs.is_empty()); + assert_eq!(base_points.len(), 2); + + // `forecast` as a framed BSON string whose payload is invalid UTF-8: framing is intact, but + // `elem.value()` fails. Same for descriptive `name` and an unknown field. + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("forecast"), "QQQQFC"); + doc.append(cstr!("teSymbol"), "FDTR"); + doc.append(cstr!("name"), "QQQQNM"); + doc.append(cstr!("country"), "United States"); + doc.append(cstr!("category"), "Interest Rate"); + doc.append(cstr!("data"), two_point_data()); + doc.append(cstr!("someFutureField"), "QQQQUF"); + let mut bytes = doc.as_bytes().to_vec(); + patch_bytes(&mut bytes, b"QQQQFC", &[0xFF, 0xFE, 0xFF, 0xFE, 0xFF, 0xFE]); + patch_bytes(&mut bytes, b"QQQQNM", &[0xFF, 0xFE, 0xFF, 0xFE, 0xFF, 0xFE]); + patch_bytes(&mut bytes, b"QQQQUF", &[0xFF, 0xFE, 0xFF, 0xFE, 0xFF, 0xFE]); + + // Fixture sanity: resolving these values really fails, so a reader that called + // `elem.value()` on them would surface an error. + let raw = RawDocument::from_bytes(&bytes).expect("framing intact"); + for key in ["forecast", "name", "someFutureField"] { + let elem = raw + .iter_elements() + .map(|e| e.expect("element framing intact")) + .find(|e| e.key().as_str() == key) + .expect("key present"); + assert!( + elem.value().is_err(), + "fixture for {key} must fail at elem.value()" + ); + } + + let (points, errs, stats) = decode_bytes_owned(&bytes); + assert!( + errs.is_empty(), + "skipped fields must never be resolved: {errs:?}" + ); + assert_eq!(stats, base_stats); + assert_eq!(points, base_points); +} + +#[test] +fn qa_forecast_only_document_is_rejected_as_missing_data_with_no_fallback() { + let mut fc = RawArrayBuf::new(); + fc.push(make_point_f64("2027-12-31", 9.99_f64)); + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("teSymbol"), "FDTR"); + doc.append(cstr!("country"), "United States"); + doc.append(cstr!("category"), "Interest Rate"); + doc.append(cstr!("forecast"), fc); + + let (points, errs, stats) = decode_bytes_owned(doc.as_bytes()); + assert!( + points.is_empty(), + "forecast must never substitute for missing data" + ); + assert_eq!(errs, vec![BsonTeDataError::MissingData]); + assert_eq!(stats.rejected_data_missing, 1); + assert_eq!(stats.docs_accepted, 0); + assert_eq!(stats.points_in, 0); +} + +#[test] +fn qa_provider_labels_are_verbatim_and_borrowed_from_input_bytes() { + let doc = make_writer_order_doc( + " usgdp ", + "Côte d'Ivoire", + "GDP Growth Rate ", + two_point_data(), + None, + ); + let bytes = doc.as_bytes(); + let range = bytes.as_ptr_range(); + let mut points = Vec::new(); + let stats = decode_te_data_bytes(bytes, |p| points.push(p), |e| panic!("unexpected {e:?}")); + assert_stats_conserved(&stats); + assert_eq!(points.len(), 2); + for p in &points { + // No trimming, case folding or ISO mapping. + assert_eq!(p.te_symbol, " usgdp "); + assert_eq!(p.country, "Côte d'Ivoire"); + assert_eq!(p.category, "GDP Growth Rate "); + // Zero-copy: every label slice points into the caller's buffer. + for s in [p.te_symbol, p.country, p.category] { + assert!( + range.contains(&s.as_ptr()), + "label {s:?} not borrowed from input" + ); + } + } +} + +#[test] +fn qa_additional_strict_date_and_value_type_rejections() { + let bad_dates = [ + "2024-01-01 ", + "2024-01-01T00:00:00Z", + "2024-01-01T00:00:00.000Z", + "2024/01/01", + "", + "2024-13-01", + "2024-00-10", + "2024-01-00", + "2024-04-31", + ]; + let mut data = RawArrayBuf::new(); + for d in bad_dates { + data.push(make_point_f64(d, 1.0)); + } + // `d` as BSON DateTime (not a string) is rejected, not coerced. + let mut pt = RawDocumentBuf::new(); + pt.append(cstr!("d"), DateTime::from_millis(1_704_067_200_000)); + pt.append(cstr!("v"), 1.0_f64); + data.push(pt); + // `v` as DateTime and as an embedded document are rejected. + let mut pt = RawDocumentBuf::new(); + pt.append(cstr!("d"), "2024-01-02"); + pt.append(cstr!("v"), DateTime::from_millis(0)); + data.push(pt); + let mut pt = RawDocumentBuf::new(); + pt.append(cstr!("d"), "2024-01-03"); + pt.append(cstr!("v"), RawDocumentBuf::new()); + data.push(pt); + // Field order `v` before `d` plus an unknown point field still decodes. + let mut pt = RawDocumentBuf::new(); + pt.append(cstr!("v"), i32::MIN); + pt.append(cstr!("note"), "ignored"); + pt.append(cstr!("d"), "2000-02-29"); + data.push(pt); + let mut pt = RawDocumentBuf::new(); + pt.append(cstr!("d"), "1969-12-31"); + pt.append(cstr!("v"), i64::MAX); + data.push(pt); + + let doc = make_writer_order_doc("X", "Y", "Z", data, None); + let mut points = Vec::new(); + let mut errs = Vec::new(); + let stats = decode_te_data_doc(&doc, |p| points.push(OwnedPoint::from(p)), |e| errs.push(e)); + assert_stats_conserved(&stats); + assert_eq!(stats.points_in, 14); + assert_eq!(stats.rejected_invalid_date, 10); + assert_eq!(stats.rejected_invalid_value, 2); + assert_eq!(stats.points_decoded, 2); + assert!(errs.iter().any(|e| matches!( + e, + BsonTeDataError::WrongPointFieldType { + point_index: 9, + field: FIELD_POINT_D, + actual: ElementType::DateTime + } + ))); + assert!(errs.iter().any(|e| matches!( + e, + BsonTeDataError::WrongPointFieldType { + point_index: 11, + field: FIELD_POINT_V, + actual: ElementType::EmbeddedDocument + } + ))); + assert_eq!(points[0].period_date, day(2000, 2, 29)); + assert_eq!(points[0].value_bits, f64::from(i32::MIN).to_bits()); + assert_eq!(points[1].period_date, -1); + assert_eq!(points[1].value_bits, (i64::MAX as f64).to_bits()); +} + +#[test] +fn qa_top_level_rejection_order_is_deterministic_and_counts_once() { + // Missing teSymbol + wrong-typed country + no data: only MissingSymbol is counted. + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("data"), 1_i32); + doc.append(cstr!("country"), 5_i32); + doc.append(cstr!("category"), ""); + let (points, errs, stats) = decode_bytes_owned(doc.as_bytes()); + assert!(points.is_empty()); + assert_eq!(errs, vec![BsonTeDataError::MissingSymbol]); + assert_eq!(stats.docs_rejected_total(), 1); + assert_eq!(stats.rejected_missing_symbol, 1); + + // Valid symbol, empty country, empty category, non-array data: country wins. + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("data"), "nope"); + doc.append(cstr!("category"), ""); + doc.append(cstr!("country"), " "); + doc.append(cstr!("teSymbol"), "S"); + let (_, errs, stats) = decode_bytes_owned(doc.as_bytes()); + assert_eq!(errs, vec![BsonTeDataError::EmptyCountry]); + assert_eq!(stats.docs_rejected_total(), 1); + + // Duplicate `teSymbol` where one copy is blank fails closed in either order. + for (first, second) in [("FDTR", ""), ("", "FDTR")] { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("teSymbol"), first); + doc.append(cstr!("teSymbol"), second); + doc.append(cstr!("country"), "United States"); + doc.append(cstr!("category"), "Interest Rate"); + doc.append(cstr!("data"), two_point_data()); + let (points, errs, stats) = decode_bytes_owned(doc.as_bytes()); + assert!( + points.is_empty(), + "duplicate blank teSymbol must reject ({first:?},{second:?})" + ); + assert_eq!(errs, vec![BsonTeDataError::EmptySymbol]); + assert_eq!(stats.rejected_empty_symbol, 1); + } +} + +#[test] +fn qa_bytes_entry_point_rejects_trailing_bytes_and_short_headers() { + let doc = make_writer_order_doc( + "FDTR", + "United States", + "Interest Rate", + two_point_data(), + None, + ); + let mut bytes = doc.as_bytes().to_vec(); + bytes.push(0); + let (points, errs, stats) = decode_bytes_owned(&bytes); + assert!(points.is_empty()); + assert_eq!(stats.rejected_corrupt_document, 1); + assert!(matches!( + errs.as_slice(), + [BsonTeDataError::CorruptDocumentLength { offset: 0, .. }] + )); + + let (points, errs, stats) = decode_bytes_owned(&[1, 0]); + assert!(points.is_empty()); + assert_eq!(stats.docs_in, 1); + assert!(matches!( + errs.as_slice(), + [BsonTeDataError::TruncatedDocument { + offset: 0, + remaining: 2, + declared_len: None + }] + )); +} + +#[test] +fn qa_empty_buffer_yields_zero_stats() { + let stats = decode_te_data_buffer( + &[], + |_| panic!("no points"), + |_, e| panic!("no errors: {e:?}"), + ); + assert_eq!(stats, BsonTeDataDecodeStats::default()); +} + +#[test] +fn qa_buffer_semantic_errors_report_the_owning_document_offset() { + let good = make_writer_order_doc("A", "Canada", "GDP", two_point_data(), None); + let mut bad_point_data = RawArrayBuf::new(); + bad_point_data.push(make_point_f64("2024-02-30", 1.0)); + let bad_point = make_writer_order_doc("B", "Canada", "GDP", bad_point_data, None); + let mut no_symbol = RawDocumentBuf::new(); + no_symbol.append(cstr!("country"), "Canada"); + no_symbol.append(cstr!("category"), "GDP"); + no_symbol.append(cstr!("data"), two_point_data()); + + let mut buf = Vec::new(); + buf.extend_from_slice(good.as_bytes()); + let bad_point_off = buf.len(); + buf.extend_from_slice(bad_point.as_bytes()); + let no_symbol_off = buf.len(); + buf.extend_from_slice(no_symbol.as_bytes()); + + let mut points = Vec::new(); + let mut errs = Vec::new(); + let stats = decode_te_data_buffer( + &buf, + |p| points.push(OwnedPoint::from(p)), + |o, e| errs.push((o, e)), + ); + assert_stats_conserved(&stats); + assert_eq!(points.len(), 2); + assert!(points.iter().all(|p| p.te_symbol == "A")); + assert_eq!( + errs, + vec![ + ( + bad_point_off, + BsonTeDataError::InvalidPointDate { point_index: 0 } + ), + (no_symbol_off, BsonTeDataError::MissingSymbol), + ] + ); +} + +#[test] +fn qa_unreadable_scalar_in_data_is_counted_and_never_fabricates_points() { + // A framed scalar string with invalid UTF-8 inside `data`, between two valid points. + let mut data = RawArrayBuf::new(); + data.push(make_point_f64("2024-01-31", 1.5)); + data.push("QQQQBD"); + data.push(make_point_f64("2024-02-29", 2.5)); + let doc = make_writer_order_doc("FDTR", "United States", "Interest Rate", data, None); + let mut bytes = doc.as_bytes().to_vec(); + patch_bytes(&mut bytes, b"QQQQBD", &[0xFF, 0xFE, 0xFF, 0xFE, 0xFF, 0xFE]); + + let (points, errs, stats) = decode_bytes_owned(&bytes); + assert_eq!(stats.docs_accepted, 1); + assert_eq!(points[0].period_date, day(2024, 1, 31)); + assert_eq!(points[0].value_bits, 1.5_f64.to_bits()); + // Every emitted point is one of the genuine observations, never a fabricated one. + for p in &points { + assert!( + (p.period_date == day(2024, 1, 31) && p.value_bits == 1.5_f64.to_bits()) + || (p.period_date == day(2024, 2, 29) && p.value_bits == 2.5_f64.to_bits()), + "fabricated point {p:?}" + ); + } + assert!( + stats.rejected_total() >= 1, + "unreadable item must be counted: {stats:?}" + ); + assert!(errs.iter().any(|e| matches!( + e, + BsonTeDataError::CorruptPointBson { point_index: 1, .. } + | BsonTeDataError::PointNotDocument { point_index: 1, .. } + ))); +} diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index 11a967b9..3483d0ed 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -26,6 +26,15 @@ use crate::bench::{ DEFAULT_PARQUET_FX_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS, DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, DEFAULT_SHORTS_BENCH_ROWS, }; +use crate::bson_ceo_posts::{ + CeoPostsTimestampUnit, DEFAULT_BOT_FIELD as DEFAULT_POSTS_BOT_FIELD, + DEFAULT_EDITED_FIELD as DEFAULT_POSTS_EDITED_FIELD, + DEFAULT_KEY_FIELD as DEFAULT_POSTS_KEY_FIELD, + DEFAULT_SPIEL_ID_FIELD as DEFAULT_POSTS_SPIEL_ID_FIELD, + DEFAULT_TEXT_FIELD as DEFAULT_POSTS_TEXT_FIELD, + DEFAULT_TIMESTAMP_FIELD as DEFAULT_POSTS_TIMESTAMP_FIELD, + DEFAULT_USER_ID_FIELD as DEFAULT_POSTS_USER_ID_FIELD, +}; use crate::bson_ceo_shorts::{DEFAULT_KEY_FIELD, DEFAULT_REPORT_DATE_FIELD}; use crate::bson_eod_prices::parse_ymd_strict_days; use crate::bson_qm_events::{ @@ -44,6 +53,9 @@ use crate::run_curate_bars::{ use crate::run_curate_corporate_actions::CurateCorporateActionsArgs; use crate::run_curate_events::{CurateEventsArgs, DEFAULT_EVENTS_MAPPING_SOURCE}; use crate::run_curate_fx::{is_supported_te_symbol, CurateFx1dArgs, DEFAULT_TE_SYMBOL}; +use crate::run_curate_posts::{ + CuratePostsArgs, DEFAULT_MAPPING_SOURCE as DEFAULT_POSTS_MAPPING_SOURCE, +}; use crate::run_curate_shorts::{CurateShortsArgs, DEFAULT_MAPPING_SOURCE}; use crate::run_mongo::{ CurateAdjFactorsMongoArgs, CurateBars1dMongoArgs, CurateCorporateActionsMongoArgs, @@ -68,6 +80,7 @@ pub enum CliAction { CurateShortsMongo(CurateShortsMongoArgs), CurateEvents(CurateEventsArgs), CurateEventsMongo(CurateEventsMongoArgs), + CuratePosts(CuratePostsArgs), BenchSplit(usize), BenchAdj(usize), BenchCorporateActions(usize), @@ -127,8 +140,11 @@ pub fn format_usage(name: &str, version: &str) -> String { {name} curate-shorts --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] --provider-mapping --out --shares-short-field [--key-field ] [--report-date-field ] [--net-change-field ] [--pct-float-field ] [--mapping-source ]\n\ Curate shorts from ceoShorts BSON or read-only MongoDB + provider_mapping TSV into shorts/part.parquet (defaults: --key-field {DEFAULT_KEY_FIELD}, --report-date-field {DEFAULT_REPORT_DATE_FIELD}, --mapping-source {DEFAULT_MAPPING_SOURCE})\n\ {name} curate-events --qm-filings --qm-earnings --provider-mapping --out --filings-form-type-field [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--earnings-key-field ] [--earnings-report-date-field ] [--earnings-announce-time-field ] [--earnings-fiscal-period-end-field ] [--earnings-actual-eps-field ] [--earnings-revenue-field ] [--mapping-source ]\n\ + {name} curate-posts --ceo-posts --provider-mapping --out --timestamp-unit [--key-field ] [--spiel-id-field ] [--timestamp-field ] [--edited-field ] [--bot-field ] [--user-id-field ] [--text-field ] [--mapping-source ]\n\ {name} curate-events --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] [--date-gte ] [--date-lt ] --provider-mapping --out --filings-form-type-field [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--earnings-key-field ] [--earnings-report-date-field ] [--earnings-announce-time-field ] [--earnings-fiscal-period-end-field ] [--earnings-actual-eps-field ] [--earnings-revenue-field ] [--mapping-source ]\n\ Curate events from qmFilings + qmEarnings BSON or read-only MongoDB + provider_mapping TSV into events/year=YYYY/part.parquet (defaults: --filings-key-field {DEFAULT_FILINGS_KEY_FIELD}, --filings-timefiled-field {DEFAULT_FILINGS_TIMEFILED_FIELD}, --earnings-key-field {DEFAULT_EARNINGS_KEY_FIELD}, --earnings-report-date-field {DEFAULT_EARNINGS_REPORT_DATE_FIELD}, --earnings-announce-time-field {DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD}, --mapping-source {DEFAULT_EVENTS_MAPPING_SOURCE})\n\ + {name} curate-posts --ceo-posts --provider-mapping --out --timestamp-unit [--key-field ] [--spiel-id-field ] [--timestamp-field ] [--edited-field ] [--bot-field ] [--user-id-field ] [--text-field ] [--mapping-source ]\n\ + Curate ceoPosts from BSON + provider_mapping TSV into /events/year=YYYY/part.parquet using a dedicated --out directory (--timestamp-unit has no default; defaults: --key-field {DEFAULT_POSTS_KEY_FIELD}, --spiel-id-field {DEFAULT_POSTS_SPIEL_ID_FIELD}, --timestamp-field {DEFAULT_POSTS_TIMESTAMP_FIELD}, --edited-field {DEFAULT_POSTS_EDITED_FIELD}, --bot-field {DEFAULT_POSTS_BOT_FIELD}, --user-id-field {DEFAULT_POSTS_USER_ID_FIELD}, --text-field {DEFAULT_POSTS_TEXT_FIELD}, --mapping-source {DEFAULT_POSTS_MAPPING_SOURCE})\n\ {name} bench-split [rows] Run fixed-seed split lookup + un-adjust benchmark (default: {DEFAULT_BENCH_ROWS})\n\ {name} bench-adj [events] Run fixed-seed adj_factors build benchmark (default: {DEFAULT_ADJ_BENCH_EVENTS})\n\ {name} bench-corporate-actions [events] Run fixed-seed corporate_actions build benchmark (default: {DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS})\n\ @@ -177,6 +193,7 @@ pub fn format_usage_stderr(name: &str) -> String { {name} curate-fx-1d --eod-prices --te-market-data [--te-symbol ] --out \n\ {name} curate-shorts --ceo-shorts --provider-mapping --out --shares-short-field [--key-field ] [--report-date-field ] [--net-change-field ] [--pct-float-field ] [--mapping-source ]\n\ {name} curate-events --qm-filings --qm-earnings --provider-mapping --out --filings-form-type-field [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--earnings-key-field ] [--earnings-report-date-field ] [--earnings-announce-time-field ] [--earnings-fiscal-period-end-field ] [--earnings-actual-eps-field ] [--earnings-revenue-field ] [--mapping-source ]\n\ + {name} curate-posts --ceo-posts --provider-mapping --out --timestamp-unit [--key-field ] [--spiel-id-field ] [--timestamp-field ] [--edited-field ] [--bot-field ] [--user-id-field ] [--text-field ] [--mapping-source ]\n\ {name} bench-split [rows]\n\ {name} bench-adj [events]\n\ {name} bench-corporate-actions [events]\n\ @@ -992,6 +1009,28 @@ fn parse_curate_fx_1d_args(args: &[&str]) -> Result { })) } +fn set_path(slot: &mut Option, flag_name: &str, raw: &str) -> Result<(), String> { + if slot.is_some() { + return Err(format!("duplicate flag '{flag_name}'")); + } + if raw.is_empty() { + return Err(format!("empty value for flag '{flag_name}'")); + } + *slot = Some(PathBuf::from(raw)); + Ok(()) +} + +fn set_name(slot: &mut Option, flag_name: &str, raw: &str) -> Result<(), String> { + if slot.is_some() { + return Err(format!("duplicate flag '{flag_name}'")); + } + if raw.trim().is_empty() { + return Err(format!("empty value for flag '{flag_name}'")); + } + *slot = Some(raw.to_string()); + Ok(()) +} + fn parse_curate_shorts_args(args: &[&str]) -> Result { let mut mongo = MongoFlagState::default(); let mut ceo_shorts: Option = None; @@ -1040,28 +1079,6 @@ fn parse_curate_shorts_args(args: &[&str]) -> Result { continue; } - let set_path = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(PathBuf::from(raw)); - Ok(()) - }; - - let set_name = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.trim().is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(raw.to_string()); - Ok(()) - }; - match flag { "--ceo-shorts" => set_path(&mut ceo_shorts, "--ceo-shorts", value)?, "--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?, @@ -1149,6 +1166,119 @@ fn parse_curate_shorts_args(args: &[&str]) -> Result { Ok(CliAction::CurateShorts(parsed)) } +fn parse_curate_posts_args(args: &[&str]) -> Result { + let mut ceo_posts: Option = None; + let mut provider_mapping: Option = None; + let mut out_dir: Option = None; + let mut timestamp_unit: Option = None; + let mut key_field: Option = None; + let mut spiel_id_field: Option = None; + let mut timestamp_field: Option = None; + let mut edited_field: Option = None; + let mut bot_field: Option = None; + let mut user_id_field: Option = None; + let mut text_field: Option = None; + let mut mapping_source: Option = None; + + let mut i = 0usize; + while i < args.len() { + let token = args[i]; + if !token.starts_with("--") { + return Err(format!( + "unexpected positional argument '{token}' for curate-posts" + )); + } + + let flag_name = token.split_once('=').map_or(token, |(k, _)| k); + if !matches!( + flag_name, + "--ceo-posts" + | "--provider-mapping" + | "--out" + | "--timestamp-unit" + | "--key-field" + | "--spiel-id-field" + | "--timestamp-field" + | "--edited-field" + | "--bot-field" + | "--user-id-field" + | "--text-field" + | "--mapping-source" + ) { + return Err(format!("unknown flag '{flag_name}' for curate-posts")); + } + + let (flag, value) = if let Some((k, v)) = token.split_once('=') { + i += 1; + (k, v) + } else { + let Some(&v) = args.get(i + 1) else { + return Err(format!("missing value for flag '{token}'")); + }; + if v.starts_with("--") { + return Err(format!("missing value for flag '{token}'")); + } + i += 2; + (token, v) + }; + + match flag { + "--ceo-posts" => set_path(&mut ceo_posts, "--ceo-posts", value)?, + "--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?, + "--out" => set_path(&mut out_dir, "--out", value)?, + "--timestamp-unit" => { + if timestamp_unit.is_some() { + return Err("duplicate flag '--timestamp-unit'".to_string()); + } + timestamp_unit = Some(match value { + "seconds" => CeoPostsTimestampUnit::Seconds, + "millis" => CeoPostsTimestampUnit::Millis, + _ => { + return Err(format!( + "invalid --timestamp-unit '{value}' (expected 'seconds' or 'millis')" + )); + } + }); + } + "--key-field" => set_name(&mut key_field, "--key-field", value)?, + "--spiel-id-field" => set_name(&mut spiel_id_field, "--spiel-id-field", value)?, + "--timestamp-field" => set_name(&mut timestamp_field, "--timestamp-field", value)?, + "--edited-field" => set_name(&mut edited_field, "--edited-field", value)?, + "--bot-field" => set_name(&mut bot_field, "--bot-field", value)?, + "--user-id-field" => set_name(&mut user_id_field, "--user-id-field", value)?, + "--text-field" => set_name(&mut text_field, "--text-field", value)?, + "--mapping-source" => set_name(&mut mapping_source, "--mapping-source", value)?, + other => return Err(format!("unknown flag '{other}' for curate-posts")), + } + } + + let ceo_posts = ceo_posts.ok_or_else(|| "missing required flag '--ceo-posts'".to_string())?; + let provider_mapping = + provider_mapping.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; + let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; + let timestamp_unit = + timestamp_unit.ok_or_else(|| "missing required flag '--timestamp-unit'".to_string())?; + + let parsed = CuratePostsArgs { + ceo_posts, + provider_mapping, + out_dir, + timestamp_unit, + key_field: key_field.unwrap_or_else(|| DEFAULT_POSTS_KEY_FIELD.to_string()), + spiel_id_field: spiel_id_field.unwrap_or_else(|| DEFAULT_POSTS_SPIEL_ID_FIELD.to_string()), + timestamp_field: timestamp_field + .unwrap_or_else(|| DEFAULT_POSTS_TIMESTAMP_FIELD.to_string()), + edited_field: edited_field.unwrap_or_else(|| DEFAULT_POSTS_EDITED_FIELD.to_string()), + bot_field: bot_field.unwrap_or_else(|| DEFAULT_POSTS_BOT_FIELD.to_string()), + user_id_field: user_id_field.unwrap_or_else(|| DEFAULT_POSTS_USER_ID_FIELD.to_string()), + text_field: text_field.unwrap_or_else(|| DEFAULT_POSTS_TEXT_FIELD.to_string()), + mapping_source: mapping_source.unwrap_or_else(|| DEFAULT_POSTS_MAPPING_SOURCE.to_string()), + }; + + parsed.field_names().validate().map_err(|e| e.to_string())?; + Ok(CliAction::CuratePosts(parsed)) +} + fn parse_curate_events_args(args: &[&str]) -> Result { let mut mongo = MongoFlagState::default(); let mut qm_filings: Option = None; @@ -1437,6 +1567,7 @@ pub fn parse_args(args: &[String]) -> Result { ["curate-fx-1d", rest @ ..] => parse_curate_fx_1d_args(rest), ["curate-shorts", rest @ ..] => parse_curate_shorts_args(rest), ["curate-events", rest @ ..] => parse_curate_events_args(rest), + ["curate-posts", rest @ ..] => parse_curate_posts_args(rest), ["bench-split"] => Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)), ["bench-split", raw] => match raw.parse::() { Ok(n) if n > 0 => Ok(CliAction::BenchSplit(n)), @@ -3459,4 +3590,390 @@ mod tests { assert!(parse_args(&to_args(&["bench-fundamentals", "abc"])).is_err()); assert!(parse_args(&to_args(&["bench-fundamentals", "1", "2"])).is_err()); } + + #[test] + fn curate_posts_parsing_validation_and_usage() { + let usage = format_usage("curate-etl", "0.1.0"); + let stderr_usage = format_usage_stderr("curate-etl"); + assert!(usage.contains("curate-posts --ceo-posts")); + assert!(stderr_usage.contains("curate-posts --ceo-posts")); + + // Minimal valid invocation with --timestamp-unit seconds fills all 8 defaults + assert_eq!( + parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "posts.bson", + "--provider-mapping", + "map.tsv", + "--out", + "posts_out", + "--timestamp-unit", + "seconds", + ])), + Ok(CliAction::CuratePosts(CuratePostsArgs { + ceo_posts: PathBuf::from("posts.bson"), + provider_mapping: PathBuf::from("map.tsv"), + out_dir: PathBuf::from("posts_out"), + timestamp_unit: CeoPostsTimestampUnit::Seconds, + key_field: "ceoId".to_string(), + spiel_id_field: "spielId".to_string(), + timestamp_field: "timestamp".to_string(), + edited_field: "edited".to_string(), + bot_field: "bot".to_string(), + user_id_field: "userId".to_string(), + text_field: "spiel".to_string(), + mapping_source: "ceo".to_string(), + })) + ); + + // Minimal valid invocation with --timestamp-unit millis + assert_eq!( + parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "posts.bson", + "--provider-mapping", + "map.tsv", + "--out", + "posts_out", + "--timestamp-unit", + "millis", + ])), + Ok(CliAction::CuratePosts(CuratePostsArgs { + ceo_posts: PathBuf::from("posts.bson"), + provider_mapping: PathBuf::from("map.tsv"), + out_dir: PathBuf::from("posts_out"), + timestamp_unit: CeoPostsTimestampUnit::Millis, + key_field: DEFAULT_POSTS_KEY_FIELD.to_string(), + spiel_id_field: DEFAULT_POSTS_SPIEL_ID_FIELD.to_string(), + timestamp_field: DEFAULT_POSTS_TIMESTAMP_FIELD.to_string(), + edited_field: DEFAULT_POSTS_EDITED_FIELD.to_string(), + bot_field: DEFAULT_POSTS_BOT_FIELD.to_string(), + user_id_field: DEFAULT_POSTS_USER_ID_FIELD.to_string(), + text_field: DEFAULT_POSTS_TEXT_FIELD.to_string(), + mapping_source: DEFAULT_POSTS_MAPPING_SOURCE.to_string(), + })) + ); + + // All 8 optional flags overridden using --flag=value syntax + assert_eq!( + parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts=p2.bson", + "--provider-mapping=m2.tsv", + "--out=o2", + "--timestamp-unit=millis", + "--key-field=channel", + "--spiel-id-field=postId", + "--timestamp-field=createdAt", + "--edited-field=updatedAt", + "--bot-field=isBot", + "--user-id-field=authorId", + "--text-field=body", + "--mapping-source=ceo_alt", + ])), + Ok(CliAction::CuratePosts(CuratePostsArgs { + ceo_posts: PathBuf::from("p2.bson"), + provider_mapping: PathBuf::from("m2.tsv"), + out_dir: PathBuf::from("o2"), + timestamp_unit: CeoPostsTimestampUnit::Millis, + key_field: "channel".to_string(), + spiel_id_field: "postId".to_string(), + timestamp_field: "createdAt".to_string(), + edited_field: "updatedAt".to_string(), + bot_field: "isBot".to_string(), + user_id_field: "authorId".to_string(), + text_field: "body".to_string(), + mapping_source: "ceo_alt".to_string(), + })) + ); + + // Each missing required flag errors + for (missing_flag, args) in [ + ( + "--ceo-posts", + &[ + "curate-posts", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + ][..], + ), + ( + "--provider-mapping", + &[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--out", + "o", + "--timestamp-unit", + "seconds", + ][..], + ), + ( + "--out", + &[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--timestamp-unit", + "seconds", + ][..], + ), + ( + "--timestamp-unit", + &[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + ][..], + ), + ] { + let err = parse_args(&to_args(args)).unwrap_err(); + assert!( + err.contains(&format!("missing required flag '{missing_flag}'")), + "expected missing {missing_flag}, got: {err}" + ); + } + + // Invalid --timestamp-unit values + for bad_unit in ["", " ", "ms", "sec", "SECONDS", "MILLIS", "micros"] { + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + bad_unit, + ])) + .unwrap_err(); + assert!( + err.contains("invalid --timestamp-unit"), + "expected invalid --timestamp-unit for '{bad_unit}', got: {err}" + ); + } + + // Missing flag value (at end and followed by --flag) + let err = parse_args(&to_args(&["curate-posts", "--ceo-posts"])).unwrap_err(); + assert!(err.contains("missing value for flag '--ceo-posts'"), "{err}"); + + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + ])) + .unwrap_err(); + assert!(err.contains("missing value for flag '--ceo-posts'"), "{err}"); + + // Duplicate flags including --timestamp-unit + for (dup_flag, args) in [ + ( + "--ceo-posts", + &[ + "curate-posts", + "--ceo-posts", + "a.bson", + "--ceo-posts=b.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + ][..], + ), + ( + "--timestamp-unit", + &[ + "curate-posts", + "--ceo-posts", + "a.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + "--timestamp-unit=millis", + ][..], + ), + ( + "--key-field", + &[ + "curate-posts", + "--ceo-posts", + "a.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + "--key-field", + "k1", + "--key-field=k2", + ][..], + ), + ] { + let err = parse_args(&to_args(args)).unwrap_err(); + assert!( + err.contains(&format!("duplicate flag '{dup_flag}'")), + "expected duplicate {dup_flag}, got: {err}" + ); + } + + // Unknown flags and --from-mongo (bare, followed by other flags, or with =) + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + "--bogus", + "1", + ])) + .unwrap_err(); + assert_eq!(err, "unknown flag '--bogus' for curate-posts"); + + for from_mongo_args in [ + &["curate-posts", "--from-mongo"][..], + &[ + "curate-posts", + "--from-mongo", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + ][..], + &["curate-posts", "--from-mongo=true"][..], + ] { + let err = parse_args(&to_args(from_mongo_args)).unwrap_err(); + assert_eq!(err, "unknown flag '--from-mongo' for curate-posts"); + } + + // Positional argument rejected + let err = parse_args(&to_args(&[ + "curate-posts", + "extra", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + ])) + .unwrap_err(); + assert_eq!(err, "unexpected positional argument 'extra' for curate-posts"); + + // Empty / blank field names and path values rejected + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts=", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + ])) + .unwrap_err(); + assert!(err.contains("empty value for flag '--ceo-posts'"), "{err}"); + + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + "--text-field", + " ", + ])) + .unwrap_err(); + assert!(err.contains("empty value for flag '--text-field'"), "{err}"); + + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + "--mapping-source", + " ", + ])) + .unwrap_err(); + assert!( + err.contains("empty value for flag '--mapping-source'"), + "{err}" + ); + + // Role collisions after defaults are applied + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + "--text-field", + "ceoId", + ])) + .unwrap_err(); + assert!(err.contains("cannot share BSON field 'ceoId'"), "{err}"); + + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + "--bot-field", + "shared", + "--user-id-field", + "shared", + ])) + .unwrap_err(); + assert!(err.contains("cannot share BSON field 'shared'"), "{err}"); + } } diff --git a/tools/curate-etl/src/curate_fundamentals.rs b/tools/curate-etl/src/curate_fundamentals.rs new file mode 100644 index 00000000..02092a68 --- /dev/null +++ b/tools/curate-etl/src/curate_fundamentals.rs @@ -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, + 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 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 for CurateFundamentalsWriteError { + fn from(err: CurateFundamentalsError) -> Self { + Self::Curate(err) + } +} + +impl From 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( + observations: IO, + filings: IF, + mapping_source: &str, + mapping: &ProviderMappingTable, + venues: &BTreeMap, + k: usize, +) -> Result +where + K: AsRef, + IO: IntoIterator>, + IF: IntoIterator>, +{ + 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> = + Vec::with_capacity(obs_iter.size_hint().0); + let mut mapped_filings: Vec> = 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 = snapshots + .into_iter() + .map(FundamentalsPitParquetRow::from) + .collect(); + + let mut last_listing_id: Option = 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 `/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( + out_dir: P, + observations: IO, + filings: IF, + mapping_source: &str, + mapping: &ProviderMappingTable, + venues: &BTreeMap, + k: usize, + options: FundamentalsPitWriteOptions, +) -> Result +where + P: AsRef, + K: AsRef, + IO: IntoIterator>, + IF: IntoIterator>, +{ + 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; diff --git a/tools/curate-etl/src/curate_fundamentals_tests.rs b/tools/curate-etl/src/curate_fundamentals_tests.rs new file mode 100644 index 00000000..5dd241b1 --- /dev/null +++ b/tools/curate-etl/src/curate_fundamentals_tests.rs @@ -0,0 +1,1719 @@ +//! Unit, replay, PIT-leakage, mapping, determinism, error, and Parquet round-trip tests for +//! `curate_fundamentals`. + +use std::collections::{BTreeMap, HashMap}; +use std::error::Error; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + +use parquet::basic::Compression; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::{ + curate_and_write_fundamentals, curate_fundamentals, CurateFundamentalsError, + CurateFundamentalsStats, CurateFundamentalsWriteError, +}; +use crate::events::{ + parse_filing_timefiled, partition_year_utc, QmFiling, KNOWN_AT_SOURCE_FILING_TIMESTAMP, + KNOWN_AT_SOURCE_STATUTORY_LAG, +}; +use crate::fundamentals::{ + FinancialObservation, FiscalPeriod, FundamentalsError, FundamentalsFields, FundamentalsTtm, + StatutoryLagVenue, TtmFlowFields, +}; +use crate::parquet_fundamentals::{FundamentalsPitParquetRow, FundamentalsPitWriteOptions}; +use crate::provider_mapping::{ProviderMappingRow, ProviderMappingTable}; +use crate::shorts::et_to_utc_micros; +use crate::split::ymd_to_epoch_days; + +static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDirGuard { + path: PathBuf, +} + +impl TempDirGuard { + fn new(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = std::env::temp_dir().join(format!( + "curate-etl-curate-fundamentals-test-{label}-{pid}-{seq}" + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid test date") +} + +fn utc_micros(y: i32, m: u32, d: u32, hour: u8, minute: u8, second: u8) -> i64 { + let epoch_day = day(y, m, d); + let secs = i64::from(epoch_day) * 86_400 + + i64::from(hour) * 3_600 + + i64::from(minute) * 60 + + i64::from(second); + secs * 1_000_000 +} + +fn mapping_row( + source: &str, + source_id: &str, + valid_from: i32, + valid_to: Option, + listing_id: i32, +) -> ProviderMappingRow { + ProviderMappingRow { + source: source.to_string(), + source_id: source_id.to_string(), + valid_from, + valid_to, + listing_id, + } +} + +fn filing(key: &str, timefiled: &str, form_type: &str) -> QmFiling { + QmFiling { + key: key.to_string(), + timefiled: timefiled.to_string(), + form_type: form_type.to_string(), + filing_id: None, + url: None, + } +} + +fn obs( + key: &str, + period_end: i32, + fiscal_period: FiscalPeriod, + currency: &str, + report_date: Option, + fields: FundamentalsFields, +) -> FinancialObservation { + FinancialObservation { + key: key.to_string(), + period_end, + fiscal_period, + currency: currency.to_string(), + report_date, + fields, + } +} + +fn sample_fields( + rev: f64, + ni: f64, + ocf: f64, + assets: f64, + equity: f64, + shares: f64, +) -> FundamentalsFields { + FundamentalsFields { + revenue: Some(rev), + net_income: Some(ni), + operating_cash_flow: Some(ocf), + total_assets: Some(assets), + total_equity: Some(equity), + shares_outstanding: Some(shares), + } +} + +fn assert_stage_conservation(stats: &CurateFundamentalsStats) { + assert_eq!( + stats.observations_in, + stats.observations_dropped_unmapped + stats.build.observations_in, + "observation stage conservation failed: {stats:?}" + ); + assert_eq!( + stats.filings_in, + stats.filings_dropped_unmapped + + stats.filings_dropped_invalid_timestamp + + stats.build.filings_in, + "filing stage conservation failed: {stats:?}" + ); + assert_eq!( + stats.build.filings_dropped_invalid_timestamp, 0, + "malformed filings must be dropped at the stage before build_fundamentals_rows" + ); + assert_eq!( + stats.build.observations_in, + stats.build.rows_out + + stats.build.observations_dropped_unknown_key + + stats.build.observations_dropped_non_finite + + stats.build.observations_dropped_date_out_of_range + + stats + .build + .observations_dropped_report_date_not_after_period_end + + stats.build.observations_dropped_unanchored_vintage + + stats.build.observations_dropped_stale_estimate + + stats.build.duplicate_collapsed + + stats.build.duplicate_conflict_dropped, + "builder observation conservation failed: {stats:?}" + ); + assert_eq!( + stats.build.filings_in, + stats.build.filings_eligible + + stats.build.filings_dropped_unknown_key + + stats.build.filings_ignored_non_periodic + + stats.build.filings_dropped_invalid_timestamp + + stats.build.filings_dropped_date_out_of_range + + stats.build.filings_dropped_before_period_end, + "builder filing conservation failed: {stats:?}" + ); +} + +fn permutations(items: &[T]) -> Vec> { + if items.is_empty() { + return vec![Vec::new()]; + } + 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) { + let mut perm = Vec::with_capacity(items.len()); + perm.push(head.clone()); + perm.append(&mut tail); + out.push(perm); + } + } + out +} + +#[derive(Debug, Clone, PartialEq)] +struct DecodedParquetRow { + listing_id: i32, + effective_known_at: i64, + known_at_source: String, + has_estimated_lag: bool, + period_end: i32, + fiscal_period: String, + currency: String, + period_known_at: i64, + revenue: Option, + net_income: Option, + operating_cash_flow: Option, + total_assets: Option, + total_equity: Option, + shares_outstanding: Option, + ttm_period_end: Option, + ttm_currency: Option, + ttm_revenue: Option, + ttm_net_income: Option, + ttm_operating_cash_flow: Option, + ttm_has_estimated_lag: Option, +} + +/// Reads a `fundamentals_pit` Parquet file resolving every column strictly by schema column name +/// (never by positional index). +fn read_parquet_rows_by_name(path: &Path) -> Vec { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let meta = reader.metadata(); + let schema_descr = meta.file_metadata().schema_descr(); + + let mut col_idx_by_name: HashMap<&str, usize> = HashMap::new(); + for (idx, col) in schema_descr.columns().iter().enumerate() { + col_idx_by_name.insert(col.name(), idx); + } + + let col_idx = |name: &str| -> usize { + *col_idx_by_name + .get(name) + .unwrap_or_else(|| panic!("missing expected Parquet column '{name}'")) + }; + + let mut out = Vec::new(); + for rg_idx in 0..meta.num_row_groups() { + let rg_meta = meta.row_group(rg_idx); + for c in 0..rg_meta.num_columns() { + assert_eq!( + rg_meta.column(c).compression(), + Compression::ZSTD(Default::default()), + "expected Zstd compression on column {c}" + ); + } + + let rg_rows = rg_meta.num_rows() as usize; + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + + let read_req_i32 = |name: &str| -> Vec { + let idx = col_idx(name); + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read req i32"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected INT32 for column '{name}'"), + } + vals + }; + + let read_opt_i32 = |name: &str| -> Vec> { + let idx = col_idx(name); + let mut vals = Vec::with_capacity(rg_rows); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) + .expect("read opt i32"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected INT32 for column '{name}'"), + } + let mut vi = 0usize; + defs.into_iter() + .map(|d| { + if d == 1 { + let v = vals[vi]; + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) + .collect() + }; + + let read_req_i64 = |name: &str| -> Vec { + let idx = col_idx(name); + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(idx).expect("col reader") { + ColumnReader::Int64ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read req i64"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected INT64 for column '{name}'"), + } + vals + }; + + let read_req_bool = |name: &str| -> Vec { + let idx = col_idx(name); + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(idx).expect("col reader") { + ColumnReader::BoolColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read req bool"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BOOLEAN for column '{name}'"), + } + vals + }; + + let read_opt_bool = |name: &str| -> Vec> { + let idx = col_idx(name); + let mut vals = Vec::with_capacity(rg_rows); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(idx).expect("col reader") { + ColumnReader::BoolColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) + .expect("read opt bool"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BOOLEAN for column '{name}'"), + } + let mut vi = 0usize; + defs.into_iter() + .map(|d| { + if d == 1 { + let v = vals[vi]; + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) + .collect() + }; + + let read_opt_f64 = |name: &str| -> Vec> { + let idx = col_idx(name); + let mut vals = Vec::with_capacity(rg_rows); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(idx).expect("col reader") { + ColumnReader::DoubleColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) + .expect("read opt f64"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected DOUBLE for column '{name}'"), + } + let mut vi = 0usize; + defs.into_iter() + .map(|d| { + if d == 1 { + let v = vals[vi]; + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) + .collect() + }; + + let read_req_str = |name: &str| -> Vec { + let idx = col_idx(name); + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read req str"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BYTE_ARRAY for column '{name}'"), + } + vals.into_iter() + .map(|b| String::from_utf8(b.data().to_vec()).expect("utf8")) + .collect() + }; + + let read_opt_str = |name: &str| -> Vec> { + let idx = col_idx(name); + let mut vals = Vec::with_capacity(rg_rows); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) + .expect("read opt str"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BYTE_ARRAY for column '{name}'"), + } + let mut vi = 0usize; + defs.into_iter() + .map(|d| { + if d == 1 { + let v = String::from_utf8(vals[vi].data().to_vec()).expect("utf8"); + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) + .collect() + }; + + let listing_id = read_req_i32("listing_id"); + let effective_known_at = read_req_i64("effective_known_at"); + let known_at_source = read_req_str("known_at_source"); + let has_estimated_lag = read_req_bool("has_estimated_lag"); + let period_end = read_req_i32("period_end"); + let fiscal_period = read_req_str("fiscal_period"); + let currency = read_req_str("currency"); + let period_known_at = read_req_i64("period_known_at"); + let revenue = read_opt_f64("revenue"); + let net_income = read_opt_f64("net_income"); + let operating_cash_flow = read_opt_f64("operating_cash_flow"); + let total_assets = read_opt_f64("total_assets"); + let total_equity = read_opt_f64("total_equity"); + let shares_outstanding = read_opt_f64("shares_outstanding"); + let ttm_period_end = read_opt_i32("ttm_period_end"); + let ttm_currency = read_opt_str("ttm_currency"); + let ttm_revenue = read_opt_f64("ttm_revenue"); + let ttm_net_income = read_opt_f64("ttm_net_income"); + let ttm_operating_cash_flow = read_opt_f64("ttm_operating_cash_flow"); + let ttm_has_estimated_lag = read_opt_bool("ttm_has_estimated_lag"); + + for i in 0..rg_rows { + out.push(DecodedParquetRow { + listing_id: listing_id[i], + effective_known_at: effective_known_at[i], + known_at_source: known_at_source[i].clone(), + has_estimated_lag: has_estimated_lag[i], + period_end: period_end[i], + fiscal_period: fiscal_period[i].clone(), + currency: currency[i].clone(), + period_known_at: period_known_at[i], + revenue: revenue[i], + net_income: net_income[i], + operating_cash_flow: operating_cash_flow[i], + total_assets: total_assets[i], + total_equity: total_equity[i], + shares_outstanding: shares_outstanding[i], + ttm_period_end: ttm_period_end[i], + ttm_currency: ttm_currency[i].clone(), + ttm_revenue: ttm_revenue[i], + ttm_net_income: ttm_net_income[i], + ttm_operating_cash_flow: ttm_operating_cash_flow[i], + ttm_has_estimated_lag: ttm_has_estimated_lag[i], + }); + } + } + out +} + +fn decoded_from_curated(row: &FundamentalsPitParquetRow) -> DecodedParquetRow { + let latest = row + .latest_period() + .expect("curated row must have latest_period"); + DecodedParquetRow { + listing_id: row.listing_id, + effective_known_at: row.effective_known_at_micros, + known_at_source: row.known_at_source.to_string(), + has_estimated_lag: row.has_estimated_lag, + period_end: latest.period_end, + fiscal_period: latest.fiscal_period.to_string(), + currency: latest.currency.clone(), + period_known_at: latest.period_known_at_micros, + revenue: latest.fields.revenue, + net_income: latest.fields.net_income, + operating_cash_flow: latest.fields.operating_cash_flow, + total_assets: latest.fields.total_assets, + total_equity: latest.fields.total_equity, + shares_outstanding: latest.fields.shares_outstanding, + ttm_period_end: row.ttm.as_ref().map(|t| t.ending_period_end), + ttm_currency: row.ttm.as_ref().map(|t| t.currency.clone()), + ttm_revenue: row.ttm.as_ref().and_then(|t| t.flows.revenue), + ttm_net_income: row.ttm.as_ref().and_then(|t| t.flows.net_income), + ttm_operating_cash_flow: row.ttm.as_ref().and_then(|t| t.flows.operating_cash_flow), + ttm_has_estimated_lag: row.ttm.as_ref().map(|t| t.has_estimated_lag), + } +} + +#[test] +fn restatement_after_q2_preserves_prior_snapshots_and_never_displaces_q2() { + let mapping = + ProviderMappingTable::from_rows([mapping_row("qm", "ACME", day(2024, 1, 1), None, 1001)]) + .expect("valid mapping"); + let venues = BTreeMap::from([(1001, StatutoryLagVenue::UsTsx)]); + + let q1_end = day(2024, 3, 31); + let q2_end = day(2024, 6, 30); + let q1_fields = sample_fields(100.0, 12.0, 15.0, 500.0, 250.0, 10.0); + let q2_fields = sample_fields(130.0, 18.0, 21.0, 540.0, 270.0, 10.0); + let q1_restated_fields = sample_fields(92.0, 9.0, 11.0, 490.0, 245.0, 10.0); + + let base_observations = vec![ + obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 1)), + q1_fields, + ), + obs( + "ACME", + q2_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 8, 1)), + q2_fields, + ), + ]; + let base_filings = vec![ + filing("ACME", "2024-05-01T16:10:00 EDT", "10-Q"), + filing("ACME", "2024-08-01T16:15:00 EDT", "10-Q"), + ]; + + let baseline = curate_fundamentals( + base_observations.clone(), + base_filings.clone(), + "qm", + &mapping, + &venues, + 4, + ) + .expect("baseline curate"); + assert_stage_conservation(&baseline.stats); + assert_eq!(baseline.rows.len(), 2); + + let mut revised_observations = base_observations; + revised_observations.push(obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 9, 15)), + q1_restated_fields, + )); + let mut revised_filings = base_filings; + revised_filings.push(filing("ACME", "2024-09-15T16:30:00 EDT", "10-Q/A")); + + let revised = curate_fundamentals( + revised_observations, + revised_filings, + "qm", + &mapping, + &venues, + 4, + ) + .expect("revised curate"); + assert_stage_conservation(&revised.stats); + assert_eq!(revised.rows.len(), 3); + + let q2_known_at = parse_filing_timefiled("2024-08-01T16:15:00 EDT") + .expect("q2 ts") + .utc_micros; + let amend_known_at = parse_filing_timefiled("2024-09-15T16:30:00 EDT") + .expect("amend ts") + .utc_micros; + + // Snapshots before the amendment must be bit-for-bit identical to the baseline replay. + assert_eq!(&revised.rows[..2], &baseline.rows[..]); + + // The amendment produces a new snapshot at the amendment timestamp, while Q2 remains latest. + assert_eq!(revised.rows[2].effective_known_at_micros, amend_known_at); + for row in revised + .rows + .iter() + .filter(|r| r.effective_known_at_micros >= q2_known_at) + { + let latest = row.latest_period().expect("latest period"); + assert_eq!(latest.period_end, q2_end); + assert_eq!(latest.fields, q2_fields); + assert_eq!(latest.period_known_at_micros, q2_known_at); + assert_ne!(latest.period_end, q1_end); + } +} + +#[test] +fn statutory_lag_deadlines_and_filing_timestamp_provenance() { + let mapping = ProviderMappingTable::from_rows([ + mapping_row("qm", "US_CO", day(2024, 1, 1), None, 10), + mapping_row("qm", "TSXV_CO", day(2024, 1, 1), None, 20), + mapping_row("qm", "LINKED_CO", day(2024, 1, 1), None, 30), + ]) + .expect("valid mapping"); + let venues = BTreeMap::from([ + (10, StatutoryLagVenue::UsTsx), + (20, StatutoryLagVenue::TsxvCse), + (30, StatutoryLagVenue::UsTsx), + ]); + + let q_end = day(2024, 3, 31); + let fy_end = day(2024, 12, 31); + let fields = sample_fields(50.0, 5.0, 6.0, 200.0, 120.0, 8.0); + + // 1. UsTsx quarterly (+45d -> 2024-05-15 16:05 EDT = 20:05 UTC) + let us_q = curate_fundamentals( + [obs( + "US_CO", + q_end, + FiscalPeriod::Quarterly, + "USD", + None, + fields, + )], + Vec::>::new(), + "qm", + &mapping, + &venues, + 4, + ) + .expect("us quarterly"); + assert_eq!(us_q.rows.len(), 1); + let expected_us_q = et_to_utc_micros(q_end + 45, 16, 5, 0).expect("us q et"); + assert_eq!(expected_us_q, utc_micros(2024, 5, 15, 20, 5, 0)); + assert_eq!(us_q.rows[0].effective_known_at_micros, expected_us_q); + assert_eq!( + us_q.rows[0].known_at_source.as_ref(), + KNOWN_AT_SOURCE_STATUTORY_LAG + ); + assert!(us_q.rows[0].has_estimated_lag); + + // 2. UsTsx annual (+90d -> 2025-03-31 16:05 EDT = 20:05 UTC) + let us_fy = curate_fundamentals( + [obs( + "US_CO", + fy_end, + FiscalPeriod::Annual, + "USD", + None, + fields, + )], + Vec::>::new(), + "qm", + &mapping, + &venues, + 4, + ) + .expect("us annual"); + assert_eq!(us_fy.rows.len(), 1); + let expected_us_fy = et_to_utc_micros(fy_end + 90, 16, 5, 0).expect("us fy et"); + assert_eq!(expected_us_fy, utc_micros(2025, 3, 31, 20, 5, 0)); + assert_eq!(us_fy.rows[0].effective_known_at_micros, expected_us_fy); + assert_eq!( + us_fy.rows[0].known_at_source.as_ref(), + KNOWN_AT_SOURCE_STATUTORY_LAG + ); + assert!(us_fy.rows[0].has_estimated_lag); + + // 3. TsxvCse quarterly (+60d -> 2024-05-30 16:05 EDT = 20:05 UTC) + let tsxv_q = curate_fundamentals( + [obs( + "TSXV_CO", + q_end, + FiscalPeriod::Quarterly, + "CAD", + None, + fields, + )], + Vec::>::new(), + "qm", + &mapping, + &venues, + 4, + ) + .expect("tsxv quarterly"); + assert_eq!(tsxv_q.rows.len(), 1); + let expected_tsxv_q = et_to_utc_micros(q_end + 60, 16, 5, 0).expect("tsxv q et"); + assert_eq!(expected_tsxv_q, utc_micros(2024, 5, 30, 20, 5, 0)); + assert_eq!(tsxv_q.rows[0].effective_known_at_micros, expected_tsxv_q); + assert_eq!( + tsxv_q.rows[0].known_at_source.as_ref(), + KNOWN_AT_SOURCE_STATUTORY_LAG + ); + assert!(tsxv_q.rows[0].has_estimated_lag); + + // 4. TsxvCse annual (+120d -> 2025-04-30 16:05 EDT = 20:05 UTC) + let tsxv_fy = curate_fundamentals( + [obs( + "TSXV_CO", + fy_end, + FiscalPeriod::Annual, + "CAD", + None, + fields, + )], + Vec::>::new(), + "qm", + &mapping, + &venues, + 4, + ) + .expect("tsxv annual"); + assert_eq!(tsxv_fy.rows.len(), 1); + let expected_tsxv_fy = et_to_utc_micros(fy_end + 120, 16, 5, 0).expect("tsxv fy et"); + assert_eq!(expected_tsxv_fy, utc_micros(2025, 4, 30, 20, 5, 0)); + assert_eq!(tsxv_fy.rows[0].effective_known_at_micros, expected_tsxv_fy); + assert_eq!( + tsxv_fy.rows[0].known_at_source.as_ref(), + KNOWN_AT_SOURCE_STATUTORY_LAG + ); + assert!(tsxv_fy.rows[0].has_estimated_lag); + + // 5. Filing-linked observation uses exact parsed filing timestamp and filing_timestamp source. + let linked = curate_fundamentals( + [obs( + "LINKED_CO", + q_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 2)), + fields, + )], + [filing("LINKED_CO", "2024-05-02T08:30:15 EDT", "10-Q")], + "qm", + &mapping, + &venues, + 4, + ) + .expect("linked quarterly"); + assert_eq!(linked.rows.len(), 1); + let expected_linked = utc_micros(2024, 5, 2, 12, 30, 15); + assert_eq!(linked.rows[0].effective_known_at_micros, expected_linked); + assert_eq!( + linked.rows[0].known_at_source.as_ref(), + KNOWN_AT_SOURCE_FILING_TIMESTAMP + ); + assert!(!linked.rows[0].has_estimated_lag); +} + +#[test] +fn ticker_remap_across_utc_midnight_separates_listings_and_prevents_cross_listing_ttm() { + // Source key "REUSED" belongs to listing 101 through 2023-08-05 ET, then listing 202 starting + // 2023-08-06 ET. + let mapping = ProviderMappingTable::from_rows([ + mapping_row("qm", "REUSED", day(2023, 1, 1), Some(day(2023, 8, 5)), 101), + mapping_row("qm", "REUSED", day(2023, 8, 6), None, 202), + ]) + .expect("valid remap"); + let venues = BTreeMap::from([ + (101, StatutoryLagVenue::UsTsx), + (202, StatutoryLagVenue::UsTsx), + ]); + + let f = sample_fields(10.0, 1.0, 2.0, 50.0, 25.0, 5.0); + + // Listing 101 gets Q1 (2023-03-31) and Q2 (2023-06-30). + // Q2's filing is at 2023-08-05T21:00:00 EDT (2023-08-06T01:00:00 UTC): Eastern date is + // 2023-08-05 (listing 101), whereas UTC date is 2023-08-06 (listing 202). + // Listing 202 gets Q3 (2023-09-30) and Q4 (2023-12-31). + let observations = vec![ + obs( + "REUSED", + day(2023, 3, 31), + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 5, 10)), + f, + ), + obs( + "REUSED", + day(2023, 6, 30), + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 8, 5)), + f, + ), + obs( + "REUSED", + day(2023, 9, 30), + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 11, 8)), + f, + ), + obs( + "REUSED", + day(2023, 12, 31), + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 2, 12)), + f, + ), + ]; + let filings = vec![ + filing("REUSED", "2023-05-10T16:00:00 EDT", "10-Q"), + filing("REUSED", "2023-08-05T21:00:00 EDT", "10-Q"), + filing("REUSED", "2023-11-08T16:00:00 EST", "10-Q"), + filing("REUSED", "2024-02-12T16:00:00 EST", "10-Q"), + ]; + + let out = curate_fundamentals(observations, filings, "qm", &mapping, &venues, 4) + .expect("remap curate"); + assert_stage_conservation(&out.stats); + assert_eq!(out.stats.listings_out, 2); + assert_eq!(out.rows.len(), 4); + + let l101: Vec<&FundamentalsPitParquetRow> = + out.rows.iter().filter(|r| r.listing_id == 101).collect(); + let l202: Vec<&FundamentalsPitParquetRow> = + out.rows.iter().filter(|r| r.listing_id == 202).collect(); + assert_eq!(l101.len(), 2); + assert_eq!(l202.len(), 2); + + // Late-evening EDT filing must link to listing 101's Q2 (not listing 202). + assert_eq!( + l101[1].effective_known_at_micros, + utc_micros(2023, 8, 6, 1, 0, 0) + ); + assert_eq!( + l101[1].known_at_source.as_ref(), + KNOWN_AT_SOURCE_FILING_TIMESTAMP + ); + assert!(!l101[1].has_estimated_lag); + + // Neither listing has 4 quarters, so TTM must never span across the ticker remap. + assert!(out.rows.iter().all(|r| r.ttm.is_none())); + + // Also verify observation resolution uses period_end even when report_date falls after remap. + let after_remap_report = curate_fundamentals( + [obs( + "REUSED", + day(2023, 6, 30), + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 8, 10)), // after 2023-08-05 remap, <= statutory lag 2023-08-14 + f, + )], + Vec::>::new(), + "qm", + &mapping, + &venues, + 4, + ) + .expect("period_end resolution"); + assert_eq!(after_remap_report.rows.len(), 1); + assert_eq!(after_remap_report.rows[0].listing_id, 101); +} + +#[test] +fn unmapped_and_malformed_inputs_are_counted_and_conserved() { + let mapping = ProviderMappingTable::from_rows([mapping_row( + "qm", + "KNOWN", + day(2024, 1, 1), + Some(day(2024, 12, 31)), + 501, + )]) + .expect("valid mapping"); + let venues = BTreeMap::from([(501, StatutoryLagVenue::UsTsx)]); + let f = sample_fields(25.0, 3.0, 4.0, 100.0, 60.0, 2.0); + + let valid_obs = obs( + "KNOWN", + day(2024, 3, 31), + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 1)), + f, + ); + let valid_filing = filing("KNOWN", "2024-05-01T17:00:00 EDT", "10-Q"); + + let clean = curate_fundamentals( + [valid_obs.clone()], + [valid_filing.clone()], + "qm", + &mapping, + &venues, + 4, + ) + .expect("clean curate"); + + let with_noise = curate_fundamentals( + [ + valid_obs, + // Unmapped observation (unknown key) + obs( + "UNKNOWN", + day(2024, 3, 31), + FiscalPeriod::Quarterly, + "USD", + None, + f, + ), + // Unmapped observation (known key, period_end outside range) + obs( + "KNOWN", + day(2023, 12, 31), + FiscalPeriod::Quarterly, + "USD", + None, + f, + ), + ], + [ + valid_filing, + // Parseable unmapped filing + filing("UNKNOWN", "2024-05-01T10:00:00 EDT", "10-Q"), + // Malformed filing timestamp for mapped key + filing("KNOWN", "2024-05-01 09:00:00 UTC", "10-Q"), + ], + "qm", + &mapping, + &venues, + 4, + ) + .expect("noisy curate"); + + assert_stage_conservation(&with_noise.stats); + assert_eq!(with_noise.stats.observations_in, 3); + assert_eq!(with_noise.stats.observations_dropped_unmapped, 2); + assert_eq!(with_noise.stats.build.observations_in, 1); + + assert_eq!(with_noise.stats.filings_in, 3); + assert_eq!(with_noise.stats.filings_dropped_unmapped, 1); + assert_eq!(with_noise.stats.filings_dropped_invalid_timestamp, 1); + assert_eq!(with_noise.stats.build.filings_in, 1); + assert_eq!(with_noise.stats.build.filings_eligible, 1); + + // Malformed and unmapped inputs must have zero effect on availability or emitted rows. + assert_eq!(with_noise.rows, clean.rows); +} + +#[test] +fn permutation_invariance_and_strict_ascending_order() { + let mapping = ProviderMappingTable::from_rows([ + mapping_row("qm", "ALPHA", day(2024, 1, 1), None, 200), + mapping_row("qm", "BETA", day(2024, 1, 1), None, 100), + ]) + .expect("valid mapping"); + let venues = BTreeMap::from([ + (100, StatutoryLagVenue::UsTsx), + (200, StatutoryLagVenue::TsxvCse), + ]); + + let f1 = sample_fields(10.0, 1.0, 2.0, 40.0, 20.0, 4.0); + let f2 = sample_fields(15.0, 2.0, 3.0, 45.0, 22.0, 4.0); + let f3 = sample_fields(20.0, 3.0, 4.0, 60.0, 30.0, 6.0); + + let base_obs = vec![ + obs( + "ALPHA", + day(2024, 3, 31), + FiscalPeriod::Quarterly, + "CAD", + Some(day(2024, 5, 1)), + f1, + ), + obs( + "ALPHA", + day(2024, 6, 30), + FiscalPeriod::Quarterly, + "CAD", + Some(day(2024, 8, 1)), + f2, + ), + obs( + "BETA", + day(2024, 3, 31), + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 1)), + f3, + ), + ]; + let base_filings = vec![ + filing( + "ALPHA", + "2024-05-01T16:00:00 EDT", + "Interim financial statements", + ), + filing( + "ALPHA", + "2024-08-01T16:00:00 EDT", + "Interim financial statements", + ), + // Same-instant filing for BETA + filing("BETA", "2024-05-01T16:00:00 EDT", "10-Q"), + ]; + + let reference = curate_fundamentals( + base_obs.clone(), + base_filings.clone(), + "qm", + &mapping, + &venues, + 4, + ) + .expect("reference run"); + assert_stage_conservation(&reference.stats); + assert_eq!(reference.rows.len(), 3); + + for pair in reference.rows.windows(2) { + let a = (pair[0].listing_id, pair[0].effective_known_at_micros); + let b = (pair[1].listing_id, pair[1].effective_known_at_micros); + assert!(a < b, "rows not strictly ascending: {a:?} >= {b:?}"); + } + + let obs_perms = permutations(&base_obs); + let filing_perms = permutations(&base_filings); + assert_eq!(obs_perms.len(), 6); + assert_eq!(filing_perms.len(), 6); + + for op in &obs_perms { + for fp in &filing_perms { + let out = curate_fundamentals( + op.iter().cloned(), + fp.iter().cloned(), + "qm", + &mapping, + &venues, + 4, + ) + .expect("permuted run"); + assert_eq!(out.rows, reference.rows); + assert_eq!(out.stats, reference.stats); + } + } +} + +#[test] +fn typed_errors_and_untouched_out_dir_on_curation_failure() { + let mapping = + ProviderMappingTable::from_rows([mapping_row("qm", "ACME", day(2024, 1, 1), None, 10)]) + .expect("valid mapping"); + let venues = BTreeMap::from([(10, StatutoryLagVenue::UsTsx)]); + let invalid_writer_opts = FundamentalsPitWriteOptions { + row_group_rows: 0, + ..FundamentalsPitWriteOptions::default() + }; + + for blank_source in ["", " \t\n "] { + let err = curate_fundamentals( + Vec::>::new(), + Vec::>::new(), + blank_source, + &mapping, + &venues, + 4, + ) + .expect_err("blank mapping_source must fail"); + assert_eq!(err, CurateFundamentalsError::EmptyMappingSource); + assert!(err.source().is_none()); + assert!(err.to_string().contains("mapping_source")); + + let tmp = TempDirGuard::new("empty-source"); + let write_err = curate_and_write_fundamentals( + tmp.path(), + Vec::>::new(), + Vec::>::new(), + blank_source, + &mapping, + &venues, + 4, + invalid_writer_opts, + ) + .expect_err("curation error must take precedence over invalid writer options"); + assert!(matches!( + write_err, + CurateFundamentalsWriteError::Curate(CurateFundamentalsError::EmptyMappingSource) + )); + assert!(write_err.source().is_some()); + assert!(write_err + .to_string() + .contains("fundamentals curation failed")); + assert!( + !tmp.path().join("fundamentals_pit").exists(), + "out_dir must remain untouched on curation failure" + ); + } + + let k_err = curate_fundamentals( + Vec::>::new(), + Vec::>::new(), + "qm", + &mapping, + &venues, + 0, + ) + .expect_err("k == 0 must fail"); + assert_eq!( + k_err, + CurateFundamentalsError::Fundamentals(FundamentalsError::InvalidPeriodLimit { k: 0 }) + ); + assert!(k_err.source().is_some()); + + let tmp_k = TempDirGuard::new("k-zero"); + let write_k_err = curate_and_write_fundamentals( + tmp_k.path(), + Vec::>::new(), + Vec::>::new(), + "qm", + &mapping, + &venues, + 0, + invalid_writer_opts, + ) + .expect_err("k == 0 must fail before writer"); + assert!(matches!( + write_k_err, + CurateFundamentalsWriteError::Curate(CurateFundamentalsError::Fundamentals( + FundamentalsError::InvalidPeriodLimit { k: 0 } + )) + )); + assert!( + !tmp_k.path().join("fundamentals_pit").exists(), + "out_dir must remain untouched on k == 0 failure" + ); +} + +#[test] +fn curate_and_write_fundamentals_round_trips_four_quarters_and_ttm_by_column_name() { + let mapping = + ProviderMappingTable::from_rows([mapping_row("qm", "GROW", day(2023, 1, 1), None, 777)]) + .expect("valid mapping"); + let venues = BTreeMap::from([(777, StatutoryLagVenue::UsTsx)]); + + let q1_f = sample_fields(100.0, 10.0, 15.0, 500.0, 200.0, 10.0); + let q2_f = sample_fields(110.0, 12.0, 18.0, 520.0, 212.0, 10.0); + let q3_f = sample_fields(125.0, 14.0, 20.0, 545.0, 226.0, 10.0); + let q4_f = sample_fields(140.0, 16.0, 22.0, 575.0, 242.0, 10.0); + + let observations = vec![ + obs( + "GROW", + day(2023, 3, 31), + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 5, 1)), + q1_f, + ), + obs( + "GROW", + day(2023, 6, 30), + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 8, 1)), + q2_f, + ), + obs( + "GROW", + day(2023, 9, 30), + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 11, 1)), + q3_f, + ), + obs( + "GROW", + day(2023, 12, 31), + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 2, 15)), + q4_f, + ), + ]; + let filings = vec![ + filing("GROW", "2023-05-01T16:10:00 EDT", "10-Q"), + filing("GROW", "2023-08-01T16:10:00 EDT", "10-Q"), + filing("GROW", "2023-11-01T16:10:00 EDT", "10-Q"), + filing("GROW", "2024-02-15T16:10:00 EST", "10-Q"), + ]; + + let curated = curate_fundamentals( + observations.clone(), + filings.clone(), + "qm", + &mapping, + &venues, + 4, + ) + .expect("curate four quarters"); + assert_stage_conservation(&curated.stats); + assert_eq!(curated.rows.len(), 4); + assert!(curated.rows[0].ttm.is_none()); + assert!(curated.rows[1].ttm.is_none()); + assert!(curated.rows[2].ttm.is_none()); + assert_eq!( + curated.rows[3].ttm, + Some(FundamentalsTtm { + ending_period_end: day(2023, 12, 31), + currency: "USD".to_string(), + flows: TtmFlowFields { + revenue: Some(100.0 + 110.0 + 125.0 + 140.0), + net_income: Some(10.0 + 12.0 + 14.0 + 16.0), + operating_cash_flow: Some(15.0 + 18.0 + 20.0 + 22.0), + }, + has_estimated_lag: false, + }) + ); + + let tmp = TempDirGuard::new("round-trip"); + let report = curate_and_write_fundamentals( + tmp.path(), + observations, + filings, + "qm", + &mapping, + &venues, + 4, + FundamentalsPitWriteOptions::default(), + ) + .expect("curate and write"); + + assert_eq!(report.curate_stats, curated.stats); + assert_eq!(report.write_stats.files_written, 2); + assert_eq!(report.write_stats.rows_written, 4); + assert_eq!( + report.write_stats.rows_by_year, + BTreeMap::from([(2023, 3), (2024, 1)]) + ); + + let mut read_back = Vec::new(); + for year in [2023, 2024] { + let part_path = tmp + .path() + .join("fundamentals_pit") + .join(format!("year={year}")) + .join("part.parquet"); + assert!( + part_path.exists(), + "missing partition {}", + part_path.display() + ); + let part_rows = read_parquet_rows_by_name(&part_path); + for row in &part_rows { + assert_eq!(partition_year_utc(row.effective_known_at), year); + } + read_back.extend(part_rows); + } + + let expected: Vec = curated.rows.iter().map(decoded_from_curated).collect(); + assert_eq!(read_back, expected); +} + +// --------------------------------------------------------------------------------------------- +// QA additions (T-169): amendment TTM propagation, UTC-year partitioning, Eastern-date filing +// resolution, builder venue misses, cutoff-truncation PIT replay, and empty input. +// --------------------------------------------------------------------------------------------- + +fn grow_four_quarters() -> (Vec>, Vec>) { + let observations = vec![ + obs( + "GROW", + day(2023, 3, 31), + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 5, 1)), + sample_fields(100.0, 10.0, 15.0, 500.0, 200.0, 10.0), + ), + obs( + "GROW", + day(2023, 6, 30), + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 8, 1)), + sample_fields(110.0, 12.0, 18.0, 520.0, 212.0, 10.0), + ), + obs( + "GROW", + day(2023, 9, 30), + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 11, 1)), + sample_fields(125.0, 14.0, 20.0, 545.0, 226.0, 10.0), + ), + obs( + "GROW", + day(2023, 12, 31), + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 2, 15)), + sample_fields(140.0, 16.0, 22.0, 575.0, 242.0, 10.0), + ), + ]; + let filings = vec![ + filing("GROW", "2023-05-01T16:10:00 EDT", "10-Q"), + filing("GROW", "2023-08-01T16:10:00 EDT", "10-Q"), + filing("GROW", "2023-11-01T16:10:00 EDT", "10-Q"), + filing("GROW", "2024-02-15T16:10:00 EST", "10-Q"), + ]; + (observations, filings) +} + +fn grow_mapping() -> (ProviderMappingTable, BTreeMap) { + let mapping = + ProviderMappingTable::from_rows([mapping_row("qm", "GROW", day(2023, 1, 1), None, 777)]) + .expect("valid mapping"); + (mapping, BTreeMap::from([(777, StatutoryLagVenue::UsTsx)])) +} + +#[test] +fn q1_amendment_after_q4_first_changes_ttm_at_its_filing_instant_and_keeps_q4_latest() { + let (mapping, venues) = grow_mapping(); + let (observations, filings) = grow_four_quarters(); + + let baseline = curate_fundamentals( + observations.clone(), + filings.clone(), + "qm", + &mapping, + &venues, + 4, + ) + .expect("baseline"); + assert_eq!(baseline.rows.len(), 4); + let baseline_ttm = baseline.rows[3].ttm.clone().expect("baseline ttm"); + assert_eq!(baseline_ttm.flows.revenue, Some(475.0)); + + let mut revised_obs = observations; + revised_obs.push(obs( + "GROW", + day(2023, 3, 31), + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 3, 20)), + sample_fields(80.0, 4.0, 9.0, 480.0, 190.0, 10.0), + )); + let mut revised_filings = filings; + revised_filings.push(filing("GROW", "2024-03-20T17:45:00 EDT", "10-Q/A")); + + let revised = curate_fundamentals(revised_obs, revised_filings, "qm", &mapping, &venues, 4) + .expect("revised"); + assert_stage_conservation(&revised.stats); + assert_eq!(revised.rows.len(), 5); + + // Every pre-amendment snapshot is unchanged (no look-back leak of the restated Q1). + assert_eq!(&revised.rows[..4], &baseline.rows[..]); + + let amend_at = utc_micros(2024, 3, 20, 21, 45, 0); + let amended = &revised.rows[4]; + assert_eq!(amended.effective_known_at_micros, amend_at); + assert_eq!( + amended.known_at_source.as_ref(), + KNOWN_AT_SOURCE_FILING_TIMESTAMP + ); + + // Latest period stays Q4 with Q4's fields and Q4's original availability. + let latest = amended.latest_period().expect("latest"); + assert_eq!(latest.period_end, day(2023, 12, 31)); + assert_eq!( + latest.fields, + sample_fields(140.0, 16.0, 22.0, 575.0, 242.0, 10.0) + ); + assert_eq!( + latest.period_known_at_micros, + utc_micros(2024, 2, 15, 21, 10, 0) + ); + + // The TTM total first reflects the restated Q1 at the amendment instant. + let ttm = amended.ttm.as_ref().expect("amended ttm"); + assert_eq!(ttm.ending_period_end, day(2023, 12, 31)); + assert_eq!(ttm.flows.revenue, Some(80.0 + 110.0 + 125.0 + 140.0)); + assert_eq!(ttm.flows.net_income, Some(4.0 + 12.0 + 14.0 + 16.0)); + assert_eq!( + ttm.flows.operating_cash_flow, + Some(9.0 + 18.0 + 20.0 + 22.0) + ); + assert_ne!(ttm.flows, baseline_ttm.flows); +} + +#[test] +fn late_december_eastern_filing_partitions_into_next_utc_year() { + // Listing 900 is valid through 2023-12-31 ET only; a 21:00 EST filing on Dec 31 is + // 2024-01-01T02:00Z, so it must resolve on the Eastern date but partition by UTC year. + let mapping = ProviderMappingTable::from_rows([mapping_row( + "qm", + "NYE", + day(2023, 1, 1), + Some(day(2023, 12, 31)), + 900, + )]) + .expect("valid mapping"); + let venues = BTreeMap::from([(900, StatutoryLagVenue::UsTsx)]); + + let observations = vec![ + obs( + "NYE", + day(2023, 8, 31), + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 10, 10)), + sample_fields(5.0, 1.0, 1.0, 20.0, 10.0, 1.0), + ), + obs( + "NYE", + day(2023, 11, 30), + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 12, 31)), + sample_fields(6.0, 1.5, 1.2, 22.0, 11.0, 1.0), + ), + ]; + let filings = vec![ + filing("NYE", "2023-10-10T16:00:00 EDT", "10-Q"), + filing("NYE", "2023-12-31T21:00:00 EST", "10-Q"), + ]; + + let tmp = TempDirGuard::new("nye"); + let report = curate_and_write_fundamentals( + tmp.path(), + observations.clone(), + filings.clone(), + "qm", + &mapping, + &venues, + 4, + FundamentalsPitWriteOptions::default(), + ) + .expect("curate and write"); + assert_stage_conservation(&report.curate_stats); + assert_eq!(report.curate_stats.filings_dropped_unmapped, 0); + assert_eq!(report.curate_stats.build.rows_linked_to_filing, 2); + assert_eq!( + report.write_stats.rows_by_year, + BTreeMap::from([(2023, 1), (2024, 1)]) + ); + + let curated = + curate_fundamentals(observations, filings, "qm", &mapping, &venues, 4).expect("curate"); + let nye_row = &curated.rows[1]; + assert_eq!( + nye_row.effective_known_at_micros, + utc_micros(2024, 1, 1, 2, 0, 0) + ); + + let y2024 = read_parquet_rows_by_name( + &tmp.path() + .join("fundamentals_pit") + .join("year=2024") + .join("part.parquet"), + ); + assert_eq!(y2024, vec![decoded_from_curated(nye_row)]); + let y2023 = read_parquet_rows_by_name( + &tmp.path() + .join("fundamentals_pit") + .join("year=2023") + .join("part.parquet"), + ); + assert_eq!(y2023, vec![decoded_from_curated(&curated.rows[0])]); +} + +#[test] +fn filing_matching_mapping_only_by_utc_date_is_dropped_unmapped() { + // Mapping starts 2024-05-02 ET. The filing is 2024-05-01T21:00 EDT (= 2024-05-02T01:00Z): + // mapped on its UTC date it would link; on its Eastern date it must not. + let mapping = + ProviderMappingTable::from_rows([mapping_row("qm", "EDGE", day(2024, 5, 2), None, 42)]) + .expect("valid mapping"); + let venues = BTreeMap::from([(42, StatutoryLagVenue::UsTsx)]); + + let out = curate_fundamentals( + [obs( + "EDGE", + day(2024, 6, 30), + FiscalPeriod::Quarterly, + "USD", + None, + sample_fields(1.0, 1.0, 1.0, 1.0, 1.0, 1.0), + )], + [filing("EDGE", "2024-05-01T21:00:00 EDT", "10-Q")], + "qm", + &mapping, + &venues, + 4, + ) + .expect("curate"); + assert_stage_conservation(&out.stats); + assert_eq!(out.stats.filings_in, 1); + assert_eq!(out.stats.filings_dropped_unmapped, 1); + assert_eq!(out.stats.build.filings_in, 0); + assert_eq!(out.stats.observations_dropped_unmapped, 0); + assert_eq!(out.rows.len(), 1); + assert_eq!(out.rows[0].listing_id, 42); +} + +#[test] +fn wrong_mapping_source_drops_everything_and_mapped_listing_without_venue_is_counted_by_builder() { + let mapping = ProviderMappingTable::from_rows([ + mapping_row("qm", "NOVENUE", day(2024, 1, 1), None, 7), + mapping_row("qm", "OK", day(2024, 1, 1), None, 8), + ]) + .expect("valid mapping"); + let venues = BTreeMap::from([(8, StatutoryLagVenue::TsxvCse)]); + let f = sample_fields(3.0, 1.0, 1.0, 9.0, 4.0, 1.0); + let observations = vec![ + obs( + "NOVENUE", + day(2024, 3, 31), + FiscalPeriod::Quarterly, + "CAD", + Some(day(2024, 5, 20)), + f, + ), + obs( + "OK", + day(2024, 3, 31), + FiscalPeriod::Quarterly, + "CAD", + Some(day(2024, 5, 21)), + f, + ), + ]; + let filings = vec![ + filing( + "NOVENUE", + "2024-05-20T16:00:00 EDT", + "Interim financial statements", + ), + filing( + "OK", + "2024-05-21T16:00:00 EDT", + "Interim financial statements", + ), + ]; + + let out = curate_fundamentals( + observations.clone(), + filings.clone(), + "qm", + &mapping, + &venues, + 4, + ) + .expect("curate"); + assert_stage_conservation(&out.stats); + assert_eq!(out.stats.observations_dropped_unmapped, 0); + assert_eq!(out.stats.build.observations_dropped_unknown_key, 1); + assert_eq!(out.stats.build.filings_dropped_unknown_key, 1); + assert_eq!(out.stats.listings_out, 1); + assert_eq!(out.stats.rows_out, 1); + assert_eq!(out.rows[0].listing_id, 8); + + let other = curate_fundamentals(observations, filings, "eodhd", &mapping, &venues, 4) + .expect("other source"); + assert_stage_conservation(&other.stats); + assert_eq!(other.stats.observations_dropped_unmapped, 2); + assert_eq!(other.stats.filings_dropped_unmapped, 2); + assert!(other.rows.is_empty()); + assert_eq!(other.stats.listings_out, 0); +} + +#[test] +fn rebuilding_from_inputs_available_by_each_cutoff_reproduces_the_published_prefix() { + // PIT audit: for each published instant t, rebuild from only the (observation, filing) + // pairs available at or before t; the result must equal the full run's rows with + // effective_known_at <= t. Then append an extreme far-future revision and require every + // earlier row to stay byte-identical. + let mapping = ProviderMappingTable::from_rows([ + mapping_row("qm", "GROW", day(2023, 1, 1), None, 777), + mapping_row("qm", "SMALL", day(2023, 1, 1), None, 555), + ]) + .expect("valid mapping"); + let venues = BTreeMap::from([ + (777, StatutoryLagVenue::UsTsx), + (555, StatutoryLagVenue::TsxvCse), + ]); + let (mut observations, mut filings) = grow_four_quarters(); + observations.push(obs( + "SMALL", + day(2023, 6, 30), + FiscalPeriod::Quarterly, + "CAD", + Some(day(2023, 8, 1)), + sample_fields(2.0, 0.5, 0.4, 8.0, 3.0, 50.0), + )); + filings.push(filing( + "SMALL", + "2023-08-01T16:10:00 EDT", + "Interim financial statements", + )); + observations.push(obs( + "SMALL", + day(2023, 9, 30), + FiscalPeriod::Quarterly, + "CAD", + Some(day(2023, 11, 20)), + sample_fields(2.5, 0.6, 0.5, 9.0, 3.4, 50.0), + )); + filings.push(filing( + "SMALL", + "2023-11-20T09:00:00 EST", + "Interim financial statements", + )); + + let full = curate_fundamentals( + observations.clone(), + filings.clone(), + "qm", + &mapping, + &venues, + 4, + ) + .expect("full"); + assert_eq!(full.rows.len(), 6); + + let pair_known_at: Vec = filings + .iter() + .map(|f| parse_filing_timefiled(&f.timefiled).expect("ts").utc_micros) + .collect(); + for cutoff in full.rows.iter().map(|r| r.effective_known_at_micros) { + let keep: Vec = (0..filings.len()) + .filter(|&i| pair_known_at[i] <= cutoff) + .collect(); + let truncated = curate_fundamentals( + keep.iter().map(|&i| observations[i].clone()), + keep.iter().map(|&i| filings[i].clone()), + "qm", + &mapping, + &venues, + 4, + ) + .expect("truncated"); + let mut expected: Vec = full + .rows + .iter() + .filter(|r| r.effective_known_at_micros <= cutoff) + .cloned() + .collect(); + expected.sort_by_key(|r| (r.listing_id, r.effective_known_at_micros)); + assert_eq!(truncated.rows, expected, "cutoff {cutoff}"); + } + + let mut future_obs = observations.clone(); + future_obs.push(obs( + "GROW", + day(2023, 3, 31), + FiscalPeriod::Quarterly, + "USD", + Some(day(2030, 1, 2)), + sample_fields(1.0e12, -1.0e12, 1.0e12, 1.0e13, -1.0e12, 1.0), + )); + let mut future_filings = filings.clone(); + future_filings.push(filing("GROW", "2030-01-02T16:00:00 EST", "10-Q/A")); + let with_future = curate_fundamentals(future_obs, future_filings, "qm", &mapping, &venues, 4) + .expect("with future revision"); + assert_stage_conservation(&with_future.stats); + let future_at = utc_micros(2030, 1, 2, 21, 0, 0); + let before: Vec<_> = with_future + .rows + .iter() + .filter(|r| r.effective_known_at_micros < future_at) + .cloned() + .collect(); + assert_eq!(before, full.rows); + assert_eq!(with_future.rows.len(), full.rows.len() + 1); +} + +#[test] +fn empty_inputs_yield_no_rows_and_zero_stats() { + let (mapping, venues) = grow_mapping(); + let out = curate_fundamentals( + Vec::>::new(), + Vec::>::new(), + "qm", + &mapping, + &venues, + 4, + ) + .expect("empty"); + assert!(out.rows.is_empty()); + assert_eq!(out.stats, CurateFundamentalsStats::default()); +} diff --git a/tools/curate-etl/src/curate_macro.rs b/tools/curate-etl/src/curate_macro.rs new file mode 100644 index 00000000..73fb72ff --- /dev/null +++ b/tools/curate-etl/src/curate_macro.rs @@ -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, + 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), +} + +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> for CurateMacroError { + fn from(err: MacroError) -> 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 for CurateMacroWriteError { + fn from(err: CurateMacroError) -> Self { + Self::Curate(err) + } +} + +impl From 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 { + 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` 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 +where + I: IntoIterator>, + F: Fn(&str, &str, &str) -> Option, +{ + let iter = points.into_iter(); + let (lower, _) = iter.size_hint(); + let mut stats = CurateMacroStats::default(); + let mut observations: Vec> = Vec::with_capacity(lower); + let mut target_lags: BTreeMap> = 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 = 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 `/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 +where + P: AsRef, + I: IntoIterator>, + F: Fn(&str, &str, &str) -> Option, +{ + 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; diff --git a/tools/curate-etl/src/curate_macro_tests.rs b/tools/curate-etl/src/curate_macro_tests.rs new file mode 100644 index 00000000..c7c6a291 --- /dev/null +++ b/tools/curate-etl/src/curate_macro_tests.rs @@ -0,0 +1,1564 @@ +use std::borrow::Cow; +use std::error::Error as StdError; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + +use bson::raw::{cstr, RawArrayBuf, RawDocumentBuf}; +use bson::DateTime; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::{ + curate_and_write_macro, curate_macro, CurateMacroError, CurateMacroStats, + CurateMacroWriteError, MacroSeriesTarget, +}; +use crate::bson_te_data::{decode_te_data_doc, TeDataPoint}; +use crate::macro_series::{ + MacroError, MacroLagClass, GDP65_LAG_DAYS, GDP90_LAG_DAYS, MACRO_KNOWN_AT_SOURCE, + MONTHLY_RELEASE_LAG_DAYS, POLICY_RATE_LAG_DAYS, +}; +use crate::parquet_macro::{ + write_macro_dataset, MacroParquetRow, MacroWriteOptions, MacroWriteStats, ParquetMacroError, +}; +use crate::split::ymd_to_epoch_days; + +const MICROS_PER_DAY: i64 = 86_400_000_000; + +static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDirGuard { + path: PathBuf, +} + +impl TempDirGuard { + fn new(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = + std::env::temp_dir().join(format!("curate-etl-curate-macro-test-{label}-{pid}-{seq}")); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn make_point_doc(d: &str, v: f64) -> RawDocumentBuf { + let mut pt = RawDocumentBuf::new(); + pt.append(cstr!("d"), d); + pt.append(cstr!("v"), v); + pt +} + +fn make_te_data_doc( + te_symbol: &str, + country: &str, + category: &str, + data_points: &[(&str, f64)], + forecast_points: &[(&str, f64)], +) -> RawDocumentBuf { + let mut data_arr = RawArrayBuf::new(); + for &(d, v) in data_points { + data_arr.push(make_point_doc(d, v)); + } + + let mut forecast_arr = RawArrayBuf::new(); + for &(d, v) in forecast_points { + forecast_arr.push(make_point_doc(d, v)); + } + + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("teSymbol"), te_symbol); + doc.append(cstr!("name"), format!("{country} {category}")); + doc.append(cstr!("unit"), "percent"); + doc.append(cstr!("source"), "TradingEconomics"); + doc.append(cstr!("frequency"), "Monthly"); + doc.append(cstr!("country"), country); + doc.append(cstr!("category"), category); + doc.append(cstr!("data"), data_arr); + doc.append(cstr!("forecast"), forecast_arr); + doc.append( + cstr!("lastUpdated"), + DateTime::from_millis(1_710_000_000_000), + ); + doc.append(cstr!("createdAt"), DateTime::from_millis(1_700_000_000_000)); + doc +} + +fn target(country_iso: &str, indicator: &str, lag_class: MacroLagClass) -> MacroSeriesTarget { + MacroSeriesTarget { + country_iso: country_iso.to_owned(), + indicator: indicator.to_owned(), + lag_class, + } +} + +fn expected_row( + country_iso: &'static str, + indicator: &'static str, + period_date: i32, + lag_days: i32, + value: f64, +) -> MacroParquetRow { + MacroParquetRow { + country_iso: Cow::Borrowed(country_iso), + indicator: Cow::Borrowed(indicator), + period_date, + known_at_micros: i64::from(period_date + lag_days) * MICROS_PER_DAY, + known_at_source: Cow::Borrowed(MACRO_KNOWN_AT_SOURCE), + value, + } +} + +fn read_parquet_rows(path: &Path) -> Vec { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let metadata = reader.metadata(); + let mut out = Vec::new(); + + for rg_idx in 0..metadata.num_row_groups() { + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + let num_rows = metadata.row_group(rg_idx).num_rows() as usize; + + let read_i32 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read i32"); + assert_eq!(read, num_rows); + } + _ => panic!("expected INT32 column at index {col_idx}"), + } + vals + }; + let read_i64 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int64ColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read i64"); + assert_eq!(read, num_rows); + } + _ => panic!("expected INT64 column at index {col_idx}"), + } + vals + }; + let read_f64 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::DoubleColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read f64"); + assert_eq!(read, num_rows); + } + _ => panic!("expected DOUBLE column at index {col_idx}"), + } + vals + }; + let read_str = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read utf8"); + assert_eq!(read, num_rows); + } + _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), + } + vals.into_iter() + .map(|b| { + std::str::from_utf8(b.data()) + .expect("valid utf8") + .to_owned() + }) + .collect() + }; + + let country_iso = read_str(0); + let indicator = read_str(1); + let period_date = read_i32(2); + let known_at_micros = read_i64(3); + let known_at_source = read_str(4); + let value = read_f64(5); + + for i in 0..num_rows { + out.push(MacroParquetRow { + country_iso: Cow::Owned(country_iso[i].clone()), + indicator: Cow::Owned(indicator[i].clone()), + period_date: period_date[i], + known_at_micros: known_at_micros[i], + known_at_source: Cow::Owned(known_at_source[i].clone()), + value: value[i], + }); + } + } + out +} + +fn assert_rows_bitwise_eq(actual: &[MacroParquetRow], expected: &[MacroParquetRow]) { + assert_eq!(actual.len(), expected.len(), "row count mismatch"); + for (idx, (a, e)) in actual.iter().zip(expected.iter()).enumerate() { + assert_eq!(a.country_iso, e.country_iso, "row {idx} country_iso"); + assert_eq!(a.indicator, e.indicator, "row {idx} indicator"); + assert_eq!(a.period_date, e.period_date, "row {idx} period_date"); + assert_eq!( + a.known_at_micros, e.known_at_micros, + "row {idx} known_at_micros" + ); + assert_eq!( + a.known_at_source, e.known_at_source, + "row {idx} known_at_source" + ); + assert_eq!( + a.value.to_bits(), + e.value.to_bits(), + "row {idx} value bits ({} vs {})", + a.value, + e.value + ); + } +} + +fn assert_strictly_ascending_unique(rows: &[MacroParquetRow]) { + for pair in rows.windows(2) { + let prev = ( + pair[0].country_iso.as_ref(), + pair[0].indicator.as_ref(), + pair[0].period_date, + ); + let next = ( + pair[1].country_iso.as_ref(), + pair[1].indicator.as_ref(), + pair[1].period_date, + ); + assert!( + prev < next, + "rows not strictly ascending and unique: {prev:?} >= {next:?}" + ); + } +} + +fn assert_stats_conserved(stats: &CurateMacroStats) { + assert_eq!( + stats.points_in, + stats.dropped_unmapped_series + stats.builder.input, + "stage input conservation failed: {stats:?}" + ); + assert_eq!( + stats.rows_out, stats.builder.emitted, + "stage output conservation failed: {stats:?}" + ); + assert_eq!( + stats.builder.skipped_unmapped_indicator, 0, + "builder should never observe unmapped indicators from stage: {stats:?}" + ); + assert_eq!( + stats.builder.input, + stats.builder.emitted + + stats.builder.skipped_unmapped_indicator + + stats.builder.skipped_non_finite_value + + stats.builder.skipped_duplicate, + "builder conservation failed: {stats:?}" + ); +} + +fn sorted_dir_entries(dir: &Path) -> Vec { + if !dir.exists() { + return Vec::new(); + } + let mut entries: Vec = fs::read_dir(dir) + .expect("read dir") + .map(|entry| { + entry + .expect("dir entry") + .file_name() + .to_string_lossy() + .into_owned() + }) + .collect(); + entries.sort(); + entries +} + +fn seed_existing_parquet(out_dir: &Path) -> (PathBuf, Vec, Vec) { + let seed = vec![ + expected_row( + "CA", + "policy_rate", + day(2024, 1, 24), + POLICY_RATE_LAG_DAYS, + 5.0, + ), + expected_row( + "US", + "cpi_yoy", + day(2024, 1, 31), + MONTHLY_RELEASE_LAG_DAYS, + 3.1, + ), + ]; + write_macro_dataset(out_dir, &seed, MacroWriteOptions::default()).expect("seed parquet"); + let part = out_dir.join("macro/part.parquet"); + let bytes = fs::read(&part).expect("read seeded parquet"); + let entries = sorted_dir_entries(&out_dir.join("macro")); + (part, bytes, entries) +} + +#[test] +fn decode_te_data_bson_curate_and_write_all_four_lag_classes_without_forecast_leakage() { + let docs = vec![ + make_te_data_doc( + "USGDPQOQ", + "United States", + "GDP Growth Rate", + &[("2024-03-31", 1.4), ("2024-06-30", -0.0)], + &[("2025-12-31", 99.9)], + ), + make_te_data_doc( + "CAGDPQOQ", + "Canada", + "GDP Growth Rate", + &[("2024-03-31", -0.25)], + &[("2026-03-31", 88.8)], + ), + make_te_data_doc( + "USCPIYOY", + "United States", + "Inflation Rate", + &[("2024-02-29", 3.2), ("2024-01-31", 3.1)], + &[("2025-06-30", 77.7)], + ), + make_te_data_doc( + "CABOCRATE", + "Canada", + "Interest Rate", + &[("2024-01-24", 5.0), ("2024-06-05", 0.0)], + &[("2025-09-30", 66.6)], + ), + make_te_data_doc( + "UKUNEMP", + "United Kingdom", + "Unemployment Rate", + &[("2024-01-31", 4.2)], + &[("2025-10-31", 55.5)], + ), + ]; + + let mut decoded_points: Vec> = Vec::new(); + let mut decode_errors = Vec::new(); + let mut total_points_in = 0usize; + let mut total_points_decoded = 0usize; + for doc in &docs { + let stats = decode_te_data_doc( + doc.as_ref(), + |pt| decoded_points.push(pt), + |err| decode_errors.push(err), + ); + assert_eq!(stats.docs_accepted, 1); + assert_eq!(stats.docs_rejected_total(), 0); + assert_eq!(stats.rejected_total(), 0); + total_points_in += stats.points_in; + total_points_decoded += stats.points_decoded; + } + assert!( + decode_errors.is_empty(), + "unexpected decode errors: {decode_errors:?}" + ); + // Only the 8 historical data points were decoded; none of the 5 forecast points leaked. + assert_eq!(total_points_in, 8); + assert_eq!(total_points_decoded, 8); + assert_eq!(decoded_points.len(), 8); + + let series_map = + |te_symbol: &str, country: &str, category: &str| match (te_symbol, country, category) { + ("CABOCRATE", "Canada", "Interest Rate") => { + Some(target("CA", "policy_rate", MacroLagClass::PolicyRate)) + } + ("USCPIYOY", "United States", "Inflation Rate") => { + Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)) + } + ("USGDPQOQ", "United States", "GDP Growth Rate") => { + Some(target("US", "gdp_qoq", MacroLagClass::Gdp65)) + } + ("CAGDPQOQ", "Canada", "GDP Growth Rate") => { + Some(target("CA", "gdp_qoq", MacroLagClass::Gdp90)) + } + _ => None, + }; + + let tmp = TempDirGuard::new("bson-roundtrip"); + let report = curate_and_write_macro( + tmp.path(), + decoded_points, + series_map, + MacroWriteOptions::default(), + ) + .expect("curate_and_write_macro should succeed"); + + assert_stats_conserved(&report.curate_stats); + assert_eq!(report.curate_stats.points_in, 8); + assert_eq!(report.curate_stats.dropped_unmapped_series, 1); + assert_eq!(report.curate_stats.builder.input, 7); + assert_eq!(report.curate_stats.builder.emitted, 7); + assert_eq!(report.curate_stats.rows_out, 7); + assert_eq!(report.curate_stats.series_out, 4); + assert_eq!(report.write_stats.rows_written, 7); + assert_eq!(report.write_stats.files_written, 1); + + let part_path = tmp.path().join("macro/part.parquet"); + assert!(part_path.exists()); + assert_eq!( + sorted_dir_entries(&tmp.path().join("macro")), + vec!["part.parquet"] + ); + + let read_back = read_parquet_rows(&part_path); + assert_strictly_ascending_unique(&read_back); + + let expected = vec![ + expected_row("CA", "gdp_qoq", day(2024, 3, 31), GDP90_LAG_DAYS, -0.25), + expected_row( + "CA", + "policy_rate", + day(2024, 1, 24), + POLICY_RATE_LAG_DAYS, + 5.0, + ), + expected_row( + "CA", + "policy_rate", + day(2024, 6, 5), + POLICY_RATE_LAG_DAYS, + 0.0, + ), + expected_row( + "US", + "cpi_yoy", + day(2024, 1, 31), + MONTHLY_RELEASE_LAG_DAYS, + 3.1, + ), + expected_row( + "US", + "cpi_yoy", + day(2024, 2, 29), + MONTHLY_RELEASE_LAG_DAYS, + 3.2, + ), + expected_row("US", "gdp_qoq", day(2024, 3, 31), GDP65_LAG_DAYS, 1.4), + expected_row("US", "gdp_qoq", day(2024, 6, 30), GDP65_LAG_DAYS, -0.0), + ]; + assert_rows_bitwise_eq(&read_back, &expected); + + // Explicitly verify each lag class UTC midnight timestamp and provenance label, and absence of + // all forecast dates. + let forecast_dates = [ + day(2025, 12, 31), + day(2026, 3, 31), + day(2025, 6, 30), + day(2025, 9, 30), + day(2025, 10, 31), + ]; + for row in &read_back { + assert_eq!(row.known_at_source.as_ref(), MACRO_KNOWN_AT_SOURCE); + assert_eq!(row.known_at_source.as_ref(), "publication_lag_estimate"); + assert_eq!(row.known_at_micros % MICROS_PER_DAY, 0); + assert!( + !forecast_dates.contains(&row.period_date), + "forecast date leaked into output: {row:?}" + ); + } + assert_eq!( + read_back[0].known_at_micros, + i64::from(day(2024, 3, 31) + 90) * MICROS_PER_DAY + ); + assert_eq!( + read_back[1].known_at_micros, + i64::from(day(2024, 1, 24) + 1) * MICROS_PER_DAY + ); + assert_eq!( + read_back[3].known_at_micros, + i64::from(day(2024, 1, 31) + 35) * MICROS_PER_DAY + ); + assert_eq!( + read_back[5].known_at_micros, + i64::from(day(2024, 3, 31) + 65) * MICROS_PER_DAY + ); +} + +#[test] +fn permutation_invariance_unmapped_duplicates_and_non_finite_accounting() { + let base_points = vec![ + // Mapped US cpi_yoy (+35d): two dates + exact duplicate + NaN + +inf + TeDataPoint { + te_symbol: "USCPIYOY", + country: "United States", + category: "Inflation Rate", + period_date: day(2024, 2, 29), + value: 3.2, + }, + TeDataPoint { + te_symbol: "USCPIYOY", + country: "United States", + category: "Inflation Rate", + period_date: day(2024, 1, 31), + value: 3.1, + }, + TeDataPoint { + te_symbol: "USCPIYOY", + country: "United States", + category: "Inflation Rate", + period_date: day(2024, 1, 31), + value: 3.1, + }, + TeDataPoint { + te_symbol: "USCPIYOY", + country: "United States", + category: "Inflation Rate", + period_date: day(2024, 3, 31), + value: f64::NAN, + }, + TeDataPoint { + te_symbol: "USCPIYOY", + country: "United States", + category: "Inflation Rate", + period_date: day(2024, 4, 30), + value: f64::INFINITY, + }, + // Mapped CA policy_rate (+1d): one finite + one -inf + TeDataPoint { + te_symbol: "CABOCRATE", + country: "Canada", + category: "Interest Rate", + period_date: day(2024, 1, 24), + value: 5.0, + }, + TeDataPoint { + te_symbol: "CABOCRATE", + country: "Canada", + category: "Interest Rate", + period_date: day(2024, 3, 6), + value: f64::NEG_INFINITY, + }, + // Unmapped tuples: case difference, whitespace difference, and unknown series + TeDataPoint { + te_symbol: "uscpiyoy", + country: "United States", + category: "Inflation Rate", + period_date: day(2024, 1, 31), + value: 9.9, + }, + TeDataPoint { + te_symbol: "USCPIYOY ", + country: "United States", + category: "Inflation Rate", + period_date: day(2024, 1, 31), + value: 9.9, + }, + TeDataPoint { + te_symbol: "DEUNEMP", + country: "Germany", + category: "Unemployment Rate", + period_date: day(2024, 1, 31), + value: 5.9, + }, + ]; + + let series_map = + |te_symbol: &str, country: &str, category: &str| match (te_symbol, country, category) { + ("USCPIYOY", "United States", "Inflation Rate") => { + Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)) + } + ("CABOCRATE", "Canada", "Interest Rate") => { + Some(target("CA", "policy_rate", MacroLagClass::PolicyRate)) + } + _ => None, + }; + + let mut reversed = base_points.clone(); + reversed.reverse(); + + let interleaved: Vec> = vec![ + base_points[9], + base_points[5], + base_points[2], + base_points[7], + base_points[4], + base_points[0], + base_points[8], + base_points[6], + base_points[3], + base_points[1], + ]; + + let out_base = curate_macro(base_points, series_map).expect("base ok"); + let out_rev = curate_macro(reversed, series_map).expect("reversed ok"); + let out_inter = curate_macro(interleaved, series_map).expect("interleaved ok"); + + for out in [&out_base, &out_rev, &out_inter] { + assert_strictly_ascending_unique(&out.rows); + assert_stats_conserved(&out.stats); + assert_eq!(out.stats.points_in, 10); + assert_eq!(out.stats.dropped_unmapped_series, 3); + assert_eq!(out.stats.builder.input, 7); + assert_eq!(out.stats.builder.emitted, 3); + assert_eq!(out.stats.builder.skipped_non_finite_value, 3); + assert_eq!(out.stats.builder.skipped_duplicate, 1); + assert_eq!(out.stats.rows_out, 3); + assert_eq!(out.stats.series_out, 2); + } + + assert_eq!(out_base.stats, out_rev.stats); + assert_eq!(out_base.stats, out_inter.stats); + assert_rows_bitwise_eq(&out_base.rows, &out_rev.rows); + assert_rows_bitwise_eq(&out_base.rows, &out_inter.rows); + + let expected = vec![ + expected_row( + "CA", + "policy_rate", + day(2024, 1, 24), + POLICY_RATE_LAG_DAYS, + 5.0, + ), + expected_row( + "US", + "cpi_yoy", + day(2024, 1, 31), + MONTHLY_RELEASE_LAG_DAYS, + 3.1, + ), + expected_row( + "US", + "cpi_yoy", + day(2024, 2, 29), + MONTHLY_RELEASE_LAG_DAYS, + 3.2, + ), + ]; + assert_rows_bitwise_eq(&out_base.rows, &expected); +} + +#[test] +fn empty_and_all_unmapped_inputs_produce_zero_rows_and_do_not_touch_out_dir() { + let never_map = |_: &str, _: &str, _: &str| -> Option { None }; + + // 1. Fresh directory with empty input + let fresh_empty = TempDirGuard::new("fresh-empty"); + let report = curate_and_write_macro( + fresh_empty.path(), + std::iter::empty::>(), + never_map, + MacroWriteOptions::default(), + ) + .expect("empty input succeeds"); + assert_stats_conserved(&report.curate_stats); + assert_eq!(report.curate_stats.points_in, 0); + assert_eq!(report.curate_stats.rows_out, 0); + assert_eq!(report.curate_stats.series_out, 0); + assert_eq!(report.write_stats, MacroWriteStats::default()); + assert!(!fresh_empty.path().join("macro").exists()); + + // 2. Fresh directory with all-unmapped input + let fresh_unmapped = TempDirGuard::new("fresh-unmapped"); + let unmapped = [TeDataPoint { + te_symbol: "UNKNOWN", + country: "Nowhere", + category: "Mystery", + period_date: day(2024, 1, 1), + value: 1.0, + }]; + let report = curate_and_write_macro( + fresh_unmapped.path(), + unmapped, + never_map, + MacroWriteOptions::default(), + ) + .expect("all-unmapped input succeeds"); + assert_stats_conserved(&report.curate_stats); + assert_eq!(report.curate_stats.points_in, 1); + assert_eq!(report.curate_stats.dropped_unmapped_series, 1); + assert_eq!(report.curate_stats.rows_out, 0); + assert_eq!(report.curate_stats.series_out, 0); + assert_eq!(report.write_stats, MacroWriteStats::default()); + assert!(!fresh_unmapped.path().join("macro").exists()); + + // 3. Pre-existing part.parquet is preserved byte-identical on all-unmapped input + let existing = TempDirGuard::new("existing-unmapped"); + let (part, before_bytes, before_entries) = seed_existing_parquet(existing.path()); + let report = curate_and_write_macro( + existing.path(), + unmapped, + never_map, + MacroWriteOptions::default(), + ) + .expect("all-unmapped against existing succeeds"); + assert_eq!(report.write_stats, MacroWriteStats::default()); + assert_eq!(fs::read(&part).expect("read after"), before_bytes); + assert_eq!( + sorted_dir_entries(&existing.path().join("macro")), + before_entries + ); +} + +#[test] +fn conflicting_duplicate_and_signed_zero_propagate_macro_error() { + let map_cpi = + |_: &str, _: &str, _: &str| Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)); + + // Unequal finite values at same (country_iso, indicator, period_date) + let unequal = [ + TeDataPoint { + te_symbol: "USCPIYOY", + country: "United States", + category: "Inflation Rate", + period_date: day(2024, 1, 31), + value: 3.1, + }, + TeDataPoint { + te_symbol: "USCPIYOY", + country: "United States", + category: "Inflation Rate", + period_date: day(2024, 1, 31), + value: 3.2, + }, + ]; + let err = curate_macro(unequal, map_cpi).expect_err("unequal duplicate must fail"); + assert_eq!( + err, + CurateMacroError::Macro(MacroError::ConflictingDuplicate { + country_iso: "US".to_owned(), + indicator: "cpi_yoy".to_owned(), + period_date: day(2024, 1, 31), + }) + ); + assert!(err.source().is_some()); + + // Opposite signed zeros (+0.0 vs -0.0) at same (country_iso, indicator, period_date) + let signed_zeros = [ + TeDataPoint { + te_symbol: "USCPIYOY", + country: "United States", + category: "Inflation Rate", + period_date: day(2024, 2, 29), + value: 0.0, + }, + TeDataPoint { + te_symbol: "USCPIYOY", + country: "United States", + category: "Inflation Rate", + period_date: day(2024, 2, 29), + value: -0.0, + }, + ]; + let err = curate_macro(signed_zeros, map_cpi).expect_err("signed zero conflict must fail"); + assert_eq!( + err, + CurateMacroError::Macro(MacroError::ConflictingDuplicate { + country_iso: "US".to_owned(), + indicator: "cpi_yoy".to_owned(), + period_date: day(2024, 2, 29), + }) + ); +} + +#[test] +fn conflicting_lag_class_is_order_independent_and_checks_before_non_finite_filtering() { + // Two distinct provider aliases targeting the same (country_iso, indicator) on different dates + // with different lag classes, including one non-finite point. + let p_gdp65 = TeDataPoint { + te_symbol: "USGDP_FAST", + country: "United States", + category: "GDP Growth Rate", + period_date: day(2024, 3, 31), + value: 1.4, + }; + let p_gdp90_nan = TeDataPoint { + te_symbol: "USGDP_SLOW", + country: "United States", + category: "GDP Growth Rate Revised", + period_date: day(2024, 6, 30), + value: f64::NAN, + }; + + let alias_map = |te_symbol: &str, _: &str, _: &str| match te_symbol { + "USGDP_FAST" => Some(target("US", "gdp_qoq", MacroLagClass::Gdp65)), + "USGDP_SLOW" => Some(target("US", "gdp_qoq", MacroLagClass::Gdp90)), + _ => None, + }; + + let err_ab = curate_macro([p_gdp65, p_gdp90_nan], alias_map).expect_err("order A must fail"); + let err_ba = curate_macro([p_gdp90_nan, p_gdp65], alias_map).expect_err("order B must fail"); + + let expected = CurateMacroError::ConflictingLagClass { + country_iso: "US".to_owned(), + indicator: "gdp_qoq".to_owned(), + first_lag_class: MacroLagClass::Gdp65, + second_lag_class: MacroLagClass::Gdp90, + }; + assert_eq!(err_ab, expected); + assert_eq!(err_ba, expected); + assert!(err_ab.source().is_none()); + + // Multiple conflicting targets: always report the lowest (country_iso, indicator) in key order. + let ca_rate_a = TeDataPoint { + te_symbol: "CA_A", + country: "Canada", + category: "Rate", + period_date: day(2024, 1, 1), + value: 5.0, + }; + let ca_rate_b = TeDataPoint { + te_symbol: "CA_B", + country: "Canada", + category: "Rate", + period_date: day(2024, 2, 1), + value: 5.0, + }; + let multi_map = |te_symbol: &str, _: &str, _: &str| match te_symbol { + "USGDP_FAST" => Some(target("US", "gdp_qoq", MacroLagClass::Gdp65)), + "USGDP_SLOW" => Some(target("US", "gdp_qoq", MacroLagClass::Gdp90)), + "CA_A" => Some(target("CA", "policy_rate", MacroLagClass::PolicyRate)), + "CA_B" => Some(target("CA", "policy_rate", MacroLagClass::MonthlyRelease)), + _ => None, + }; + + let err_multi_1 = curate_macro([p_gdp65, p_gdp90_nan, ca_rate_a, ca_rate_b], multi_map) + .expect_err("multi 1 must fail"); + let err_multi_2 = curate_macro([ca_rate_b, p_gdp90_nan, ca_rate_a, p_gdp65], multi_map) + .expect_err("multi 2 must fail"); + assert_eq!( + err_multi_1, + CurateMacroError::ConflictingLagClass { + country_iso: "CA".to_owned(), + indicator: "policy_rate".to_owned(), + first_lag_class: MacroLagClass::PolicyRate, + second_lag_class: MacroLagClass::MonthlyRelease, + } + ); + assert_eq!(err_multi_1, err_multi_2); +} + +#[test] +fn known_at_overflow_and_invalid_write_options_and_single_line_display() { + // 1. KnownAtOverflow propagated from build_macro_rows + let overflow_pt = [TeDataPoint { + te_symbol: "EXTREME", + country: "United States", + category: "GDP", + period_date: i32::MAX, + value: 1.0, + }]; + let map_gdp90 = |_: &str, _: &str, _: &str| Some(target("US", "gdp", MacroLagClass::Gdp90)); + let err = curate_macro(overflow_pt, map_gdp90).expect_err("overflow must fail"); + assert_eq!( + err, + CurateMacroError::Macro(MacroError::KnownAtOverflow { + period_date: i32::MAX, + lag_class: MacroLagClass::Gdp90, + }) + ); + assert!(err.source().is_some()); + let msg = err.to_string(); + assert!( + !msg.contains('\n') && !msg.contains('\r'), + "multi-line: {msg:?}" + ); + + // 2. InvalidRowGroupRows wrapped in CurateMacroWriteError::Parquet + let tmp = TempDirGuard::new("invalid-opts"); + let valid_pt = [TeDataPoint { + te_symbol: "CABOCRATE", + country: "Canada", + category: "Interest Rate", + period_date: day(2024, 1, 24), + value: 5.0, + }]; + let map_rate = + |_: &str, _: &str, _: &str| Some(target("CA", "policy_rate", MacroLagClass::PolicyRate)); + let write_err = curate_and_write_macro( + tmp.path(), + valid_pt, + map_rate, + MacroWriteOptions { + row_group_rows: 0, + ..MacroWriteOptions::default() + }, + ) + .expect_err("row_group_rows=0 must fail"); + assert!(matches!( + write_err, + CurateMacroWriteError::Parquet(ParquetMacroError::InvalidRowGroupRows) + )); + assert!(write_err.source().is_some()); + let msg = write_err.to_string(); + assert!( + !msg.contains('\n') && !msg.contains('\r'), + "multi-line: {msg:?}" + ); + + // 3. Newline-bearing diagnostic labels stay single-line in both CurateMacroError and + // CurateMacroWriteError (covering ConflictingLagClass, ConflictingDuplicate, and Parquet). + let nl_lag_err = CurateMacroWriteError::from(CurateMacroError::ConflictingLagClass { + country_iso: "US\nline2".to_owned(), + indicator: "cpi\r\nyoy".to_owned(), + first_lag_class: MacroLagClass::PolicyRate, + second_lag_class: MacroLagClass::MonthlyRelease, + }); + let nl_lag_msg = nl_lag_err.to_string(); + assert!( + !nl_lag_msg.contains('\n') && !nl_lag_msg.contains('\r'), + "ConflictingLagClass display must be single-line: {nl_lag_msg:?}" + ); + assert!(nl_lag_msg.contains("US\\nline2")); + assert!(nl_lag_msg.contains("cpi\\r\\nyoy")); + + let nl_dup_err = + CurateMacroWriteError::from(CurateMacroError::from(MacroError::ConflictingDuplicate { + country_iso: "CA\n2".to_owned(), + indicator: "gdp\r3".to_owned(), + period_date: day(2024, 1, 1), + })); + let nl_dup_msg = nl_dup_err.to_string(); + assert!( + !nl_dup_msg.contains('\n') && !nl_dup_msg.contains('\r'), + "ConflictingDuplicate display must be single-line: {nl_dup_msg:?}" + ); + + // ParquetMacroError::EmptyCountryIso displays `indicator` with `{indicator}`, so newlines + // would leak unless CurateMacroWriteError escapes them. + let nl_pq_err = curate_and_write_macro( + tmp.path(), + valid_pt, + |_: &str, _: &str, _: &str| { + Some(target( + " ", + "bad\nindicator\rname", + MacroLagClass::PolicyRate, + )) + }, + MacroWriteOptions::default(), + ) + .expect_err("blank country_iso must fail in writer"); + assert!(matches!( + nl_pq_err, + CurateMacroWriteError::Parquet(ParquetMacroError::EmptyCountryIso { .. }) + )); + let nl_pq_msg = nl_pq_err.to_string(); + assert!( + !nl_pq_msg.contains('\n') && !nl_pq_msg.contains('\r'), + "Parquet display must be single-line: {nl_pq_msg:?}" + ); + assert!(nl_pq_msg.contains("bad\\nindicator\\rname")); +} + +#[test] +fn curation_errors_never_write_or_modify_out_dir() { + // 1. ConflictingLagClass + let lag_conflict_points = [ + TeDataPoint { + te_symbol: "A", + country: "US", + category: "GDP", + period_date: day(2024, 3, 31), + value: 1.4, + }, + TeDataPoint { + te_symbol: "B", + country: "US", + category: "GDP", + period_date: day(2024, 6, 30), + value: 1.8, + }, + ]; + let lag_conflict_map = |sym: &str, _: &str, _: &str| match sym { + "A" => Some(target("US", "gdp", MacroLagClass::Gdp65)), + "B" => Some(target("US", "gdp", MacroLagClass::Gdp90)), + _ => None, + }; + + // 2. ConflictingDuplicate + let dup_conflict_points = [ + TeDataPoint { + te_symbol: "A", + country: "US", + category: "CPI", + period_date: day(2024, 1, 31), + value: 3.1, + }, + TeDataPoint { + te_symbol: "A", + country: "US", + category: "CPI", + period_date: day(2024, 1, 31), + value: 3.2, + }, + ]; + let cpi_map = + |_: &str, _: &str, _: &str| Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)); + + // 3. KnownAtOverflow + let overflow_points = [TeDataPoint { + te_symbol: "A", + country: "US", + category: "GDP", + period_date: i32::MAX, + value: 1.0, + }]; + let gdp_map = |_: &str, _: &str, _: &str| Some(target("US", "gdp", MacroLagClass::Gdp90)); + + // Fresh destination checks + for (label, result, dir) in [ + { + let dir = TempDirGuard::new("err-fresh-lag"); + let res = curate_and_write_macro( + dir.path(), + lag_conflict_points, + lag_conflict_map, + MacroWriteOptions::default(), + ); + ("ConflictingLagClass", res, dir) + }, + { + let dir = TempDirGuard::new("err-fresh-dup"); + let res = curate_and_write_macro( + dir.path(), + dup_conflict_points, + cpi_map, + MacroWriteOptions::default(), + ); + ("ConflictingDuplicate", res, dir) + }, + { + let dir = TempDirGuard::new("err-fresh-overflow"); + let res = curate_and_write_macro( + dir.path(), + overflow_points, + gdp_map, + MacroWriteOptions::default(), + ); + ("KnownAtOverflow", res, dir) + }, + ] { + let err = result.expect_err(&format!("{label} must fail")); + assert!( + matches!(err, CurateMacroWriteError::Curate(_)), + "{label} should be Curate error: {err}" + ); + assert!( + !dir.path().join("macro").exists(), + "{label} must not create macro/ dir" + ); + assert!( + sorted_dir_entries(dir.path()).is_empty(), + "{label} must leave fresh out_dir empty" + ); + } + + // Existing valid macro/part.parquet preservation checks + for (label, result, part, before_bytes, before_entries, dir) in [ + { + let dir = TempDirGuard::new("err-existing-lag"); + let (part, before_bytes, before_entries) = seed_existing_parquet(dir.path()); + let res = curate_and_write_macro( + dir.path(), + lag_conflict_points, + lag_conflict_map, + MacroWriteOptions::default(), + ); + ( + "ConflictingLagClass", + res, + part, + before_bytes, + before_entries, + dir, + ) + }, + { + let dir = TempDirGuard::new("err-existing-dup"); + let (part, before_bytes, before_entries) = seed_existing_parquet(dir.path()); + let res = curate_and_write_macro( + dir.path(), + dup_conflict_points, + cpi_map, + MacroWriteOptions::default(), + ); + ( + "ConflictingDuplicate", + res, + part, + before_bytes, + before_entries, + dir, + ) + }, + { + let dir = TempDirGuard::new("err-existing-overflow"); + let (part, before_bytes, before_entries) = seed_existing_parquet(dir.path()); + let res = curate_and_write_macro( + dir.path(), + overflow_points, + gdp_map, + MacroWriteOptions::default(), + ); + ( + "KnownAtOverflow", + res, + part, + before_bytes, + before_entries, + dir, + ) + }, + ] { + let err = result.expect_err(&format!("{label} must fail")); + assert!( + matches!(err, CurateMacroWriteError::Curate(_)), + "{label} should be Curate error: {err}" + ); + assert_eq!( + fs::read(&part).expect("read existing parquet"), + before_bytes, + "{label} must leave existing part.parquet byte-identical" + ); + assert_eq!( + sorted_dir_entries(&dir.path().join("macro")), + before_entries, + "{label} must leave macro/ directory entries unchanged" + ); + } +} + +fn te_point( + te_symbol: &'static str, + country: &'static str, + category: &'static str, + period_date: i32, + value: f64, +) -> TeDataPoint<'static> { + TeDataPoint { + te_symbol, + country, + category, + period_date, + value, + } +} + +#[test] +fn mapped_target_with_only_non_finite_values_does_not_count_as_emitted_series() { + let points = vec![ + te_point( + "USCPIYOY", + "United States", + "Inflation Rate", + day(2024, 1, 31), + 3.1, + ), + te_point( + "CABOCRATE", + "Canada", + "Interest Rate", + day(2024, 1, 24), + 5.0, + ), + te_point( + "DEGDP", + "Germany", + "GDP Growth Rate", + day(2024, 3, 31), + f64::NAN, + ), + te_point( + "DEGDP", + "Germany", + "GDP Growth Rate", + day(2024, 6, 30), + f64::INFINITY, + ), + te_point( + "DEGDP", + "Germany", + "GDP Growth Rate", + day(2024, 9, 30), + f64::NEG_INFINITY, + ), + ]; + let series_map = |te_symbol: &str, _: &str, _: &str| match te_symbol { + "USCPIYOY" => Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)), + "CABOCRATE" => Some(target("CA", "policy_rate", MacroLagClass::PolicyRate)), + "DEGDP" => Some(target("DE", "gdp_qoq", MacroLagClass::Gdp65)), + _ => None, + }; + + let mut reversed = points.clone(); + reversed.reverse(); + let rotated: Vec<_> = points[2..] + .iter() + .chain(points[..2].iter()) + .copied() + .collect(); + + let mut outputs = Vec::new(); + for perm in [points, reversed, rotated] { + let out = curate_macro(perm, series_map).expect("curation succeeds"); + assert_stats_conserved(&out.stats); + assert_eq!(out.stats.points_in, 5); + assert_eq!(out.stats.dropped_unmapped_series, 0); + assert_eq!(out.stats.builder.input, 5); + assert_eq!(out.stats.builder.skipped_non_finite_value, 3); + assert_eq!(out.stats.builder.emitted, 2); + assert_eq!(out.stats.rows_out, 2); + assert_eq!( + out.stats.series_out, 2, + "non-finite-only target must not count" + ); + assert!(out.rows.iter().all(|r| r.country_iso != "DE")); + outputs.push(out); + } + assert_eq!(outputs[0].stats, outputs[1].stats); + assert_eq!(outputs[0].stats, outputs[2].stats); + assert_rows_bitwise_eq(&outputs[0].rows, &outputs[1].rows); + assert_rows_bitwise_eq(&outputs[0].rows, &outputs[2].rows); +} + +#[test] +fn lookup_receives_verbatim_provider_labels_once_per_point() { + use std::cell::RefCell; + + let points = [ + te_point( + " USCPIYOY", + "United States ", + "Inflation\tRate", + day(2024, 1, 31), + 3.1, + ), + te_point( + "cabocrate", + "CANADA", + "Interest Rate", + day(2024, 1, 24), + 5.0, + ), + te_point( + "ÜMLAUT", + "Österreich", + "Kategorie", + day(2024, 2, 1), + f64::NAN, + ), + ]; + let calls: RefCell> = RefCell::new(Vec::new()); + let out = curate_macro(points, |s: &str, c: &str, k: &str| { + calls + .borrow_mut() + .push((s.to_owned(), c.to_owned(), k.to_owned())); + None + }) + .expect("all-unmapped succeeds"); + + assert_eq!( + calls.into_inner(), + vec![ + ( + " USCPIYOY".into(), + "United States ".into(), + "Inflation\tRate".into() + ), + ("cabocrate".into(), "CANADA".into(), "Interest Rate".into()), + ("ÜMLAUT".into(), "Österreich".into(), "Kategorie".into()), + ] + ); + assert_stats_conserved(&out.stats); + assert_eq!(out.stats.dropped_unmapped_series, 3); + assert_eq!(out.stats.builder.input, 0); + // Unmapped non-finite points never reach the builder's non-finite counter. + assert_eq!(out.stats.builder.skipped_non_finite_value, 0); + assert!(out.rows.is_empty()); +} + +#[test] +fn unmapped_points_never_trigger_builder_errors() { + // Unmapped points that would overflow known_at or conflict with a mapped value are dropped + // before build_macro_rows, so they cannot fail the stage. + let points = [ + te_point( + "USCPIYOY", + "United States", + "Inflation Rate", + day(2024, 1, 31), + 3.1, + ), + te_point( + "USCPIYOY_ALT", + "United States", + "Inflation Rate", + day(2024, 1, 31), + 9.9, + ), + te_point("EXTREME", "United States", "GDP", i32::MAX, 1.0), + ]; + let series_map = |te_symbol: &str, _: &str, _: &str| match te_symbol { + "USCPIYOY" => Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)), + _ => None, + }; + let out = curate_macro(points, series_map).expect("unmapped points must be ignored"); + assert_stats_conserved(&out.stats); + assert_eq!(out.stats.dropped_unmapped_series, 2); + assert_rows_bitwise_eq( + &out.rows, + &[expected_row( + "US", + "cpi_yoy", + day(2024, 1, 31), + MONTHLY_RELEASE_LAG_DAYS, + 3.1, + )], + ); +} + +#[test] +fn aliases_with_same_lag_class_merge_into_one_series_and_cross_alias_duplicates_collapse() { + let points = [ + te_point( + "USCPIYOY", + "United States", + "Inflation Rate", + day(2024, 1, 31), + 3.1, + ), + te_point("USCPI_ALT", "USA", "CPI YoY", day(2024, 1, 31), 3.1), + te_point("USCPI_ALT", "USA", "CPI YoY", day(2024, 2, 29), 3.2), + ]; + let series_map = |te_symbol: &str, _: &str, _: &str| match te_symbol { + "USCPIYOY" | "USCPI_ALT" => Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)), + _ => None, + }; + let out = curate_macro(points, series_map).expect("same lag class is not a conflict"); + assert_stats_conserved(&out.stats); + assert_eq!(out.stats.builder.skipped_duplicate, 1); + assert_eq!(out.stats.series_out, 1); + assert_rows_bitwise_eq( + &out.rows, + &[ + expected_row( + "US", + "cpi_yoy", + day(2024, 1, 31), + MONTHLY_RELEASE_LAG_DAYS, + 3.1, + ), + expected_row( + "US", + "cpi_yoy", + day(2024, 2, 29), + MONTHLY_RELEASE_LAG_DAYS, + 3.2, + ), + ], + ); + + // Cross-alias conflicting values on the same target/date are rejected by the builder. + let conflicting = [ + te_point( + "USCPIYOY", + "United States", + "Inflation Rate", + day(2024, 1, 31), + 3.1, + ), + te_point("USCPI_ALT", "USA", "CPI YoY", day(2024, 1, 31), 3.0), + ]; + assert_eq!( + curate_macro(conflicting, series_map).expect_err("cross-alias conflict"), + CurateMacroError::Macro(MacroError::ConflictingDuplicate { + country_iso: "US".to_owned(), + indicator: "cpi_yoy".to_owned(), + period_date: day(2024, 1, 31), + }) + ); +} + +#[test] +fn same_indicator_in_different_countries_may_use_different_lag_classes() { + let points = [ + te_point("USGDP", "United States", "GDP", day(2024, 3, 31), 1.4), + te_point("CAGDP", "Canada", "GDP", day(2024, 3, 31), 0.5), + ]; + let series_map = |te_symbol: &str, _: &str, _: &str| match te_symbol { + "USGDP" => Some(target("US", "gdp_qoq", MacroLagClass::Gdp65)), + "CAGDP" => Some(target("CA", "gdp_qoq", MacroLagClass::Gdp90)), + _ => None, + }; + let out = curate_macro(points, series_map).expect("per-country lag classes are independent"); + assert_eq!(out.stats.series_out, 2); + assert_rows_bitwise_eq( + &out.rows, + &[ + expected_row("CA", "gdp_qoq", day(2024, 3, 31), GDP90_LAG_DAYS, 0.5), + expected_row("US", "gdp_qoq", day(2024, 3, 31), GDP65_LAG_DAYS, 1.4), + ], + ); +} + +#[test] +fn three_way_lag_conflict_reports_min_and_max_class_for_every_order() { + let a = te_point("A", "X", "Y", day(2024, 1, 31), 1.0); + let b = te_point("B", "X", "Y", day(2024, 2, 29), 2.0); + let c = te_point("C", "X", "Y", day(2024, 3, 31), 3.0); + let series_map = |te_symbol: &str, _: &str, _: &str| match te_symbol { + "A" => Some(target("US", "mix", MacroLagClass::MonthlyRelease)), + "B" => Some(target("US", "mix", MacroLagClass::Gdp90)), + "C" => Some(target("US", "mix", MacroLagClass::PolicyRate)), + _ => None, + }; + let expected = CurateMacroError::ConflictingLagClass { + country_iso: "US".to_owned(), + indicator: "mix".to_owned(), + first_lag_class: MacroLagClass::PolicyRate, + second_lag_class: MacroLagClass::Gdp90, + }; + for perm in [ + [a, b, c], + [a, c, b], + [b, a, c], + [b, c, a], + [c, a, b], + [c, b, a], + ] { + assert_eq!( + curate_macro(perm, series_map).expect_err("conflict"), + expected + ); + } + let msg = expected.to_string(); + assert!(msg.contains("+1d") && msg.contains("+90d"), "{msg}"); +} + +#[test] +fn write_error_source_chain_reaches_macro_error() { + let points = [ + te_point("A", "US", "CPI", day(2024, 1, 31), 3.1), + te_point("A", "US", "CPI", day(2024, 1, 31), 3.2), + ]; + let tmp = TempDirGuard::new("source-chain"); + let err = curate_and_write_macro( + tmp.path(), + points, + |_: &str, _: &str, _: &str| Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)), + MacroWriteOptions::default(), + ) + .expect_err("duplicate conflict"); + let lvl1 = err.source().expect("curate error source"); + assert!(lvl1.downcast_ref::().is_some()); + let lvl2 = lvl1.source().expect("macro error source"); + assert!(lvl2.downcast_ref::>().is_some()); + assert!(err.to_string().starts_with("macro curation failed: ")); +} + +#[test] +fn successful_write_replaces_existing_part_parquet_with_curated_rows() { + let tmp = TempDirGuard::new("replace-existing"); + let (part, before_bytes, _) = seed_existing_parquet(tmp.path()); + + let points = [te_point( + "USGDP", + "United States", + "GDP", + day(2024, 6, 30), + 2.8, + )]; + let report = curate_and_write_macro( + tmp.path(), + points, + |_: &str, _: &str, _: &str| Some(target("US", "gdp_qoq", MacroLagClass::Gdp90)), + MacroWriteOptions::default(), + ) + .expect("write succeeds"); + assert_eq!(report.write_stats.rows_written, 1); + assert_ne!(fs::read(&part).expect("read after"), before_bytes); + assert_eq!( + sorted_dir_entries(&tmp.path().join("macro")), + vec!["part.parquet"] + ); + assert_rows_bitwise_eq( + &read_parquet_rows(&part), + &[expected_row( + "US", + "gdp_qoq", + day(2024, 6, 30), + GDP90_LAG_DAYS, + 2.8, + )], + ); +} + +#[test] +fn extreme_finite_values_and_pre_epoch_dates_round_trip_bitwise_through_write() { + // Arrange: one Monthly1 series with pre-1970 and extreme-but-finite values. + let subnormal = f64::from_bits(1); + let neg_subnormal = -f64::from_bits(1); + let cases: [(i32, f64); 6] = [ + (day(1950, 1, 31), -0.0), + (day(1969, 12, 31), subnormal), + (day(1970, 1, 1), neg_subnormal), + (day(1999, 12, 31), f64::MAX), + (day(2000, 1, 31), f64::MIN), + (day(2024, 2, 29), -f64::MIN_POSITIVE), + ]; + // Feed in reverse so the stage must rely on the builder's ordering. + let points: Vec> = cases + .iter() + .rev() + .map(|&(d, v)| te_point("USCPI", "United States", "Inflation Rate", d, v)) + .collect(); + let tmp = TempDirGuard::new("extreme-values"); + + // Act + let report = curate_and_write_macro( + tmp.path(), + points, + |_: &str, _: &str, _: &str| Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)), + MacroWriteOptions::default(), + ) + .expect("extreme finite values are valid"); + + // Assert + assert_eq!(report.curate_stats.points_in, cases.len()); + assert_eq!(report.curate_stats.rows_out, cases.len()); + assert_eq!(report.curate_stats.series_out, 1); + assert_eq!(report.curate_stats.builder.skipped_non_finite_value, 0); + assert_stats_conserved(&report.curate_stats); + let expected: Vec = cases + .iter() + .map(|&(d, v)| expected_row("US", "cpi_yoy", d, MONTHLY_RELEASE_LAG_DAYS, v)) + .collect(); + let actual = read_parquet_rows(&tmp.path().join("macro").join("part.parquet")); + assert_rows_bitwise_eq(&actual, &expected); + assert_eq!(actual[0].value.to_bits(), (-0.0f64).to_bits()); + assert!( + actual[0].known_at_micros < 0, + "pre-epoch known_at stays negative" + ); +} diff --git a/tools/curate-etl/src/curate_posts.rs b/tools/curate-etl/src/curate_posts.rs new file mode 100644 index 00000000..752ae9c9 --- /dev/null +++ b/tools/curate-etl/src/curate_posts.rs @@ -0,0 +1,300 @@ +//! Pure, in-memory `posts` curation stage joining [`crate::posts::build_posts`], +//! [`crate::provider_mapping::ProviderMappingTable`], [`crate::parquet_posts`], and +//! [`crate::parquet_events::write_events_dataset`] into contract [`EventsParquetRow`]s. +//! +//! # Contract & Point-in-Time Rules +//! - Calls [`build_posts`] unchanged on source keys so global `spiel_id` deduplication, +//! `bot == "1"` newswire vs. retail splitting, and the `edited` text `known_at` guard run +//! before `provider_mapping` resolution. +//! - **Eastern local posting date (`posted_at`, not UTC date or `known_at`):** resolves each +//! post's `(mapping_source, key, et_date)` to a permanent `listing_id: i32` where `et_date` is +//! the `America/Toronto` (Eastern) local calendar date of `posted_at` via +//! [`crate::session_close::utc_micros_to_et_local`]. Late edits never shift a post onto a +//! different listing, while text availability remains guarded by `known_at`. +//! - Timestamps outside the range supported by `utc_micros_to_et_local` (`1976-01-01..=2030-12-31` +//! Eastern) are dropped and counted in [`CuratePostsStats::dropped_unsupported_date`] before +//! checking mapping coverage, without aborting or panicking. +//! - Rows with no covering `provider_mapping` range are dropped into +//! [`CuratePostsStats::dropped_unmapped`]. Because `build_posts` sorts by +//! `(key, known_at, spiel_id)` rather than `posted_at`, per-key lookups rely on +//! [`ProviderMappingCursor::resolve`]'s binary-search fallback whenever `et_date` steps +//! backward. +//! - Converts each mapped [`PostRow`] via [`EventsParquetRow::from`] (reusing +//! [`crate::parquet_posts`] labels and payload encoding verbatim), frees builder vectors before +//! re-sorting in place by the exact 7-field writer key +//! `(listing_id, ts_micros, kind, subtype, payload_json, known_at_micros, known_at_source)`, +//! and collapses exact 7-field duplicates into [`CuratePostsStats::listing_duplicate_collapsed`] +//! as a defensive writer-key uniqueness guard. + +use std::cmp::Ordering; +use std::error::Error; +use std::fmt; +use std::path::Path; + +use crate::parquet_events::{ + write_events_dataset, EventsParquetRow, EventsWriteOptions, EventsWriteStats, + ParquetEventsError, +}; +use crate::parquet_posts::{POST_SUBTYPE_NEWSWIRE, POST_SUBTYPE_RETAIL}; +use crate::posts::{build_posts, CeoPost, PostRow, PostsBuild, PostsError, PostsStats}; +use crate::provider_mapping::{ProviderMappingCursor, ProviderMappingTable}; +use crate::session_close::utc_micros_to_et_local; + +/// Accounting summary produced alongside [`CuratePostsOutput::rows`]. +/// +/// Conservation invariants: +/// - `rows_in == builder.newswire + builder.retail` +/// - `rows_in == rows_out + dropped_unmapped + dropped_unsupported_date + listing_duplicate_collapsed` +/// - `rows_out == newswire_out + retail_out` +/// - `builder` independently satisfies all [`PostsStats`] conservation invariants. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CuratePostsStats { + pub builder: PostsStats, + pub rows_in: usize, + pub rows_out: usize, + pub newswire_out: usize, + pub retail_out: usize, + pub listings_out: usize, + pub dropped_unmapped: usize, + pub dropped_unsupported_date: usize, + pub listing_duplicate_collapsed: usize, +} + +/// Output of [`curate_posts`]: contract Parquet rows strictly ascending in the 7-field writer +/// sort key and full stage + builder stats. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CuratePostsOutput { + pub rows: Vec, + pub stats: CuratePostsStats, +} + +/// Typed caller errors returned by [`curate_posts`]. +/// +/// Unmapped rows and posts outside the supported Eastern calendar range are dropped and counted +/// in [`CuratePostsStats`] rather than aborting the stage. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CuratePostsError { + /// Error propagated from [`build_posts`] (e.g., [`PostsError::TimestampOverflow`]). + Posts(PostsError), + /// Caller-supplied `mapping_source` was empty or contained only whitespace. + EmptyMappingSource, +} + +impl fmt::Display for CuratePostsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Posts(err) => write!(f, "{err}"), + Self::EmptyMappingSource => { + write!(f, "mapping_source must not be empty or blank") + } + } + } +} + +impl Error for CuratePostsError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Posts(err) => Some(err), + Self::EmptyMappingSource => None, + } + } +} + +impl From for CuratePostsError { + fn from(err: PostsError) -> Self { + Self::Posts(err) + } +} + +/// Combined stats returned by [`curate_and_write_posts`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CuratePostsWriteReport { + pub curate_stats: CuratePostsStats, + pub write_stats: EventsWriteStats, +} + +/// Typed error returned by [`curate_and_write_posts`]. +#[derive(Debug)] +pub enum CuratePostsWriteError { + Curate(CuratePostsError), + Parquet(ParquetEventsError), +} + +impl fmt::Display for CuratePostsWriteError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Curate(err) => write!(f, "posts curation failed: {err}"), + Self::Parquet(err) => write!(f, "posts Parquet write failed: {err}"), + } + } +} + +impl Error for CuratePostsWriteError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Curate(err) => Some(err), + Self::Parquet(err) => Some(err), + } + } +} + +impl From for CuratePostsWriteError { + fn from(err: CuratePostsError) -> Self { + Self::Curate(err) + } +} + +impl From for CuratePostsWriteError { + fn from(err: ParquetEventsError) -> Self { + Self::Parquet(err) + } +} + +#[inline] +fn compare_event_rows(a: &EventsParquetRow, b: &EventsParquetRow) -> Ordering { + a.listing_id + .cmp(&b.listing_id) + .then_with(|| a.ts_micros.cmp(&b.ts_micros)) + .then_with(|| a.kind.as_ref().cmp(b.kind.as_ref())) + .then_with(|| a.subtype.cmp(&b.subtype)) + .then_with(|| a.payload_json.cmp(&b.payload_json)) + .then_with(|| a.known_at_micros.cmp(&b.known_at_micros)) + .then_with(|| a.known_at_source.as_ref().cmp(b.known_at_source.as_ref())) +} + +fn resolve_and_finalize( + build: PostsBuild, + mapping_source: &str, + mapping: &ProviderMappingTable, +) -> CuratePostsOutput +where + K: Ord + Clone + AsRef, +{ + let rows_in = build.newswire.len() + build.retail.len(); + let mut stats = CuratePostsStats { + builder: build.stats, + rows_in, + ..CuratePostsStats::default() + }; + + let mut rows: Vec = Vec::with_capacity(rows_in); + + for stream in [build.newswire, build.retail] { + let mut current_key: Option = None; + let mut current_cursor: Option> = None; + + for row in stream { + if current_key.as_ref() != Some(&row.key) { + current_cursor = Some(mapping.cursor_for(mapping_source, row.key.as_ref())); + current_key = Some(row.key); + } + + let Ok(et_local) = utc_micros_to_et_local(row.posted_at) else { + stats.dropped_unsupported_date += 1; + continue; + }; + + let cursor = current_cursor + .as_mut() + .expect("cursor initialized for current key run"); + if cursor.ranges().is_empty() { + stats.dropped_unmapped += 1; + continue; + } + + let Some(listing_id) = cursor.resolve(et_local.session_date) else { + stats.dropped_unmapped += 1; + continue; + }; + + let mapped_row = PostRow { + key: listing_id, + spiel_id: row.spiel_id, + posted_at: row.posted_at, + known_at: row.known_at, + is_bot: row.is_bot, + is_edited: row.is_edited, + user_id: row.user_id, + text: row.text, + source: row.source, + }; + rows.push(EventsParquetRow::from(mapped_row)); + } + } + + rows.sort_unstable_by(compare_event_rows); + + let mapped_len = rows.len(); + rows.dedup(); + stats.listing_duplicate_collapsed = mapped_len - rows.len(); + + let mut last_listing_id: Option = None; + for row in &rows { + if last_listing_id != Some(row.listing_id) { + stats.listings_out += 1; + last_listing_id = Some(row.listing_id); + } + match row.subtype.as_str() { + POST_SUBTYPE_NEWSWIRE => stats.newswire_out += 1, + POST_SUBTYPE_RETAIL => stats.retail_out += 1, + other => unreachable!("unexpected post subtype from parquet_posts: {other:?}"), + } + } + stats.rows_out = rows.len(); + + CuratePostsOutput { rows, stats } +} + +/// Pure `posts` curation stage: builds point-in-time `ceoPosts` newswire and retail streams on +/// source keys via [`build_posts`], resolves `(mapping_source, key, et_date) -> listing_id` on +/// each post's `America/Toronto` (Eastern) local posting date via `provider_mapping`, and emits +/// contract [`EventsParquetRow`]s strictly ascending in the 7-field writer key. +/// +/// Mapping lookup always uses the Eastern local calendar date of `posted_at` (never UTC date and +/// never `known_at`). Posts outside the supported Eastern calendar range are dropped into +/// `dropped_unsupported_date`; unmapped posts are dropped into `dropped_unmapped`. +pub fn curate_posts( + posts: I, + mapping_source: &str, + mapping: &ProviderMappingTable, +) -> Result +where + K: Ord + Clone + AsRef, + I: IntoIterator>, +{ + if mapping_source.trim().is_empty() { + return Err(CuratePostsError::EmptyMappingSource); + } + + let built = build_posts(posts)?; + Ok(resolve_and_finalize(built, mapping_source, mapping)) +} + +/// Thin end-to-end wrapper running [`curate_posts`] and publishing the resulting contract rows +/// via [`write_events_dataset`] to `/events/year=YYYY/part.parquet`. +/// +/// Any [`CuratePostsError`] returns before [`write_events_dataset`] is invoked, leaving +/// `out_dir` untouched. +pub fn curate_and_write_posts( + out_dir: P, + posts: I, + mapping_source: &str, + mapping: &ProviderMappingTable, + options: EventsWriteOptions, +) -> Result +where + P: AsRef, + K: Ord + Clone + AsRef, + I: IntoIterator>, +{ + let curated = curate_posts(posts, mapping_source, mapping)?; + let write_stats = write_events_dataset(out_dir, &curated.rows, options)?; + Ok(CuratePostsWriteReport { + curate_stats: curated.stats, + write_stats, + }) +} + +#[cfg(test)] +#[path = "curate_posts_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/curate_posts_tests.rs b/tools/curate-etl/src/curate_posts_tests.rs new file mode 100644 index 00000000..b58de460 --- /dev/null +++ b/tools/curate-etl/src/curate_posts_tests.rs @@ -0,0 +1,1406 @@ +use std::borrow::Cow; +use std::collections::HashSet; +use std::error::Error; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + +use parquet::basic::Compression; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::*; +use crate::events::partition_year_utc; +use crate::parquet_posts::{ + EVENT_KIND_POST, KNOWN_AT_SOURCE_POST_EDITED, KNOWN_AT_SOURCE_POST_TIMESTAMP, + POST_SUBTYPE_NEWSWIRE, POST_SUBTYPE_RETAIL, +}; +use crate::posts::{PostRow, PostsBuild, PostsError, PostsStats, POSTS_SOURCE_CEO}; +use crate::provider_mapping::{ProviderMappingRow, ProviderMappingTable}; +use crate::split::ymd_to_epoch_days; + +static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDirGuard { + path: PathBuf, +} + +impl TempDirGuard { + fn new(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = + std::env::temp_dir().join(format!("curate-etl-curate-posts-test-{label}-{pid}-{seq}")); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + fn new_uncreated(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = std::env::temp_dir().join(format!( + "curate-etl-curate-posts-uncreated-{label}-{pid}-{seq}" + )); + let _ = fs::remove_dir_all(&path); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn d(year: i32, month: u32, day: u32) -> i32 { + ymd_to_epoch_days(year, month, day).expect("valid test date") +} + +fn utc_ms(year: i32, month: u32, day: u32, hour: u8, minute: u8, second: u8) -> i64 { + let epoch_day = d(year, month, day); + let secs = i64::from(epoch_day) * 86_400 + + i64::from(hour) * 3_600 + + i64::from(minute) * 60 + + i64::from(second); + secs * 1_000 +} + +fn map_row( + source: &str, + source_id: &str, + valid_from: i32, + valid_to: Option, + listing_id: i32, +) -> ProviderMappingRow { + ProviderMappingRow { + source: source.to_string(), + source_id: source_id.to_string(), + valid_from, + valid_to, + listing_id, + } +} + +fn post( + key: &str, + spiel_id: &str, + timestamp_ms: i64, + edited_ms: Option, + bot: Option<&str>, + user_id: Option<&str>, + text: &str, +) -> CeoPost { + CeoPost { + key: key.to_string(), + spiel_id: spiel_id.to_string(), + timestamp_ms, + edited_ms, + bot: bot.map(str::to_string), + user_id: user_id.map(str::to_string), + text: text.to_string(), + } +} + +fn assert_stats_invariants(output: &CuratePostsOutput) { + let s = output.stats; + assert_eq!( + s.builder.input, + s.builder.newswire + + s.builder.retail + + s.builder.duplicates_dropped + + s.builder.rejected_invalid + ); + assert_eq!(s.rows_in, s.builder.newswire + s.builder.retail); + assert_eq!( + s.rows_in, + s.rows_out + + s.dropped_unmapped + + s.dropped_unsupported_date + + s.listing_duplicate_collapsed + ); + assert_eq!(s.rows_out, s.newswire_out + s.retail_out); + assert_eq!(s.rows_out, output.rows.len()); + + let distinct_listings: HashSet = output.rows.iter().map(|r| r.listing_id).collect(); + assert_eq!(s.listings_out, distinct_listings.len()); + + for pair in output.rows.windows(2) { + assert_eq!( + compare_event_rows(&pair[0], &pair[1]), + Ordering::Less, + "rows must be strictly ascending in 7-field writer key" + ); + } +} + +fn all_permutations(items: &[T]) -> Vec> { + let mut out = Vec::new(); + let mut arr = items.to_vec(); + let n = arr.len(); + let mut c = vec![0usize; n]; + out.push(arr.clone()); + + let mut i = 0; + while i < n { + if c[i] < i { + if i % 2 == 0 { + arr.swap(0, i); + } else { + arr.swap(c[i], i); + } + out.push(arr.clone()); + c[i] += 1; + i = 0; + } else { + c[i] = 0; + i += 1; + } + } + out +} + +fn read_events_parquet_and_verify_zstd(path: &Path) -> Vec { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let meta = reader.metadata(); + let mut out = Vec::new(); + + for rg_idx in 0..meta.num_row_groups() { + let rg_meta = meta.row_group(rg_idx); + assert_eq!( + rg_meta.num_columns(), + 7, + "expected 7 columns in events schema" + ); + for col_idx in 0..rg_meta.num_columns() { + let compression = rg_meta.column(col_idx).compression(); + assert!( + matches!(compression, Compression::ZSTD(_)), + "expected ZSTD compression for row_group={rg_idx} col={col_idx}, got {compression:?}" + ); + } + + let rg_rows = rg_meta.num_rows() as usize; + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + + let read_i32_col = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read i32 records"); + assert!(n > 0, "unexpected short read in INT32 column {col_idx}"); + read += n; + } + } + _ => panic!("expected INT32 column at index {col_idx}"), + } + vals + }; + + let read_i64_col = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int64ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read i64 records"); + assert!(n > 0, "unexpected short read in INT64 column {col_idx}"); + read += n; + } + } + _ => panic!("expected INT64 column at index {col_idx}"), + } + vals + }; + + let read_str_col = |col_idx: usize| -> Vec { + let mut raw = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut raw) + .expect("read byte_array records"); + assert!( + n > 0, + "unexpected short read in BYTE_ARRAY column {col_idx}" + ); + read += n; + } + } + _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), + } + raw.iter() + .map(|b| { + std::str::from_utf8(b.data()) + .expect("valid utf8") + .to_string() + }) + .collect() + }; + + let listing_ids = read_i32_col(0); + let ts = read_i64_col(1); + let known_at = read_i64_col(2); + let known_at_source = read_str_col(3); + let kind = read_str_col(4); + let subtype = read_str_col(5); + let payload_json = read_str_col(6); + + for i in 0..rg_rows { + out.push(EventsParquetRow { + listing_id: listing_ids[i], + ts_micros: ts[i], + known_at_micros: known_at[i], + known_at_source: Cow::Owned(known_at_source[i].clone()), + kind: Cow::Owned(kind[i].clone()), + subtype: subtype[i].clone(), + payload_json: payload_json[i].clone(), + }); + } + } + + out +} + +#[test] +fn bot_and_retail_posts_map_to_listing_with_matching_subtypes_and_counts() { + let mapping = + ProviderMappingTable::from_rows(vec![map_row("ceo", "CEO_ABC", d(2024, 1, 1), None, 42)]) + .expect("valid mapping"); + + let t_wire = utc_ms(2024, 6, 15, 14, 0, 0); + let t_retail = utc_ms(2024, 6, 15, 14, 5, 0); + + let output = curate_posts( + vec![ + post( + "CEO_ABC", + "sp_wire", + t_wire, + None, + Some("1"), + Some("thenewswire"), + "Company announces drill results", + ), + post( + "CEO_ABC", + "sp_retail", + t_retail, + None, + Some("0"), + Some("retail_user"), + "Looking strong today", + ), + ], + "ceo", + &mapping, + ) + .expect("curate_posts should succeed"); + + assert_stats_invariants(&output); + assert_eq!(output.rows.len(), 2); + assert_eq!(output.stats.rows_in, 2); + assert_eq!(output.stats.rows_out, 2); + assert_eq!(output.stats.newswire_out, 1); + assert_eq!(output.stats.retail_out, 1); + assert_eq!(output.stats.listings_out, 1); + + assert_eq!(output.rows[0].listing_id, 42); + assert_eq!(output.rows[0].kind.as_ref(), EVENT_KIND_POST); + assert_eq!(output.rows[0].subtype, POST_SUBTYPE_NEWSWIRE); + assert_eq!( + output.rows[0].known_at_source.as_ref(), + KNOWN_AT_SOURCE_POST_TIMESTAMP + ); + + assert_eq!(output.rows[1].listing_id, 42); + assert_eq!(output.rows[1].kind.as_ref(), EVENT_KIND_POST); + assert_eq!(output.rows[1].subtype, POST_SUBTYPE_RETAIL); + assert_eq!( + output.rows[1].known_at_source.as_ref(), + KNOWN_AT_SOURCE_POST_TIMESTAMP + ); +} + +#[test] +fn eastern_boundary_late_edit_and_non_monotonic_cursor_resolve_to_posting_date_listing() { + // Adjacent Eastern ranges: + // 2024-06-14 -> listing 101 + // 2024-06-15.. -> listing 202 + let mapping = ProviderMappingTable::from_rows(vec![ + map_row( + "ceo", + "CEO_REUSE", + d(2024, 6, 14), + Some(d(2024, 6, 14)), + 101, + ), + map_row("ceo", "CEO_REUSE", d(2024, 6, 15), None, 202), + ]) + .expect("valid mapping"); + + // 2024-06-15T03:30:00Z is 2024-06-14 23:30 EDT (Eastern date = June 14 -> listing 101). + // Edited on 2024-06-17T15:00:00Z (well inside listing 202's range), so its builder known_at + // comes AFTER the later post, forcing backward posted_at lookup on the same key & subtype. + let t_early_utc_next_day = utc_ms(2024, 6, 15, 3, 30, 0); + let t_early_edit = utc_ms(2024, 6, 17, 15, 0, 0); + // 2024-06-15T04:30:00Z is 2024-06-15 00:30 EDT (Eastern date = June 15 -> listing 202). + let t_later_et_next_day = utc_ms(2024, 6, 15, 4, 30, 0); + + let inputs = vec![ + post( + "CEO_REUSE", + "sp_june14_et_edited_late", + t_early_utc_next_day, + Some(t_early_edit), + None, + Some("u1"), + "Posted late evening June 14 EDT, edited June 17", + ), + post( + "CEO_REUSE", + "sp_june15_et_unedited", + t_later_et_next_day, + None, + None, + Some("u2"), + "Posted early morning June 15 EDT", + ), + ]; + + // Confirm the builder really puts the June 15 post BEFORE the June 14 post in the same + // (key, subtype) stream so the cursor must step backward from June 15 to June 14. + let built = build_posts(inputs.clone()).expect("build_posts"); + assert_eq!(built.retail.len(), 2); + assert_eq!(built.retail[0].spiel_id, "sp_june15_et_unedited"); + assert_eq!(built.retail[1].spiel_id, "sp_june14_et_edited_late"); + + let output = curate_posts(inputs, "ceo", &mapping).expect("curate_posts"); + assert_stats_invariants(&output); + assert_eq!(output.rows.len(), 2); + assert_eq!(output.stats.listings_out, 2); + + // Output is sorted by listing_id ascending: listing 101 first, listing 202 second. + let early = &output.rows[0]; + assert_eq!(early.listing_id, 101); + assert_eq!(early.ts_micros, t_early_utc_next_day * 1_000); + assert_eq!(early.known_at_micros, t_early_edit * 1_000); + assert!(early.known_at_micros > early.ts_micros); + assert_eq!(early.known_at_source.as_ref(), KNOWN_AT_SOURCE_POST_EDITED); + assert!(early.payload_json.contains("\"sp_june14_et_edited_late\"")); + + let later = &output.rows[1]; + assert_eq!(later.listing_id, 202); + assert_eq!(later.ts_micros, t_later_et_next_day * 1_000); + assert_eq!(later.known_at_micros, t_later_et_next_day * 1_000); + assert_eq!( + later.known_at_source.as_ref(), + KNOWN_AT_SOURCE_POST_TIMESTAMP + ); + assert!(later.payload_json.contains("\"sp_june15_et_unedited\"")); + + // Point-in-time guard: immediately before the edit timestamp, the edited text is excluded. + let cutoff_before_edit = early.known_at_micros - 1; + let visible_before: Vec<&EventsParquetRow> = output + .rows + .iter() + .filter(|r| r.known_at_micros <= cutoff_before_edit) + .collect(); + assert_eq!(visible_before.len(), 1); + assert_eq!(visible_before[0].listing_id, 202); + + let visible_at_edit: Vec<&EventsParquetRow> = output + .rows + .iter() + .filter(|r| r.known_at_micros <= early.known_at_micros) + .collect(); + assert_eq!(visible_at_edit.len(), 2); +} + +#[test] +fn unmapped_keys_out_of_range_dates_and_unsupported_timestamps_are_dropped_cleanly() { + let mapping = ProviderMappingTable::from_rows(vec![map_row( + "ceo", + "CEO_MAPPED", + d(2024, 6, 1), + Some(d(2024, 6, 30)), + 77, + )]) + .expect("valid mapping"); + + let t_inside = utc_ms(2024, 6, 15, 15, 0, 0); + let t_before_range = utc_ms(2024, 5, 31, 15, 0, 0); + let t_after_range = utc_ms(2024, 7, 1, 15, 0, 0); + // 2032-01-01T00:00:00Z converts to micros without overflow but exceeds 2030-12-31 ET. + let t_unsupported_future = utc_ms(2032, 1, 1, 0, 0, 0); + + let output = curate_posts( + vec![ + post( + "CEO_MAPPED", + "sp_ok", + t_inside, + None, + None, + Some("u1"), + "in range", + ), + post( + "CEO_MAPPED", + "sp_before", + t_before_range, + None, + None, + None, + "before range", + ), + post( + "CEO_MAPPED", + "sp_after", + t_after_range, + None, + Some("1"), + None, + "after range", + ), + post( + "CEO_UNKNOWN", + "sp_unknown_key", + t_inside, + None, + None, + None, + "unknown key", + ), + post( + "CEO_MAPPED", + "sp_unsupported_mapped", + t_unsupported_future, + None, + None, + None, + "unsupported year on mapped key", + ), + post( + "CEO_UNKNOWN", + "sp_unsupported_unmapped", + t_unsupported_future, + None, + Some("1"), + None, + "unsupported year on unmapped key counted as unsupported date first", + ), + ], + "ceo", + &mapping, + ) + .expect("curate_posts should not error on unmapped or unsupported-date rows"); + + assert_stats_invariants(&output); + assert_eq!(output.stats.rows_in, 6); + assert_eq!(output.stats.rows_out, 1); + assert_eq!(output.stats.retail_out, 1); + assert_eq!(output.stats.newswire_out, 0); + assert_eq!(output.stats.dropped_unmapped, 3); + assert_eq!(output.stats.dropped_unsupported_date, 2); + assert_eq!(output.stats.listing_duplicate_collapsed, 0); + assert_eq!(output.rows[0].listing_id, 77); +} + +#[test] +fn resolve_and_finalize_collapses_exact_seven_field_duplicates_across_source_keys() { + let mapping = ProviderMappingTable::from_rows(vec![ + map_row("ceo", "CEO_ALIAS_A", d(2024, 1, 1), None, 500), + map_row("ceo", "CEO_ALIAS_B", d(2024, 1, 1), None, 500), + ]) + .expect("valid mapping"); + + let posted_at = utc_ms(2024, 8, 10, 14, 0, 0) * 1_000; + let known_at = utc_ms(2024, 8, 10, 14, 15, 0) * 1_000; + + let build = PostsBuild { + newswire: Vec::new(), + retail: vec![ + PostRow { + key: "CEO_ALIAS_A".to_string(), + spiel_id: "sp_shared".to_string(), + posted_at, + known_at, + is_bot: false, + is_edited: true, + user_id: Some("u_same".to_string()), + text: "Identical post body".to_string(), + source: POSTS_SOURCE_CEO, + }, + PostRow { + key: "CEO_ALIAS_B".to_string(), + spiel_id: "sp_shared".to_string(), + posted_at, + known_at, + is_bot: false, + is_edited: true, + user_id: Some("u_same".to_string()), + text: "Identical post body".to_string(), + source: POSTS_SOURCE_CEO, + }, + ], + stats: PostsStats { + input: 2, + newswire: 0, + retail: 2, + edited: 2, + edited_before_posted: 0, + duplicates_dropped: 0, + rejected_invalid: 0, + }, + }; + + let output = resolve_and_finalize(build, "ceo", &mapping); + assert_stats_invariants(&output); + assert_eq!(output.stats.rows_in, 2); + assert_eq!(output.stats.rows_out, 1); + assert_eq!(output.stats.retail_out, 1); + assert_eq!(output.stats.newswire_out, 0); + assert_eq!(output.stats.listings_out, 1); + assert_eq!(output.stats.listing_duplicate_collapsed, 1); + assert_eq!(output.rows[0].listing_id, 500); +} + +#[test] +fn public_curate_posts_dedups_repeated_spiel_id_in_builder_and_keeps_distinct_spiel_ids() { + let mapping = ProviderMappingTable::from_rows(vec![ + map_row("ceo", "CEO_ALIAS_A", d(2024, 1, 1), None, 500), + map_row("ceo", "CEO_ALIAS_B", d(2024, 1, 1), None, 500), + ]) + .expect("valid mapping"); + + let t_post = utc_ms(2024, 8, 10, 14, 0, 0); + + // Same spiel_id under two source keys mapping to the same listing -> builder dedups before + // mapping, so duplicates_dropped == 1 and listing_duplicate_collapsed == 0. + let same_spiel = curate_posts( + vec![ + post( + "CEO_ALIAS_A", + "sp_dup", + t_post, + None, + None, + Some("u1"), + "Same post", + ), + post( + "CEO_ALIAS_B", + "sp_dup", + t_post, + None, + None, + Some("u1"), + "Same post", + ), + ], + "ceo", + &mapping, + ) + .expect("curate_posts"); + + assert_stats_invariants(&same_spiel); + assert_eq!(same_spiel.stats.builder.duplicates_dropped, 1); + assert_eq!(same_spiel.stats.rows_in, 1); + assert_eq!(same_spiel.stats.rows_out, 1); + assert_eq!(same_spiel.stats.listing_duplicate_collapsed, 0); + assert_eq!(same_spiel.rows[0].listing_id, 500); + + // Distinct spiel_ids (everything else identical) under the two alias keys -> both survive. + let distinct_spiel = curate_posts( + vec![ + post( + "CEO_ALIAS_A", + "sp_one", + t_post, + None, + None, + Some("u1"), + "Same text", + ), + post( + "CEO_ALIAS_B", + "sp_two", + t_post, + None, + None, + Some("u1"), + "Same text", + ), + ], + "ceo", + &mapping, + ) + .expect("curate_posts"); + + assert_stats_invariants(&distinct_spiel); + assert_eq!(distinct_spiel.stats.builder.duplicates_dropped, 0); + assert_eq!(distinct_spiel.stats.rows_in, 2); + assert_eq!(distinct_spiel.stats.rows_out, 2); + assert_eq!(distinct_spiel.stats.listing_duplicate_collapsed, 0); + assert_eq!(distinct_spiel.stats.listings_out, 1); +} + +#[test] +fn permutation_invariance_strict_sort_order_and_empty_input_accounting() { + let mapping = ProviderMappingTable::from_rows(vec![ + map_row("ceo", "CEO_A", d(2024, 1, 1), None, 10), + map_row("ceo", "CEO_B", d(2024, 1, 1), None, 20), + ]) + .expect("valid mapping"); + + // Empty input -> empty rows and default stats. + let empty = curate_posts(Vec::>::new(), "ceo", &mapping).expect("empty"); + assert!(empty.rows.is_empty()); + assert_eq!(empty.stats, CuratePostsStats::default()); + assert_stats_invariants(&empty); + + // Mixed fixture: newswire, retail, edited, unmapped, unsupported date, invalid row. + let t0 = utc_ms(2024, 9, 10, 14, 0, 0); + let t1 = utc_ms(2024, 9, 10, 15, 0, 0); + let t_future = utc_ms(2035, 1, 1, 0, 0, 0); + + let fixture = vec![ + post( + "CEO_B", + "sp_b_wire", + t0, + None, + Some("1"), + Some("wire"), + "Newswire release", + ), + post( + "CEO_A", + "sp_a_retail", + t1, + Some(t1 + 60_000), + None, + Some("u_a"), + "Edited retail post", + ), + post( + "CEO_A", + "sp_a_wire", + t0, + None, + Some(" 1 "), + None, + "Another wire", + ), + post( + "CEO_UNKNOWN", + "sp_unmapped", + t0, + None, + None, + None, + "Unmapped", + ), + post( + "CEO_A", + "sp_unsupported", + t_future, + None, + None, + None, + "Future unsupported", + ), + post("CEO_A", "", t0, None, None, None, "Invalid empty spiel_id"), + ]; + + let baseline = curate_posts(fixture.clone(), "ceo", &mapping).expect("baseline"); + assert_stats_invariants(&baseline); + assert_eq!(baseline.stats.builder.input, 6); + assert_eq!(baseline.stats.builder.rejected_invalid, 1); + assert_eq!(baseline.stats.rows_in, 5); + assert_eq!(baseline.stats.rows_out, 3); + assert_eq!(baseline.stats.newswire_out, 2); + assert_eq!(baseline.stats.retail_out, 1); + assert_eq!(baseline.stats.listings_out, 2); + assert_eq!(baseline.stats.dropped_unmapped, 1); + assert_eq!(baseline.stats.dropped_unsupported_date, 1); + + let perms = all_permutations(&fixture); + assert_eq!(perms.len(), 720); + for perm in perms { + let got = curate_posts(perm, "ceo", &mapping).expect("permuted curate_posts"); + assert_eq!(got, baseline); + } +} + +struct PanicOnConsumeIter; + +impl Iterator for PanicOnConsumeIter { + type Item = CeoPost; + + fn next(&mut self) -> Option { + panic!("iterator must not be consumed when mapping_source is blank"); + } +} + +#[test] +fn typed_errors_for_blank_mapping_source_and_timestamp_overflow_leave_out_dir_untouched() { + let mapping = ProviderMappingTable::default(); + + for blank in ["", " ", "\t\n"] { + let err = curate_posts(PanicOnConsumeIter, blank, &mapping) + .expect_err("blank mapping_source must fail before consuming iterator"); + assert_eq!(err, CuratePostsError::EmptyMappingSource); + assert!(err.source().is_none()); + assert!(err.to_string().contains("mapping_source")); + + // Missing output path stays missing. + let missing_dir = TempDirGuard::new_uncreated("blank-missing"); + let write_err = curate_and_write_posts( + missing_dir.path(), + PanicOnConsumeIter, + blank, + &mapping, + EventsWriteOptions::default(), + ) + .expect_err("curate_and_write_posts must fail on blank mapping_source"); + assert!(matches!( + write_err, + CuratePostsWriteError::Curate(CuratePostsError::EmptyMappingSource) + )); + assert!(write_err.source().is_some()); + assert!(write_err.to_string().contains("posts curation failed")); + assert!(!missing_dir.path().exists()); + + // Existing empty output directory stays empty. + let empty_dir = TempDirGuard::new("blank-empty"); + let _ = curate_and_write_posts( + empty_dir.path(), + PanicOnConsumeIter, + blank, + &mapping, + EventsWriteOptions::default(), + ) + .expect_err("curate_and_write_posts must fail on blank mapping_source"); + assert_eq!(fs::read_dir(empty_dir.path()).expect("read dir").count(), 0); + } + + // TimestampOverflow propagates as CuratePostsError::Posts and leaves out_dir untouched. + let overflow_posts = vec![post( + "CEO_A", + "sp_overflow", + i64::MAX, + None, + None, + None, + "overflow timestamp", + )]; + + let err = curate_posts(overflow_posts.clone(), "ceo", &mapping) + .expect_err("overflow timestamp must fail"); + assert_eq!( + err, + CuratePostsError::Posts(PostsError::TimestampOverflow { + spiel_id: "sp_overflow".to_string(), + field: "timestamp_ms", + timestamp_ms: i64::MAX, + }) + ); + assert!(err.source().is_some()); + assert!(err.to_string().contains("sp_overflow")); + + let missing_dir = TempDirGuard::new_uncreated("overflow-missing"); + let write_err = curate_and_write_posts( + missing_dir.path(), + overflow_posts.clone(), + "ceo", + &mapping, + EventsWriteOptions::default(), + ) + .expect_err("curate_and_write_posts must fail on overflow"); + assert!(matches!( + write_err, + CuratePostsWriteError::Curate(CuratePostsError::Posts( + PostsError::TimestampOverflow { .. } + )) + )); + assert!(write_err.source().is_some()); + assert!(!missing_dir.path().exists()); + + let empty_dir = TempDirGuard::new("overflow-empty"); + let _ = curate_and_write_posts( + empty_dir.path(), + overflow_posts, + "ceo", + &mapping, + EventsWriteOptions::default(), + ) + .expect_err("curate_and_write_posts must fail on overflow"); + assert_eq!(fs::read_dir(empty_dir.path()).expect("read dir").count(), 0); +} + +#[test] +fn curate_and_write_posts_round_trips_zstd_parquet_field_for_field() { + let dir = TempDirGuard::new("round-trip"); + let mapping = ProviderMappingTable::from_rows(vec![ + map_row("ceo", "CEO_A", d(2024, 1, 1), None, 101), + map_row("ceo", "CEO_B", d(2024, 1, 1), None, 202), + ]) + .expect("valid mapping"); + + let t_2024 = utc_ms(2024, 12, 31, 23, 30, 0); + let t_2025_edit = utc_ms(2025, 1, 1, 0, 10, 0); + let t_2025 = utc_ms(2025, 2, 14, 15, 0, 0); + + let fixture = vec![ + post( + "CEO_A", + "sp_2024_special", + t_2024, + Some(t_2025_edit), + None, + Some("user\"1"), + "Quote \"here\", newline\nline2, non-ASCII café €", + ), + post( + "CEO_B", + "sp_2024_wire", + t_2024, + None, + Some("1"), + Some("thenewswire"), + "Year-end wire release", + ), + post( + "CEO_A", + "sp_2025_retail", + t_2025, + None, + None, + None, + "2025 commentary", + ), + post( + "CEO_UNMAPPED", + "sp_dropped", + t_2025, + None, + None, + None, + "Dropped unmapped", + ), + ]; + + let pure = curate_posts(fixture.clone(), "ceo", &mapping).expect("pure curate_posts"); + assert_stats_invariants(&pure); + assert_eq!(pure.rows.len(), 3); + + let report = curate_and_write_posts( + dir.path(), + fixture, + "ceo", + &mapping, + EventsWriteOptions::default(), + ) + .expect("curate_and_write_posts should succeed"); + + assert_eq!(report.curate_stats, pure.stats); + assert_eq!(report.write_stats.rows_written, pure.stats.rows_out); + assert_eq!(report.write_stats.files_written, 2); + assert_eq!(report.write_stats.rows_by_year.get(&2024), Some(&2)); + assert_eq!(report.write_stats.rows_by_year.get(&2025), Some(&1)); + + let path_2024 = dir.path().join("events/year=2024/part.parquet"); + let path_2025 = dir.path().join("events/year=2025/part.parquet"); + assert!(path_2024.exists()); + assert!(path_2025.exists()); + + let read_2024 = read_events_parquet_and_verify_zstd(&path_2024); + let read_2025 = read_events_parquet_and_verify_zstd(&path_2025); + + let expected_2024: Vec = pure + .rows + .iter() + .filter(|r| partition_year_utc(r.ts_micros) == 2024) + .cloned() + .collect(); + let expected_2025: Vec = pure + .rows + .iter() + .filter(|r| partition_year_utc(r.ts_micros) == 2025) + .cloned() + .collect(); + + assert_eq!(read_2024, expected_2024); + assert_eq!(read_2025, expected_2025); + assert!(read_2024[0].payload_json.contains("café €")); + assert!(read_2024[0].payload_json.contains("\\nline2")); + assert!(read_2024[0].payload_json.contains("\\\"here\\\"")); +} + +// --------------------------------------------------------------------------- +// QA edge cases (T-162). +// --------------------------------------------------------------------------- + +/// Independent 7-field writer key built from raw fields (does not reuse `compare_event_rows`). +fn writer_key(r: &EventsParquetRow) -> (i32, i64, String, String, String, i64, String) { + ( + r.listing_id, + r.ts_micros, + r.kind.to_string(), + r.subtype.clone(), + r.payload_json.clone(), + r.known_at_micros, + r.known_at_source.to_string(), + ) +} + +fn assert_strictly_ascending_by_tuple(rows: &[EventsParquetRow]) { + for pair in rows.windows(2) { + assert!( + writer_key(&pair[0]) < writer_key(&pair[1]), + "rows not strictly ascending by 7-field tuple: {:?} !< {:?}", + writer_key(&pair[0]), + writer_key(&pair[1]) + ); + } +} + +#[test] +fn supported_eastern_range_boundaries_are_inclusive_and_drop_outside_without_error() { + use crate::session_close::{ + SESSION_MAX_SUPPORTED_UTC_MICROS, SESSION_MIN_SUPPORTED_UTC_MICROS, + }; + + // Mapping covers the whole supported range for one key. + let mapping = + ProviderMappingTable::from_rows(vec![map_row("ceo", "CEO_EDGE", d(1976, 1, 1), None, 9)]) + .expect("valid mapping"); + + // `posted_at` = ms * 1000, so millisecond-aligned edges. + let min_ms = SESSION_MIN_SUPPORTED_UTC_MICROS / 1_000; + assert_eq!(min_ms * 1_000, SESSION_MIN_SUPPORTED_UTC_MICROS); + let max_ms = SESSION_MAX_SUPPORTED_UTC_MICROS / 1_000; // 2031-01-01T04:59:59.999Z + assert_eq!(min_ms, utc_ms(1976, 1, 1, 5, 0, 0)); + assert_eq!(max_ms + 1, utc_ms(2031, 1, 1, 5, 0, 0)); + + let output = curate_posts( + vec![ + post( + "CEO_EDGE", + "sp_min", + min_ms, + None, + None, + None, + "first supported ms", + ), + post( + "CEO_EDGE", + "sp_min_minus", + min_ms - 1, + None, + None, + None, + "1975 EST", + ), + post( + "CEO_EDGE", + "sp_max", + max_ms, + None, + Some("1"), + None, + "last supported ms", + ), + post( + "CEO_EDGE", + "sp_max_plus", + max_ms + 1, + None, + None, + None, + "2031 EST", + ), + // Positive but early (1970) timestamp passes the builder and must be dropped too. + post("CEO_EDGE", "sp_1970", 1, None, None, None, "epoch + 1ms"), + ], + "ceo", + &mapping, + ) + .expect("out-of-range dates must not error"); + + assert_stats_invariants(&output); + assert_eq!(output.stats.builder.rejected_invalid, 0); + assert_eq!(output.stats.rows_in, 5); + assert_eq!(output.stats.rows_out, 2); + assert_eq!(output.stats.dropped_unsupported_date, 3); + assert_eq!(output.stats.dropped_unmapped, 0); + let ts: Vec = output.rows.iter().map(|r| r.ts_micros).collect(); + assert_eq!(ts, vec![min_ms * 1_000, max_ms * 1_000]); + assert!(output.rows.iter().all(|r| r.listing_id == 9)); +} + +#[test] +fn winter_est_midnight_boundary_uses_eastern_date_not_utc_date() { + // EST (UTC-5) in January: 04:59:59Z is still the previous Eastern day, 05:00:00Z is not. + let mapping = ProviderMappingTable::from_rows(vec![ + map_row("ceo", "CEO_W", d(2024, 1, 1), Some(d(2024, 1, 14)), 31), + map_row("ceo", "CEO_W", d(2024, 1, 15), None, 32), + ]) + .expect("valid mapping"); + + let before_et_midnight = utc_ms(2024, 1, 15, 4, 59, 59); // 2024-01-14 23:59:59 EST + let at_et_midnight = utc_ms(2024, 1, 15, 5, 0, 0); // 2024-01-15 00:00:00 EST + let utc_prev_day_evening = utc_ms(2024, 1, 14, 23, 0, 0); // 2024-01-14 18:00 EST + + let output = curate_posts( + vec![ + post("CEO_W", "sp_a", before_et_midnight, None, None, None, "a"), + post("CEO_W", "sp_b", at_et_midnight, None, None, None, "b"), + post("CEO_W", "sp_c", utc_prev_day_evening, None, None, None, "c"), + ], + "ceo", + &mapping, + ) + .expect("curate_posts"); + assert_stats_invariants(&output); + + let listing_of = |spiel: &str| { + output + .rows + .iter() + .find(|r| r.payload_json.contains(&format!("\"{spiel}\""))) + .map(|r| r.listing_id) + .expect("row present") + }; + assert_eq!( + listing_of("sp_a"), + 31, + "UTC date is Jan 15 but Eastern date is Jan 14" + ); + assert_eq!(listing_of("sp_b"), 32); + assert_eq!(listing_of("sp_c"), 31); +} + +#[test] +fn multi_range_key_with_repeated_backward_date_jumps_matches_table_resolve() { + // Three ranges plus a gap; late edits scramble known_at order relative to posted_at. + let mapping = ProviderMappingTable::from_rows(vec![ + map_row("ceo", "CEO_M", d(2023, 1, 1), Some(d(2023, 3, 31)), 1), + map_row("ceo", "CEO_M", d(2023, 4, 1), Some(d(2023, 6, 30)), 2), + // gap 2023-07-01..=2023-07-31 + map_row("ceo", "CEO_M", d(2023, 8, 1), None, 3), + ]) + .expect("valid mapping"); + + // (spiel, posted, edited, expected listing or None for unmapped gap) + let cases: Vec<(&str, i64, Option, Option)> = vec![ + ( + "sp_feb", + utc_ms(2023, 2, 10, 15, 0, 0), + Some(utc_ms(2023, 12, 1, 15, 0, 0)), + Some(1), + ), + ( + "sp_may", + utc_ms(2023, 5, 10, 15, 0, 0), + Some(utc_ms(2023, 11, 1, 15, 0, 0)), + Some(2), + ), + ("sp_sep", utc_ms(2023, 9, 10, 15, 0, 0), None, Some(3)), + ( + "sp_jul_gap", + utc_ms(2023, 7, 10, 15, 0, 0), + Some(utc_ms(2023, 10, 1, 15, 0, 0)), + None, + ), + ( + "sp_jan", + utc_ms(2023, 1, 5, 15, 0, 0), + Some(utc_ms(2024, 1, 1, 15, 0, 0)), + Some(1), + ), + ("sp_jun", utc_ms(2023, 6, 30, 15, 0, 0), None, Some(2)), + // 2023-04-01T03:00Z = 2023-03-31 23:00 EDT -> listing 1, edited later. + ( + "sp_mar_et", + utc_ms(2023, 4, 1, 3, 0, 0), + Some(utc_ms(2023, 12, 15, 15, 0, 0)), + Some(1), + ), + ]; + + let inputs: Vec> = cases + .iter() + .map(|(s, p, e, _)| post("CEO_M", s, *p, *e, None, None, s)) + .collect(); + + // Prove the builder stream really is non-monotonic in posted_at. + let built = build_posts(inputs.clone()).expect("build"); + let posted: Vec = built.retail.iter().map(|r| r.posted_at).collect(); + assert!(posted.windows(2).filter(|w| w[1] < w[0]).count() >= 2); + + let output = curate_posts(inputs, "ceo", &mapping).expect("curate"); + assert_stats_invariants(&output); + assert_eq!(output.stats.dropped_unmapped, 1); + assert_eq!(output.stats.rows_out, 6); + + for (spiel, posted_ms, _, expected) in &cases { + let got = output + .rows + .iter() + .find(|r| { + r.payload_json + .contains(&format!("\"spiel_id\":\"{spiel}\"")) + }) + .map(|r| r.listing_id); + assert_eq!(got, *expected, "spiel {spiel}"); + // Oracle: fresh table-level binary search on the Eastern posting date. + let et = utc_micros_to_et_local(posted_ms * 1_000).expect("supported"); + assert_eq!(mapping.resolve("ceo", "CEO_M", et.session_date), *expected); + } +} + +#[test] +fn mapping_rows_for_another_source_do_not_resolve() { + let mapping = ProviderMappingTable::from_rows(vec![ + map_row("eod", "CEO_X", d(2024, 1, 1), None, 7), + map_row("ceo", "CEO_Y", d(2024, 1, 1), None, 8), + ]) + .expect("valid mapping"); + let t = utc_ms(2024, 5, 1, 15, 0, 0); + + let output = curate_posts( + vec![ + post("CEO_X", "sp_x", t, None, None, None, "x"), + post("CEO_Y", "sp_y", t, None, None, None, "y"), + ], + "ceo", + &mapping, + ) + .expect("curate"); + assert_stats_invariants(&output); + assert_eq!(output.stats.dropped_unmapped, 1); + assert_eq!(output.rows.len(), 1); + assert_eq!(output.rows[0].listing_id, 8); +} + +#[test] +fn same_key_in_newswire_and_retail_streams_resolves_both() { + // The key appears in both builder streams; each stream needs its own cursor run. + let mapping = ProviderMappingTable::from_rows(vec![ + map_row("ceo", "CEO_A", d(2024, 1, 1), Some(d(2024, 3, 31)), 1), + map_row("ceo", "CEO_A", d(2024, 4, 1), None, 2), + map_row("ceo", "CEO_Z", d(2024, 1, 1), None, 3), + ]) + .expect("valid mapping"); + + let output = curate_posts( + vec![ + post( + "CEO_A", + "w1", + utc_ms(2024, 5, 1, 15, 0, 0), + None, + Some("1"), + None, + "w1", + ), + post( + "CEO_Z", + "w2", + utc_ms(2024, 5, 1, 15, 0, 0), + None, + Some("1"), + None, + "w2", + ), + post( + "CEO_A", + "r1", + utc_ms(2024, 2, 1, 15, 0, 0), + None, + None, + None, + "r1", + ), + post( + "CEO_Z", + "r2", + utc_ms(2024, 2, 1, 15, 0, 0), + None, + None, + None, + "r2", + ), + ], + "ceo", + &mapping, + ) + .expect("curate"); + assert_stats_invariants(&output); + let got: Vec<(i32, &str)> = output + .rows + .iter() + .map(|r| (r.listing_id, r.subtype.as_str())) + .collect(); + assert_eq!( + got, + // Listing 3: Feb retail precedes May newswire by ts_micros. + vec![ + (1, "retail"), + (2, "newswire"), + (3, "retail"), + (3, "newswire") + ] + ); + assert_eq!(output.stats.listings_out, 3); +} + +#[test] +fn parquet_writer_error_is_wrapped_and_curate_stats_not_returned() { + let dir = TempDirGuard::new("writer-error"); + let mapping = + ProviderMappingTable::from_rows(vec![map_row("ceo", "CEO_A", d(2024, 1, 1), None, 1)]) + .expect("valid mapping"); + + let err = curate_and_write_posts( + dir.path(), + vec![post( + "CEO_A", + "sp", + utc_ms(2024, 5, 1, 15, 0, 0), + None, + None, + None, + "t", + )], + "ceo", + &mapping, + EventsWriteOptions { + row_group_rows: 0, + ..EventsWriteOptions::default() + }, + ) + .expect_err("invalid writer options must fail"); + assert!(matches!( + err, + CuratePostsWriteError::Parquet(ParquetEventsError::InvalidRowGroupRows) + )); + assert!(err.source().is_some()); + assert!(err.to_string().contains("posts Parquet write failed")); + assert!(!dir.path().join("events/year=2024/part.parquet").exists()); +} + +#[test] +fn same_listing_same_timestamp_tie_breaks_on_subtype_then_payload_and_round_trips() { + let dir = TempDirGuard::new("tie-break"); + let mapping = + ProviderMappingTable::from_rows(vec![map_row("ceo", "CEO_T", d(2024, 1, 1), None, 55)]) + .expect("valid mapping"); + + let t = utc_ms(2024, 7, 1, 14, 0, 0); + let fixture = vec![ + // Same listing + ts: two retail (payload differs via spiel_id) and two newswire. + post( + "CEO_T", + "sp_r_b", + t, + None, + None, + Some("u"), + "retail \"b\"\nné", + ), + post( + "CEO_T", + "sp_r_a", + t, + Some(t + 5_000), + None, + Some("u"), + "retail a", + ), + post("CEO_T", "sp_w_b", t, None, Some("1"), None, "wire b"), + post("CEO_T", "sp_w_a", t, None, Some("1"), None, "wire a"), + ]; + + let pure = curate_posts(fixture.clone(), "ceo", &mapping).expect("curate"); + assert_stats_invariants(&pure); + assert_strictly_ascending_by_tuple(&pure.rows); + + let order: Vec<(String, String)> = pure + .rows + .iter() + .map(|r| { + let spiel = r.payload_json[13..].split('"').next().unwrap().to_string(); + (r.subtype.clone(), spiel) + }) + .collect(); + assert_eq!( + order, + vec![ + ("newswire".to_string(), "sp_w_a".to_string()), + ("newswire".to_string(), "sp_w_b".to_string()), + ("retail".to_string(), "sp_r_a".to_string()), + ("retail".to_string(), "sp_r_b".to_string()), + ] + ); + assert_eq!( + pure.rows[2].known_at_source.as_ref(), + KNOWN_AT_SOURCE_POST_EDITED + ); + assert_eq!(pure.rows[2].known_at_micros, (t + 5_000) * 1_000); + + let report = curate_and_write_posts( + dir.path(), + fixture, + "ceo", + &mapping, + EventsWriteOptions::default(), + ) + .expect("write"); + assert_eq!(report.curate_stats, pure.stats); + assert_eq!(report.write_stats.rows_written, 4); + let read = + read_events_parquet_and_verify_zstd(&dir.path().join("events/year=2024/part.parquet")); + assert_eq!(read, pure.rows); + assert_strictly_ascending_by_tuple(&read); +} + +#[test] +fn permutation_fixture_is_strictly_ascending_by_independent_tuple() { + let mapping = ProviderMappingTable::from_rows(vec![ + map_row("ceo", "CEO_A", d(2024, 1, 1), None, 10), + map_row("ceo", "CEO_B", d(2024, 1, 1), None, 20), + ]) + .expect("valid mapping"); + let t0 = utc_ms(2024, 9, 10, 14, 0, 0); + let fixture = vec![ + post("CEO_B", "b1", t0, None, Some("1"), None, "x"), + post("CEO_A", "a1", t0, None, None, None, "x"), + post("CEO_A", "a2", t0, None, Some("1"), None, "x"), + post("CEO_A", "a3", t0, Some(t0 + 1), None, None, "x"), + post("CEO_B", "b2", t0 - 1, None, None, None, "x"), + ]; + let baseline = curate_posts(fixture.clone(), "ceo", &mapping).expect("baseline"); + assert_strictly_ascending_by_tuple(&baseline.rows); + for perm in all_permutations(&fixture) { + let got = curate_posts(perm, "ceo", &mapping).expect("perm"); + assert_eq!(got, baseline); + } +} diff --git a/tools/curate-etl/src/events.rs b/tools/curate-etl/src/events.rs index e1f6b52b..a66653d5 100644 --- a/tools/curate-etl/src/events.rs +++ b/tools/curate-etl/src/events.rs @@ -494,7 +494,7 @@ fn sanitize_opt_f64(value: Option) -> Option { const HEX_LOWER: &[u8; 16] = b"0123456789abcdef"; -fn push_json_str(out: &mut String, s: &str) { +pub(crate) fn push_json_str(out: &mut String, s: &str) { out.push('"'); let bytes = s.as_bytes(); let mut start = 0usize; @@ -534,7 +534,7 @@ fn push_json_str(out: &mut String, s: &str) { } #[inline] -fn push_json_opt_str(out: &mut String, s: Option<&str>) { +pub(crate) fn push_json_opt_str(out: &mut String, s: Option<&str>) { match s { Some(v) => push_json_str(out, v), None => out.push_str("null"), diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 1a8ff478..c1dcf4ee 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -4,14 +4,17 @@ pub mod adj; pub mod bars; pub mod bars_1m; pub mod bench; +pub mod bson_ceo_posts; pub mod bson_ceo_shorts; 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; @@ -19,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; @@ -27,6 +31,8 @@ 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; pub mod posts; @@ -49,6 +55,10 @@ pub use bars_1m::{ SessionCloseCheck, SessionCloseCutoffPolicy, SessionCloseMismatchSample, SessionCloseStats, BARS_1M_SOURCE_EOD, BARS_1M_SOURCE_QM, RTH_END_MINUTE_ET, RTH_START_MINUTE_ET, }; +pub use bson_ceo_posts::{ + decode_ceo_posts_buffer, decode_ceo_posts_bytes, decode_ceo_posts_doc, + BsonCeoPostsDecodeStats, BsonCeoPostsError, CeoPostsFieldNames, CeoPostsTimestampUnit, +}; pub use bson_ceo_shorts::{ decode_ceo_shorts_buffer, decode_ceo_shorts_bytes, decode_ceo_shorts_doc, BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames, DEFAULT_KEY_FIELD, @@ -76,20 +86,33 @@ 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, }; pub use bson_stream::{ - decode_ceo_shorts_chunks, 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, BsonCeoShortsStreamError, - BsonQmEventsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunk, RawBsonChunkReader, - DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES, + decode_ceo_posts_chunks, decode_ceo_posts_stream, decode_ceo_shorts_chunks, + 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_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, @@ -132,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, @@ -172,6 +200,14 @@ 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, +}; pub use parquet_shorts::{ shorts_parquet_schema, write_shorts_dataset, ParquetShortsError, ShortsParquetRow, ShortsWriteOptions, ShortsWriteStats, @@ -220,6 +256,25 @@ pub use curate_events::{ CurateEventsStats, CurateEventsWriteError, CurateEventsWriteReport, }; +pub mod curate_posts; +pub use curate_posts::{ + curate_and_write_posts, curate_posts, CuratePostsError, CuratePostsOutput, CuratePostsStats, + 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, @@ -292,6 +347,19 @@ pub use run_curate_fx::{ ALLOWED_TE_SYMBOLS, DEFAULT_TE_SYMBOL, EOD_CAD_FOREX_CODE, }; +pub mod run_curate_posts; +pub use run_curate_posts::{ + format_curate_posts_report, run_curate_posts, run_curate_posts_with_reader, CuratePostsArgs, + 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, @@ -312,6 +380,8 @@ pub use run_mongo::{ CurateEventsMongoArgs, CurateFx1dMongoArgs, CurateShortsMongoArgs, RunMongoCurateError, }; +#[cfg(test)] +mod parquet_posts_tests; #[cfg(test)] mod posts_tests; #[cfg(test)] diff --git a/tools/curate-etl/src/macro_series.rs b/tools/curate-etl/src/macro_series.rs new file mode 100644 index 00000000..247ec0d9 --- /dev/null +++ b/tools/curate-etl/src/macro_series.rs @@ -0,0 +1,284 @@ +//! Pure, in-memory `macro` builder for lagged `teData` regime series (`MacroObservation` + +//! caller-supplied [`MacroLagClass`] → sorted, unique [`MacroRow`]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` +//! 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 { + 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 { + 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 { + pub rows: Vec>, + pub stats: MacroBuildStats, +} + +/// Typed errors returned by [`build_macro_rows`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum MacroError { + /// 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 fmt::Display for MacroError { + 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 Error for MacroError {} + +struct MappedObservation { + 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` 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( + observations: I, + lag_for: F, +) -> Result, MacroError> +where + K: Ord, + I: IntoIterator>, + F: Fn(&K, &K) -> Option, +{ + let iter = observations.into_iter(); + let (lower, _) = iter.size_hint(); + let mut stats = MacroBuildStats::default(); + let mut mapped: Vec> = 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> = 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; diff --git a/tools/curate-etl/src/macro_series_tests.rs b/tools/curate-etl/src/macro_series_tests.rs new file mode 100644 index 00000000..464f2f56 --- /dev/null +++ b/tools/curate-etl/src/macro_series_tests.rs @@ -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 { + MacroObservation { + country_iso: country_iso.to_string(), + indicator: indicator.to_string(), + period_date, + value, + } +} + +fn assert_accounting_and_order(build: &MacroBuild) { + 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(left: &[MacroRow], right: &[MacroRow]) { + 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> = 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 { + 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(items: &[T]) -> Vec> { + 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> = 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"); +} diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index 6f3be0c3..936c0d64 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -28,6 +28,7 @@ use curate_etl::run_curate_corporate_actions::{ }; use curate_etl::run_curate_events::{format_curate_events_report, run_curate_events}; use curate_etl::run_curate_fx::{format_curate_fx_report, run_curate_fx_1d}; +use curate_etl::run_curate_posts::{format_curate_posts_report, run_curate_posts}; use curate_etl::run_curate_shorts::{format_curate_shorts_report, run_curate_shorts}; use curate_etl::run_mongo::{ run_curate_adj_factors_mongo, run_curate_bars_1d_mongo, run_curate_corporate_actions_mongo, @@ -197,6 +198,16 @@ fn main() -> ExitCode { } } } + Ok(CliAction::CuratePosts(curate_args)) => match run_curate_posts(&curate_args) { + Ok(report) => { + println!("{}", format_curate_posts_report(&report)); + ExitCode::SUCCESS + } + Err(err) => { + eprintln!("error: {err}"); + ExitCode::FAILURE + } + }, Ok(CliAction::BenchSplit(rows)) => { let report = match run_split_benchmark(rows) { Ok(report) => report, diff --git a/tools/curate-etl/src/parquet_macro.rs b/tools/curate-etl/src/parquet_macro.rs new file mode 100644 index 00000000..d2a21f3e --- /dev/null +++ b/tools/curate-etl/src/parquet_macro.rs @@ -0,0 +1,776 @@ +//! Streaming, atomic Zstd Parquet writer for `macro`. +//! +//! Writes `/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>` 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> From<&MacroRow> for MacroParquetRow { + #[inline] + fn from(row: &MacroRow) -> 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, + failures: Vec, + }, + 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 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 { + let fields: Vec = 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, + country_iso_interner: StringInterner, + indicator_ids: Vec, + indicator_interner: StringInterner, + period_date: Vec, + known_at_micros: Vec, + known_at_source_ids: Vec, + known_at_source_interner: StringInterner, + value: Vec, +} + +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>, + 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 { + 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) -> 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, + ) -> Result { + 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 `/macro/part.parquet`. +/// +/// # Empty Input +/// Empty input (with valid options) returns `Ok(MacroWriteStats::default())` without creating +/// `/macro` and without modifying or removing any pre-existing `part.parquet`. +/// +/// # Concurrency & Atomicity +/// Concurrent writers targeting the same `/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..tmp`), flushed, +/// and `sync_all`'d before publication. If a pre-existing `part.parquet` regular file exists, +/// a live-preserving backup (`part.parquet..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( + out_dir: P, + rows: I, + options: MacroWriteOptions, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, +{ + write_macro_dataset_with_hooks( + out_dir, + rows, + options, + DEFAULT_LOCK_TIMEOUT, + |_, _| {}, + |path| fs::remove_file(path), + ) +} + +fn write_macro_dataset_with_hooks( + out_dir: P, + rows: I, + options: MacroWriteOptions, + lock_timeout: Duration, + mut on_after_backup: F, + mut remove_backup: Rm, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, + 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(¯o_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(¯o_dir); + let _in_process_guard = dataset_mu.lock().unwrap_or_else(|err| err.into_inner()); + let _file_lock = DatasetFileLock::acquire_with_timeout(¯o_dir, lock_timeout)?; + + let run_id = next_run_id(); + let (tmp_path, tmp_file) = create_exclusive_tmp_file(¯o_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 = 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; diff --git a/tools/curate-etl/src/parquet_macro_tests.rs b/tools/curate-etl/src/parquet_macro_tests.rs new file mode 100644 index 00000000..e3865b0b --- /dev/null +++ b/tools/curate-etl/src/parquet_macro_tests.rs @@ -0,0 +1,1391 @@ +use std::borrow::Cow; +use std::error::Error as StdError; +use std::fs::{self, File}; +use std::io; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use parquet::basic::{Compression, ConvertedType, Encoding, LogicalType, Repetition, TimeUnit, Type as PhysicalType}; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::{ + macro_parquet_schema, write_macro_dataset, write_macro_dataset_with_hooks, MacroParquetRow, + MacroWriteOptions, MacroWriteStats, ParquetMacroError, +}; +use crate::macro_series::{ + build_macro_rows, MacroLagClass, MacroObservation, MacroRow, MACRO_KNOWN_AT_SOURCE, + MONTHLY_RELEASE_LAG_DAYS, POLICY_RATE_LAG_DAYS, +}; +use crate::split::ymd_to_epoch_days; + +const MICROS_PER_DAY: i64 = 86_400_000_000; + +static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDirGuard { + path: PathBuf, +} + +impl TempDirGuard { + fn new(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = + std::env::temp_dir().join(format!("curate-etl-pq-macro-test-{label}-{pid}-{seq}")); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn make_row( + country_iso: &'static str, + indicator: &'static str, + period_date: i32, + lag_days: i32, + value: f64, +) -> MacroParquetRow { + MacroParquetRow { + country_iso: Cow::Borrowed(country_iso), + indicator: Cow::Borrowed(indicator), + period_date, + known_at_micros: i64::from(period_date + lag_days) * MICROS_PER_DAY, + known_at_source: Cow::Borrowed(MACRO_KNOWN_AT_SOURCE), + value, + } +} + +fn read_parquet_rows(path: &Path) -> Vec { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let metadata = reader.metadata(); + let mut out = Vec::new(); + + for rg_idx in 0..metadata.num_row_groups() { + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + let num_rows = metadata.row_group(rg_idx).num_rows() as usize; + + let read_i32 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read i32"); + assert_eq!(read, num_rows); + } + _ => panic!("expected INT32 column at index {col_idx}"), + } + vals + }; + let read_i64 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int64ColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read i64"); + assert_eq!(read, num_rows); + } + _ => panic!("expected INT64 column at index {col_idx}"), + } + vals + }; + let read_f64 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::DoubleColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read f64"); + assert_eq!(read, num_rows); + } + _ => panic!("expected DOUBLE column at index {col_idx}"), + } + vals + }; + let read_str = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read utf8"); + assert_eq!(read, num_rows); + } + _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), + } + vals.into_iter() + .map(|b| std::str::from_utf8(b.data()).expect("valid utf8").to_owned()) + .collect() + }; + + let country_iso = read_str(0); + let indicator = read_str(1); + let period_date = read_i32(2); + let known_at_micros = read_i64(3); + let known_at_source = read_str(4); + let value = read_f64(5); + + for i in 0..num_rows { + out.push(MacroParquetRow { + country_iso: Cow::Owned(country_iso[i].clone()), + indicator: Cow::Owned(indicator[i].clone()), + period_date: period_date[i], + known_at_micros: known_at_micros[i], + known_at_source: Cow::Owned(known_at_source[i].clone()), + value: value[i], + }); + } + } + out +} + +fn assert_row_bitwise_eq(actual: &MacroParquetRow, expected: &MacroParquetRow) { + assert_eq!(actual.country_iso, expected.country_iso); + assert_eq!(actual.indicator, expected.indicator); + assert_eq!(actual.period_date, expected.period_date); + assert_eq!(actual.known_at_micros, expected.known_at_micros); + assert_eq!(actual.known_at_source, expected.known_at_source); + assert_eq!(actual.value.to_bits(), expected.value.to_bits()); +} + +fn assert_no_transient_files(dir: &Path) { + if !dir.exists() { + return; + } + for entry in fs::read_dir(dir).expect("read dir") { + let entry = entry.expect("dir entry"); + let name = entry.file_name().to_string_lossy().into_owned(); + assert!( + !name.ends_with(".tmp") && !name.ends_with(".bak") && name != ".write.lock", + "unexpected transient file remaining: {}", + entry.path().display() + ); + } +} + +fn seed_existing(out_dir: &Path) -> (PathBuf, Vec) { + let seed = vec![ + make_row("CA", "policy_rate", day(2024, 1, 24), POLICY_RATE_LAG_DAYS, 5.0), + make_row("US", "cpi_yoy", day(2024, 1, 31), MONTHLY_RELEASE_LAG_DAYS, 3.1), + ]; + write_macro_dataset(out_dir, &seed, MacroWriteOptions::default()).unwrap(); + let part = out_dir.join("macro/part.parquet"); + let before = fs::read(&part).unwrap(); + (part, before) +} + +/// Pinned `build_macro_rows` fixture with 2 countries (`CA`, `US`), 2 indicators +/// (`cpi_yoy`, `policy_rate`), 2 lag classes (`MonthlyRelease`, `PolicyRate`), +/// negative values, and both `-0.0` and `+0.0` at distinct keys. +fn pinned_builder_fixture() -> Vec> { + let observations = vec![ + // Intentionally unsorted so `build_macro_rows` establishes canonical sort order. + MacroObservation { + country_iso: "US".to_string(), + indicator: "policy_rate".to_string(), + period_date: day(2024, 3, 20), + value: 5.5, + }, + MacroObservation { + country_iso: "CA".to_string(), + indicator: "cpi_yoy".to_string(), + period_date: day(2024, 2, 29), + value: 0.0_f64, + }, + MacroObservation { + country_iso: "CA".to_string(), + indicator: "cpi_yoy".to_string(), + period_date: day(2024, 1, 31), + value: -0.0_f64, + }, + MacroObservation { + country_iso: "US".to_string(), + indicator: "cpi_yoy".to_string(), + period_date: day(2024, 1, 31), + value: -0.25, + }, + MacroObservation { + country_iso: "CA".to_string(), + indicator: "policy_rate".to_string(), + period_date: day(2024, 3, 6), + value: 5.0, + }, + ]; + + let built = build_macro_rows(observations, |country, indicator| match ( + country.as_str(), + indicator.as_str(), + ) { + ("CA" | "US", "policy_rate") => Some(MacroLagClass::PolicyRate), + ("CA" | "US", "cpi_yoy") => Some(MacroLagClass::MonthlyRelease), + _ => None, + }) + .expect("build_macro_rows fixture"); + + assert_eq!(built.rows.len(), 5); + assert_eq!(built.stats.emitted, 5); + built.rows +} + +#[test] +fn schema_matches_contract_names_types_nullability_and_order() { + let schema = macro_parquet_schema().expect("build schema"); + assert_eq!(schema.name(), "macro"); + let fields = schema.get_fields(); + assert_eq!(fields.len(), 6); + + let expected: [( + &str, + PhysicalType, + Repetition, + Option, + ConvertedType, + ); 6] = [ + ( + "country_iso", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "indicator", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "period_date", + PhysicalType::INT32, + Repetition::REQUIRED, + Some(LogicalType::Date), + ConvertedType::DATE, + ), + ( + "known_at", + PhysicalType::INT64, + Repetition::REQUIRED, + Some(LogicalType::timestamp(true, TimeUnit::MICROS)), + ConvertedType::TIMESTAMP_MICROS, + ), + ( + "known_at_source", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "value", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ]; + + for (idx, (name, phys, rep, logical, converted)) in expected.into_iter().enumerate() { + let f = &fields[idx]; + assert_eq!(f.name(), name, "field {idx} name"); + assert_eq!(f.get_physical_type(), phys, "field {name} physical type"); + assert_eq!( + f.get_basic_info().repetition(), + rep, + "field {name} repetition" + ); + assert_eq!( + f.get_basic_info().logical_type_ref().cloned(), + logical, + "field {name} logical type" + ); + assert_eq!( + f.get_basic_info().converted_type(), + converted, + "field {name} converted type" + ); + } +} + +#[test] +fn build_macro_rows_round_trip_bitwise_and_written_file_schema_zstd() { + let tmp = TempDirGuard::new("round-trip"); + let builder_rows = pinned_builder_fixture(); + + let parquet_rows: Vec = builder_rows + .iter() + .map(|r| { + let row = MacroParquetRow::from(r); + assert!(matches!(row.known_at_source, Cow::Borrowed(_))); + row + }) + .collect(); + + // Verify `From<&MacroRow<&str>>` compiles and matches as well. + let borrowed_macro_row = MacroRow { + country_iso: "US", + indicator: "policy_rate", + period_date: day(2024, 3, 20), + known_at: i64::from(day(2024, 3, 21)) * MICROS_PER_DAY, + known_at_source: MACRO_KNOWN_AT_SOURCE, + value: 5.5, + }; + let converted = MacroParquetRow::from(&borrowed_macro_row); + assert_eq!(converted.country_iso.as_ref(), "US"); + assert_eq!(converted.known_at_micros, borrowed_macro_row.known_at); + + let stats = write_macro_dataset(tmp.path(), &parquet_rows, MacroWriteOptions::default()).unwrap(); + assert_eq!(stats.rows_written, 5); + assert_eq!(stats.files_written, 1); + assert_eq!(stats.row_groups_written, 1); + assert!(stats.bytes_written > 0); + + let path = tmp.path().join("macro/part.parquet"); + assert_eq!(fs::metadata(&path).unwrap().len(), stats.bytes_written); + + let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); + let meta = reader.metadata(); + assert_eq!(meta.file_metadata().num_rows(), 5); + assert_eq!(meta.num_row_groups(), 1); + + // Inspect written file schema directly. + let file_fields = meta.file_metadata().schema().get_fields(); + assert_eq!(file_fields.len(), 6); + assert_eq!(file_fields[0].name(), "country_iso"); + assert_eq!(file_fields[1].name(), "indicator"); + assert_eq!(file_fields[2].name(), "period_date"); + assert_eq!(file_fields[3].name(), "known_at"); + assert_eq!(file_fields[4].name(), "known_at_source"); + assert_eq!(file_fields[5].name(), "value"); + for f in file_fields { + assert_eq!(f.get_basic_info().repetition(), Repetition::REQUIRED); + } + assert_eq!( + file_fields[2].get_basic_info().logical_type_ref().cloned(), + Some(LogicalType::Date) + ); + assert_eq!( + file_fields[3].get_basic_info().logical_type_ref().cloned(), + Some(LogicalType::timestamp(true, TimeUnit::MICROS)) + ); + assert_eq!(file_fields[5].get_physical_type(), PhysicalType::DOUBLE); + + // Every column chunk must use Zstd compression. + for rg in meta.row_groups() { + for col in rg.columns() { + assert!( + matches!(col.compression(), Compression::ZSTD(_)), + "column {} expected ZSTD, got {:?}", + col.column_path(), + col.compression() + ); + } + } + + // Bitwise round-trip against `build_macro_rows` baseline. + let actual = read_parquet_rows(&path); + assert_eq!(actual.len(), builder_rows.len()); + for (a, b) in actual.iter().zip(&builder_rows) { + assert_eq!(a.country_iso.as_ref(), b.country_iso.as_str()); + assert_eq!(a.indicator.as_ref(), b.indicator.as_str()); + assert_eq!(a.period_date, b.period_date); + assert_eq!(a.known_at_micros, b.known_at); + assert_eq!(a.known_at_source.as_ref(), MACRO_KNOWN_AT_SOURCE); + assert_eq!(a.value.to_bits(), b.value.to_bits()); + } + + // Explicitly verify `-0.0` vs `+0.0` bit preservation in the same row group, + // and exact UTC microseconds at expected lagged midnights. + assert_eq!(actual[0].country_iso.as_ref(), "CA"); + assert_eq!(actual[0].indicator.as_ref(), "cpi_yoy"); + assert_eq!(actual[0].value.to_bits(), (-0.0_f64).to_bits()); + assert_eq!( + actual[0].known_at_micros, + i64::from(day(2024, 1, 31) + MONTHLY_RELEASE_LAG_DAYS) * MICROS_PER_DAY + ); + + assert_eq!(actual[1].country_iso.as_ref(), "CA"); + assert_eq!(actual[1].indicator.as_ref(), "cpi_yoy"); + assert_eq!(actual[1].value.to_bits(), (0.0_f64).to_bits()); + assert_eq!( + actual[1].known_at_micros, + i64::from(day(2024, 2, 29) + MONTHLY_RELEASE_LAG_DAYS) * MICROS_PER_DAY + ); + + assert_eq!(actual[2].country_iso.as_ref(), "CA"); + assert_eq!(actual[2].indicator.as_ref(), "policy_rate"); + assert_eq!( + actual[2].known_at_micros, + i64::from(day(2024, 3, 6) + POLICY_RATE_LAG_DAYS) * MICROS_PER_DAY + ); + + assert_no_transient_files(&tmp.path().join("macro")); +} + +#[test] +fn multi_row_group_with_partial_final_group_matches_baseline_and_metadata() { + let tmp = TempDirGuard::new("multi-rg"); + let builder_rows = pinned_builder_fixture(); + let parquet_rows: Vec = builder_rows.iter().map(MacroParquetRow::from).collect(); + + // 5 rows with row_group_rows = 2 => 3 row groups: [2, 2, 1] + let opts = MacroWriteOptions { + row_group_rows: 2, + ..MacroWriteOptions::default() + }; + let stats = write_macro_dataset(tmp.path(), &parquet_rows, opts).unwrap(); + assert_eq!(stats.rows_written, 5); + assert_eq!(stats.files_written, 1); + assert_eq!(stats.row_groups_written, 3); + + let path = tmp.path().join("macro/part.parquet"); + assert_eq!(fs::metadata(&path).unwrap().len(), stats.bytes_written); + + let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); + let meta = reader.metadata(); + assert_eq!(meta.file_metadata().num_rows(), 5); + assert_eq!(meta.num_row_groups(), 3); + let rg_sizes: Vec = (0..meta.num_row_groups()) + .map(|i| meta.row_group(i).num_rows()) + .collect(); + assert_eq!(rg_sizes, vec![2, 2, 1]); + + for rg in meta.row_groups() { + for col in rg.columns() { + assert!( + matches!(col.compression(), Compression::ZSTD(_)), + "column {} expected ZSTD, got {:?}", + col.column_path(), + col.compression() + ); + } + } + + let actual = read_parquet_rows(&path); + assert_eq!(actual.len(), parquet_rows.len()); + for (a, e) in actual.iter().zip(&parquet_rows) { + assert_row_bitwise_eq(a, e); + } + assert_no_transient_files(&tmp.path().join("macro")); +} + +#[test] +fn string_columns_use_dictionary_encoding_and_output_is_deterministic() { + let tmp = TempDirGuard::new("dict-determinism"); + let base = day(2024, 1, 1); + let rows: Vec = (0..64_i32) + .map(|i| { + let country = if i < 32 { "CA" } else { "US" }; + let indicator = if (i % 32) < 16 { "cpi_yoy" } else { "policy_rate" }; + make_row( + country, + indicator, + base + (i % 16), + POLICY_RATE_LAG_DAYS, + f64::from(i) * 0.125, + ) + }) + .collect(); + + let out_a = tmp.path().join("a"); + let out_b = tmp.path().join("b"); + let opts = MacroWriteOptions { + row_group_rows: 32, + ..MacroWriteOptions::default() + }; + write_macro_dataset(&out_a, &rows, opts).unwrap(); + write_macro_dataset(&out_b, &rows, opts).unwrap(); + + let path_a = out_a.join("macro/part.parquet"); + let path_b = out_b.join("macro/part.parquet"); + assert_eq!(fs::read(&path_a).unwrap(), fs::read(&path_b).unwrap()); + + let reader = SerializedFileReader::new(File::open(&path_a).unwrap()).unwrap(); + let rg0 = reader.metadata().row_group(0); + for (col_idx, name) in [ + (0usize, "country_iso"), + (1usize, "indicator"), + (4usize, "known_at_source"), + ] { + let col = rg0.column(col_idx); + assert!( + col.encodings().any(|e| { + matches!(e, Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY) + }), + "expected dictionary encoding on {name}, got {:?}", + col.encodings().collect::>() + ); + } +} + +#[test] +fn empty_input_returns_default_stats_and_preserves_fresh_and_seeded_destinations() { + let tmp = TempDirGuard::new("empty"); + let fresh = tmp.path().join("fresh"); + let stats = write_macro_dataset( + &fresh, + std::iter::empty::(), + MacroWriteOptions::default(), + ) + .unwrap(); + assert_eq!(stats, MacroWriteStats::default()); + assert!(!fresh.exists(), "empty input must not create out_dir"); + + let seeded = tmp.path().join("seeded"); + let (part, before) = seed_existing(&seeded); + let empty_stats = write_macro_dataset( + &seeded, + std::iter::empty::(), + MacroWriteOptions::default(), + ) + .unwrap(); + assert_eq!(empty_stats, MacroWriteStats::default()); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&seeded.join("macro")); +} + +#[test] +fn invalid_options_fail_closed_in_fresh_and_seeded_dirs() { + let tmp = TempDirGuard::new("bad-opts"); + let fresh = tmp.path().join("fresh"); + let seeded = tmp.path().join("seeded"); + let (part, before) = seed_existing(&seeded); + let rows = vec![make_row( + "US", + "policy_rate", + day(2024, 3, 20), + POLICY_RATE_LAG_DAYS, + 5.5, + )]; + + for (dir, is_fresh) in [(&fresh, true), (&seeded, false)] { + assert!(matches!( + write_macro_dataset( + dir, + &rows, + MacroWriteOptions { + row_group_rows: 0, + ..MacroWriteOptions::default() + } + ), + Err(ParquetMacroError::InvalidRowGroupRows) + )); + // Even with empty input, invalid options must fail before returning default stats. + assert!(matches!( + write_macro_dataset( + dir, + std::iter::empty::(), + MacroWriteOptions { + row_group_rows: 0, + ..MacroWriteOptions::default() + } + ), + Err(ParquetMacroError::InvalidRowGroupRows) + )); + assert!(matches!( + write_macro_dataset( + dir, + &rows, + MacroWriteOptions { + zstd_level: 23, + ..MacroWriteOptions::default() + } + ), + Err(ParquetMacroError::InvalidZstdLevel { level: 23 }) + )); + assert!(matches!( + write_macro_dataset( + dir, + &rows, + MacroWriteOptions { + zstd_level: 99, + ..MacroWriteOptions::default() + } + ), + Err(ParquetMacroError::InvalidZstdLevel { level: 99 }) + )); + + if is_fresh { + assert!(!dir.exists(), "invalid options must not create out_dir"); + } else { + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&dir.join("macro")); + } + } +} + +#[test] +fn invalid_inputs_return_typed_errors_in_fresh_and_seeded_dirs() { + let tmp = TempDirGuard::new("invalid-inputs"); + let fresh = tmp.path().join("fresh"); + let seeded = tmp.path().join("seeded"); + let (part, before) = seed_existing(&seeded); + let d1 = day(2024, 1, 31); + let d2 = day(2024, 2, 29); + + let check_both = |rows: &[MacroParquetRow], check: &dyn Fn(&ParquetMacroError)| { + let err_fresh = + write_macro_dataset(&fresh, rows, MacroWriteOptions::default()).unwrap_err(); + check(&err_fresh); + assert!( + !fresh.join("macro/part.parquet").exists(), + "fresh dir must not contain part.parquet after error: {err_fresh}" + ); + assert_no_transient_files(&fresh.join("macro")); + + let err_seeded = + write_macro_dataset(&seeded, rows, MacroWriteOptions::default()).unwrap_err(); + check(&err_seeded); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&seeded.join("macro")); + }; + + // 1. Non-finite values: NaN, +inf, -inf + for bad_val in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let rows = vec![make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, bad_val)]; + check_both(&rows, &|err| { + assert!( + matches!( + err, + ParquetMacroError::InvalidValue { + country_iso, + indicator, + period_date, + .. + } if country_iso == "US" && indicator == "cpi_yoy" && *period_date == d1 + ), + "expected InvalidValue for {bad_val}, got {err:?}" + ); + }); + } + + // 2. Empty / whitespace-only country_iso (first row and second row) + for bad_country in ["", " ", "\t\n"] { + let first_bad = vec![MacroParquetRow { + country_iso: Cow::Owned(bad_country.to_string()), + ..make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0) + }]; + check_both(&first_bad, &|err| { + assert!( + matches!( + err, + ParquetMacroError::EmptyCountryIso { indicator, period_date } + if indicator == "cpi_yoy" && *period_date == d1 + ), + "expected EmptyCountryIso for {bad_country:?}, got {err:?}" + ); + }); + + let second_bad = vec![ + make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0), + MacroParquetRow { + country_iso: Cow::Owned(bad_country.to_string()), + ..make_row("US", "cpi_yoy", d2, MONTHLY_RELEASE_LAG_DAYS, 3.1) + }, + ]; + check_both(&second_bad, &|err| { + assert!( + matches!( + err, + ParquetMacroError::EmptyCountryIso { indicator, period_date } + if indicator == "cpi_yoy" && *period_date == d2 + ), + "expected EmptyCountryIso on row 2 for {bad_country:?}, got {err:?}" + ); + }); + } + + // 3. Empty / whitespace-only indicator (first row and second row) + for bad_indicator in ["", " ", "\t\n"] { + let first_bad = vec![MacroParquetRow { + indicator: Cow::Owned(bad_indicator.to_string()), + ..make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0) + }]; + check_both(&first_bad, &|err| { + assert!( + matches!( + err, + ParquetMacroError::EmptyIndicator { country_iso, period_date } + if country_iso == "US" && *period_date == d1 + ), + "expected EmptyIndicator for {bad_indicator:?}, got {err:?}" + ); + }); + + let second_bad = vec![ + make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0), + MacroParquetRow { + indicator: Cow::Owned(bad_indicator.to_string()), + ..make_row("US", "cpi_yoy", d2, MONTHLY_RELEASE_LAG_DAYS, 3.1) + }, + ]; + check_both(&second_bad, &|err| { + assert!( + matches!( + err, + ParquetMacroError::EmptyIndicator { country_iso, period_date } + if country_iso == "US" && *period_date == d2 + ), + "expected EmptyIndicator on row 2 for {bad_indicator:?}, got {err:?}" + ); + }); + } + + // 4. Empty / whitespace-only known_at_source + for bad_source in ["", " ", "\t\n"] { + let rows = vec![MacroParquetRow { + known_at_source: Cow::Owned(bad_source.to_string()), + ..make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0) + }]; + check_both(&rows, &|err| { + assert!( + matches!( + err, + ParquetMacroError::EmptyKnownAtSource { + country_iso, + indicator, + period_date, + } if country_iso == "US" && indicator == "cpi_yoy" && *period_date == d1 + ), + "expected EmptyKnownAtSource for {bad_source:?}, got {err:?}" + ); + }); + } + + // 5. Descending country_iso + let unsorted_country = vec![ + make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0), + make_row("CA", "cpi_yoy", d2, MONTHLY_RELEASE_LAG_DAYS, 2.8), + ]; + check_both(&unsorted_country, &|err| { + assert!( + matches!( + err, + ParquetMacroError::UnsortedInput { + prev_country_iso, + prev_indicator, + prev_period_date, + country_iso, + indicator, + period_date, + } if prev_country_iso == "US" + && prev_indicator == "cpi_yoy" + && *prev_period_date == d1 + && country_iso == "CA" + && indicator == "cpi_yoy" + && *period_date == d2 + ), + "expected UnsortedInput for descending country_iso, got {err:?}" + ); + }); + + // 6. Descending indicator within same country_iso + let unsorted_indicator = vec![ + make_row("CA", "policy_rate", d1, POLICY_RATE_LAG_DAYS, 5.0), + make_row("CA", "cpi_yoy", d2, MONTHLY_RELEASE_LAG_DAYS, 2.8), + ]; + check_both(&unsorted_indicator, &|err| { + assert!( + matches!( + err, + ParquetMacroError::UnsortedInput { + prev_country_iso, + prev_indicator, + prev_period_date, + country_iso, + indicator, + period_date, + } if prev_country_iso == "CA" + && prev_indicator == "policy_rate" + && *prev_period_date == d1 + && country_iso == "CA" + && indicator == "cpi_yoy" + && *period_date == d2 + ), + "expected UnsortedInput for descending indicator, got {err:?}" + ); + }); + + // 7. Descending period_date within same (country_iso, indicator) + let unsorted_date = vec![ + make_row("US", "cpi_yoy", d2, MONTHLY_RELEASE_LAG_DAYS, 3.1), + make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0), + ]; + check_both(&unsorted_date, &|err| { + assert!( + matches!( + err, + ParquetMacroError::UnsortedInput { + prev_country_iso, + prev_indicator, + prev_period_date, + country_iso, + indicator, + period_date, + } if prev_country_iso == "US" + && prev_indicator == "cpi_yoy" + && *prev_period_date == d2 + && country_iso == "US" + && indicator == "cpi_yoy" + && *period_date == d1 + ), + "expected UnsortedInput for descending period_date, got {err:?}" + ); + }); + + // 8. Duplicate (country_iso, indicator, period_date) + let duplicate = vec![ + make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0), + make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0), + ]; + check_both(&duplicate, &|err| { + assert!( + matches!( + err, + ParquetMacroError::DuplicateKey { + country_iso, + indicator, + period_date, + } if country_iso == "US" && indicator == "cpi_yoy" && *period_date == d1 + ), + "expected DuplicateKey, got {err:?}" + ); + }); +} + +#[test] +fn mid_stream_failures_after_flushed_row_groups_preserve_state_and_clean_staging() { + let tmp = TempDirGuard::new("mid-stream-fail"); + let fresh = tmp.path().join("fresh"); + let seeded = tmp.path().join("seeded"); + let (part, before) = seed_existing(&seeded); + let base = day(2024, 1, 1); + + let prefix = vec![ + make_row("CA", "cpi_yoy", base, MONTHLY_RELEASE_LAG_DAYS, 2.5), + make_row("CA", "cpi_yoy", base + 1, MONTHLY_RELEASE_LAG_DAYS, 2.6), + make_row("CA", "policy_rate", base, POLICY_RATE_LAG_DAYS, 5.0), + make_row("CA", "policy_rate", base + 1, POLICY_RATE_LAG_DAYS, 5.0), + ]; + + let opts = MacroWriteOptions { + row_group_rows: 2, + ..MacroWriteOptions::default() + }; + + // Case A: Non-finite value on row 5 after 2 row groups have flushed. + let mut bad_val_rows = prefix.clone(); + bad_val_rows.push(make_row( + "US", + "cpi_yoy", + base, + MONTHLY_RELEASE_LAG_DAYS, + f64::NAN, + )); + + // Case B: Descending key across row-group flush boundary. + let mut unsorted_rows = prefix.clone(); + unsorted_rows.push(make_row( + "CA", + "policy_rate", + base, + POLICY_RATE_LAG_DAYS, + 4.75, + )); + + // Case C: Duplicate key across row-group flush boundary. + let mut dup_rows = prefix; + dup_rows.push(make_row( + "CA", + "policy_rate", + base + 1, + POLICY_RATE_LAG_DAYS, + 5.0, + )); + + for (rows, expected_kind) in [ + (&bad_val_rows, "invalid_value"), + (&unsorted_rows, "unsorted"), + (&dup_rows, "duplicate"), + ] { + let err_fresh = write_macro_dataset(&fresh, rows, opts).unwrap_err(); + let err_seeded = write_macro_dataset(&seeded, rows, opts).unwrap_err(); + + for err in [&err_fresh, &err_seeded] { + match expected_kind { + "invalid_value" => assert!(matches!(err, ParquetMacroError::InvalidValue { .. })), + "unsorted" => assert!(matches!(err, ParquetMacroError::UnsortedInput { .. })), + "duplicate" => assert!(matches!(err, ParquetMacroError::DuplicateKey { .. })), + _ => unreachable!(), + } + } + + assert!( + !fresh.join("macro/part.parquet").exists(), + "fresh dir must not publish part.parquet on {expected_kind}" + ); + assert_no_transient_files(&fresh.join("macro")); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&seeded.join("macro")); + } +} + +#[test] +fn overwrite_replaces_existing_part_parquet_and_cleans_backup() { + let tmp = TempDirGuard::new("overwrite"); + let (part, before) = seed_existing(tmp.path()); + + let replacement = vec![ + make_row("CA", "cpi_yoy", day(2025, 1, 31), MONTHLY_RELEASE_LAG_DAYS, 1.9), + make_row("US", "policy_rate", day(2025, 1, 29), POLICY_RATE_LAG_DAYS, 4.5), + ]; + let stats = write_macro_dataset(tmp.path(), &replacement, MacroWriteOptions::default()).unwrap(); + assert_eq!(stats.rows_written, 2); + assert_eq!(stats.files_written, 1); + assert_eq!(stats.row_groups_written, 1); + + let after = fs::read(&part).unwrap(); + assert_ne!(after, before); + let actual = read_parquet_rows(&part); + assert_eq!(actual.len(), replacement.len()); + for (a, e) in actual.iter().zip(&replacement) { + assert_row_bitwise_eq(a, e); + } + assert_no_transient_files(&tmp.path().join("macro")); +} + +#[test] +fn live_part_parquet_stays_readable_between_backup_and_rename() { + let tmp = TempDirGuard::new("live-readable"); + let (part, before) = seed_existing(tmp.path()); + + let replacement = vec![make_row( + "US", + "policy_rate", + day(2025, 3, 19), + POLICY_RATE_LAG_DAYS, + 4.25, + )]; + let observed_live = Arc::new(Mutex::new(false)); + let observed_clone = Arc::clone(&observed_live); + + write_macro_dataset_with_hooks( + tmp.path(), + &replacement, + MacroWriteOptions::default(), + Duration::from_secs(5), + |final_path, backup_path| { + assert_eq!(final_path, part.as_path()); + let bak = backup_path.expect("backup must be created for existing file"); + assert!(bak.exists()); + assert_eq!(fs::read(final_path).unwrap(), before); + assert_eq!(fs::read(bak).unwrap(), before); + *observed_clone.lock().unwrap() = true; + }, + |path| fs::remove_file(path), + ) + .unwrap(); + + assert!(*observed_live.lock().unwrap()); + let actual = read_parquet_rows(&part); + assert_eq!(actual.len(), 1); + assert_row_bitwise_eq(&actual[0], &replacement[0]); + assert_no_transient_files(&tmp.path().join("macro")); +} + +#[test] +fn stale_lock_times_out_and_backup_cleanup_failure_restores_previous_file() { + let tmp = TempDirGuard::new("lock-and-rollback"); + let (part, before) = seed_existing(tmp.path()); + let lock_path = tmp.path().join("macro/.write.lock"); + fs::write(&lock_path, b"999999\n").unwrap(); + + let rows = vec![make_row( + "US", + "policy_rate", + day(2025, 5, 7), + POLICY_RATE_LAG_DAYS, + 4.5, + )]; + let err = write_macro_dataset_with_hooks( + tmp.path(), + &rows, + MacroWriteOptions::default(), + Duration::from_millis(30), + |_, _| {}, + |path| fs::remove_file(path), + ) + .unwrap_err(); + assert!( + matches!(err, ParquetMacroError::LockTimeout { ref path, .. } if path == &lock_path), + "expected LockTimeout, got {err:?}" + ); + assert!(lock_path.exists(), "stale lock must remain untouched"); + assert_eq!(fs::read(&part).unwrap(), before); + fs::remove_file(&lock_path).unwrap(); + + // Simulate backup removal failure: previous file must be restored from backup. + let err2 = write_macro_dataset_with_hooks( + tmp.path(), + &rows, + MacroWriteOptions::default(), + Duration::from_secs(5), + |_, _| {}, + |_bak| Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected")), + ) + .unwrap_err(); + assert!(matches!(err2, ParquetMacroError::Io { .. })); + assert!(StdError::source(&err2).is_some()); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("macro")); +} + +// --------------------------------------------------------------------------- +// QA (T-173) edge cases: builder/writer ordering agreement, extreme values, +// owned iterators, I/O blockers, rename failure, concurrency, panic unwind, +// and rollback failure reporting. +// --------------------------------------------------------------------------- + +/// `build_macro_rows` sorts by `K: Ord` (byte order for `String`); the writer must accept +/// every builder output, including prefix keys (`US` < `USA`), uppercase before lowercase, +/// and non-ASCII UTF-8, and round-trip it bit-for-bit across all four lag classes. +#[test] +fn builder_byte_order_keys_and_all_lag_classes_are_accepted_and_round_trip() { + let tmp = TempDirGuard::new("builder-order"); + let base = day(2023, 12, 31); + let obs = |c: &str, i: &str, d: i32, v: f64| MacroObservation { + country_iso: c.to_string(), + indicator: i.to_string(), + period_date: d, + value: v, + }; + let observations = vec![ + obs("USA", "gdp_q", base, 1.0), + obs("US", "gdp_q", base, 2.0), + obs("US", "Gdp_q", base, 3.0), + obs("US", "gdp_q_é", base, 4.0), + obs("US", "gdp_q", base - 1, f64::MIN_POSITIVE / 2.0), // subnormal + obs("CA", "rate", base, f64::MAX), + obs("CA", "rate", base + 1, -f64::MAX), + ]; + let built = build_macro_rows(observations, |_, indicator| match indicator.as_str() { + "gdp_q" => Some(MacroLagClass::Gdp65), + "Gdp_q" => Some(MacroLagClass::Gdp90), + "gdp_q_é" => Some(MacroLagClass::MonthlyRelease), + "rate" => Some(MacroLagClass::PolicyRate), + _ => None, + }) + .expect("builder"); + assert_eq!(built.rows.len(), 7); + + let rows: Vec = built.rows.iter().map(MacroParquetRow::from).collect(); + // row_group_rows = 3 so ordering is checked across flush boundaries too. + let opts = MacroWriteOptions { + row_group_rows: 3, + ..MacroWriteOptions::default() + }; + let stats = write_macro_dataset(tmp.path(), &rows, opts).expect("builder output accepted"); + assert_eq!(stats.rows_written, 7); + assert_eq!(stats.row_groups_written, 3); + + let actual = read_parquet_rows(&tmp.path().join("macro/part.parquet")); + assert_eq!(actual.len(), built.rows.len()); + for (a, b) in actual.iter().zip(&built.rows) { + assert_eq!(a.country_iso.as_ref(), b.country_iso.as_str()); + assert_eq!(a.indicator.as_ref(), b.indicator.as_str()); + assert_eq!(a.period_date, b.period_date); + assert_eq!(a.known_at_micros, b.known_at); + assert_eq!(a.known_at_source.as_ref(), b.known_at_source); + assert_eq!(a.value.to_bits(), b.value.to_bits()); + } + let order: Vec<(&str, &str)> = actual + .iter() + .map(|r| (r.country_iso.as_ref(), r.indicator.as_ref())) + .collect(); + assert_eq!( + order, + vec![ + ("CA", "rate"), + ("CA", "rate"), + ("US", "Gdp_q"), + ("US", "gdp_q"), + ("US", "gdp_q"), + ("US", "gdp_q_é"), + ("USA", "gdp_q"), + ] + ); + // Gdp90 lag preserved exactly. + assert_eq!( + actual[2].known_at_micros, + i64::from(base + 90) * MICROS_PER_DAY + ); + assert_no_transient_files(&tmp.path().join("macro")); +} + +/// The writer stores `period_date`/`known_at` verbatim; it must not reject or alter +/// pre-1970 or extreme integers (bounds are the builder's job). +#[test] +fn extreme_dates_and_timestamps_round_trip_verbatim_with_owned_iterator() { + let tmp = TempDirGuard::new("extremes"); + let rows = vec![ + MacroParquetRow { + period_date: i32::MIN, + known_at_micros: i64::MIN, + ..make_row("AA", "x", 0, 0, 1.5) + }, + MacroParquetRow { + known_at_micros: -1, + ..make_row("AA", "x", -1, 0, -1.5) + }, + MacroParquetRow { + period_date: i32::MAX, + known_at_micros: i64::MAX, + ..make_row("AA", "x", 0, 0, 0.1) + }, + ]; + // Owned (by-value) iterator path. + let stats = + write_macro_dataset(tmp.path(), rows.clone().into_iter(), MacroWriteOptions::default()) + .unwrap(); + assert_eq!(stats.rows_written, 3); + let actual = read_parquet_rows(&tmp.path().join("macro/part.parquet")); + assert_eq!(actual.len(), 3); + for (a, e) in actual.iter().zip(&rows) { + assert_row_bitwise_eq(a, e); + } +} + +#[test] +fn out_dir_or_macro_dir_occupied_by_regular_file_returns_io_error() { + let tmp = TempDirGuard::new("io-blocker"); + let rows = vec![make_row("US", "policy_rate", day(2024, 3, 20), POLICY_RATE_LAG_DAYS, 5.5)]; + + let file_as_out = tmp.path().join("not-a-dir"); + fs::write(&file_as_out, b"sentinel").unwrap(); + let err = write_macro_dataset(&file_as_out, &rows, MacroWriteOptions::default()).unwrap_err(); + assert!(matches!(err, ParquetMacroError::Io { .. }), "got {err:?}"); + assert!(StdError::source(&err).is_some()); + assert_eq!(fs::read(&file_as_out).unwrap(), b"sentinel"); + + let out = tmp.path().join("macro-is-file"); + fs::create_dir_all(&out).unwrap(); + let macro_file = out.join("macro"); + fs::write(¯o_file, b"file-not-dir").unwrap(); + let err2 = write_macro_dataset(&out, &rows, MacroWriteOptions::default()).unwrap_err(); + assert!(matches!(err2, ParquetMacroError::Io { .. }), "got {err2:?}"); + assert_eq!(fs::read(¯o_file).unwrap(), b"file-not-dir"); +} + +#[test] +fn rename_failure_over_directory_blocker_cleans_up_staging_and_preserves_unowned_tmp() { + let tmp = TempDirGuard::new("rename-blocker"); + let macro_dir = tmp.path().join("macro"); + let blocking_dir = macro_dir.join("part.parquet"); + fs::create_dir_all(&blocking_dir).unwrap(); + let unowned_tmp = macro_dir.join("part.parquet.unowned-other-run.tmp"); + fs::write(&unowned_tmp, b"keep-me").unwrap(); + + let rows = vec![make_row("US", "policy_rate", day(2024, 3, 20), POLICY_RATE_LAG_DAYS, 5.5)]; + let err = write_macro_dataset(tmp.path(), &rows, MacroWriteOptions::default()).unwrap_err(); + assert!(matches!(err, ParquetMacroError::Io { .. }), "got {err:?}"); + assert!(blocking_dir.is_dir(), "directory blocker must remain intact"); + assert_eq!(fs::read(&unowned_tmp).unwrap(), b"keep-me"); + + let mut entries: Vec = fs::read_dir(¯o_dir) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + entries.sort(); + assert_eq!( + entries, + vec![ + "part.parquet".to_string(), + "part.parquet.unowned-other-run.tmp".to_string(), + ] + ); +} + +#[test] +fn concurrent_in_process_writers_serialize_to_one_generation() { + let tmp = TempDirGuard::new("concurrent"); + let out = Arc::new(tmp.path().to_path_buf()); + let base = day(2024, 1, 31); + + let out_1 = Arc::clone(&out); + let h1 = std::thread::spawn(move || { + let iter = (0..2_i32).map(move |i| { + if i == 1 { + std::thread::sleep(Duration::from_millis(30)); + } + make_row("CA", "cpi_yoy", base + i, MONTHLY_RELEASE_LAG_DAYS, 2.0) + }); + write_macro_dataset(out_1.as_path(), iter, MacroWriteOptions::default()) + }); + std::thread::sleep(Duration::from_millis(5)); + let out_2 = Arc::clone(&out); + let h2 = std::thread::spawn(move || { + let iter = (0..2_i32) + .map(move |i| make_row("US", "policy_rate", base + i, POLICY_RATE_LAG_DAYS, 5.5)); + write_macro_dataset(out_2.as_path(), iter, MacroWriteOptions::default()) + }); + + assert_eq!(h1.join().unwrap().unwrap().rows_written, 2); + assert_eq!(h2.join().unwrap().unwrap().rows_written, 2); + + let got = read_parquet_rows(&tmp.path().join("macro/part.parquet")); + assert_eq!(got.len(), 2); + assert!( + got.iter().all(|r| r.country_iso == "CA") || got.iter().all(|r| r.country_iso == "US"), + "output must come entirely from one writer generation" + ); + assert_no_transient_files(&tmp.path().join("macro")); +} + +#[test] +fn panicking_iterator_after_flush_cleans_staging_releases_lock_and_preserves_live_file() { + let tmp = TempDirGuard::new("panic-unwind"); + let (part, before) = seed_existing(tmp.path()); + let out = tmp.path().to_path_buf(); + let opts = MacroWriteOptions { + row_group_rows: 2, + ..MacroWriteOptions::default() + }; + let result = std::panic::catch_unwind(move || { + let base = day(2024, 1, 31); + let iter = (0..5_i32).map(move |i| { + if i == 3 { + panic!("simulated iterator panic after row-group flush"); + } + make_row("US", "cpi_yoy", base + i, MONTHLY_RELEASE_LAG_DAYS, 3.0) + }); + let _ = write_macro_dataset(&out, iter, opts); + }); + assert!(result.is_err(), "iterator must have panicked"); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("macro")); + + // Next writer proceeds without hitting a stale lock. + let replacement = vec![make_row("US", "policy_rate", day(2025, 1, 29), POLICY_RATE_LAG_DAYS, 4.5)]; + let stats = write_macro_dataset(tmp.path(), &replacement, MacroWriteOptions::default()).unwrap(); + assert_eq!(stats.rows_written, 1); + let got = read_parquet_rows(&part); + assert_eq!(got.len(), 1); + assert_row_bitwise_eq(&got[0], &replacement[0]); + assert_no_transient_files(&tmp.path().join("macro")); +} + +#[test] +fn backup_unlink_and_restore_failure_reports_rollback_failed() { + let tmp = TempDirGuard::new("rollback-failed"); + let (part, _before) = seed_existing(tmp.path()); + let replacement = vec![make_row("US", "policy_rate", day(2025, 1, 29), POLICY_RATE_LAG_DAYS, 4.5)]; + let observed_bak: Arc>> = Arc::new(Mutex::new(None)); + let observed_clone = Arc::clone(&observed_bak); + + let err = write_macro_dataset_with_hooks( + tmp.path(), + &replacement, + MacroWriteOptions::default(), + Duration::from_secs(5), + |_, _| {}, + move |bak| { + *observed_clone.lock().unwrap() = Some(bak.to_path_buf()); + // Remove the backup so the restore rename also fails. + let _ = fs::remove_file(bak); + Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected")) + }, + ) + .unwrap_err(); + + let expected_bak = observed_bak.lock().unwrap().clone().expect("hook called"); + match err { + ParquetMacroError::RollbackFailed { cause, failures } => { + assert!( + matches!( + *cause, + ParquetMacroError::Io { ref path, ref source } + if path == &expected_bak + && source.kind() == io::ErrorKind::PermissionDenied + ), + "unexpected cause: {cause:?}" + ); + assert_eq!(failures.len(), 1); + assert_eq!(failures[0].final_path, part); + assert_eq!(failures[0].backup_path.as_deref(), Some(expected_bak.as_path())); + assert_eq!(failures[0].source.kind(), io::ErrorKind::NotFound); + } + other => panic!("expected RollbackFailed, got {other:?}"), + } + assert_no_transient_files(&tmp.path().join("macro")); +} + +#[test] +fn backup_unlink_failure_error_names_backup_path_and_restores_live_bytes() { + let tmp = TempDirGuard::new("bak-unlink-path"); + let (part, before) = seed_existing(tmp.path()); + let replacement = vec![make_row("US", "policy_rate", day(2025, 1, 29), POLICY_RATE_LAG_DAYS, 4.5)]; + let observed_bak: Arc>> = Arc::new(Mutex::new(None)); + let observed_clone = Arc::clone(&observed_bak); + + let err = write_macro_dataset_with_hooks( + tmp.path(), + &replacement, + MacroWriteOptions::default(), + Duration::from_secs(5), + |_, _| {}, + move |bak| { + *observed_clone.lock().unwrap() = Some(bak.to_path_buf()); + Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected")) + }, + ) + .unwrap_err(); + let expected_bak = observed_bak.lock().unwrap().clone().expect("hook called"); + assert!( + matches!( + err, + ParquetMacroError::Io { ref path, ref source } + if path == &expected_bak && source.kind() == io::ErrorKind::PermissionDenied + ), + "got {err:?}" + ); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("macro")); +} + +#[test] +fn error_display_messages_name_offending_key() { + let e = ParquetMacroError::DuplicateKey { + country_iso: "US".into(), + indicator: "cpi_yoy".into(), + period_date: 19_753, + }; + assert!(e.to_string().contains("(US, cpi_yoy, 19753)"), "{e}"); + let e = ParquetMacroError::InvalidValue { + country_iso: "CA".into(), + indicator: "rate".into(), + period_date: 1, + value: f64::NAN, + }; + let msg = e.to_string(); + assert!(msg.contains("NaN") && msg.contains("must be finite"), "{msg}"); + assert!(StdError::source(&e).is_none()); +} diff --git a/tools/curate-etl/src/parquet_posts.rs b/tools/curate-etl/src/parquet_posts.rs new file mode 100644 index 00000000..07500644 --- /dev/null +++ b/tools/curate-etl/src/parquet_posts.rs @@ -0,0 +1,109 @@ +//! Adapter mapping curated `ceoPosts` rows ([`PostRow`] / [`PostsBuild`]) into the +//! 7-column `events` Parquet contract ([`EventsParquetRow`], `events/year=YYYY/part.parquet`). +//! +//! Aligned with `design/DATA-CONTRACTS.md` §1 & §3A and `design/PLATFORM-PLAN.md`: +//! - `kind` is always [`EVENT_KIND_POST`] (`"post"`). +//! - `subtype` is [`POST_SUBTYPE_NEWSWIRE`] (`"newswire"`) when `is_bot` is `true`, and +//! [`POST_SUBTYPE_RETAIL`] (`"retail"`) otherwise, so wire releases are never pooled with crowd +//! chat. +//! - `ts` is the posting timestamp (`posted_at`) and `known_at` is the point-in-time text +//! availability timestamp (`known_at >= posted_at`). +//! - `known_at_source` is [`KNOWN_AT_SOURCE_POST_EDITED`] (`"post_edited"`) iff +//! `known_at > posted_at`, and [`KNOWN_AT_SOURCE_POST_TIMESTAMP`] (`"post_timestamp"`) otherwise +//! (including when an edit timestamp before `posted_at` was clamped back to `posted_at`). + +use std::borrow::Cow; + +use crate::events::{push_json_opt_str, push_json_str}; +use crate::parquet_events::EventsParquetRow; +use crate::posts::{PostRow, PostsBuild}; + +/// Canonical `events.kind` label for curated `ceoPosts` rows. +pub const EVENT_KIND_POST: &str = "post"; + +/// Canonical `events.subtype` label for `bot == "1"` newswire posts. +pub const POST_SUBTYPE_NEWSWIRE: &str = "newswire"; + +/// Canonical `events.subtype` label for non-bot retail posts. +pub const POST_SUBTYPE_RETAIL: &str = "retail"; + +/// Provenance label when `known_at` equals the post's creation timestamp (`posted_at`). +pub const KNOWN_AT_SOURCE_POST_TIMESTAMP: &str = "post_timestamp"; + +/// Provenance label when `known_at` reflects a post-creation edit timestamp (`known_at > posted_at`). +pub const KNOWN_AT_SOURCE_POST_EDITED: &str = "post_edited"; + +/// Encodes a curated post's `payload_json` as a compact RFC 8259 JSON object with fixed key order: +/// `{"spiel_id":...,"user_id":...,"is_edited":...,"source":...,"text":...}`. +fn encode_post_payload_json(row: &PostRow) -> String { + let cap = 72 + + row.spiel_id.len() + + row.user_id.as_deref().map_or(4, str::len) + + row.source.len() + + row.text.len(); + let mut out = String::with_capacity(cap); + out.push_str("{\"spiel_id\":"); + push_json_str(&mut out, &row.spiel_id); + out.push_str(",\"user_id\":"); + push_json_opt_str(&mut out, row.user_id.as_deref()); + out.push_str(",\"is_edited\":"); + out.push_str(if row.is_edited { "true" } else { "false" }); + out.push_str(",\"source\":"); + push_json_str(&mut out, row.source); + out.push_str(",\"text\":"); + push_json_str(&mut out, &row.text); + out.push('}'); + out +} + +impl From<&PostRow> for EventsParquetRow { + fn from(row: &PostRow) -> Self { + let known_at_source = if row.known_at > row.posted_at { + KNOWN_AT_SOURCE_POST_EDITED + } else { + KNOWN_AT_SOURCE_POST_TIMESTAMP + }; + let subtype = if row.is_bot { + POST_SUBTYPE_NEWSWIRE + } else { + POST_SUBTYPE_RETAIL + }; + + Self { + listing_id: row.key, + ts_micros: row.posted_at, + known_at_micros: row.known_at, + known_at_source: Cow::Borrowed(known_at_source), + kind: Cow::Borrowed(EVENT_KIND_POST), + subtype: subtype.to_string(), + payload_json: encode_post_payload_json(row), + } + } +} + +impl From> for EventsParquetRow { + fn from(row: PostRow) -> Self { + Self::from(&row) + } +} + +/// Converts both `newswire` and `retail` streams of a [`PostsBuild`] into +/// [`EventsParquetRow`] records sorted in the exact order required by +/// [`crate::parquet_events::write_events_dataset`]: +/// `(listing_id, ts_micros, kind, subtype, payload_json, known_at_micros, known_at_source)`. +pub fn posts_to_event_rows(build: &PostsBuild) -> Vec { + let mut rows = Vec::with_capacity(build.newswire.len() + build.retail.len()); + rows.extend(build.newswire.iter().map(EventsParquetRow::from)); + rows.extend(build.retail.iter().map(EventsParquetRow::from)); + rows.sort_unstable_by(|a, b| { + a.listing_id + .cmp(&b.listing_id) + .then_with(|| a.ts_micros.cmp(&b.ts_micros)) + .then_with(|| a.kind.as_ref().cmp(b.kind.as_ref())) + .then_with(|| a.subtype.cmp(&b.subtype)) + .then_with(|| a.payload_json.cmp(&b.payload_json)) + .then_with(|| a.known_at_micros.cmp(&b.known_at_micros)) + .then_with(|| a.known_at_source.as_ref().cmp(b.known_at_source.as_ref())) + }); + rows +} diff --git a/tools/curate-etl/src/parquet_posts_tests.rs b/tools/curate-etl/src/parquet_posts_tests.rs new file mode 100644 index 00000000..69812e00 --- /dev/null +++ b/tools/curate-etl/src/parquet_posts_tests.rs @@ -0,0 +1,816 @@ +use std::borrow::Cow; +use std::collections::HashSet; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + +use parquet::basic::Compression; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use crate::parquet_events::{write_events_dataset, EventsParquetRow, EventsWriteOptions}; +use crate::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, +}; +use crate::posts::{build_posts, CeoPost, POSTS_SOURCE_CEO}; +use crate::split::ymd_to_epoch_days; + +static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDirGuard { + path: PathBuf, +} + +impl TempDirGuard { + fn new(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = + std::env::temp_dir().join(format!("curate-etl-pq-posts-test-{label}-{pid}-{seq}")); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn utc_ms(year: i32, month: u32, day: u32, hour: u8, minute: u8, second: u8) -> i64 { + let epoch_day = ymd_to_epoch_days(year, month, day).expect("valid test date"); + let secs = i64::from(epoch_day) * 86_400 + + i64::from(hour) * 3_600 + + i64::from(minute) * 60 + + i64::from(second); + secs * 1_000 +} + +fn post( + listing_id: i32, + spiel_id: &str, + timestamp_ms: i64, + edited_ms: Option, + bot: Option<&str>, + user_id: Option<&str>, + text: &str, +) -> CeoPost { + CeoPost { + key: listing_id, + spiel_id: spiel_id.to_string(), + timestamp_ms, + edited_ms, + bot: bot.map(str::to_string), + user_id: user_id.map(str::to_string), + text: text.to_string(), + } +} + +/// Generates all permutations of `items` via Heap's algorithm. +fn all_permutations(items: &[T]) -> Vec> { + let mut out = Vec::new(); + let mut arr = items.to_vec(); + let n = arr.len(); + let mut c = vec![0usize; n]; + out.push(arr.clone()); + + let mut i = 0; + while i < n { + if c[i] < i { + if i % 2 == 0 { + arr.swap(0, i); + } else { + arr.swap(c[i], i); + } + out.push(arr.clone()); + c[i] += 1; + i = 0; + } else { + c[i] = 0; + i += 1; + } + } + out +} + +fn read_events_parquet_and_verify_zstd(path: &Path) -> Vec { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let meta = reader.metadata(); + let mut out = Vec::new(); + + for rg_idx in 0..meta.num_row_groups() { + let rg_meta = meta.row_group(rg_idx); + assert_eq!( + rg_meta.num_columns(), + 7, + "expected 7 columns in events schema" + ); + for col_idx in 0..rg_meta.num_columns() { + let compression = rg_meta.column(col_idx).compression(); + assert!( + matches!(compression, Compression::ZSTD(_)), + "expected ZSTD compression for row_group={rg_idx} col={col_idx}, got {compression:?}" + ); + } + + let rg_rows = rg_meta.num_rows() as usize; + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + + let read_i32_col = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read i32 records"); + assert!(n > 0, "unexpected short read in INT32 column {col_idx}"); + read += n; + } + } + _ => panic!("expected INT32 column at index {col_idx}"), + } + vals + }; + + let read_i64_col = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int64ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read i64 records"); + assert!(n > 0, "unexpected short read in INT64 column {col_idx}"); + read += n; + } + } + _ => panic!("expected INT64 column at index {col_idx}"), + } + vals + }; + + let read_str_col = |col_idx: usize| -> Vec { + let mut raw = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut raw) + .expect("read byte_array records"); + assert!( + n > 0, + "unexpected short read in BYTE_ARRAY column {col_idx}" + ); + read += n; + } + } + _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), + } + raw.iter() + .map(|b| { + std::str::from_utf8(b.data()) + .expect("valid utf8") + .to_string() + }) + .collect() + }; + + let listing_ids = read_i32_col(0); + let ts = read_i64_col(1); + let known_at = read_i64_col(2); + let known_at_source = read_str_col(3); + let kind = read_str_col(4); + let subtype = read_str_col(5); + let payload_json = read_str_col(6); + + for i in 0..rg_rows { + out.push(EventsParquetRow { + listing_id: listing_ids[i], + ts_micros: ts[i], + known_at_micros: known_at[i], + known_at_source: Cow::Owned(known_at_source[i].clone()), + kind: Cow::Owned(kind[i].clone()), + subtype: subtype[i].clone(), + payload_json: payload_json[i].clone(), + }); + } + } + + out +} + +#[test] +fn maps_retail_unedited_edited_newswire_and_clamped_edit_for_borrowed_and_owned() { + let t_post = utc_ms(2024, 6, 15, 14, 30, 0); + let t_edit_later = t_post + 600_000; // +10 minutes + let t_edit_earlier = t_post - 5_000; // -5 seconds (clamped to posted_at) + + let build = build_posts(vec![ + post( + 101, + "sp_retail_unedited", + t_post, + None, + None, + Some("u_retail"), + "Retail baseline", + ), + post( + 102, + "sp_retail_edited", + t_post, + Some(t_edit_later), + Some("0"), + Some("u_editor"), + "Edited retail text", + ), + post( + 103, + "sp_newswire", + t_post, + None, + Some("1"), + Some("thenewswire"), + "Company announces drill results", + ), + post( + 104, + "sp_edit_clamped", + t_post, + Some(t_edit_earlier), + None, + None, + "Clock-skewed edit", + ), + ]) + .expect("build_posts should succeed"); + + // Verify borrowed and owned From impls agree on every row. + for row in build.newswire.iter().chain(build.retail.iter()) { + let from_ref = EventsParquetRow::from(row); + let from_owned = EventsParquetRow::from(row.clone()); + assert_eq!(from_ref, from_owned); + } + + let mapped = posts_to_event_rows(&build); + assert_eq!(mapped.len(), 4); + + // 101: retail unedited + assert_eq!( + mapped[0], + EventsParquetRow { + listing_id: 101, + ts_micros: t_post * 1_000, + known_at_micros: t_post * 1_000, + known_at_source: Cow::Borrowed(KNOWN_AT_SOURCE_POST_TIMESTAMP), + kind: Cow::Borrowed(EVENT_KIND_POST), + subtype: POST_SUBTYPE_RETAIL.to_string(), + payload_json: format!( + "{{\"spiel_id\":\"sp_retail_unedited\",\"user_id\":\"u_retail\",\"is_edited\":false,\"source\":\"{POSTS_SOURCE_CEO}\",\"text\":\"Retail baseline\"}}" + ), + } + ); + + // 102: retail edited (known_at > posted_at) + assert_eq!( + mapped[1], + EventsParquetRow { + listing_id: 102, + ts_micros: t_post * 1_000, + known_at_micros: t_edit_later * 1_000, + known_at_source: Cow::Borrowed(KNOWN_AT_SOURCE_POST_EDITED), + kind: Cow::Borrowed(EVENT_KIND_POST), + subtype: POST_SUBTYPE_RETAIL.to_string(), + payload_json: format!( + "{{\"spiel_id\":\"sp_retail_edited\",\"user_id\":\"u_editor\",\"is_edited\":true,\"source\":\"{POSTS_SOURCE_CEO}\",\"text\":\"Edited retail text\"}}" + ), + } + ); + + // 103: newswire (bot == "1") + assert_eq!( + mapped[2], + EventsParquetRow { + listing_id: 103, + ts_micros: t_post * 1_000, + known_at_micros: t_post * 1_000, + known_at_source: Cow::Borrowed(KNOWN_AT_SOURCE_POST_TIMESTAMP), + kind: Cow::Borrowed(EVENT_KIND_POST), + subtype: POST_SUBTYPE_NEWSWIRE.to_string(), + payload_json: format!( + "{{\"spiel_id\":\"sp_newswire\",\"user_id\":\"thenewswire\",\"is_edited\":false,\"source\":\"{POSTS_SOURCE_CEO}\",\"text\":\"Company announces drill results\"}}" + ), + } + ); + + // 104: edit-before-post clamped -> known_at == ts, known_at_source == "post_timestamp", + // payload preserves is_edited: true and user_id: null. + assert_eq!( + mapped[3], + EventsParquetRow { + listing_id: 104, + ts_micros: t_post * 1_000, + known_at_micros: t_post * 1_000, + known_at_source: Cow::Borrowed(KNOWN_AT_SOURCE_POST_TIMESTAMP), + kind: Cow::Borrowed(EVENT_KIND_POST), + subtype: POST_SUBTYPE_RETAIL.to_string(), + payload_json: format!( + "{{\"spiel_id\":\"sp_edit_clamped\",\"user_id\":null,\"is_edited\":true,\"source\":\"{POSTS_SOURCE_CEO}\",\"text\":\"Clock-skewed edit\"}}" + ), + } + ); +} + +#[test] +fn payload_json_escapes_special_chars_control_chars_non_ascii_and_preserves_key_order() { + let t_post = utc_ms(2024, 7, 1, 12, 0, 0); + let build = build_posts(vec![ + post( + 10, + "sp\"with\\slash", + t_post, + None, + None, + Some("user\"1"), + "Quote \"here\", backslash \\, newline\nctrl\x01, non-ASCII café €", + ), + post( + 11, + "sp_null_user", + t_post, + Some(t_post + 1_000), + Some("1"), + None, + "Simple wire text", + ), + ]) + .expect("build_posts should succeed"); + + let rows = posts_to_event_rows(&build); + assert_eq!(rows.len(), 2); + + assert_eq!( + rows[0].payload_json, + "{\"spiel_id\":\"sp\\\"with\\\\slash\",\"user_id\":\"user\\\"1\",\"is_edited\":false,\"source\":\"ceo_posts\",\"text\":\"Quote \\\"here\\\", backslash \\\\, newline\\nctrl\\u0001, non-ASCII café €\"}" + ); + + assert_eq!( + rows[1].payload_json, + "{\"spiel_id\":\"sp_null_user\",\"user_id\":null,\"is_edited\":true,\"source\":\"ceo_posts\",\"text\":\"Simple wire text\"}" + ); +} + +#[test] +fn round_trip_writes_two_years_via_events_writer_with_zstd_and_exact_readback() { + let dir = TempDirGuard::new("round-trip"); + let t_2024_a = utc_ms(2024, 5, 10, 15, 0, 0); + let t_2024_dec = utc_ms(2024, 12, 31, 23, 55, 0); + let t_2025_jan_edit = utc_ms(2025, 1, 1, 0, 15, 0); // edited across UTC year boundary + let t_2025_feb = utc_ms(2025, 2, 20, 13, 30, 0); + + let build = build_posts(vec![ + // Two distinct posts sharing the exact same (listing_id=200, ts=t_2024_a), one newswire and one retail. + post( + 200, + "sp_2024_wire", + t_2024_a, + None, + Some("1"), + Some("thenewswire"), + "Newswire release at identical ts", + ), + post( + 200, + "sp_2024_retail_1", + t_2024_a, + None, + None, + Some("u1"), + "Retail reply 1 at identical ts", + ), + post( + 200, + "sp_2024_retail_2", + t_2024_a, + None, + None, + Some("u2"), + "Retail reply 2 at identical ts", + ), + // December 2024 post edited in January 2025: partitions by ts -> year=2024, known_at in 2025. + post( + 201, + "sp_2024_dec_edited_2025", + t_2024_dec, + Some(t_2025_jan_edit), + None, + Some("u3"), + "Edited after New Year", + ), + // 2025 newswire and retail posts. + post( + 200, + "sp_2025_wire", + t_2025_feb, + None, + Some("1"), + Some("thenewswire"), + "2025 quarterly update", + ), + post( + 202, + "sp_2025_retail", + t_2025_feb, + None, + Some("0"), + None, + "2025 retail commentary", + ), + ]) + .expect("build_posts should succeed"); + + let event_rows = posts_to_event_rows(&build); + assert_eq!(event_rows.len(), 6); + + let stats = write_events_dataset(dir.path(), &event_rows, EventsWriteOptions::default()) + .expect("write_events_dataset should accept posts_to_event_rows output"); + assert_eq!(stats.rows_written, 6); + assert_eq!(stats.files_written, 2); + assert_eq!(stats.rows_by_year.get(&2024), Some(&4)); + assert_eq!(stats.rows_by_year.get(&2025), Some(&2)); + + let path_2024 = dir.path().join("events/year=2024/part.parquet"); + let path_2025 = dir.path().join("events/year=2025/part.parquet"); + assert!(path_2024.exists(), "expected {}", path_2024.display()); + assert!(path_2025.exists(), "expected {}", path_2025.display()); + + let read_2024 = read_events_parquet_and_verify_zstd(&path_2024); + let read_2025 = read_events_parquet_and_verify_zstd(&path_2025); + + let expected_2024: Vec = event_rows + .iter() + .filter(|r| crate::events::partition_year_utc(r.ts_micros) == 2024) + .cloned() + .collect(); + let expected_2025: Vec = event_rows + .iter() + .filter(|r| crate::events::partition_year_utc(r.ts_micros) == 2025) + .cloned() + .collect(); + + assert_eq!(read_2024, expected_2024); + assert_eq!(read_2025, expected_2025); + + // Verify all read-back rows have kind == "post", both subtypes are present, and newswire vs + // retail spiel_ids are strictly disjoint (never sharing a subtype). + let mut newswire_payloads = HashSet::new(); + let mut retail_payloads = HashSet::new(); + for row in read_2024.iter().chain(read_2025.iter()) { + assert_eq!(row.kind.as_ref(), EVENT_KIND_POST); + match row.subtype.as_str() { + POST_SUBTYPE_NEWSWIRE => { + assert!(newswire_payloads.insert(row.payload_json.clone())); + } + POST_SUBTYPE_RETAIL => { + assert!(retail_payloads.insert(row.payload_json.clone())); + } + other => panic!("unexpected post subtype: {other}"), + } + } + assert_eq!(newswire_payloads.len(), 2); + assert_eq!(retail_payloads.len(), 4); + assert!(newswire_payloads.is_disjoint(&retail_payloads)); + + // Confirm the Dec 2024 post edited in Jan 2025 landed in year=2024 with 2025 known_at. + let dec_row = read_2024 + .iter() + .find(|r| r.listing_id == 201) + .expect("December post must be in year=2024 partition"); + assert_eq!(dec_row.ts_micros, t_2024_dec * 1_000); + assert_eq!(dec_row.known_at_micros, t_2025_jan_edit * 1_000); + assert_eq!( + dec_row.known_at_source.as_ref(), + KNOWN_AT_SOURCE_POST_EDITED + ); +} + +#[test] +fn posts_to_event_rows_is_permutation_invariant_and_handles_empty_input() { + let empty_build = build_posts(Vec::>::new()).expect("empty build"); + assert!(posts_to_event_rows(&empty_build).is_empty()); + + let t0 = utc_ms(2024, 9, 1, 14, 0, 0); + let t1 = t0 + 30_000; + let fixture = vec![ + // Conflicting duplicate spiel_id: later edit wins regardless of input order. + post(50, "sp_dup", t0, None, None, Some("u1"), "Original text"), + post( + 50, + "sp_dup", + t0, + Some(t1), + None, + Some("u1"), + "Edited duplicate survivor", + ), + // Two distinct posts sharing (listing_id=50, ts=t0), one newswire and one retail. + post( + 50, + "sp_same_ts_wire", + t0, + None, + Some("1"), + Some("thenewswire"), + "Wire at t0", + ), + post( + 50, + "sp_same_ts_retail", + t0, + None, + None, + Some("u2"), + "Retail at t0", + ), + // Separate listing. + post( + 40, + "sp_other_listing", + t1, + None, + None, + None, + "Earlier listing", + ), + ]; + + let reference = posts_to_event_rows(&build_posts(fixture.clone()).expect("reference build")); + assert_eq!(reference.len(), 4); + let reference_payload_bytes: Vec<&[u8]> = reference + .iter() + .map(|r| r.payload_json.as_bytes()) + .collect(); + + let perms = all_permutations(&fixture); + assert_eq!(perms.len(), 120); + for perm in perms { + let got = posts_to_event_rows(&build_posts(perm).expect("permuted build")); + assert_eq!(got, reference); + let got_payload_bytes: Vec<&[u8]> = got.iter().map(|r| r.payload_json.as_bytes()).collect(); + assert_eq!(got_payload_bytes, reference_payload_bytes); + } +} + +#[test] +fn point_in_time_guard_excludes_edited_post_until_edit_timestamp() { + let t_post = utc_ms(2024, 8, 12, 13, 30, 0); + let t_edit = t_post + 900_000; // +15 minutes + + let build = build_posts(vec![ + post( + 300, + "sp_unedited", + t_post, + None, + None, + Some("u1"), + "Posted at open", + ), + post( + 300, + "sp_edited", + t_post, + Some(t_edit), + None, + Some("u2"), + "Edited 15m later with hindsight", + ), + ]) + .expect("build_posts should succeed"); + + let rows = posts_to_event_rows(&build); + let edited = rows + .iter() + .find(|r| r.payload_json.contains("\"sp_edited\"")) + .expect("edited row present"); + + assert_eq!(edited.ts_micros, t_post * 1_000); + assert_eq!(edited.known_at_micros, t_edit * 1_000); + assert_ne!(edited.known_at_micros, edited.ts_micros); + assert_eq!(edited.known_at_source.as_ref(), KNOWN_AT_SOURCE_POST_EDITED); + + // As-of cutoff between posting and editing must exclude the edited post. + let cutoff_between = (t_post + 300_000) * 1_000; + let visible_between: Vec<&EventsParquetRow> = rows + .iter() + .filter(|r| r.known_at_micros <= cutoff_between) + .collect(); + assert_eq!(visible_between.len(), 1); + assert!(visible_between[0].payload_json.contains("\"sp_unedited\"")); + + // As-of cutoff at the exact edit timestamp includes both. + let visible_at_edit: Vec<&EventsParquetRow> = rows + .iter() + .filter(|r| r.known_at_micros <= t_edit * 1_000) + .collect(); + assert_eq!(visible_at_edit.len(), 2); +} + +// --------------------------------------------------------------------------------------------- +// QA edge cases (T-157) +// --------------------------------------------------------------------------------------------- + +#[test] +fn same_listing_and_ts_rows_are_ordered_by_payload_not_builder_known_at_order() { + // `build_posts` orders by (key, known_at, spiel_id), so the later-edited `retail_1` comes + // after `retail_2`. The writer orders by payload before known_at, so the adapter must flip it. + let dir = TempDirGuard::new("payload-tiebreak"); + let t_post = utc_ms(2024, 3, 4, 15, 0, 0); + let build = build_posts(vec![ + post( + 7, + "sp_retail_1", + t_post, + Some(t_post + 120_000), + None, + Some("u1"), + "first by payload, edited later", + ), + post( + 7, + "sp_retail_2", + t_post, + None, + None, + Some("u2"), + "second by payload", + ), + ]) + .expect("build_posts"); + assert_eq!( + build.retail[0].spiel_id, "sp_retail_2", + "builder sorts by known_at first" + ); + + let rows = posts_to_event_rows(&build); + assert!(rows[0].payload_json.contains("\"sp_retail_1\"")); + assert!(rows[1].payload_json.contains("\"sp_retail_2\"")); + assert_eq!(rows[0].known_at_micros, (t_post + 120_000) * 1_000); + assert_eq!( + rows[0].known_at_source.as_ref(), + KNOWN_AT_SOURCE_POST_EDITED + ); + + write_events_dataset(dir.path(), &rows, EventsWriteOptions::default()) + .expect("writer accepts payload-ordered rows"); + let back = + read_events_parquet_and_verify_zstd(&dir.path().join("events/year=2024/part.parquet")); + assert_eq!(back, rows); +} + +#[test] +fn rows_are_reordered_by_ts_when_an_earlier_post_was_edited_after_a_later_post() { + // Builder order is by known_at; the writer needs ts order within a listing. + let dir = TempDirGuard::new("ts-reorder"); + let t1 = utc_ms(2023, 11, 1, 10, 0, 0); + let t2 = utc_ms(2023, 11, 1, 11, 0, 0); + let t1_edit = utc_ms(2023, 11, 2, 9, 0, 0); + let build = build_posts(vec![ + post(5, "sp_late", t2, None, Some("1"), None, "later wire"), + post( + 5, + "sp_early_edited", + t1, + Some(t1_edit), + None, + Some("u"), + "early, edited next day", + ), + post(4, "sp_other", t2, None, None, None, "lower listing"), + ]) + .expect("build_posts"); + + let rows = posts_to_event_rows(&build); + let order: Vec<(i32, i64)> = rows.iter().map(|r| (r.listing_id, r.ts_micros)).collect(); + assert_eq!( + order, + vec![(4, t2 * 1_000), (5, t1 * 1_000), (5, t2 * 1_000)] + ); + + let stats = write_events_dataset(dir.path(), &rows, EventsWriteOptions::default()) + .expect("writer accepts ts-ordered rows"); + assert_eq!(stats.rows_written, 3); +} + +#[test] +fn newswire_requires_trimmed_bot_one_and_everything_else_is_retail() { + let t = utc_ms(2024, 1, 2, 12, 0, 0); + let build = build_posts(vec![ + post(1, "sp_ws", t, None, Some(" 1 "), None, "wire padded"), + post(1, "sp_true", t, None, Some("true"), None, "not wire"), + post(1, "sp_empty", t, None, Some(""), None, "not wire"), + post(1, "sp_two", t, None, Some("2"), None, "not wire"), + ]) + .expect("build_posts"); + + let rows = posts_to_event_rows(&build); + assert_eq!(rows.len(), 4); + for row in &rows { + assert_eq!(row.kind.as_ref(), EVENT_KIND_POST); + let expected = if row.payload_json.contains("\"sp_ws\"") { + POST_SUBTYPE_NEWSWIRE + } else { + POST_SUBTYPE_RETAIL + }; + assert_eq!(row.subtype, expected, "payload={}", row.payload_json); + } +} + +#[test] +fn edit_exactly_at_posting_time_is_post_timestamp_and_keeps_is_edited() { + let t = utc_ms(2024, 2, 29, 23, 59, 59); + let build = build_posts(vec![post(9, "sp_same", t, Some(t), None, None, "x")]).expect("build"); + let row = EventsParquetRow::from(&build.retail[0]); + assert_eq!(row.known_at_micros, row.ts_micros); + assert_eq!(row.known_at_source.as_ref(), KNOWN_AT_SOURCE_POST_TIMESTAMP); + assert!(row.payload_json.contains("\"is_edited\":true")); +} + +#[test] +fn multiple_row_groups_round_trip_and_rewrite_is_byte_identical() { + let t0 = utc_ms(2022, 6, 1, 0, 0, 0); + let fixture: Vec> = (0..11) + .map(|i| { + post( + i % 3, + &format!("sp_{i:02}"), + t0 + i64::from(i) * 60_000, + if i % 4 == 0 { + Some(t0 + 86_400_000) + } else { + None + }, + if i % 2 == 0 { Some("1") } else { None }, + Some("u"), + "row-group text", + ) + }) + .collect(); + let rows = posts_to_event_rows(&build_posts(fixture).expect("build")); + let options = EventsWriteOptions { + row_group_rows: 3, + ..EventsWriteOptions::default() + }; + + let dir_a = TempDirGuard::new("rg-a"); + let dir_b = TempDirGuard::new("rg-b"); + write_events_dataset(dir_a.path(), &rows, options).expect("write a"); + write_events_dataset(dir_b.path(), &rows, options).expect("write b"); + + let path_a = dir_a.path().join("events/year=2022/part.parquet"); + let path_b = dir_b.path().join("events/year=2022/part.parquet"); + let reader = SerializedFileReader::new(File::open(&path_a).expect("open")).expect("reader"); + assert_eq!(reader.metadata().num_row_groups(), 4); + drop(reader); + + assert_eq!(read_events_parquet_and_verify_zstd(&path_a), rows); + assert_eq!( + fs::read(&path_a).expect("read a"), + fs::read(&path_b).expect("read b"), + "same posts must produce byte-identical Parquet" + ); +} + +#[test] +fn post_2200_timestamp_is_preserved_by_adapter_and_rejected_by_writer() { + let dir = TempDirGuard::new("year-range"); + // `build_posts` rejects `timestamp_ms <= 0`, so the reachable out-of-range side is > 2200. + let t = utc_ms(2201, 1, 1, 12, 0, 0); + let rows = posts_to_event_rows( + &build_posts(vec![post(1, "sp_old", t, None, None, None, "old")]).expect("build"), + ); + assert_eq!(rows[0].ts_micros, t * 1_000); + + let err = write_events_dataset(dir.path(), &rows, EventsWriteOptions::default()) + .expect_err("writer must reject year 2201"); + assert!( + matches!( + err, + crate::parquet_events::ParquetEventsError::PartitionYearOutOfRange { year: 2201, .. } + ), + "got {err:?}" + ); + assert!(!dir.path().join("events/year=2201").exists()); +} diff --git a/tools/curate-etl/src/posts.rs b/tools/curate-etl/src/posts.rs index 3769fcf8..a4af96cb 100644 --- a/tools/curate-etl/src/posts.rs +++ b/tools/curate-etl/src/posts.rs @@ -10,6 +10,8 @@ //! never `posted_at`. In `ceoPosts`, an edit overwrites `spiel` in place without version //! history, so the builder retains one supplied version per `spiel_id` and cannot recover //! earlier pre-edit text. +//! - See [`crate::parquet_posts`] for mapping [`PostRow`] / [`PostsBuild`] into the +//! `events` Parquet contract (`kind = "post"`, `subtype = "newswire" | "retail"`). use std::error::Error; use std::fmt; diff --git a/tools/curate-etl/src/run_curate_fundamentals.rs b/tools/curate-etl/src/run_curate_fundamentals.rs new file mode 100644 index 00000000..f62c9e70 --- /dev/null +++ b/tools/curate-etl/src/run_curate_fundamentals.rs @@ -0,0 +1,1200 @@ +//! File-to-file `curate-fundamentals` runner (`M2.2m`). +//! +//! Streams concatenated raw BSON `qmFinancials` and `qmFilings` dump files alongside +//! `provider_mapping.tsv` and `listing_venues.tsv` into atomically published +//! `/fundamentals_pit/year=YYYY/part.parquet` partitions via +//! [`curate_and_write_fundamentals`]. +//! +//! # Contract & Point-in-Time Rules +//! - `qmFinancials` field defaults are restricted strictly to repo-evidenced top-level names +//! (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`). The `currency` path, all six +//! numeric metric paths (`Option`), and [`CurateFundamentalsFiscalPeriod`] have **no +//! defaults** and must be supplied explicitly. +//! - `qmFilings` field defaults match `run_curate_events` (`symbol`, `timefiled`), while +//! `form_type` has no default and `filing_id` / `url` are optional. +//! - `provider_mapping.tsv` uses the strict headerless 5-column TSV format from +//! [`crate::run_curate_bars::load_provider_mapping_tsv`]. +//! - `listing_venues.tsv` uses a strict headerless 2-column TSV format `listing_idvenue` +//! where `venue` is exactly `us_tsx` or `tsxv_cse` ([`load_listing_venues_tsv`]). +//! - Decoded provider keys are preserved verbatim (no trimming or suffix rewriting) and resolved +//! to permanent `listing_id`s inside [`curate_and_write_fundamentals`]. +//! - **In-memory accumulation:** [`RawBsonChunkReader`] bounds only the raw BSON framing buffer +//! (`*_peak_chunk_bytes`); decoded observations and filings accumulate in memory before +//! [`curate_and_write_fundamentals`] runs. +//! - **Empty / all-unmapped behavior:** delegated unchanged to [`curate_and_write_fundamentals`], +//! returning `Ok` with `rows_written == 0` and `files_written == 0` without creating +//! `/fundamentals_pit` or modifying any pre-existing partitions. +//! - **Fail-closed safety:** invalid field/fiscal config, blank `mapping_source`, `k == 0`, +//! unreadable inputs, malformed/overlapping `provider_mapping.tsv`, malformed/duplicate +//! `listing_venues.tsv`, truncated/corrupt BSON, `out_dir` or `/fundamentals_pit` +//! occupied by a regular file, or any input path resolving to `out_dir`, `/fundamentals_pit`, +//! or an existing `year=YYYY` partition target all return a typed [`RunCurateFundamentalsError`] +//! before anything is created or modified under `out_dir`. +//! +//! # Counter Conservation Invariants +//! Every successful [`CurateFundamentalsRunReport`] satisfies: +//! - `financials_docs_framed as usize == financials_decode.docs_in == financials_decode.rows_out + financials_decode.skipped_total()` +//! - `filings_docs_framed as usize == filings_decode.docs_in == filings_decode.rows_out + filings_decode.skipped_total()` +//! - `financials_decode.rows_out == curate_stats.observations_in` +//! - `filings_decode.rows_out == curate_stats.filings_in` +//! - `write_stats.rows_written == curate_stats.rows_out` + +use std::collections::{BTreeMap, HashSet}; +use std::error::Error; +use std::fmt::{self, Write as _}; +use std::fs::{self, File}; +use std::io; +use std::path::{Component, Path, PathBuf}; +use std::sync::Arc; +use std::time::Instant; + +use crate::bson_qm_events::{ + BsonQmEventsError, BsonQmFilingsDecodeStats, QmFilingsFieldNames, DEFAULT_FILINGS_KEY_FIELD, + DEFAULT_FILINGS_TIMEFILED_FIELD, +}; +use crate::bson_qm_financials::{ + 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, +}; +use crate::bson_stream::{ + decode_qm_filings_chunks, decode_qm_financials_chunks, BsonQmEventsStreamError, + BsonQmFinancialsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunkReader, +}; +use crate::curate_fundamentals::{ + curate_and_write_fundamentals, CurateFundamentalsStats, CurateFundamentalsWriteError, +}; +use crate::events::QmFiling; +use crate::fundamentals::{FinancialObservation, FiscalPeriod, StatutoryLagVenue}; +use crate::parquet_fundamentals::{FundamentalsPitWriteOptions, FundamentalsPitWriteStats}; +use crate::provider_mapping::{ProviderMappingError, ProviderMappingTable}; +use crate::run_curate_bars::{ + load_provider_mapping_tsv, parse_strict_positive_i32, read_tsv_lines, RunCurateBarsError, +}; + +/// Default `mapping_source` passed to `provider_mapping` lookups for `qmFinancials` / `qmFilings`. +pub const DEFAULT_FUNDAMENTALS_MAPPING_SOURCE: &str = "qm"; + +/// Owned fiscal-period resolution policy for [`CurateFundamentalsArgs`]. +/// +/// Mirrors [`QmFinancialsFiscalPeriod`] without borrowing lifetimes so arguments can be stored +/// and passed cleanly to [`run_curate_fundamentals`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CurateFundamentalsFiscalPeriod { + /// Assign a fixed [`FiscalPeriod`] to every decoded `qmFinancials` document. + Fixed(FiscalPeriod), + /// Match exact `report_period` BSON string values against explicit quarterly and annual lists. + ByTokens { + quarterly: Vec, + annual: Vec, + }, +} + +impl CurateFundamentalsFiscalPeriod { + /// Borrows this policy as [`QmFinancialsFiscalPeriod`] for validation or decoding. + pub fn with_borrowed(&self, f: impl FnOnce(QmFinancialsFiscalPeriod<'_>) -> R) -> R { + match self { + Self::Fixed(period) => f(QmFinancialsFiscalPeriod::Fixed(*period)), + Self::ByTokens { quarterly, annual } => { + let q_refs: Vec<&str> = quarterly.iter().map(String::as_str).collect(); + let a_refs: Vec<&str> = annual.iter().map(String::as_str).collect(); + f(QmFinancialsFiscalPeriod::ByTokens { + quarterly: &q_refs, + annual: &a_refs, + }) + } + } + } +} + +/// Arguments for [`run_curate_fundamentals`] and [`run_curate_fundamentals_with_readers`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurateFundamentalsArgs { + pub qm_financials: PathBuf, + pub qm_filings: PathBuf, + pub provider_mapping: PathBuf, + pub listing_venues: PathBuf, + pub out_dir: PathBuf, + pub financials_key_field: String, + pub financials_period_end_field: String, + pub financials_report_date_field: String, + pub financials_report_period_field: String, + pub financials_currency_field: String, + pub financials_revenue_field: Option, + pub financials_net_income_field: Option, + pub financials_operating_cash_flow_field: Option, + pub financials_total_assets_field: Option, + pub financials_total_equity_field: Option, + pub financials_shares_outstanding_field: Option, + pub fiscal_period: CurateFundamentalsFiscalPeriod, + pub filings_key_field: String, + pub filings_timefiled_field: String, + pub filings_form_type_field: String, + pub filings_filing_id_field: Option, + pub filings_url_field: Option, + pub mapping_source: String, + pub k: usize, +} + +impl CurateFundamentalsArgs { + /// Constructs arguments pre-populated with the four repo-evidenced `qmFinancials` defaults + /// (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`), the two verified + /// `qmFilings` defaults (`symbol`, `timefiled`), and `mapping_source = "qm"`. + /// + /// Unverified fields (`financials_currency_field`, all six numeric `Option` paths, + /// `fiscal_period`, `filings_form_type_field`, and snapshot period limit `k`) must be supplied + /// explicitly. `filings_filing_id_field` and `filings_url_field` default to `None`. + #[allow(clippy::too_many_arguments)] + pub fn with_verified_defaults( + qm_financials: PathBuf, + qm_filings: PathBuf, + provider_mapping: PathBuf, + listing_venues: PathBuf, + out_dir: PathBuf, + financials_currency_field: impl Into, + financials_revenue_field: Option, + financials_net_income_field: Option, + financials_operating_cash_flow_field: Option, + financials_total_assets_field: Option, + financials_total_equity_field: Option, + financials_shares_outstanding_field: Option, + fiscal_period: CurateFundamentalsFiscalPeriod, + filings_form_type_field: impl Into, + k: usize, + ) -> Self { + Self { + qm_financials, + qm_filings, + provider_mapping, + listing_venues, + out_dir, + financials_key_field: DEFAULT_QM_FINANCIALS_KEY_FIELD.to_string(), + financials_period_end_field: DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD.to_string(), + financials_report_date_field: DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD.to_string(), + financials_report_period_field: DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD.to_string(), + financials_currency_field: financials_currency_field.into(), + financials_revenue_field, + financials_net_income_field, + financials_operating_cash_flow_field, + financials_total_assets_field, + financials_total_equity_field, + financials_shares_outstanding_field, + fiscal_period, + filings_key_field: DEFAULT_FILINGS_KEY_FIELD.to_string(), + filings_timefiled_field: DEFAULT_FILINGS_TIMEFILED_FIELD.to_string(), + filings_form_type_field: filings_form_type_field.into(), + filings_filing_id_field: None, + filings_url_field: None, + mapping_source: DEFAULT_FUNDAMENTALS_MAPPING_SOURCE.to_string(), + k, + } + } + + /// Borrows the configured `qmFinancials` BSON field paths as [`QmFinancialsFieldNames`]. + #[inline] + pub fn financials_field_names(&self) -> QmFinancialsFieldNames<'_> { + QmFinancialsFieldNames { + key: self.financials_key_field.as_str(), + period_end: self.financials_period_end_field.as_str(), + report_date: self.financials_report_date_field.as_str(), + report_period: self.financials_report_period_field.as_str(), + currency: self.financials_currency_field.as_str(), + revenue: self.financials_revenue_field.as_deref(), + net_income: self.financials_net_income_field.as_deref(), + operating_cash_flow: self.financials_operating_cash_flow_field.as_deref(), + total_assets: self.financials_total_assets_field.as_deref(), + total_equity: self.financials_total_equity_field.as_deref(), + shares_outstanding: self.financials_shares_outstanding_field.as_deref(), + } + } + + /// Borrows the configured `qmFilings` BSON field names as [`QmFilingsFieldNames`]. + #[inline] + pub fn filings_field_names(&self) -> QmFilingsFieldNames<'_> { + QmFilingsFieldNames { + key: self.filings_key_field.as_str(), + timefiled: self.filings_timefiled_field.as_str(), + form_type: self.filings_form_type_field.as_str(), + filing_id: self.filings_filing_id_field.as_deref(), + url: self.filings_url_field.as_deref(), + } + } +} + +/// Full run report produced by [`run_curate_fundamentals`] and +/// [`run_curate_fundamentals_with_readers`]. +#[derive(Debug, Clone, PartialEq)] +pub struct CurateFundamentalsRunReport { + pub financials_docs_framed: u64, + pub financials_bytes_read: u64, + pub financials_peak_chunk_bytes: usize, + pub financials_decode: BsonQmFinancialsDecodeStats, + pub filings_docs_framed: u64, + pub filings_bytes_read: u64, + pub filings_peak_chunk_bytes: usize, + pub filings_decode: BsonQmFilingsDecodeStats, + pub curate_stats: CurateFundamentalsStats, + pub write_stats: FundamentalsPitWriteStats, + pub elapsed_secs: f64, +} + +/// Typed errors returned by [`load_listing_venues_tsv`], [`run_curate_fundamentals`], and +/// [`run_curate_fundamentals_with_readers`]. +/// +/// Every variant's `Display` output is a single line naming the offending path (and line number or +/// byte offset where applicable). +#[derive(Debug)] +pub enum RunCurateFundamentalsError { + InvalidOutDir { + path: PathBuf, + detail: String, + }, + InspectOutDir { + path: PathBuf, + source: io::Error, + }, + InvalidFinancialsConfig { + path: PathBuf, + source: BsonQmFinancialsError, + }, + InvalidFilingsFieldNames { + path: PathBuf, + source: BsonQmEventsError, + }, + EmptyMappingSource, + InvalidPeriodLimit { + k: usize, + }, + OpenInput { + label: &'static str, + path: PathBuf, + source: io::Error, + }, + ReadInput { + label: &'static str, + path: PathBuf, + source: io::Error, + }, + TsvParse { + path: PathBuf, + line: usize, + detail: String, + }, + ProviderMapping { + path: PathBuf, + source: ProviderMappingError, + }, + BsonStream { + label: &'static str, + path: PathBuf, + source: BsonStreamError, + }, + CorruptFinancialsBson { + path: PathBuf, + offset: u64, + source: BsonQmFinancialsError, + }, + CorruptFilingsBson { + path: PathBuf, + offset: u64, + source: BsonQmEventsError, + }, + CurateWrite { + out_dir: PathBuf, + source: CurateFundamentalsWriteError, + }, +} + +struct SingleLineWriter<'a, 'b> { + f: &'a mut fmt::Formatter<'b>, +} + +impl fmt::Write for SingleLineWriter<'_, '_> { + fn write_str(&mut self, s: &str) -> fmt::Result { + let mut rest = s; + while let Some(idx) = rest.find(['\n', '\r']) { + let (head, tail) = rest.split_at(idx); + if !head.is_empty() { + self.f.write_str(head)?; + } + let mut chars = tail.chars(); + match chars.next() { + Some('\n') => self.f.write_str("\\n")?, + Some('\r') => self.f.write_str("\\r")?, + _ => unreachable!(), + } + rest = chars.as_str(); + } + if !rest.is_empty() { + self.f.write_str(rest)?; + } + Ok(()) + } +} + +impl fmt::Display for RunCurateFundamentalsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut w = SingleLineWriter { f }; + match self { + Self::InvalidOutDir { path, detail } => { + write!(w, "invalid --out '{}': {detail}", path.display()) + } + Self::InspectOutDir { path, source } => { + write!( + w, + "failed to inspect output path '{}': {source}", + path.display() + ) + } + Self::InvalidFinancialsConfig { path, source } => { + write!( + w, + "invalid qm-financials config for '{}': {source}", + path.display() + ) + } + Self::InvalidFilingsFieldNames { path, source } => { + write!( + w, + "invalid qm-filings field config for '{}': {source}", + path.display() + ) + } + Self::EmptyMappingSource => { + write!(w, "invalid --mapping-source: must not be empty or blank") + } + Self::InvalidPeriodLimit { k } => { + write!(w, "invalid snapshot period limit k={k}: must be >= 1") + } + Self::OpenInput { + label, + path, + source, + } => write!(w, "failed to open {label} '{}': {source}", path.display()), + Self::ReadInput { + label, + path, + source, + } => write!(w, "failed to read {label} '{}': {source}", path.display()), + Self::TsvParse { path, line, detail } => { + write!(w, "{}:{line}: {detail}", path.display()) + } + Self::ProviderMapping { path, source } => { + write!(w, "invalid provider_mapping '{}': {source}", path.display()) + } + Self::BsonStream { + label, + path, + source, + } => write!(w, "failed reading {label} '{}': {source}", path.display()), + Self::CorruptFinancialsBson { + path, + offset, + source, + } => write!( + w, + "corrupt qm-financials BSON '{}' at byte offset {offset}: {source}", + path.display() + ), + Self::CorruptFilingsBson { + path, + offset, + source, + } => write!( + w, + "corrupt qm-filings BSON '{}' at byte offset {offset}: {source}", + path.display() + ), + Self::CurateWrite { out_dir, source } => { + write!(w, "curate/write to '{}' failed: {source}", out_dir.display()) + } + } + } +} + +impl Error for RunCurateFundamentalsError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::InspectOutDir { source, .. } => Some(source), + Self::InvalidFinancialsConfig { source, .. } => Some(source), + Self::InvalidFilingsFieldNames { source, .. } => Some(source), + Self::OpenInput { source, .. } | Self::ReadInput { source, .. } => Some(source), + Self::ProviderMapping { source, .. } => Some(source), + Self::BsonStream { source, .. } => Some(source), + Self::CorruptFinancialsBson { source, .. } => Some(source), + Self::CorruptFilingsBson { source, .. } => Some(source), + Self::CurateWrite { source, .. } => Some(source), + Self::InvalidOutDir { .. } + | Self::EmptyMappingSource + | Self::InvalidPeriodLimit { .. } + | Self::TsvParse { .. } => None, + } + } +} + +fn map_tsv_error(path: &Path, err: RunCurateBarsError) -> RunCurateFundamentalsError { + match err { + RunCurateBarsError::OpenInput { + label, + path, + source, + } => RunCurateFundamentalsError::OpenInput { + label, + path, + source, + }, + RunCurateBarsError::ReadInput { + label, + path, + source, + } => RunCurateFundamentalsError::ReadInput { + label, + path, + source, + }, + RunCurateBarsError::TsvParse { path, line, detail } => { + RunCurateFundamentalsError::TsvParse { path, line, detail } + } + RunCurateBarsError::ProviderMapping { path, source } => { + RunCurateFundamentalsError::ProviderMapping { path, source } + } + other => RunCurateFundamentalsError::TsvParse { + path: path.to_path_buf(), + line: 0, + detail: other.to_string(), + }, + } +} + +/// Loads `listing_venues.tsv` into an ordered `listing_id -> StatutoryLagVenue` map. +/// +/// Format (no header, 2 `\t`-separated columns): +/// `listing_id \t venue` +/// +/// `listing_id` must be a strictly positive ASCII base-10 `i32` (no sign or surrounding +/// whitespace). `venue` must be exact `"us_tsx"` or `"tsxv_cse"`. Duplicate `listing_id`s, +/// wrong column counts, unknown venues, and interior blank lines fail closed with a typed +/// single-line error naming `path` and the 1-based line number. +pub fn load_listing_venues_tsv( + path: &Path, +) -> Result, RunCurateFundamentalsError> { + let mut venues = BTreeMap::new(); + read_tsv_lines(path, "listing-venues", |_line_no, line| { + let mut cols = line.split('\t'); + let id_str = cols + .next() + .ok_or_else(|| "expected 2 tab-separated columns (listing_id, venue)".to_string())?; + let venue_str = cols.next().ok_or_else(|| { + "expected 2 tab-separated columns (listing_id, venue), got 1".to_string() + })?; + if cols.next().is_some() { + let count = line.split('\t').count(); + return Err(format!( + "expected 2 tab-separated columns (listing_id, venue), got {count}" + )); + } + + let listing_id = parse_strict_positive_i32(id_str).ok_or_else(|| { + format!("invalid listing_id '{id_str}': expected strictly positive integer") + })?; + + let venue = match venue_str { + "us_tsx" => StatutoryLagVenue::UsTsx, + "tsxv_cse" => StatutoryLagVenue::TsxvCse, + other => { + return Err(format!( + "unknown venue '{other}': expected 'us_tsx' or 'tsxv_cse'" + )); + } + }; + + if venues.insert(listing_id, venue).is_some() { + return Err(format!("duplicate listing_id {listing_id}")); + } + + Ok(()) + }) + .map_err(|err| map_tsv_error(path, err))?; + + Ok(venues) +} + +/// Resolves `path` to an absolute normalized path while preserving OS symlink-before-`..` +/// semantics: if `path` exists it is canonicalized directly; otherwise components are walked +/// left-to-right, canonicalizing each existing prefix before resolving `..`, and only lexically +/// normalizing `..` within any non-existent suffix. +fn resolve_normalized_path(path: &Path) -> PathBuf { + if let Ok(canon) = path.canonicalize() { + return canon; + } + + let abs = if path.is_absolute() { + path.to_path_buf() + } else if let Ok(cwd) = std::env::current_dir() { + cwd.join(path) + } else { + path.to_path_buf() + }; + + if let Ok(canon) = abs.canonicalize() { + return canon; + } + + let mut resolved = PathBuf::new(); + for comp in abs.components() { + match comp { + Component::Prefix(prefix) => resolved.push(prefix.as_os_str()), + Component::RootDir => resolved.push(Component::RootDir.as_os_str()), + Component::CurDir => {} + Component::Normal(seg) => { + resolved.push(seg); + if let Ok(canon) = resolved.canonicalize() { + resolved = canon; + } + } + Component::ParentDir => { + resolved.push(Component::ParentDir.as_os_str()); + if let Ok(canon) = resolved.canonicalize() { + resolved = canon; + } else { + resolved.pop(); + if matches!(resolved.components().next_back(), Some(Component::Normal(_))) { + resolved.pop(); + } + } + } + } + } + + resolved +} + +fn validate_out_dir_and_inputs( + args: &CurateFundamentalsArgs, +) -> Result<(), RunCurateFundamentalsError> { + if args.out_dir.as_os_str().is_empty() { + return Err(RunCurateFundamentalsError::InvalidOutDir { + path: args.out_dir.clone(), + detail: "output directory path must not be empty".to_string(), + }); + } + + match fs::metadata(&args.out_dir) { + Ok(meta) if !meta.is_dir() => { + return Err(RunCurateFundamentalsError::InvalidOutDir { + path: args.out_dir.clone(), + detail: "path exists and is not a directory".to_string(), + }); + } + Ok(_) => {} + Err(err) if err.kind() == io::ErrorKind::NotFound => {} + Err(source) => { + return Err(RunCurateFundamentalsError::InspectOutDir { + path: args.out_dir.clone(), + source, + }); + } + } + + let fundamentals_dir = args.out_dir.join("fundamentals_pit"); + let fundamentals_dir_exists = match fs::metadata(&fundamentals_dir) { + Ok(meta) if !meta.is_dir() => { + return Err(RunCurateFundamentalsError::InvalidOutDir { + path: fundamentals_dir, + detail: "fundamentals_pit output path exists and is not a directory".to_string(), + }); + } + Ok(_) => true, + Err(err) if err.kind() == io::ErrorKind::NotFound => false, + Err(source) => { + return Err(RunCurateFundamentalsError::InspectOutDir { + path: fundamentals_dir, + source, + }); + } + }; + + let resolved_out = resolve_normalized_path(&args.out_dir); + let resolved_fundamentals = resolve_normalized_path(&fundamentals_dir); + + let resolved_inputs = [ + ( + "qm-financials", + &args.qm_financials, + resolve_normalized_path(&args.qm_financials), + ), + ( + "qm-filings", + &args.qm_filings, + resolve_normalized_path(&args.qm_filings), + ), + ( + "provider-mapping", + &args.provider_mapping, + resolve_normalized_path(&args.provider_mapping), + ), + ( + "listing-venues", + &args.listing_venues, + resolve_normalized_path(&args.listing_venues), + ), + ]; + + for (label, input_path, resolved_in) in &resolved_inputs { + if *resolved_in == resolved_out + || *resolved_in == resolved_fundamentals + || resolved_in.starts_with(&resolved_fundamentals) + { + return Err(RunCurateFundamentalsError::InvalidOutDir { + path: args.out_dir.clone(), + detail: format!( + "output directory would overlap {label} input '{}'", + input_path.display() + ), + }); + } + } + + // Check existing `year=YYYY` partition directories and their `part.parquet` targets for: + // 1. unresolvable / dangling `year=*` symlinks (whose target could be created mid-run and + // silently alias another year's partition), + // 2. two distinct `year=*` entries resolving to the same directory or `part.parquet` file + // (which would cause publishing one year to silently overwrite another year's data), and + // 3. aliases to any input path, catching symlinked year directories whose resolved targets + // live outside `/fundamentals_pit`. + if fundamentals_dir_exists { + let entries = fs::read_dir(&fundamentals_dir).map_err(|source| { + RunCurateFundamentalsError::InspectOutDir { + path: fundamentals_dir.clone(), + source, + } + })?; + let mut year_dirs: Vec = Vec::new(); + for entry_res in entries { + let entry = entry_res.map_err(|source| RunCurateFundamentalsError::InspectOutDir { + path: fundamentals_dir.clone(), + source, + })?; + let name = entry.file_name(); + if name.to_string_lossy().starts_with("year=") { + year_dirs.push(entry.path()); + } + } + year_dirs.sort(); + + let mut seen_year_dirs: BTreeMap = BTreeMap::new(); + let mut seen_part_files: BTreeMap = BTreeMap::new(); + + for year_dir in year_dirs { + let entry_meta = fs::symlink_metadata(&year_dir).map_err(|source| { + RunCurateFundamentalsError::InspectOutDir { + path: year_dir.clone(), + source, + } + })?; + let resolved_year_dir = if entry_meta.file_type().is_symlink() { + fs::canonicalize(&year_dir).map_err(|err| { + RunCurateFundamentalsError::InvalidOutDir { + path: year_dir.clone(), + detail: format!("partition symlink target cannot be resolved: {err}"), + } + })? + } else { + resolve_normalized_path(&year_dir) + }; + let resolved_part_via_dir = resolved_year_dir.join("part.parquet"); + let resolved_part = resolve_normalized_path(&year_dir.join("part.parquet")); + + if let Some(prev_year_dir) = + seen_year_dirs.insert(resolved_year_dir.clone(), year_dir.clone()) + { + return Err(RunCurateFundamentalsError::InvalidOutDir { + path: year_dir, + detail: format!( + "partition directory aliases '{}' via shared target '{}'", + prev_year_dir.display(), + resolved_year_dir.display() + ), + }); + } + + if let Some(prev_year_dir) = + seen_part_files.insert(resolved_part.clone(), year_dir.clone()) + { + return Err(RunCurateFundamentalsError::InvalidOutDir { + path: year_dir, + detail: format!( + "partition file aliases '{}' via shared target '{}'", + prev_year_dir.display(), + resolved_part.display() + ), + }); + } + + for (label, input_path, resolved_in) in &resolved_inputs { + if *resolved_in == resolved_year_dir + || *resolved_in == resolved_part_via_dir + || *resolved_in == resolved_part + || resolved_in.starts_with(&resolved_year_dir) + { + return Err(RunCurateFundamentalsError::InvalidOutDir { + path: year_dir, + detail: format!( + "partition output '{}' would overlap {label} input '{}'", + resolved_part_via_dir.display(), + input_path.display() + ), + }); + } + } + } + } + + Ok(()) +} + +fn financials_bson_error_offset(err: &BsonQmFinancialsError) -> u64 { + match err { + BsonQmFinancialsError::TruncatedDocument { offset, .. } + | BsonQmFinancialsError::CorruptDocumentLength { offset, .. } + | BsonQmFinancialsError::CorruptBson { offset, .. } => *offset, + BsonQmFinancialsError::InvalidFieldNames { .. } + | BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. } => 0, + } +} + +fn filings_bson_error_offset(err: &BsonQmEventsError) -> u64 { + match err { + BsonQmEventsError::TruncatedDocument { offset, .. } + | BsonQmEventsError::CorruptDocumentLength { offset, .. } + | BsonQmEventsError::CorruptBson { offset, .. } => *offset, + BsonQmEventsError::InvalidFieldNames { .. } => 0, + } +} + +fn map_financials_stream_error( + path: &Path, + err: BsonQmFinancialsStreamError, +) -> RunCurateFundamentalsError { + match err { + BsonQmFinancialsStreamError::Stream(source) => RunCurateFundamentalsError::BsonStream { + label: "qm-financials", + path: path.to_path_buf(), + source, + }, + BsonQmFinancialsStreamError::Decode(source) => match &source { + BsonQmFinancialsError::InvalidFieldNames { .. } + | BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. } => { + RunCurateFundamentalsError::InvalidFinancialsConfig { + path: path.to_path_buf(), + source, + } + } + _ => { + let offset = financials_bson_error_offset(&source); + RunCurateFundamentalsError::CorruptFinancialsBson { + path: path.to_path_buf(), + offset, + source, + } + } + }, + } +} + +fn map_filings_stream_error( + path: &Path, + err: BsonQmEventsStreamError, +) -> RunCurateFundamentalsError { + match err { + BsonQmEventsStreamError::Stream(source) => RunCurateFundamentalsError::BsonStream { + label: "qm-filings", + path: path.to_path_buf(), + source, + }, + BsonQmEventsStreamError::Decode(source) => match &source { + BsonQmEventsError::InvalidFieldNames { .. } => { + RunCurateFundamentalsError::InvalidFilingsFieldNames { + path: path.to_path_buf(), + source, + } + } + _ => { + let offset = filings_bson_error_offset(&source); + RunCurateFundamentalsError::CorruptFilingsBson { + path: path.to_path_buf(), + offset, + source, + } + } + }, + } +} + +#[inline] +fn intern_key(interner: &mut HashSet>, key: &str) -> Arc { + if let Some(existing) = interner.get(key) { + Arc::clone(existing) + } else { + let arc: Arc = Arc::from(key); + interner.insert(Arc::clone(&arc)); + arc + } +} + +struct DecodedFundamentalsInputs { + mapping: ProviderMappingTable, + venues: BTreeMap, + observations: Vec>>, + filings: Vec>>, + financials_docs_framed: u64, + financials_bytes_read: u64, + financials_peak_chunk_bytes: usize, + financials_decode: BsonQmFinancialsDecodeStats, + filings_docs_framed: u64, + filings_bytes_read: u64, + filings_peak_chunk_bytes: usize, + filings_decode: BsonQmFilingsDecodeStats, +} + +fn decode_inputs_from_openers( + args: &CurateFundamentalsArgs, + open_financials: FF, + open_filings: FL, +) -> Result +where + RF: io::Read, + FF: FnOnce() -> Result, + RL: io::Read, + FL: FnOnce() -> Result, +{ + let financials_fields = args.financials_field_names(); + financials_fields.validate().map_err(|source| { + RunCurateFundamentalsError::InvalidFinancialsConfig { + path: args.qm_financials.clone(), + source, + } + })?; + + args.fiscal_period + .with_borrowed(|fp| fp.validate()) + .map_err(|source| RunCurateFundamentalsError::InvalidFinancialsConfig { + path: args.qm_financials.clone(), + source, + })?; + + let filings_fields = args.filings_field_names(); + filings_fields.validate().map_err(|source| { + RunCurateFundamentalsError::InvalidFilingsFieldNames { + path: args.qm_filings.clone(), + source, + } + })?; + + if args.mapping_source.trim().is_empty() { + return Err(RunCurateFundamentalsError::EmptyMappingSource); + } + + if args.k == 0 { + return Err(RunCurateFundamentalsError::InvalidPeriodLimit { k: args.k }); + } + + let mapping_rows = load_provider_mapping_tsv(&args.provider_mapping) + .map_err(|err| map_tsv_error(&args.provider_mapping, err))?; + let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| { + RunCurateFundamentalsError::ProviderMapping { + path: args.provider_mapping.clone(), + source, + } + })?; + + let venues = load_listing_venues_tsv(&args.listing_venues)?; + + let mut key_interner: HashSet> = HashSet::new(); + + // Stream and decode qmFinancials, releasing the chunk reader immediately afterward. + let ( + observations, + financials_docs_framed, + financials_bytes_read, + financials_peak_chunk_bytes, + financials_decode, + ) = { + let financials_stream = open_financials()?; + let mut financials_reader = + RawBsonChunkReader::with_options(financials_stream, BsonStreamOptions::default()) + .map_err(|source| RunCurateFundamentalsError::BsonStream { + label: "qm-financials", + path: args.qm_financials.clone(), + source, + })?; + + let mut observations: Vec>> = Vec::new(); + let decode = args.fiscal_period.with_borrowed(|fp| { + decode_qm_financials_chunks(&mut financials_reader, &financials_fields, fp, |obs| { + let key = intern_key(&mut key_interner, obs.key); + observations.push(FinancialObservation { + key, + period_end: obs.period_end, + fiscal_period: obs.fiscal_period, + currency: obs.currency, + report_date: obs.report_date, + fields: obs.fields, + }); + }) + }) + .map_err(|err| map_financials_stream_error(&args.qm_financials, err))?; + + ( + observations, + financials_reader.docs_framed(), + financials_reader.bytes_read(), + financials_reader.buffer_capacity(), + decode, + ) + }; + + // Stream and decode qmFilings, reusing the same key interner and releasing the chunk reader. + let (filings, filings_docs_framed, filings_bytes_read, filings_peak_chunk_bytes, filings_decode) = { + let filings_stream = open_filings()?; + let mut filings_reader = + RawBsonChunkReader::with_options(filings_stream, BsonStreamOptions::default()) + .map_err(|source| RunCurateFundamentalsError::BsonStream { + label: "qm-filings", + path: args.qm_filings.clone(), + source, + })?; + + let mut filings: Vec>> = Vec::new(); + let decode = decode_qm_filings_chunks(&mut filings_reader, &filings_fields, |raw| { + let key = intern_key(&mut key_interner, raw.key); + filings.push(raw.to_qm_filing(key)); + }) + .map_err(|err| map_filings_stream_error(&args.qm_filings, err))?; + + ( + filings, + filings_reader.docs_framed(), + filings_reader.bytes_read(), + filings_reader.buffer_capacity(), + decode, + ) + }; + + Ok(DecodedFundamentalsInputs { + mapping, + venues, + observations, + filings, + financials_docs_framed, + financials_bytes_read, + financials_peak_chunk_bytes, + financials_decode, + filings_docs_framed, + filings_bytes_read, + filings_peak_chunk_bytes, + filings_decode, + }) +} + +fn run_curate_fundamentals_from_openers( + args: &CurateFundamentalsArgs, + open_financials: FF, + open_filings: FL, +) -> Result +where + RF: io::Read, + FF: FnOnce() -> Result, + RL: io::Read, + FL: FnOnce() -> Result, +{ + let start = Instant::now(); + validate_out_dir_and_inputs(args)?; + + let decoded = decode_inputs_from_openers(args, open_financials, open_filings)?; + + let write_report = curate_and_write_fundamentals( + &args.out_dir, + decoded.observations, + decoded.filings, + &args.mapping_source, + &decoded.mapping, + &decoded.venues, + args.k, + FundamentalsPitWriteOptions::default(), + ) + .map_err(|source| RunCurateFundamentalsError::CurateWrite { + out_dir: args.out_dir.clone(), + source, + })?; + + Ok(CurateFundamentalsRunReport { + financials_docs_framed: decoded.financials_docs_framed, + financials_bytes_read: decoded.financials_bytes_read, + financials_peak_chunk_bytes: decoded.financials_peak_chunk_bytes, + financials_decode: decoded.financials_decode, + filings_docs_framed: decoded.filings_docs_framed, + filings_bytes_read: decoded.filings_bytes_read, + filings_peak_chunk_bytes: decoded.filings_peak_chunk_bytes, + filings_decode: decoded.filings_decode, + curate_stats: write_report.curate_stats, + write_stats: write_report.write_stats, + elapsed_secs: start.elapsed().as_secs_f64(), + }) +} + +/// Runs the end-to-end `curate-fundamentals` file-to-Parquet pipeline via +/// [`curate_and_write_fundamentals`]. +/// +/// Any validation, path-alias, I/O, TSV, mapping, BSON framing/corruption, or curation error +/// returns before touching `args.out_dir`, leaving any pre-existing +/// `/fundamentals_pit/` partitions byte-identical. +pub fn run_curate_fundamentals( + args: &CurateFundamentalsArgs, +) -> Result { + run_curate_fundamentals_from_openers( + args, + || { + File::open(&args.qm_financials).map_err(|source| { + RunCurateFundamentalsError::OpenInput { + label: "qm-financials", + path: args.qm_financials.clone(), + source, + } + }) + }, + || { + File::open(&args.qm_filings).map_err(|source| RunCurateFundamentalsError::OpenInput { + label: "qm-filings", + path: args.qm_filings.clone(), + source, + }) + }, + ) +} + +/// Runs `curate-fundamentals` from arbitrary raw-BSON [`io::Read`] streams while still running +/// full preflight validation (including output/input path safety against the diagnostic paths in +/// `args`) and loading `provider_mapping.tsv` / `listing_venues.tsv` from disk. +pub fn run_curate_fundamentals_with_readers( + args: &CurateFundamentalsArgs, + financials_reader: RF, + filings_reader: RL, +) -> Result { + run_curate_fundamentals_from_openers(args, || Ok(financials_reader), || Ok(filings_reader)) +} + +/// Formats [`CurateFundamentalsRunReport`] into a deterministic machine-readable `key=value` +/// summary. +/// +/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`). +pub fn format_curate_fundamentals_report(report: &CurateFundamentalsRunReport) -> String { + let fin = &report.financials_decode; + let fil = &report.filings_decode; + let b = &report.curate_stats.build; + let c = &report.curate_stats; + let w = &report.write_stats; + + let mut years = String::new(); + for (idx, (year, count)) in w.rows_by_year.iter().enumerate() { + if idx > 0 { + years.push(' '); + } + let _ = write!(years, "{year:04}={count}"); + } + if years.is_empty() { + years.push_str("none"); + } + + format!( + "curate-etl curate-fundamentals\n\ + \x20 financials_bson: docs_framed={} bytes_read={} peak_chunk_bytes={} docs_in={} rows_out={} skipped={} (missing_key={} wrong_key_type={} empty_key={} missing_period_end={} wrong_period_end_type={} invalid_period_end={} period_end_oor={} missing_report_period={} wrong_report_period_type={} unmapped_report_period={} wrong_report_date_type={} invalid_report_date={} report_date_oor={} missing_currency={} wrong_currency_type={} empty_currency={}) nulled=(missing_path={} wrong_type={} unparsable_string={} non_finite={})\n\ + \x20 filings_bson: docs_framed={} bytes_read={} peak_chunk_bytes={} docs_in={} rows_out={} skipped={} (missing_key={} wrong_key_type={} empty_key={} missing_timefiled={} wrong_timefiled_type={} empty_timefiled={} missing_form_type={} wrong_form_type_type={} empty_form_type={}) nulled_wrong_type=(filing_id={} url={})\n\ + \x20 builder: observations_in={} rows_out={} keys_out={} linked={} statutory_lag={} dropped=(unknown_key={} non_finite={} date_oor={} report_date_not_after_period_end={} unanchored_vintage={} stale_estimate={}) dup_collapsed={} dup_conflict={} filings_in={} filings_eligible={} filings_dropped=(unknown_key={} non_periodic={} invalid_ts={} date_oor={} before_period_end={})\n\ + \x20 curate: observations_in={} obs_unmapped={} filings_in={} filings_unmapped={} filings_invalid_ts={} rows_out={} listings_out={}\n\ + \x20 write: files={} row_groups={} rows_written={} bytes_written={}\n\ + \x20 years: {}\n\ + \x20 timing: elapsed_secs={:.6}", + report.financials_docs_framed, + report.financials_bytes_read, + report.financials_peak_chunk_bytes, + fin.docs_in, + fin.rows_out, + fin.skipped_total(), + fin.skipped_missing_key, + fin.skipped_wrong_key_type, + fin.skipped_empty_key, + fin.skipped_missing_period_end, + fin.skipped_wrong_period_end_type, + fin.skipped_invalid_period_end, + fin.skipped_period_end_out_of_range, + fin.skipped_missing_report_period, + fin.skipped_wrong_report_period_type, + fin.skipped_unmapped_report_period, + fin.skipped_wrong_report_date_type, + fin.skipped_invalid_report_date, + fin.skipped_report_date_out_of_range, + fin.skipped_missing_currency, + fin.skipped_wrong_currency_type, + fin.skipped_empty_currency, + fin.nulled_missing_path, + fin.nulled_wrong_type, + fin.nulled_unparsable_string, + fin.nulled_non_finite, + report.filings_docs_framed, + report.filings_bytes_read, + report.filings_peak_chunk_bytes, + fil.docs_in, + fil.rows_out, + fil.skipped_total(), + fil.skipped_missing_key, + fil.skipped_wrong_key_type, + fil.skipped_empty_key, + fil.skipped_missing_timefiled, + fil.skipped_wrong_timefiled_type, + fil.skipped_empty_timefiled, + fil.skipped_missing_form_type, + fil.skipped_wrong_form_type_type, + fil.skipped_empty_form_type, + fil.nulled_wrong_type_filing_id, + fil.nulled_wrong_type_url, + b.observations_in, + b.rows_out, + b.keys_out, + b.rows_linked_to_filing, + b.rows_statutory_lag_estimate, + b.observations_dropped_unknown_key, + b.observations_dropped_non_finite, + b.observations_dropped_date_out_of_range, + b.observations_dropped_report_date_not_after_period_end, + b.observations_dropped_unanchored_vintage, + b.observations_dropped_stale_estimate, + b.duplicate_collapsed, + b.duplicate_conflict_dropped, + b.filings_in, + b.filings_eligible, + b.filings_dropped_unknown_key, + b.filings_ignored_non_periodic, + b.filings_dropped_invalid_timestamp, + b.filings_dropped_date_out_of_range, + b.filings_dropped_before_period_end, + c.observations_in, + c.observations_dropped_unmapped, + c.filings_in, + c.filings_dropped_unmapped, + c.filings_dropped_invalid_timestamp, + c.rows_out, + c.listings_out, + w.files_written, + w.row_groups_written, + w.rows_written, + w.bytes_written, + years, + report.elapsed_secs, + ) +} + +#[cfg(test)] +#[path = "run_curate_fundamentals_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/run_curate_fundamentals_tests.rs b/tools/curate-etl/src/run_curate_fundamentals_tests.rs new file mode 100644 index 00000000..37afd1bf --- /dev/null +++ b/tools/curate-etl/src/run_curate_fundamentals_tests.rs @@ -0,0 +1,2759 @@ +//! End-to-end fixture, PIT restatement, venue-lag, conservation, fail-closed, alias-safety, +//! empty-input, and TSV parser tests for `run_curate_fundamentals`. + +use std::collections::{BTreeMap, HashMap}; +use std::error::Error as _; +use std::fs::{self, File}; +use std::io::{self, Cursor, Read}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + +use bson::raw::{cstr, RawDocumentBuf}; +use parquet::basic::Compression; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::{ + format_curate_fundamentals_report, load_listing_venues_tsv, run_curate_fundamentals, + run_curate_fundamentals_with_readers, CurateFundamentalsArgs, CurateFundamentalsFiscalPeriod, + CurateFundamentalsRunReport, RunCurateFundamentalsError, DEFAULT_FUNDAMENTALS_MAPPING_SOURCE, +}; +use crate::bson_qm_events::decode_qm_filing_buffer; +use crate::bson_qm_financials::decode_qm_financials_buffer; +use crate::bson_stream::BsonStreamError; +use crate::curate_fundamentals::curate_fundamentals; +use crate::events::{ + partition_year_utc, KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, +}; +use crate::fundamentals::{ + FinancialObservation, FundamentalsFields, FUNDAMENTALS_FALLBACK_HOUR_ET, + FUNDAMENTALS_FALLBACK_MINUTE_ET, STATUTORY_LAG_TSXV_CSE_ANNUAL_DAYS, + STATUTORY_LAG_TSXV_CSE_QUARTERLY_DAYS, STATUTORY_LAG_US_TSX_ANNUAL_DAYS, + STATUTORY_LAG_US_TSX_QUARTERLY_DAYS, +}; +use crate::parquet_fundamentals::FundamentalsPitParquetRow; +use crate::provider_mapping::{ProviderMappingError, ProviderMappingTable}; +use crate::run_curate_bars::load_provider_mapping_tsv; +use crate::shorts::et_to_utc_micros; +use crate::split::ymd_to_epoch_days; + +static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDirGuard { + path: PathBuf, +} + +impl TempDirGuard { + fn new(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = std::env::temp_dir().join(format!( + "curate-etl-run-curate-fundamentals-{label}-{pid}-{seq}" + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum TreeEntry { + Dir, + File(Vec), + Symlink(PathBuf), +} + +fn snapshot_tree(root: &Path) -> BTreeMap { + let mut out = BTreeMap::new(); + if !root.exists() && fs::symlink_metadata(root).is_err() { + return out; + } + fn walk(base: &Path, cur: &Path, out: &mut BTreeMap) { + let meta = fs::symlink_metadata(cur).expect("symlink_metadata"); + let rel = cur.strip_prefix(base).unwrap_or(cur).to_path_buf(); + if meta.file_type().is_symlink() { + let target = fs::read_link(cur).expect("read_link"); + out.insert(rel, TreeEntry::Symlink(target)); + } else if meta.is_dir() { + out.insert(rel, TreeEntry::Dir); + let mut children: Vec = fs::read_dir(cur) + .expect("read_dir") + .map(|e| e.expect("dir entry").path()) + .collect(); + children.sort(); + for child in children { + walk(base, &child, out); + } + } else { + let bytes = fs::read(cur).expect("read file"); + out.insert(rel, TreeEntry::File(bytes)); + } + } + walk(root, root, &mut out); + out +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid test date") +} + +fn make_financials_doc( + key: Option<&str>, + period_end: &str, + report_date: Option<&str>, + report_period: &str, + currency: &str, + fields: FundamentalsFields, +) -> Vec { + 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(v) = fields.revenue { + income.append(cstr!("revenue"), v); + } + if let Some(v) = fields.net_income { + income.append(cstr!("netIncome"), v); + } + doc.append(cstr!("IncomeStatement"), income); + + let mut cashflow = RawDocumentBuf::new(); + if let Some(v) = fields.operating_cash_flow { + cashflow.append(cstr!("operatingCashFlow"), v); + } + doc.append(cstr!("CashFlow"), cashflow); + + let mut balance = RawDocumentBuf::new(); + if let Some(v) = fields.total_assets { + balance.append(cstr!("totalAssets"), v); + } + if let Some(v) = fields.total_equity { + balance.append(cstr!("totalEquity"), v); + } + if let Some(v) = fields.shares_outstanding { + balance.append(cstr!("sharesOutstanding"), v); + } + doc.append(cstr!("BalanceSheet"), balance); + + doc.into_bytes() +} + +fn make_filing_doc( + key: Option<&str>, + timefiled: &str, + form_type: &str, + filing_id: Option<&str>, + url: Option<&str>, +) -> Vec { + let mut doc = RawDocumentBuf::new(); + if let Some(k) = key { + doc.append(cstr!("symbol"), k); + } + doc.append(cstr!("timefiled"), timefiled); + doc.append(cstr!("formType"), form_type); + if let Some(id) = filing_id { + doc.append(cstr!("filingId"), id); + } + if let Some(u) = url { + doc.append(cstr!("url"), u); + } + doc.into_bytes() +} + +fn default_test_args( + qm_financials: PathBuf, + qm_filings: PathBuf, + provider_mapping: PathBuf, + listing_venues: PathBuf, + out_dir: PathBuf, +) -> CurateFundamentalsArgs { + let mut args = CurateFundamentalsArgs::with_verified_defaults( + qm_financials, + qm_filings, + provider_mapping, + listing_venues, + out_dir, + "currency", + Some("IncomeStatement.revenue".to_string()), + Some("IncomeStatement.netIncome".to_string()), + Some("CashFlow.operatingCashFlow".to_string()), + Some("BalanceSheet.totalAssets".to_string()), + Some("BalanceSheet.totalEquity".to_string()), + Some("BalanceSheet.sharesOutstanding".to_string()), + CurateFundamentalsFiscalPeriod::ByTokens { + quarterly: vec![ + "Q1".to_string(), + "Q2".to_string(), + "Q3".to_string(), + "Q4".to_string(), + ], + annual: vec!["FY".to_string()], + }, + "formType", + 4, + ); + args.filings_filing_id_field = Some("filingId".to_string()); + args.filings_url_field = Some("url".to_string()); + args +} + +#[derive(Debug, Clone, PartialEq)] +struct DecodedParquetRow { + listing_id: i32, + effective_known_at: i64, + known_at_source: String, + has_estimated_lag: bool, + period_end: i32, + fiscal_period: String, + currency: String, + period_known_at: i64, + revenue: Option, + net_income: Option, + operating_cash_flow: Option, + total_assets: Option, + total_equity: Option, + shares_outstanding: Option, + ttm_period_end: Option, + ttm_currency: Option, + ttm_revenue: Option, + ttm_net_income: Option, + ttm_operating_cash_flow: Option, + ttm_has_estimated_lag: Option, +} + +fn from_stage_row(row: &FundamentalsPitParquetRow) -> DecodedParquetRow { + let lp = row.latest_period().expect("latest_period"); + DecodedParquetRow { + listing_id: row.listing_id, + effective_known_at: row.effective_known_at_micros, + known_at_source: row.known_at_source.as_ref().to_string(), + has_estimated_lag: row.has_estimated_lag, + period_end: lp.period_end, + fiscal_period: lp.fiscal_period.as_ref().to_string(), + currency: lp.currency.clone(), + period_known_at: lp.period_known_at_micros, + revenue: lp.fields.revenue, + net_income: lp.fields.net_income, + operating_cash_flow: lp.fields.operating_cash_flow, + total_assets: lp.fields.total_assets, + total_equity: lp.fields.total_equity, + shares_outstanding: lp.fields.shares_outstanding, + ttm_period_end: row.ttm.as_ref().map(|t| t.ending_period_end), + ttm_currency: row.ttm.as_ref().map(|t| t.currency.clone()), + ttm_revenue: row.ttm.as_ref().and_then(|t| t.flows.revenue), + ttm_net_income: row.ttm.as_ref().and_then(|t| t.flows.net_income), + ttm_operating_cash_flow: row.ttm.as_ref().and_then(|t| t.flows.operating_cash_flow), + ttm_has_estimated_lag: row.ttm.as_ref().map(|t| t.has_estimated_lag), + } +} + +fn read_parquet_rows_by_name(path: &Path) -> Vec { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let meta = reader.metadata(); + let schema_descr = meta.file_metadata().schema_descr(); + + let mut col_idx_by_name: HashMap<&str, usize> = HashMap::new(); + for (idx, col) in schema_descr.columns().iter().enumerate() { + col_idx_by_name.insert(col.name(), idx); + } + let col_idx = |name: &str| -> usize { + *col_idx_by_name + .get(name) + .unwrap_or_else(|| panic!("missing expected Parquet column '{name}'")) + }; + + let mut out = Vec::new(); + for rg_idx in 0..meta.num_row_groups() { + let rg_meta = meta.row_group(rg_idx); + for c in 0..rg_meta.num_columns() { + assert_eq!( + rg_meta.column(c).compression(), + Compression::ZSTD(Default::default()), + "expected Zstd compression on column {c}" + ); + } + + let rg_rows = rg_meta.num_rows() as usize; + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + + let read_req_i32 = |name: &str| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx(name)).unwrap() { + ColumnReader::Int32ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .unwrap(); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected INT32 for '{name}'"), + } + vals + }; + + let read_opt_i32 = |name: &str| -> Vec> { + let mut vals = Vec::with_capacity(rg_rows); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx(name)).unwrap() { + ColumnReader::Int32ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) + .unwrap(); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected INT32 for '{name}'"), + } + let mut vi = 0usize; + defs.into_iter() + .map(|d| { + if d == 1 { + let v = vals[vi]; + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) + .collect() + }; + + let read_req_i64 = |name: &str| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx(name)).unwrap() { + ColumnReader::Int64ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .unwrap(); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected INT64 for '{name}'"), + } + vals + }; + + let read_req_bool = |name: &str| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx(name)).unwrap() { + ColumnReader::BoolColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .unwrap(); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BOOLEAN for '{name}'"), + } + vals + }; + + let read_opt_bool = |name: &str| -> Vec> { + let mut vals = Vec::with_capacity(rg_rows); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx(name)).unwrap() { + ColumnReader::BoolColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) + .unwrap(); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BOOLEAN for '{name}'"), + } + let mut vi = 0usize; + defs.into_iter() + .map(|d| { + if d == 1 { + let v = vals[vi]; + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) + .collect() + }; + + let read_opt_f64 = |name: &str| -> Vec> { + let mut vals = Vec::with_capacity(rg_rows); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx(name)).unwrap() { + ColumnReader::DoubleColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) + .unwrap(); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected DOUBLE for '{name}'"), + } + let mut vi = 0usize; + defs.into_iter() + .map(|d| { + if d == 1 { + let v = vals[vi]; + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) + .collect() + }; + + let read_req_str = |name: &str| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx(name)).unwrap() { + ColumnReader::ByteArrayColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .unwrap(); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BYTE_ARRAY for '{name}'"), + } + vals.into_iter() + .map(|ba| String::from_utf8(ba.data().to_vec()).unwrap()) + .collect() + }; + + let read_opt_str = |name: &str| -> Vec> { + let mut vals = Vec::with_capacity(rg_rows); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx(name)).unwrap() { + ColumnReader::ByteArrayColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) + .unwrap(); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BYTE_ARRAY for '{name}'"), + } + let mut vi = 0usize; + defs.into_iter() + .map(|d| { + if d == 1 { + let v = String::from_utf8(vals[vi].data().to_vec()).unwrap(); + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) + .collect() + }; + + let listing_id = read_req_i32("listing_id"); + let effective_known_at = read_req_i64("effective_known_at"); + let known_at_source = read_req_str("known_at_source"); + let has_estimated_lag = read_req_bool("has_estimated_lag"); + let period_end = read_req_i32("period_end"); + let fiscal_period = read_req_str("fiscal_period"); + let currency = read_req_str("currency"); + let period_known_at = read_req_i64("period_known_at"); + let revenue = read_opt_f64("revenue"); + let net_income = read_opt_f64("net_income"); + let operating_cash_flow = read_opt_f64("operating_cash_flow"); + let total_assets = read_opt_f64("total_assets"); + let total_equity = read_opt_f64("total_equity"); + let shares_outstanding = read_opt_f64("shares_outstanding"); + let ttm_period_end = read_opt_i32("ttm_period_end"); + let ttm_currency = read_opt_str("ttm_currency"); + let ttm_revenue = read_opt_f64("ttm_revenue"); + let ttm_net_income = read_opt_f64("ttm_net_income"); + let ttm_operating_cash_flow = read_opt_f64("ttm_operating_cash_flow"); + let ttm_has_estimated_lag = read_opt_bool("ttm_has_estimated_lag"); + + for i in 0..rg_rows { + out.push(DecodedParquetRow { + listing_id: listing_id[i], + effective_known_at: effective_known_at[i], + known_at_source: known_at_source[i].clone(), + has_estimated_lag: has_estimated_lag[i], + period_end: period_end[i], + fiscal_period: fiscal_period[i].clone(), + currency: currency[i].clone(), + period_known_at: period_known_at[i], + revenue: revenue[i], + net_income: net_income[i], + operating_cash_flow: operating_cash_flow[i], + total_assets: total_assets[i], + total_equity: total_equity[i], + shares_outstanding: shares_outstanding[i], + ttm_period_end: ttm_period_end[i], + ttm_currency: ttm_currency[i].clone(), + ttm_revenue: ttm_revenue[i], + ttm_net_income: ttm_net_income[i], + ttm_operating_cash_flow: ttm_operating_cash_flow[i], + ttm_has_estimated_lag: ttm_has_estimated_lag[i], + }); + } + } + out +} + +fn read_dataset_by_year(out_dir: &Path) -> BTreeMap> { + let dataset_dir = out_dir.join("fundamentals_pit"); + let mut by_year = BTreeMap::new(); + if !dataset_dir.exists() { + return by_year; + } + for entry in fs::read_dir(&dataset_dir).expect("read dataset dir") { + let entry = entry.expect("dir entry"); + let name = entry.file_name().to_string_lossy().to_string(); + if let Some(year_str) = name.strip_prefix("year=") { + let year: i32 = year_str.parse().expect("valid year dir"); + let part = entry.path().join("part.parquet"); + assert!(part.is_file(), "expected part.parquet in {}", entry.path().display()); + by_year.insert(year, read_parquet_rows_by_name(&part)); + } + } + by_year +} + +fn assert_single_line(msg: &str) { + assert!( + !msg.contains('\n') && !msg.contains('\r'), + "error Display must be single-line, got: {msg:?}" + ); +} + +fn assert_reports_eq_ignoring_timing( + a: &CurateFundamentalsRunReport, + b: &CurateFundamentalsRunReport, +) { + assert_eq!(a.financials_docs_framed, b.financials_docs_framed); + assert_eq!(a.financials_bytes_read, b.financials_bytes_read); + assert_eq!(a.financials_peak_chunk_bytes, b.financials_peak_chunk_bytes); + assert_eq!(a.financials_decode, b.financials_decode); + assert_eq!(a.filings_docs_framed, b.filings_docs_framed); + assert_eq!(a.filings_bytes_read, b.filings_bytes_read); + assert_eq!(a.filings_peak_chunk_bytes, b.filings_peak_chunk_bytes); + assert_eq!(a.filings_decode, b.filings_decode); + assert_eq!(a.curate_stats, b.curate_stats); + assert_eq!(a.write_stats, b.write_stats); +} + +fn assert_conservation(report: &CurateFundamentalsRunReport) { + assert_eq!( + report.financials_docs_framed as usize, + report.financials_decode.docs_in + ); + assert_eq!( + report.financials_decode.docs_in, + report.financials_decode.rows_out + report.financials_decode.skipped_total() + ); + assert_eq!( + report.filings_docs_framed as usize, + report.filings_decode.docs_in + ); + assert_eq!( + report.filings_decode.docs_in, + report.filings_decode.rows_out + report.filings_decode.skipped_total() + ); + assert_eq!( + report.financials_decode.rows_out, + report.curate_stats.observations_in + ); + assert_eq!( + report.filings_decode.rows_out, + report.curate_stats.filings_in + ); + assert_eq!( + report.write_stats.rows_written, + report.curate_stats.rows_out + ); +} + +#[test] +fn fundamentals_two_listing_parquet_matches_stage() { + let tmp = TempDirGuard::new("two-listing"); + let fin_path = tmp.path().join("qmFinancials.bson"); + let fil_path = tmp.path().join("qmFilings.bson"); + let map_path = tmp.path().join("provider_mapping.tsv"); + let venues_path = tmp.path().join("listing_venues.tsv"); + let out_file_api = tmp.path().join("out_file"); + let out_reader_api = tmp.path().join("out_reader"); + + // 2 listings: 101 (NVDA, us_tsx, USD) with 4 consecutive quarters spanning 2023-2024 so TTM + // is populated, plus 202 (MINE:V, tsxv_cse, CAD) with a nullable stock metric and unlinked FY. + fs::write( + &map_path, + "qm\tNVDA\t2020-01-01\t\t101\nqm\tMINE:V\t2020-01-01\t\t202\n", + ) + .unwrap(); + // Include both LF and CRLF line endings in the valid venue fixture. + fs::write(&venues_path, "101\tus_tsx\r\n202\ttsxv_cse\n").unwrap(); + + let mut fin_bytes = Vec::new(); + // 4 consecutive quarters for NVDA (Q1 2023 .. Q4 2023), filed across 2023 and 2024. + fin_bytes.extend_from_slice(&make_financials_doc( + Some("NVDA"), + "2023-03-31", + Some("2023-05-02"), + "Q1", + "USD", + FundamentalsFields { + revenue: Some(100.0), + net_income: Some(20.0), + operating_cash_flow: Some(25.0), + total_assets: Some(1000.0), + total_equity: Some(600.0), + shares_outstanding: Some(50.0), + }, + )); + fin_bytes.extend_from_slice(&make_financials_doc( + Some("NVDA"), + "2023-06-30", + Some("2023-08-03"), + "Q2", + "USD", + FundamentalsFields { + revenue: Some(110.0), + net_income: Some(22.0), + operating_cash_flow: Some(28.0), + total_assets: Some(1050.0), + total_equity: Some(620.0), + shares_outstanding: Some(50.0), + }, + )); + fin_bytes.extend_from_slice(&make_financials_doc( + Some("NVDA"), + "2023-09-30", + Some("2023-11-04"), + "Q3", + "USD", + FundamentalsFields { + revenue: Some(120.0), + net_income: Some(24.0), + operating_cash_flow: Some(30.0), + total_assets: Some(1100.0), + total_equity: Some(640.0), + shares_outstanding: Some(51.0), + }, + )); + fin_bytes.extend_from_slice(&make_financials_doc( + Some("NVDA"), + "2023-12-31", + Some("2024-02-10"), + "Q4", + "USD", + FundamentalsFields { + revenue: Some(130.0), + net_income: Some(26.0), + operating_cash_flow: Some(32.0), + total_assets: Some(1150.0), + total_equity: Some(660.0), + shares_outstanding: Some(51.0), + }, + )); + // Listing 202 (MINE:V): Q1 2024 linked to SEDAR interim filing, with nullable total_equity. + fin_bytes.extend_from_slice(&make_financials_doc( + Some("MINE:V"), + "2024-03-31", + Some("2024-05-20"), + "Q1", + "CAD", + FundamentalsFields { + revenue: Some(5.5), + net_income: Some(-1.2), + operating_cash_flow: None, + total_assets: Some(40.0), + total_equity: None, + shares_outstanding: Some(120.0), + }, + )); + fs::write(&fin_path, &fin_bytes).unwrap(); + + let mut fil_bytes = Vec::new(); + fil_bytes.extend_from_slice(&make_filing_doc( + Some("NVDA"), + "2023-05-02T16:15:00 EDT", + "10-Q", + Some("f-q1"), + Some("https://example.test/q1"), + )); + fil_bytes.extend_from_slice(&make_filing_doc( + Some("NVDA"), + "2023-08-03T16:20:00 EDT", + "10-Q", + Some("f-q2"), + None, + )); + fil_bytes.extend_from_slice(&make_filing_doc( + Some("NVDA"), + "2023-11-04T16:30:00 EDT", + "10-Q", + Some("f-q3"), + None, + )); + fil_bytes.extend_from_slice(&make_filing_doc( + Some("NVDA"), + "2024-02-10T16:05:00 EST", + "10-Q", + Some("f-q4"), + None, + )); + fil_bytes.extend_from_slice(&make_filing_doc( + Some("MINE:V"), + "2024-05-20T09:00:00 EDT", + "Interim financial statements/report - English", + Some("f-mine-q1"), + None, + )); + fs::write(&fil_path, &fil_bytes).unwrap(); + + // Run via public file API. + let file_args = default_test_args( + fin_path.clone(), + fil_path.clone(), + map_path.clone(), + venues_path.clone(), + out_file_api.clone(), + ); + let file_report = run_curate_fundamentals(&file_args).expect("file API run"); + assert_conservation(&file_report); + assert_eq!(file_report.curate_stats.listings_out, 2); + assert_eq!(file_report.write_stats.rows_written, 5); + + // Build expected rows directly via curate_fundamentals on the same decoded inputs. + let mut direct_obs = Vec::new(); + file_args.fiscal_period.with_borrowed(|fp| { + decode_qm_financials_buffer(&fin_bytes, &file_args.financials_field_names(), fp, |o| { + direct_obs.push(FinancialObservation { + key: o.key.to_owned(), + period_end: o.period_end, + fiscal_period: o.fiscal_period, + currency: o.currency, + report_date: o.report_date, + fields: o.fields, + }); + }) + .unwrap(); + }); + let mut direct_filings = Vec::new(); + decode_qm_filing_buffer(&fil_bytes, &file_args.filings_field_names(), |raw| { + direct_filings.push(raw.to_qm_filing(raw.key.to_owned())); + }) + .unwrap(); + let mapping = ProviderMappingTable::from_rows(load_provider_mapping_tsv(&map_path).unwrap()) + .unwrap(); + let venues = load_listing_venues_tsv(&venues_path).unwrap(); + let stage_out = curate_fundamentals( + direct_obs, + direct_filings, + DEFAULT_FUNDAMENTALS_MAPPING_SOURCE, + &mapping, + &venues, + file_args.k, + ) + .unwrap(); + + let mut expected_by_year: BTreeMap> = BTreeMap::new(); + for row in &stage_out.rows { + let year = partition_year_utc(row.effective_known_at_micros); + expected_by_year + .entry(year) + .or_default() + .push(from_stage_row(row)); + } + + let got_by_year = read_dataset_by_year(&out_file_api); + assert_eq!(got_by_year.keys().copied().collect::>(), vec![2023, 2024]); + assert_eq!(got_by_year, expected_by_year); + + // Verify 4-quarter TTM is populated on the 2024 NVDA Q4 row and nulls are preserved on MINE:V. + let rows_2024 = &got_by_year[&2024]; + let nvda_q4 = rows_2024 + .iter() + .find(|r| r.listing_id == 101) + .expect("NVDA 2024 row"); + assert_eq!(nvda_q4.currency, "USD"); + assert_eq!(nvda_q4.ttm_period_end, Some(day(2023, 12, 31))); + assert_eq!(nvda_q4.ttm_currency.as_deref(), Some("USD")); + assert_eq!(nvda_q4.ttm_revenue, Some(460.0)); + assert_eq!(nvda_q4.ttm_net_income, Some(92.0)); + assert_eq!(nvda_q4.ttm_operating_cash_flow, Some(115.0)); + assert_eq!(nvda_q4.ttm_has_estimated_lag, Some(false)); + assert_eq!(nvda_q4.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + + let mine_q1 = rows_2024 + .iter() + .find(|r| r.listing_id == 202) + .expect("MINE:V 2024 row"); + assert_eq!(mine_q1.currency, "CAD"); + assert_eq!(mine_q1.operating_cash_flow, None); + assert_eq!(mine_q1.total_equity, None); + assert_eq!(mine_q1.ttm_period_end, None); + + // Run the exact same pinned fixture through the injected-reader entry point. + let reader_args = default_test_args( + fin_path, + fil_path, + map_path, + venues_path, + out_reader_api.clone(), + ); + let reader_report = run_curate_fundamentals_with_readers( + &reader_args, + Cursor::new(fin_bytes.as_slice()), + Cursor::new(fil_bytes.as_slice()), + ) + .expect("reader API run"); + assert_reports_eq_ignoring_timing(&file_report, &reader_report); + assert_eq!(read_dataset_by_year(&out_reader_api), got_by_year); +} + +#[test] +fn fundamentals_late_q1_restatement_preserves_q2() { + let tmp = TempDirGuard::new("restatement"); + let map_path = tmp.path().join("provider_mapping.tsv"); + let venues_path = tmp.path().join("listing_venues.tsv"); + fs::write(&map_path, "qm\tACME\t2020-01-01\t\t301\n").unwrap(); + fs::write(&venues_path, "301\tus_tsx\n").unwrap(); + + // Four contiguous quarters ending in Q2 2024 so Q2 and the late Q1 amendment both carry + // a 4-quarter TTM sum; the Q1 revenue revision (-12.0) must show up in TTM revenue first + // at the amendment timestamp while leaving all earlier rows and Q2's latest fields intact. + let q3_2023 = make_financials_doc( + Some("ACME"), + "2023-09-30", + Some("2023-11-05"), + "Q3", + "USD", + FundamentalsFields { + revenue: Some(90.0), + net_income: Some(8.0), + operating_cash_flow: Some(10.0), + total_assets: Some(460.0), + total_equity: Some(275.0), + shares_outstanding: Some(20.0), + }, + ); + let q4_2023 = make_financials_doc( + Some("ACME"), + "2023-12-31", + Some("2024-02-20"), + "Q4", + "USD", + FundamentalsFields { + revenue: Some(110.0), + net_income: Some(11.0), + operating_cash_flow: Some(14.0), + total_assets: Some(480.0), + total_equity: Some(288.0), + shares_outstanding: Some(20.0), + }, + ); + let q1_orig = make_financials_doc( + Some("ACME"), + "2024-03-31", + Some("2024-05-05"), + "Q1", + "USD", + FundamentalsFields { + revenue: Some(100.0), + net_income: Some(10.0), + operating_cash_flow: Some(12.0), + total_assets: Some(500.0), + total_equity: Some(300.0), + shares_outstanding: Some(20.0), + }, + ); + let q2_orig = make_financials_doc( + Some("ACME"), + "2024-06-30", + Some("2024-08-05"), + "Q2", + "USD", + FundamentalsFields { + revenue: Some(250.0), + net_income: Some(30.0), + operating_cash_flow: Some(35.0), + total_assets: Some(550.0), + total_equity: Some(330.0), + shares_outstanding: Some(20.0), + }, + ); + let q1_restated = make_financials_doc( + Some("ACME"), + "2024-03-31", + Some("2024-09-15"), + "Q1", + "USD", + FundamentalsFields { + revenue: Some(88.0), + net_income: Some(4.0), + operating_cash_flow: Some(9.0), + total_assets: Some(490.0), + total_equity: Some(294.0), + shares_outstanding: Some(20.0), + }, + ); + + let f_q3_2023 = make_filing_doc( + Some("ACME"), + "2023-11-05T16:10:00 EST", + "10-Q", + Some("q3-2023-1"), + None, + ); + let f_q4_2023 = make_filing_doc( + Some("ACME"), + "2024-02-20T16:10:00 EST", + "10-Q", + Some("q4-2023-1"), + None, + ); + let f_q1 = make_filing_doc( + Some("ACME"), + "2024-05-05T16:10:00 EDT", + "10-Q", + Some("q1-1"), + None, + ); + let f_q2 = make_filing_doc( + Some("ACME"), + "2024-08-05T16:15:00 EDT", + "10-Q", + Some("q2-1"), + None, + ); + let f_q1_amend = make_filing_doc( + Some("ACME"), + "2024-09-15T17:00:00 EDT", + "10-Q/A", + Some("q1-2"), + None, + ); + + // Run 1: Q3 2023 + Q4 2023 + Q1 2024 + Q2 2024 only. + let fin_before = tmp.path().join("fin_before.bson"); + let fil_before = tmp.path().join("fil_before.bson"); + let out_before = tmp.path().join("out_before"); + fs::write( + &fin_before, + [&q3_2023[..], &q4_2023[..], &q1_orig[..], &q2_orig[..]].concat(), + ) + .unwrap(); + fs::write( + &fil_before, + [&f_q3_2023[..], &f_q4_2023[..], &f_q1[..], &f_q2[..]].concat(), + ) + .unwrap(); + let args_before = default_test_args( + fin_before, + fil_before, + map_path.clone(), + venues_path.clone(), + out_before.clone(), + ); + let rep_before = run_curate_fundamentals(&args_before).unwrap(); + assert_eq!(rep_before.write_stats.rows_written, 4); + let by_year_before = read_dataset_by_year(&out_before); + let rows_2023_before = by_year_before.get(&2023).expect("2023 partition"); + let rows_2024_before = by_year_before.get(&2024).expect("2024 partition"); + assert_eq!(rows_2023_before.len(), 1); + assert_eq!(rows_2024_before.len(), 3); + + // Run 2: same four quarters + late Q1 2024 restatement (known_at > Q2's known_at). + let fin_after = tmp.path().join("fin_after.bson"); + let fil_after = tmp.path().join("fil_after.bson"); + let out_after = tmp.path().join("out_after"); + fs::write( + &fin_after, + [ + &q3_2023[..], + &q4_2023[..], + &q1_orig[..], + &q2_orig[..], + &q1_restated[..], + ] + .concat(), + ) + .unwrap(); + fs::write( + &fil_after, + [ + &f_q3_2023[..], + &f_q4_2023[..], + &f_q1[..], + &f_q2[..], + &f_q1_amend[..], + ] + .concat(), + ) + .unwrap(); + let args_after = default_test_args( + fin_after, + fil_after, + map_path, + venues_path, + out_after.clone(), + ); + let rep_after = run_curate_fundamentals(&args_after).unwrap(); + assert_eq!(rep_after.write_stats.rows_written, 5); + let by_year_after = read_dataset_by_year(&out_after); + let rows_2023_after = by_year_after.get(&2023).expect("2023 partition"); + let rows_2024_after = by_year_after.get(&2024).expect("2024 partition"); + assert_eq!(rows_2023_after.len(), 1); + assert_eq!(rows_2024_after.len(), 4); + + // Entire pre-amendment prefix across both years is byte/value-identical (zero leakage). + assert_eq!(rows_2023_after, rows_2023_before); + assert_eq!(&rows_2024_after[..3], &rows_2024_before[..]); + + // Fourth 2024 snapshot is at the amendment's UTC known_at (2024-09-15 17:00 EDT = 21:00 UTC), + // Q2 remains the latest period (period_end, values, and period_known_at unchanged), and + // 4-quarter TTM revenue changes first at this snapshot by exactly the Q1 revision (-12.0). + let q2_row = &rows_2024_before[2]; + let amend_row = &rows_2024_after[3]; + let expected_amend_utc = et_to_utc_micros(day(2024, 9, 15), 17, 0, 0).unwrap(); + assert_eq!(amend_row.effective_known_at, expected_amend_utc); + assert!(amend_row.effective_known_at > q2_row.effective_known_at); + assert_eq!(amend_row.period_end, day(2024, 6, 30)); + assert_eq!(amend_row.period_end, q2_row.period_end); + assert_eq!(amend_row.period_known_at, q2_row.period_known_at); + assert_eq!(amend_row.revenue, q2_row.revenue); + assert_eq!(amend_row.net_income, q2_row.net_income); + assert_eq!(amend_row.operating_cash_flow, q2_row.operating_cash_flow); + assert_eq!(amend_row.total_assets, q2_row.total_assets); + assert_eq!(amend_row.total_equity, q2_row.total_equity); + assert_eq!(amend_row.shares_outstanding, q2_row.shares_outstanding); + + // TTM assertions: 90 + 110 + 100 + 250 = 550 before amendment; 90 + 110 + 88 + 250 = 538 after. + assert_eq!(q2_row.ttm_period_end, Some(day(2024, 6, 30))); + assert_eq!(amend_row.ttm_period_end, Some(day(2024, 6, 30))); + assert_eq!(q2_row.ttm_revenue, Some(550.0)); + assert_eq!(amend_row.ttm_revenue, Some(538.0)); + assert_eq!( + amend_row.ttm_revenue.unwrap() - q2_row.ttm_revenue.unwrap(), + 88.0 - 100.0 + ); + assert_eq!(q2_row.ttm_net_income, Some(59.0)); + assert_eq!(amend_row.ttm_net_income, Some(53.0)); + assert_eq!(q2_row.ttm_operating_cash_flow, Some(71.0)); + assert_eq!(amend_row.ttm_operating_cash_flow, Some(68.0)); +} + +#[test] +fn fundamentals_unlinked_uses_venue_lag() { + let tmp = TempDirGuard::new("venue-lag"); + let fin_path = tmp.path().join("qmFinancials.bson"); + let fil_path = tmp.path().join("qmFilings.bson"); + let map_path = tmp.path().join("provider_mapping.tsv"); + let venues_path = tmp.path().join("listing_venues.tsv"); + let out_dir = tmp.path().join("out"); + + fs::write( + &map_path, + "qm\tUSCO\t2020-01-01\t\t10\nqm\tVNCO:V\t2020-01-01\t\t20\n", + ) + .unwrap(); + fs::write(&venues_path, "10\tus_tsx\n20\ttsxv_cse\n").unwrap(); + + let q_end = day(2024, 3, 31); + let fy_end = day(2024, 12, 31); + let mut fin_bytes = Vec::new(); + for (sym, ccy) in [("USCO", "USD"), ("VNCO:V", "CAD")] { + fin_bytes.extend_from_slice(&make_financials_doc( + Some(sym), + "2024-03-31", + None, + "Q1", + ccy, + FundamentalsFields { + revenue: Some(50.0), + ..Default::default() + }, + )); + fin_bytes.extend_from_slice(&make_financials_doc( + Some(sym), + "2024-12-31", + None, + "FY", + ccy, + FundamentalsFields { + revenue: Some(200.0), + ..Default::default() + }, + )); + } + fs::write(&fin_path, &fin_bytes).unwrap(); + // Empty filings dump -> all 4 observations must use statutory_lag_estimate. + fs::write(&fil_path, []).unwrap(); + + let args = default_test_args(fin_path, fil_path, map_path, venues_path, out_dir.clone()); + let report = run_curate_fundamentals(&args).unwrap(); + assert_conservation(&report); + assert_eq!(report.curate_stats.build.rows_linked_to_filing, 0); + assert_eq!(report.curate_stats.build.rows_statutory_lag_estimate, 4); + + let by_year = read_dataset_by_year(&out_dir); + let rows_2024 = &by_year[&2024]; + let rows_2025 = &by_year[&2025]; + + let expected_us_q = et_to_utc_micros( + q_end + STATUTORY_LAG_US_TSX_QUARTERLY_DAYS, + FUNDAMENTALS_FALLBACK_HOUR_ET, + FUNDAMENTALS_FALLBACK_MINUTE_ET, + 0, + ) + .unwrap(); + let expected_tsxv_q = et_to_utc_micros( + q_end + STATUTORY_LAG_TSXV_CSE_QUARTERLY_DAYS, + FUNDAMENTALS_FALLBACK_HOUR_ET, + FUNDAMENTALS_FALLBACK_MINUTE_ET, + 0, + ) + .unwrap(); + let expected_us_fy = et_to_utc_micros( + fy_end + STATUTORY_LAG_US_TSX_ANNUAL_DAYS, + FUNDAMENTALS_FALLBACK_HOUR_ET, + FUNDAMENTALS_FALLBACK_MINUTE_ET, + 0, + ) + .unwrap(); + let expected_tsxv_fy = et_to_utc_micros( + fy_end + STATUTORY_LAG_TSXV_CSE_ANNUAL_DAYS, + FUNDAMENTALS_FALLBACK_HOUR_ET, + FUNDAMENTALS_FALLBACK_MINUTE_ET, + 0, + ) + .unwrap(); + + assert_ne!(expected_us_q, expected_tsxv_q); + assert_ne!(expected_us_fy, expected_tsxv_fy); + + let us_q = rows_2024.iter().find(|r| r.listing_id == 10).unwrap(); + let tsxv_q = rows_2024.iter().find(|r| r.listing_id == 20).unwrap(); + let us_fy = rows_2025.iter().find(|r| r.listing_id == 10).unwrap(); + let tsxv_fy = rows_2025.iter().find(|r| r.listing_id == 20).unwrap(); + + for (row, expected_ts) in [ + (us_q, expected_us_q), + (tsxv_q, expected_tsxv_q), + (us_fy, expected_us_fy), + (tsxv_fy, expected_tsxv_fy), + ] { + assert_eq!(row.effective_known_at, expected_ts); + assert_eq!(row.period_known_at, expected_ts); + assert_eq!(row.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + assert!(row.has_estimated_lag); + } +} + +#[test] +fn fundamentals_report_conserves_counters() { + let tmp = TempDirGuard::new("conservation"); + let fin_path = tmp.path().join("qmFinancials.bson"); + let fil_path = tmp.path().join("qmFilings.bson"); + let map_path = tmp.path().join("provider_mapping.tsv"); + let venues_path = tmp.path().join("listing_venues.tsv"); + let out_dir = tmp.path().join("out"); + + fs::write(&map_path, "qm\tKNOWN\t2020-01-01\t\t401\n").unwrap(); + fs::write(&venues_path, "401\tus_tsx\n").unwrap(); + + let mut fin_bytes = Vec::new(); + // 1. Emitted & mapped + fin_bytes.extend_from_slice(&make_financials_doc( + Some("KNOWN"), + "2024-03-31", + Some("2024-05-01"), + "Q1", + "USD", + FundamentalsFields { + revenue: Some(10.0), + ..Default::default() + }, + )); + // 2. Skipped at BSON decode (missing key) + fin_bytes.extend_from_slice(&make_financials_doc( + None, + "2024-03-31", + Some("2024-05-01"), + "Q1", + "USD", + FundamentalsFields::default(), + )); + // 3. Emitted at BSON decode, dropped unmapped at stage + fin_bytes.extend_from_slice(&make_financials_doc( + Some("UNMAPPED"), + "2024-03-31", + Some("2024-05-01"), + "Q1", + "USD", + FundamentalsFields { + revenue: Some(20.0), + ..Default::default() + }, + )); + fs::write(&fin_path, &fin_bytes).unwrap(); + + let mut fil_bytes = Vec::new(); + // 1. Emitted & mapped + fil_bytes.extend_from_slice(&make_filing_doc( + Some("KNOWN"), + "2024-05-01T16:10:00 EDT", + "10-Q", + Some("f1"), + None, + )); + // 2. Skipped at BSON decode (missing key) + fil_bytes.extend_from_slice(&make_filing_doc( + None, + "2024-05-01T16:10:00 EDT", + "10-Q", + None, + None, + )); + // 3. Emitted at BSON decode, dropped unmapped at stage + fil_bytes.extend_from_slice(&make_filing_doc( + Some("UNMAPPED"), + "2024-05-01T16:10:00 EDT", + "10-Q", + None, + None, + )); + // 4. Emitted at BSON decode, dropped invalid timestamp at stage + fil_bytes.extend_from_slice(&make_filing_doc( + Some("KNOWN"), + "not-a-timestamp", + "10-Q", + None, + None, + )); + fs::write(&fil_path, &fil_bytes).unwrap(); + + let args = default_test_args(fin_path, fil_path, map_path, venues_path, out_dir); + let report = run_curate_fundamentals(&args).unwrap(); + + assert_conservation(&report); + assert_eq!(report.financials_docs_framed, 3); + assert_eq!(report.financials_bytes_read, fin_bytes.len() as u64); + assert_eq!(report.financials_decode.rows_out, 2); + assert_eq!(report.financials_decode.skipped_missing_key, 1); + assert_eq!(report.curate_stats.observations_in, 2); + assert_eq!(report.curate_stats.observations_dropped_unmapped, 1); + + assert_eq!(report.filings_docs_framed, 4); + assert_eq!(report.filings_bytes_read, fil_bytes.len() as u64); + assert_eq!(report.filings_decode.rows_out, 3); + assert_eq!(report.filings_decode.skipped_missing_key, 1); + assert_eq!(report.curate_stats.filings_in, 3); + assert_eq!(report.curate_stats.filings_dropped_unmapped, 1); + assert_eq!(report.curate_stats.filings_dropped_invalid_timestamp, 1); + + assert_eq!(report.curate_stats.rows_out, 1); + assert_eq!(report.write_stats.rows_written, 1); + + let formatted = format_curate_fundamentals_report(&report); + for section in [ + "curate-etl curate-fundamentals", + "financials_bson:", + "filings_bson:", + "builder:", + "curate:", + "write:", + "years:", + "timing:", + "2024=1", + ] { + assert!( + formatted.contains(section), + "formatted report missing '{section}':\n{formatted}" + ); + } +} + +#[test] +fn fundamentals_failures_preserve_output_tree() { + let tmp = TempDirGuard::new("fail-closed"); + let valid_fin = tmp.path().join("valid_fin.bson"); + let valid_fil = tmp.path().join("valid_fil.bson"); + let valid_map = tmp.path().join("valid_map.tsv"); + let valid_venues = tmp.path().join("valid_venues.tsv"); + + fs::write(&valid_map, "qm\tNVDA\t2020-01-01\t\t101\n").unwrap(); + fs::write(&valid_venues, "101\tus_tsx\n").unwrap(); + let fin_doc = make_financials_doc( + Some("NVDA"), + "2024-03-31", + Some("2024-05-01"), + "Q1", + "USD", + FundamentalsFields { + revenue: Some(100.0), + ..Default::default() + }, + ); + let fil_doc = make_filing_doc( + Some("NVDA"), + "2024-05-01T16:10:00 EDT", + "10-Q", + Some("f1"), + None, + ); + fs::write(&valid_fin, &fin_doc).unwrap(); + fs::write(&valid_fil, &fil_doc).unwrap(); + + // Seed a pre-existing partition in out_existing so we verify byte-for-byte preservation. + let out_existing = tmp.path().join("out_existing"); + let seed_args = default_test_args( + valid_fin.clone(), + valid_fil.clone(), + valid_map.clone(), + valid_venues.clone(), + out_existing.clone(), + ); + run_curate_fundamentals(&seed_args).expect("seed existing output"); + let existing_before = snapshot_tree(&out_existing); + assert!(existing_before.len() >= 3); + + // Also test against a missing output directory that must remain absent. + let out_missing = tmp.path().join("out_missing"); + assert!(!out_missing.exists()); + + let assert_preserved = |out_dir: &Path, expected: &BTreeMap| { + assert_eq!( + &snapshot_tree(out_dir), + expected, + "output tree {} was mutated on failure", + out_dir.display() + ); + }; + + for (out_dir, before) in [ + (out_existing.as_path(), existing_before.clone()), + (out_missing.as_path(), BTreeMap::new()), + ] { + let base = || { + default_test_args( + valid_fin.clone(), + valid_fil.clone(), + valid_map.clone(), + valid_venues.clone(), + out_dir.to_path_buf(), + ) + }; + + // 1. Invalid financials field path + let mut a = base(); + a.financials_revenue_field = Some("IncomeStatement..revenue".to_string()); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::InvalidFinancialsConfig { ref path, .. } + if path == &valid_fin + )); + assert!(err.to_string().contains(&valid_fin.display().to_string())); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + // 2. Invalid filings field name + let mut a = base(); + a.filings_form_type_field = " ".to_string(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::InvalidFilingsFieldNames { ref path, .. } + if path == &valid_fil + )); + assert!(err.to_string().contains(&valid_fil.display().to_string())); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + // 3. Invalid fiscal policy (blank token & overlapping tokens) + let mut a = base(); + a.fiscal_period = CurateFundamentalsFiscalPeriod::ByTokens { + quarterly: vec!["Q1".to_string(), " ".to_string()], + annual: vec!["FY".to_string()], + }; + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::InvalidFinancialsConfig { ref path, .. } + if path == &valid_fin + )); + assert!(err.to_string().contains(&valid_fin.display().to_string())); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + let mut a = base(); + a.fiscal_period = CurateFundamentalsFiscalPeriod::ByTokens { + quarterly: vec!["FY".to_string()], + annual: vec!["FY".to_string()], + }; + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::InvalidFinancialsConfig { ref path, .. } + if path == &valid_fin + )); + assert!(err.to_string().contains(&valid_fin.display().to_string())); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + // 4. Blank mapping source + let mut a = base(); + a.mapping_source = " \t ".to_string(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::EmptyMappingSource + )); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + // 5. Zero k + let mut a = base(); + a.k = 0; + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::InvalidPeriodLimit { k: 0 } + )); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + // 6. Unreadable / missing files for all four inputs + let missing_fin = tmp.path().join("no_such_fin.bson"); + let mut a = base(); + a.qm_financials = missing_fin.clone(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::OpenInput { + label: "qm-financials", + ref path, + .. + } if path == &missing_fin + )); + assert!(err.to_string().contains(&missing_fin.display().to_string())); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + let missing_fil = tmp.path().join("no_such_fil.bson"); + let mut a = base(); + a.qm_filings = missing_fil.clone(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::OpenInput { + label: "qm-filings", + ref path, + .. + } if path == &missing_fil + )); + assert!(err.to_string().contains(&missing_fil.display().to_string())); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + let missing_map = tmp.path().join("no_such_map.tsv"); + let mut a = base(); + a.provider_mapping = missing_map.clone(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::OpenInput { ref path, .. } if path == &missing_map + )); + assert!(err.to_string().contains(&missing_map.display().to_string())); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + let missing_venues = tmp.path().join("no_such_venues.tsv"); + let mut a = base(); + a.listing_venues = missing_venues.clone(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::OpenInput { + label: "listing-venues", + ref path, + .. + } if path == &missing_venues + )); + assert!(err.to_string().contains(&missing_venues.display().to_string())); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + // 7. Injected BSON read failures for both readers + struct FailingReader; + impl Read for FailingReader { + fn read(&mut self, _buf: &mut [u8]) -> io::Result { + Err(io::Error::new(io::ErrorKind::BrokenPipe, "synthetic read failure")) + } + } + let a = base(); + let err = run_curate_fundamentals_with_readers( + &a, + FailingReader, + Cursor::new(fil_doc.as_slice()), + ) + .unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::BsonStream { + label: "qm-financials", + ref path, + source: BsonStreamError::Io { offset: 0, .. }, + } if path == &valid_fin + )); + assert!(err.source().is_some()); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + let err = run_curate_fundamentals_with_readers( + &a, + Cursor::new(fin_doc.as_slice()), + FailingReader, + ) + .unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::BsonStream { + label: "qm-filings", + ref path, + source: BsonStreamError::Io { offset: 0, .. }, + } if path == &valid_fil + )); + assert!(err.source().is_some()); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + // 8. Malformed mapping TSV + let bad_map = tmp.path().join("bad_map.tsv"); + fs::write(&bad_map, "qm\tNVDA\t2020-01-01\t\t101\nbad_line_only_one_col\n").unwrap(); + let mut a = base(); + a.provider_mapping = bad_map.clone(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::TsvParse { + ref path, + line: 2, + .. + } if path == &bad_map + )); + assert!(err.to_string().contains(&format!("{}:2:", bad_map.display()))); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + // 9. Malformed venue TSV + let bad_venues = tmp.path().join("bad_venues.tsv"); + fs::write(&bad_venues, "101\tus_tsx\n202\tunknown_exchange\n").unwrap(); + let mut a = base(); + a.listing_venues = bad_venues.clone(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::TsvParse { + ref path, + line: 2, + .. + } if path == &bad_venues + )); + assert!(err.to_string().contains(&format!("{}:2:", bad_venues.display()))); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + // 10. Mapping range conflict + let conflict_map = tmp.path().join("conflict_map.tsv"); + fs::write( + &conflict_map, + "qm\tNVDA\t2020-01-01\t2024-06-01\t101\nqm\tNVDA\t2024-06-01\t\t102\n", + ) + .unwrap(); + let mut a = base(); + a.provider_mapping = conflict_map.clone(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::ProviderMapping { + ref path, + source: ProviderMappingError::OverlappingRanges { .. }, + } if path == &conflict_map + )); + assert!(err.to_string().contains(&conflict_map.display().to_string())); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + // 11. Truncated BSON in financials and filings + let trunc_fin = tmp.path().join("trunc_fin.bson"); + let mut trunc_fin_bytes = fin_doc.clone(); + trunc_fin_bytes.extend_from_slice(&fin_doc[..10]); + fs::write(&trunc_fin, &trunc_fin_bytes).unwrap(); + let mut a = base(); + a.qm_financials = trunc_fin.clone(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::BsonStream { + label: "qm-financials", + ref path, + source: BsonStreamError::TruncatedDocument { offset, .. }, + } if path == &trunc_fin && offset == fin_doc.len() as u64 + )); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + let trunc_fil = tmp.path().join("trunc_fil.bson"); + let mut trunc_fil_bytes = fil_doc.clone(); + trunc_fil_bytes.extend_from_slice(&fil_doc[..7]); + fs::write(&trunc_fil, &trunc_fil_bytes).unwrap(); + let mut a = base(); + a.qm_filings = trunc_fil.clone(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::BsonStream { + label: "qm-filings", + ref path, + source: BsonStreamError::TruncatedDocument { offset, .. }, + } if path == &trunc_fil && offset == fil_doc.len() as u64 + )); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + // 12. Corrupt BSON in financials and filings (valid framing, invalid element tag) + let corrupt_fin = tmp.path().join("corrupt_fin.bson"); + let mut bad_fin_doc = fin_doc.clone(); + bad_fin_doc[4] = 0x7E; + let mut corrupt_fin_bytes = fin_doc.clone(); + let expected_fin_off = corrupt_fin_bytes.len() as u64; + corrupt_fin_bytes.extend_from_slice(&bad_fin_doc); + fs::write(&corrupt_fin, &corrupt_fin_bytes).unwrap(); + let mut a = base(); + a.qm_financials = corrupt_fin.clone(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::CorruptFinancialsBson { + ref path, + offset, + .. + } if path == &corrupt_fin && offset == expected_fin_off + )); + assert!(err.to_string().contains(&expected_fin_off.to_string())); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + let corrupt_fil = tmp.path().join("corrupt_fil.bson"); + let mut bad_fil_doc = fil_doc.clone(); + bad_fil_doc[4] = 0x7E; + let mut corrupt_fil_bytes = fil_doc.clone(); + let expected_fil_off = corrupt_fil_bytes.len() as u64; + corrupt_fil_bytes.extend_from_slice(&bad_fil_doc); + fs::write(&corrupt_fil, &corrupt_fil_bytes).unwrap(); + let mut a = base(); + a.qm_filings = corrupt_fil.clone(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::CorruptFilingsBson { + ref path, + offset, + .. + } if path == &corrupt_fil && offset == expected_fil_off + )); + assert!(err.to_string().contains(&expected_fil_off.to_string())); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + } +} + +#[test] +fn fundamentals_rejects_output_files_and_input_aliases() { + let tmp = TempDirGuard::new("path-safety"); + let valid_fin = tmp.path().join("fin.bson"); + let valid_fil = tmp.path().join("fil.bson"); + let valid_map = tmp.path().join("map.tsv"); + let valid_venues = tmp.path().join("venues.tsv"); + + let fin_bytes = make_financials_doc( + Some("NVDA"), + "2024-03-31", + Some("2024-05-01"), + "Q1", + "USD", + FundamentalsFields { + revenue: Some(100.0), + ..Default::default() + }, + ); + let fil_bytes = make_filing_doc( + Some("NVDA"), + "2024-05-01T16:10:00 EDT", + "10-Q", + Some("f1"), + None, + ); + fs::write(&valid_fin, &fin_bytes).unwrap(); + fs::write(&valid_fil, &fil_bytes).unwrap(); + fs::write(&valid_map, "qm\tNVDA\t2020-01-01\t\t101\n").unwrap(); + fs::write(&valid_venues, "101\tus_tsx\n").unwrap(); + + // 1. Regular file at out_dir + let file_as_out = tmp.path().join("out_is_file"); + let sentinel = b"do-not-overwrite-out-file".to_vec(); + fs::write(&file_as_out, &sentinel).unwrap(); + let args = default_test_args( + valid_fin.clone(), + valid_fil.clone(), + valid_map.clone(), + valid_venues.clone(), + file_as_out.clone(), + ); + assert!(matches!( + run_curate_fundamentals(&args).unwrap_err(), + RunCurateFundamentalsError::InvalidOutDir { .. } + )); + assert!(matches!( + run_curate_fundamentals_with_readers( + &args, + Cursor::new(fin_bytes.as_slice()), + Cursor::new(fil_bytes.as_slice()), + ) + .unwrap_err(), + RunCurateFundamentalsError::InvalidOutDir { .. } + )); + assert_eq!(fs::read(&file_as_out).unwrap(), sentinel); + + // 2. Regular file at /fundamentals_pit + let out_with_file = tmp.path().join("out_with_dataset_file"); + fs::create_dir_all(&out_with_file).unwrap(); + let dataset_file = out_with_file.join("fundamentals_pit"); + fs::write(&dataset_file, b"dataset-file-sentinel").unwrap(); + let before = snapshot_tree(&out_with_file); + let args = default_test_args( + valid_fin.clone(), + valid_fil.clone(), + valid_map.clone(), + valid_venues.clone(), + out_with_file.clone(), + ); + assert!(matches!( + run_curate_fundamentals(&args).unwrap_err(), + RunCurateFundamentalsError::InvalidOutDir { .. } + )); + assert!(matches!( + run_curate_fundamentals_with_readers( + &args, + Cursor::new(fin_bytes.as_slice()), + Cursor::new(fil_bytes.as_slice()), + ) + .unwrap_err(), + RunCurateFundamentalsError::InvalidOutDir { .. } + )); + assert_eq!(snapshot_tree(&out_with_file), before); + + // 3. All four inputs resolving to out_dir or inside /fundamentals_pit + let alias_out = tmp.path().join("alias_out"); + let inside_ds = alias_out.join("fundamentals_pit").join("year=2024"); + fs::create_dir_all(&inside_ds).unwrap(); + let inside_fin = inside_ds.join("fin.bson"); + let inside_fil = inside_ds.join("fil.bson"); + let inside_map = inside_ds.join("map.tsv"); + let inside_venues = inside_ds.join("venues.tsv"); + fs::write(&inside_fin, &fin_bytes).unwrap(); + fs::write(&inside_fil, &fil_bytes).unwrap(); + fs::write(&inside_map, "qm\tNVDA\t2020-01-01\t\t101\n").unwrap(); + fs::write(&inside_venues, "101\tus_tsx\n").unwrap(); + let alias_before = snapshot_tree(&alias_out); + + for bad_args in [ + default_test_args( + inside_fin.clone(), + valid_fil.clone(), + valid_map.clone(), + valid_venues.clone(), + alias_out.clone(), + ), + default_test_args( + valid_fin.clone(), + inside_fil.clone(), + valid_map.clone(), + valid_venues.clone(), + alias_out.clone(), + ), + default_test_args( + valid_fin.clone(), + valid_fil.clone(), + inside_map.clone(), + valid_venues.clone(), + alias_out.clone(), + ), + default_test_args( + valid_fin.clone(), + valid_fil.clone(), + valid_map.clone(), + inside_venues.clone(), + alias_out.clone(), + ), + // Input equal to out_dir itself + default_test_args( + alias_out.clone(), + valid_fil.clone(), + valid_map.clone(), + valid_venues.clone(), + alias_out.clone(), + ), + ] { + assert!(matches!( + run_curate_fundamentals(&bad_args).unwrap_err(), + RunCurateFundamentalsError::InvalidOutDir { .. } + )); + assert!(matches!( + run_curate_fundamentals_with_readers( + &bad_args, + Cursor::new(fin_bytes.as_slice()), + Cursor::new(fil_bytes.as_slice()), + ) + .unwrap_err(), + RunCurateFundamentalsError::InvalidOutDir { .. } + )); + assert_eq!(snapshot_tree(&alias_out), alias_before); + } + + // 4. Unix symlink-before-`..` resolution and symlinked year=2024 partition aliasing an external input + #[cfg(unix)] + { + use std::os::unix::fs::symlink; + + // Symlink-before-`..`: link_dir -> real_parent/child; link_dir/../out_target resolves to + // real_parent/out_target (NOT tmp/out_target). + let real_parent = tmp.path().join("real_parent"); + let real_child = real_parent.join("child"); + fs::create_dir_all(&real_child).unwrap(); + let real_out = real_parent.join("out_target"); + let real_ds = real_out.join("fundamentals_pit"); + fs::create_dir_all(&real_ds).unwrap(); + let ext_input = real_ds.join("aliased_fin.bson"); + fs::write(&ext_input, &fin_bytes).unwrap(); + let ext_before = fs::read(&ext_input).unwrap(); + let real_out_before = snapshot_tree(&real_out); + + let link_dir = tmp.path().join("link_dir"); + symlink(&real_child, &link_dir).unwrap(); + let symlink_dotdot_out = link_dir.join("..").join("out_target"); + + let args = default_test_args( + ext_input.clone(), + valid_fil.clone(), + valid_map.clone(), + valid_venues.clone(), + symlink_dotdot_out, + ); + assert!(matches!( + run_curate_fundamentals(&args).unwrap_err(), + RunCurateFundamentalsError::InvalidOutDir { .. } + )); + assert!(matches!( + run_curate_fundamentals_with_readers( + &args, + Cursor::new(fin_bytes.as_slice()), + Cursor::new(fil_bytes.as_slice()), + ) + .unwrap_err(), + RunCurateFundamentalsError::InvalidOutDir { .. } + )); + assert_eq!(snapshot_tree(&real_out), real_out_before); + assert_eq!(fs::read(&ext_input).unwrap(), ext_before); + + // Symlinked year=2024 partition pointing to external dir containing an input file. + let ext_dir = tmp.path().join("external_year_target"); + fs::create_dir_all(&ext_dir).unwrap(); + let ext_part_input = ext_dir.join("part.parquet"); + fs::write(&ext_part_input, &fin_bytes).unwrap(); + let ext_part_before = fs::read(&ext_part_input).unwrap(); + + let sym_out = tmp.path().join("sym_year_out"); + let sym_ds = sym_out.join("fundamentals_pit"); + fs::create_dir_all(&sym_ds).unwrap(); + symlink(&ext_dir, sym_ds.join("year=2024")).unwrap(); + let sym_out_before = snapshot_tree(&sym_out); + + let args = default_test_args( + ext_part_input.clone(), + valid_fil.clone(), + valid_map.clone(), + valid_venues.clone(), + sym_out.clone(), + ); + assert!(matches!( + run_curate_fundamentals(&args).unwrap_err(), + RunCurateFundamentalsError::InvalidOutDir { .. } + )); + assert!(matches!( + run_curate_fundamentals_with_readers( + &args, + Cursor::new(fin_bytes.as_slice()), + Cursor::new(fil_bytes.as_slice()), + ) + .unwrap_err(), + RunCurateFundamentalsError::InvalidOutDir { .. } + )); + assert_eq!(snapshot_tree(&sym_out), sym_out_before); + assert_eq!(fs::read(&ext_part_input).unwrap(), ext_part_before); + } +} + +#[cfg(unix)] +#[test] +fn fundamentals_rejects_aliased_year_partitions() { + use std::os::unix::fs::symlink; + + let tmp = TempDirGuard::new("aliased-years"); + let map_path = tmp.path().join("map.tsv"); + let venues_path = tmp.path().join("venues.tsv"); + fs::write(&map_path, "qm\tNVDA\t2020-01-01\t\t101\n").unwrap(); + fs::write(&venues_path, "101\tus_tsx\n").unwrap(); + + // Seed a valid 2023 partition in a shared target directory. + let fin_2023 = tmp.path().join("fin_2023.bson"); + let fil_2023 = tmp.path().join("fil_2023.bson"); + fs::write( + &fin_2023, + make_financials_doc( + Some("NVDA"), + "2023-03-31", + Some("2023-05-01"), + "Q1", + "USD", + FundamentalsFields { + revenue: Some(80.0), + ..Default::default() + }, + ), + ) + .unwrap(); + fs::write( + &fil_2023, + make_filing_doc( + Some("NVDA"), + "2023-05-01T16:10:00 EDT", + "10-Q", + Some("f2023"), + None, + ), + ) + .unwrap(); + + let seed_out = tmp.path().join("seed_out"); + let seed_args = default_test_args( + fin_2023, + fil_2023, + map_path.clone(), + venues_path.clone(), + seed_out.clone(), + ); + let seed_report = run_curate_fundamentals(&seed_args).expect("seed 2023 partition"); + assert_eq!(seed_report.write_stats.rows_written, 1); + + let shared_target = tmp.path().join("shared_archive"); + fs::create_dir_all(&shared_target).unwrap(); + let seeded_part = seed_out + .join("fundamentals_pit") + .join("year=2023") + .join("part.parquet"); + let shared_part = shared_target.join("part.parquet"); + fs::copy(&seeded_part, &shared_part).unwrap(); + let shared_target_before = snapshot_tree(&shared_target); + let shared_part_bytes_before = fs::read(&shared_part).unwrap(); + + // Point both year=2023 and year=2024 at the same shared target directory. + let aliased_out = tmp.path().join("aliased_out"); + let aliased_ds = aliased_out.join("fundamentals_pit"); + fs::create_dir_all(&aliased_ds).unwrap(); + symlink(&shared_target, aliased_ds.join("year=2023")).unwrap(); + symlink(&shared_target, aliased_ds.join("year=2024")).unwrap(); + let aliased_out_before = snapshot_tree(&aliased_out); + + // Prepare a 2024-only rerun that would overwrite 2023's part.parquet if allowed. + let fin_2024 = tmp.path().join("fin_2024.bson"); + let fil_2024 = tmp.path().join("fil_2024.bson"); + let fin_2024_bytes = make_financials_doc( + Some("NVDA"), + "2024-03-31", + Some("2024-05-01"), + "Q1", + "USD", + FundamentalsFields { + revenue: Some(120.0), + ..Default::default() + }, + ); + let fil_2024_bytes = make_filing_doc( + Some("NVDA"), + "2024-05-01T16:10:00 EDT", + "10-Q", + Some("f2024"), + None, + ); + fs::write(&fin_2024, &fin_2024_bytes).unwrap(); + fs::write(&fil_2024, &fil_2024_bytes).unwrap(); + + let rerun_args = default_test_args( + fin_2024.clone(), + fil_2024.clone(), + map_path.clone(), + venues_path.clone(), + aliased_out.clone(), + ); + + let err_file = run_curate_fundamentals(&rerun_args).unwrap_err(); + assert!(matches!( + err_file, + RunCurateFundamentalsError::InvalidOutDir { .. } + )); + let msg_file = err_file.to_string(); + assert_single_line(&msg_file); + assert!(msg_file.contains("year=2024") && msg_file.contains("year=2023")); + assert_eq!(snapshot_tree(&aliased_out), aliased_out_before); + assert_eq!(snapshot_tree(&shared_target), shared_target_before); + assert_eq!(fs::read(&shared_part).unwrap(), shared_part_bytes_before); + + let err_reader = run_curate_fundamentals_with_readers( + &rerun_args, + Cursor::new(fin_2024_bytes.as_slice()), + Cursor::new(fil_2024_bytes.as_slice()), + ) + .unwrap_err(); + assert!(matches!( + err_reader, + RunCurateFundamentalsError::InvalidOutDir { .. } + )); + assert_single_line(&err_reader.to_string()); + assert_eq!(snapshot_tree(&aliased_out), aliased_out_before); + assert_eq!(snapshot_tree(&shared_target), shared_target_before); + assert_eq!(fs::read(&shared_part).unwrap(), shared_part_bytes_before); +} + +#[cfg(unix)] +#[test] +fn fundamentals_rejects_dangling_year_symlink() { + use std::os::unix::fs::symlink; + + let tmp = TempDirGuard::new("dangling-year-symlink"); + let map_path = tmp.path().join("map.tsv"); + let venues_path = tmp.path().join("venues.tsv"); + fs::write(&map_path, "qm\tNVDA\t2020-01-01\t\t101\n").unwrap(); + fs::write(&venues_path, "101\tus_tsx\n").unwrap(); + + // Two-year backfill with 2023 and 2024 snapshots for the same listing. + let mut fin_bytes = make_financials_doc( + Some("NVDA"), + "2023-03-31", + Some("2023-05-01"), + "Q1", + "USD", + FundamentalsFields { + revenue: Some(80.0), + ..Default::default() + }, + ); + fin_bytes.extend_from_slice(&make_financials_doc( + Some("NVDA"), + "2024-03-31", + Some("2024-05-01"), + "Q1", + "USD", + FundamentalsFields { + revenue: Some(120.0), + ..Default::default() + }, + )); + + let mut fil_bytes = make_filing_doc( + Some("NVDA"), + "2023-05-01T16:10:00 EDT", + "10-Q", + Some("f2023"), + None, + ); + fil_bytes.extend_from_slice(&make_filing_doc( + Some("NVDA"), + "2024-05-01T16:10:00 EDT", + "10-Q", + Some("f2024"), + None, + )); + + let fin_path = tmp.path().join("fin_backfill.bson"); + let fil_path = tmp.path().join("fil_backfill.bson"); + fs::write(&fin_path, &fin_bytes).unwrap(); + fs::write(&fil_path, &fil_bytes).unwrap(); + + // Stale year=2024 symlink pointing to the not-yet-created year=2023 directory. + let dangling_out = tmp.path().join("dangling_out"); + let dangling_ds = dangling_out.join("fundamentals_pit"); + fs::create_dir_all(&dangling_ds).unwrap(); + let dangling_link = dangling_ds.join("year=2024"); + symlink(Path::new("year=2023"), &dangling_link).unwrap(); + let before = snapshot_tree(&dangling_out); + + let args = default_test_args( + fin_path, + fil_path, + map_path, + venues_path, + dangling_out.clone(), + ); + + let err_file = run_curate_fundamentals(&args).unwrap_err(); + assert!(matches!( + err_file, + RunCurateFundamentalsError::InvalidOutDir { ref path, .. } if path == &dangling_link + )); + let msg_file = err_file.to_string(); + assert_single_line(&msg_file); + assert!(msg_file.contains("year=2024")); + assert_eq!(snapshot_tree(&dangling_out), before); + + let err_reader = run_curate_fundamentals_with_readers( + &args, + Cursor::new(fin_bytes.as_slice()), + Cursor::new(fil_bytes.as_slice()), + ) + .unwrap_err(); + assert!(matches!( + err_reader, + RunCurateFundamentalsError::InvalidOutDir { ref path, .. } if path == &dangling_link + )); + let msg_reader = err_reader.to_string(); + assert_single_line(&msg_reader); + assert!(msg_reader.contains("year=2024")); + assert_eq!(snapshot_tree(&dangling_out), before); +} + +#[test] +fn fundamentals_empty_inputs_publish_nothing() { + let tmp = TempDirGuard::new("empty"); + let fin_path = tmp.path().join("empty_fin.bson"); + let fil_path = tmp.path().join("empty_fil.bson"); + let map_path = tmp.path().join("map.tsv"); + let venues_path = tmp.path().join("venues.tsv"); + fs::write(&fin_path, []).unwrap(); + fs::write(&fil_path, []).unwrap(); + fs::write(&map_path, "qm\tNVDA\t2020-01-01\t\t101\n").unwrap(); + fs::write(&venues_path, "101\tus_tsx\n").unwrap(); + + // Fresh output directory: dataset directory must not be created. + let fresh_out = tmp.path().join("fresh_out"); + let args = default_test_args( + fin_path.clone(), + fil_path.clone(), + map_path.clone(), + venues_path.clone(), + fresh_out.clone(), + ); + let report = run_curate_fundamentals(&args).unwrap(); + assert_conservation(&report); + assert_eq!(report.write_stats.rows_written, 0); + assert_eq!(report.write_stats.files_written, 0); + assert!(!fresh_out.join("fundamentals_pit").exists()); + + // Pre-existing partition: rerun with empty inputs must leave it byte-identical. + let seeded_out = tmp.path().join("seeded_out"); + let seed_fin = tmp.path().join("seed_fin.bson"); + fs::write( + &seed_fin, + make_financials_doc( + Some("NVDA"), + "2024-03-31", + None, + "Q1", + "USD", + FundamentalsFields { + revenue: Some(50.0), + ..Default::default() + }, + ), + ) + .unwrap(); + let seed_args = default_test_args( + seed_fin, + fil_path.clone(), + map_path.clone(), + venues_path.clone(), + seeded_out.clone(), + ); + run_curate_fundamentals(&seed_args).unwrap(); + let before = snapshot_tree(&seeded_out); + + let empty_rerun = default_test_args(fin_path, fil_path, map_path, venues_path, seeded_out.clone()); + let rerun_report = run_curate_fundamentals(&empty_rerun).unwrap(); + assert_eq!(rerun_report.write_stats.rows_written, 0); + assert_eq!(rerun_report.write_stats.files_written, 0); + assert_eq!(snapshot_tree(&seeded_out), before); +} + +#[test] +fn fundamentals_all_unmapped_publish_nothing() { + let tmp = TempDirGuard::new("unmapped"); + let fin_path = tmp.path().join("unmapped_fin.bson"); + let fil_path = tmp.path().join("unmapped_fil.bson"); + let map_path = tmp.path().join("map.tsv"); + let venues_path = tmp.path().join("venues.tsv"); + + fs::write(&map_path, "qm\tKNOWN\t2020-01-01\t\t101\n").unwrap(); + fs::write(&venues_path, "101\tus_tsx\n").unwrap(); + fs::write( + &fin_path, + make_financials_doc( + Some("OTHER"), + "2024-03-31", + Some("2024-05-01"), + "Q1", + "USD", + FundamentalsFields { + revenue: Some(10.0), + ..Default::default() + }, + ), + ) + .unwrap(); + fs::write( + &fil_path, + make_filing_doc( + Some("OTHER"), + "2024-05-01T16:10:00 EDT", + "10-Q", + Some("f1"), + None, + ), + ) + .unwrap(); + + // Fresh output directory: dataset directory must not be created. + let fresh_out = tmp.path().join("fresh_out"); + let args = default_test_args( + fin_path.clone(), + fil_path.clone(), + map_path.clone(), + venues_path.clone(), + fresh_out.clone(), + ); + let report = run_curate_fundamentals(&args).unwrap(); + assert_conservation(&report); + assert_eq!(report.curate_stats.observations_in, 1); + assert_eq!(report.curate_stats.observations_dropped_unmapped, 1); + assert_eq!(report.write_stats.rows_written, 0); + assert_eq!(report.write_stats.files_written, 0); + assert!(!fresh_out.join("fundamentals_pit").exists()); + + // Pre-existing partition: rerun with all-unmapped inputs leaves it byte-identical. + let seeded_out = tmp.path().join("seeded_out"); + let seed_fin = tmp.path().join("seed_fin.bson"); + fs::write( + &seed_fin, + make_financials_doc( + Some("KNOWN"), + "2024-03-31", + None, + "Q1", + "USD", + FundamentalsFields { + revenue: Some(50.0), + ..Default::default() + }, + ), + ) + .unwrap(); + run_curate_fundamentals(&default_test_args( + seed_fin, + fil_path.clone(), + map_path.clone(), + venues_path.clone(), + seeded_out.clone(), + )) + .unwrap(); + let before = snapshot_tree(&seeded_out); + + let rerun = run_curate_fundamentals(&default_test_args( + fin_path, + fil_path, + map_path, + venues_path, + seeded_out.clone(), + )) + .unwrap(); + assert_eq!(rerun.write_stats.rows_written, 0); + assert_eq!(rerun.write_stats.files_written, 0); + assert_eq!(snapshot_tree(&seeded_out), before); +} + +#[test] +fn listing_venues_rejects_wrong_column_count() { + let tmp = TempDirGuard::new("venues-cols"); + let path = tmp.path().join("listing_venues.tsv"); + fs::write(&path, "101\tus_tsx\n202\n").unwrap(); + let err = load_listing_venues_tsv(&path).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::TsvParse { + path: ref p, + line: 2, + .. + } if p == &path + )); + let msg = err.to_string(); + assert!(msg.contains(&format!("{}:2:", path.display()))); + assert_single_line(&msg); + + // Too many columns (3 columns on line 2) + fs::write(&path, "101\tus_tsx\r\n202\ttsxv_cse\textra\r\n").unwrap(); + let err = load_listing_venues_tsv(&path).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::TsvParse { + path: ref p, + line: 2, + .. + } if p == &path + )); + let msg = err.to_string(); + assert!(msg.contains(&format!("{}:2:", path.display()))); + assert_single_line(&msg); +} + +#[test] +fn listing_venues_rejects_non_integer_id() { + let tmp = TempDirGuard::new("venues-non-int"); + let path = tmp.path().join("listing_venues.tsv"); + fs::write(&path, "101\tus_tsx\nabc\ttsxv_cse\n").unwrap(); + let err = load_listing_venues_tsv(&path).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::TsvParse { + path: ref p, + line: 2, + .. + } if p == &path + )); + let msg = err.to_string(); + assert!(msg.contains(&format!("{}:2:", path.display()))); + assert_single_line(&msg); +} + +#[test] +fn listing_venues_rejects_non_positive_id() { + let tmp = TempDirGuard::new("venues-non-pos"); + let path = tmp.path().join("listing_venues.tsv"); + for (content, expected_line) in [ + ("101\tus_tsx\n0\ttsxv_cse\n", 2), + ("101\tus_tsx\n202\ttsxv_cse\n-5\tus_tsx\n", 3), + ] { + fs::write(&path, content).unwrap(); + let err = load_listing_venues_tsv(&path).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::TsvParse { + path: ref p, + line, + .. + } if p == &path && line == expected_line + )); + let msg = err.to_string(); + assert!(msg.contains(&format!("{}:{expected_line}:", path.display()))); + assert_single_line(&msg); + } +} + +#[test] +fn listing_venues_rejects_unknown_venue() { + let tmp = TempDirGuard::new("venues-unknown"); + let path = tmp.path().join("listing_venues.tsv"); + fs::write(&path, "101\tus_tsx\n202\tUS_TSX\n").unwrap(); + let err = load_listing_venues_tsv(&path).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::TsvParse { + path: ref p, + line: 2, + .. + } if p == &path + )); + let msg = err.to_string(); + assert!(msg.contains(&format!("{}:2:", path.display()))); + assert_single_line(&msg); +} + +#[test] +fn listing_venues_rejects_duplicate_id() { + let tmp = TempDirGuard::new("venues-dup"); + let path = tmp.path().join("listing_venues.tsv"); + fs::write(&path, "101\tus_tsx\n202\ttsxv_cse\n101\ttsxv_cse\n").unwrap(); + let err = load_listing_venues_tsv(&path).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::TsvParse { + path: ref p, + line: 3, + .. + } if p == &path + )); + let msg = err.to_string(); + assert!(msg.contains(&format!("{}:3:", path.display()))); + assert_single_line(&msg); +} + +#[test] +fn listing_venues_rejects_interior_blank() { + let tmp = TempDirGuard::new("venues-blank"); + let path = tmp.path().join("listing_venues.tsv"); + fs::write(&path, "101\tus_tsx\n\n202\ttsxv_cse\n").unwrap(); + let err = load_listing_venues_tsv(&path).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::TsvParse { + path: ref p, + line: 2, + .. + } if p == &path + )); + let msg = err.to_string(); + assert!(msg.contains(&format!("{}:2:", path.display()))); + assert_single_line(&msg); +} + +// --------------------------------------------------------------------------------------------- +// QA additions (T-171): replay determinism, missing-venue fail-closed drop, regular-file year +// entry, and strict venue-token parsing edge cases. +// --------------------------------------------------------------------------------------------- + +fn write_qa_replay_fixture(dir: &Path) -> (PathBuf, PathBuf, PathBuf, PathBuf) { + let fin_path = dir.join("qmFinancials.bson"); + let fil_path = dir.join("qmFilings.bson"); + let map_path = dir.join("provider_mapping.tsv"); + let venues_path = dir.join("listing_venues.tsv"); + fs::write( + &map_path, + "qm\tNVDA\t2020-01-01\t\t101\nqm\tMINE:V\t2020-01-01\t\t202\n", + ) + .unwrap(); + fs::write(&venues_path, "101\tus_tsx\n202\ttsxv_cse\n").unwrap(); + + let mut fin = Vec::new(); + for (end, rd, period, rev) in [ + ("2023-09-30", "2023-11-04", "Q3", 120.0), + ("2023-12-31", "2024-02-10", "Q4", 130.0), + ("2024-03-31", "2024-05-02", "Q1", 140.0), + ] { + fin.extend_from_slice(&make_financials_doc( + Some("NVDA"), + end, + Some(rd), + period, + "USD", + FundamentalsFields { + revenue: Some(rev), + net_income: Some(rev / 5.0), + total_assets: Some(1000.0), + ..Default::default() + }, + )); + } + fin.extend_from_slice(&make_financials_doc( + Some("MINE:V"), + "2024-06-30", + None, + "Q2", + "CAD", + FundamentalsFields { + revenue: Some(5.0), + ..Default::default() + }, + )); + fs::write(&fin_path, &fin).unwrap(); + + let mut fil = Vec::new(); + for (ts, id) in [ + ("2023-11-04T16:30:00 EDT", "f-q3"), + ("2024-02-10T16:05:00 EST", "f-q4"), + ("2024-05-02T16:15:00 EDT", "f-q1"), + ] { + fil.extend_from_slice(&make_filing_doc(Some("NVDA"), ts, "10-Q", Some(id), None)); + } + fs::write(&fil_path, &fil).unwrap(); + (fin_path, fil_path, map_path, venues_path) +} + +#[test] +fn fundamentals_rerun_same_inputs_is_byte_identical() { + // Arrange: one pinned fixture, two fresh output roots. + let tmp = TempDirGuard::new("qa-replay"); + let (fin, fil, map, venues) = write_qa_replay_fixture(tmp.path()); + let out_a = tmp.path().join("out_a"); + let out_b = tmp.path().join("out_b"); + + // Act: file API into A, injected-reader API into B. + let report_a = run_curate_fundamentals(&default_test_args( + fin.clone(), + fil.clone(), + map.clone(), + venues.clone(), + out_a.clone(), + )) + .unwrap(); + let report_b = run_curate_fundamentals_with_readers( + &default_test_args(fin.clone(), fil.clone(), map, venues, out_b.clone()), + File::open(&fin).unwrap(), + File::open(&fil).unwrap(), + ) + .unwrap(); + + // Assert: identical counters and byte-identical Parquet partitions. + assert_conservation(&report_a); + assert_reports_eq_ignoring_timing(&report_a, &report_b); + assert!(report_a.write_stats.rows_written > 0); + let tree_a = snapshot_tree(&out_a.join("fundamentals_pit")); + let tree_b = snapshot_tree(&out_b.join("fundamentals_pit")); + assert!(!tree_a.is_empty()); + assert_eq!(tree_a, tree_b, "replay must produce byte-identical partitions"); + // No staging/backup leftovers after a successful publish. + for path in tree_a.keys() { + let name = path.to_string_lossy(); + assert!( + !name.ends_with(".tmp") && !name.contains(".bak"), + "unexpected leftover {name}" + ); + } +} + +#[test] +fn fundamentals_rerun_into_existing_output_replaces_partitions_identically() { + // Arrange + let tmp = TempDirGuard::new("qa-rerun-same-out"); + let (fin, fil, map, venues) = write_qa_replay_fixture(tmp.path()); + let out = tmp.path().join("out"); + let args = default_test_args(fin, fil, map, venues, out.clone()); + + // Act + let first = run_curate_fundamentals(&args).unwrap(); + let before = snapshot_tree(&out); + let second = run_curate_fundamentals(&args).unwrap(); + + // Assert + assert_reports_eq_ignoring_timing(&first, &second); + assert_eq!(snapshot_tree(&out), before); +} + +#[test] +fn fundamentals_mapped_listing_without_venue_is_dropped_not_guessed() { + // Arrange: listing 303 is mapped but absent from listing_venues.tsv; it has a filing-linked + // quarter and an unlinked one. Neither may be published with a guessed venue lag. + let tmp = TempDirGuard::new("qa-missing-venue"); + let fin_path = tmp.path().join("qmFinancials.bson"); + let fil_path = tmp.path().join("qmFilings.bson"); + let map_path = tmp.path().join("provider_mapping.tsv"); + let venues_path = tmp.path().join("listing_venues.tsv"); + let out = tmp.path().join("out"); + fs::write( + &map_path, + "qm\tUSCO\t2020-01-01\t\t10\nqm\tNOVEN\t2020-01-01\t\t303\n", + ) + .unwrap(); + fs::write(&venues_path, "10\tus_tsx\n").unwrap(); + let mut fin = Vec::new(); + for sym in ["USCO", "NOVEN"] { + fin.extend_from_slice(&make_financials_doc( + Some(sym), + "2024-03-31", + Some("2024-05-02"), + "Q1", + "USD", + FundamentalsFields { + revenue: Some(10.0), + ..Default::default() + }, + )); + fin.extend_from_slice(&make_financials_doc( + Some(sym), + "2024-06-30", + None, + "Q2", + "USD", + FundamentalsFields { + revenue: Some(11.0), + ..Default::default() + }, + )); + } + fs::write(&fin_path, &fin).unwrap(); + let mut fil = Vec::new(); + for sym in ["USCO", "NOVEN"] { + fil.extend_from_slice(&make_filing_doc( + Some(sym), + "2024-05-02T16:15:00 EDT", + "10-Q", + None, + None, + )); + } + fs::write(&fil_path, &fil).unwrap(); + + // Act + let report = run_curate_fundamentals(&default_test_args( + fin_path, + fil_path, + map_path, + venues_path, + out.clone(), + )) + .unwrap(); + + // Assert + assert_conservation(&report); + assert_eq!(report.curate_stats.observations_dropped_unmapped, 0); + assert_eq!(report.curate_stats.build.observations_dropped_unknown_key, 2); + assert_eq!(report.curate_stats.listings_out, 1); + let by_year = read_dataset_by_year(&out); + let all: Vec<_> = by_year.values().flatten().collect(); + assert!(!all.is_empty()); + assert!(all.iter().all(|r| r.listing_id == 10)); +} + +#[test] +fn fundamentals_regular_file_year_entry_fails_without_partial_publish() { + // Arrange: a backfill writing 2023 and 2024, where `year=2024` is occupied by a regular file. + // A pre-existing 2023 partition must survive the failed run byte-for-byte. + let tmp = TempDirGuard::new("qa-file-year"); + let (fin, fil, map, venues) = write_qa_replay_fixture(tmp.path()); + let out = tmp.path().join("out"); + let dataset = out.join("fundamentals_pit"); + fs::create_dir_all(dataset.join("year=2023")).unwrap(); + fs::write(dataset.join("year=2023").join("part.parquet"), b"seed-2023").unwrap(); + fs::write(dataset.join("year=2024"), b"not-a-directory").unwrap(); + let before = snapshot_tree(&out); + + for use_readers in [false, true] { + // Act + let args = default_test_args( + fin.clone(), + fil.clone(), + map.clone(), + venues.clone(), + out.clone(), + ); + let result = if use_readers { + run_curate_fundamentals_with_readers( + &args, + File::open(&fin).unwrap(), + File::open(&fil).unwrap(), + ) + } else { + run_curate_fundamentals(&args) + }; + + // Assert + let err = result.expect_err("regular-file year entry must fail"); + assert_single_line(&err.to_string()); + assert_eq!(snapshot_tree(&out), before, "output tree must be unchanged"); + } +} + +#[test] +fn listing_venues_accepts_crlf_and_single_trailing_blank() { + let tmp = TempDirGuard::new("qa-venues-ok"); + let path = tmp.path().join("venues.tsv"); + fs::write(&path, "7\ttsxv_cse\r\n3\tus_tsx\n\n").unwrap(); + let venues = load_listing_venues_tsv(&path).unwrap(); + assert_eq!(venues.len(), 2); + assert_eq!(venues[&3], crate::fundamentals::StatutoryLagVenue::UsTsx); + assert_eq!(venues[&7], crate::fundamentals::StatutoryLagVenue::TsxvCse); + + let empty = tmp.path().join("empty.tsv"); + fs::write(&empty, "").unwrap(); + assert!(load_listing_venues_tsv(&empty).unwrap().is_empty()); +} + +#[test] +fn listing_venues_rejects_padded_signed_and_case_variant_tokens() { + let tmp = TempDirGuard::new("qa-venues-strict"); + let path = tmp.path().join("venues.tsv"); + for (content, line) in [ + ("1\tus_tsx\n2\t us_tsx\n", 2usize), + ("1\tus_tsx\n2\tUS_TSX\n", 2), + ("1\tus_tsx \n", 1), + ("+5\tus_tsx\n", 1), + (" 5\tus_tsx\n", 1), + ("2147483648\tus_tsx\n", 1), + ("1\tus_tsx\n2\t\n", 2), + // Shared `read_tsv_lines` reports the second trailing blank line. + ("1\tus_tsx\n\n\n", 3), + ] { + fs::write(&path, content).unwrap(); + let err = load_listing_venues_tsv(&path).expect_err(content); + let msg = err.to_string(); + assert_single_line(&msg); + match &err { + RunCurateFundamentalsError::TsvParse { path: p, line: l, .. } => { + assert_eq!(p, &path, "{content:?}"); + assert_eq!(*l, line, "{content:?}: {msg}"); + } + other => panic!("expected TsvParse for {content:?}, got {other:?}"), + } + assert!(msg.contains(&format!("{}:{line}:", path.display())), "{msg}"); + } +} + +#[test] +fn listing_venues_missing_file_reports_open_error_with_path() { + let tmp = TempDirGuard::new("qa-venues-missing"); + let path = tmp.path().join("nope.tsv"); + let err = load_listing_venues_tsv(&path).unwrap_err(); + assert!(matches!(err, RunCurateFundamentalsError::OpenInput { ref path, .. } if path.ends_with("nope.tsv"))); + assert!(err.to_string().contains(&path.display().to_string())); +} diff --git a/tools/curate-etl/src/run_curate_posts.rs b/tools/curate-etl/src/run_curate_posts.rs new file mode 100644 index 00000000..9f7e6c2e --- /dev/null +++ b/tools/curate-etl/src/run_curate_posts.rs @@ -0,0 +1,692 @@ +//! File-to-file `curate-posts` runner (`M2.2i`). +//! +//! Streams a concatenated raw BSON `ceoPosts` dump file alongside `provider_mapping.tsv` into an +//! atomically published `/events/year=YYYY/part.parquet` dataset via +//! [`curate_and_write_posts`]. +//! +//! # Dedicated Output Directory & Clobber Guard +//! `write_events_dataset` replaces whole `/events/year=YYYY/part.parquet` files, and +//! [`crate::run_curate_events`] (filings + earnings) publishes to the same `/events` +//! directory. To prevent silently clobbering another stage's partitions, this runner **requires a +//! dedicated output directory** and fails closed with [`RunCuratePostsError::EventsDatasetExists`] +//! before any write whenever `/events` already contains any `year=*` entry. Combining +//! filings, earnings, and posts into one `events` dataset is a separate follow-up. +//! +//! # Contract & Point-in-Time Rules +//! - Field names are supplied via [`CuratePostsArgs`] (validated via +//! [`CeoPostsFieldNames::validate`] before reading inputs). +//! - Numeric timestamp unit ([`CeoPostsTimestampUnit`]) has **no default** and must be chosen +//! explicitly by the caller because the live MongoDB `ceoPosts` numeric unit (`Seconds` vs. +//! `Millis`) is unverified in the repository. BSON `DateTime` values are always epoch +//! milliseconds regardless of unit. +//! - `provider_mapping.tsv` uses the strict headerless 5-column TSV format from +//! [`crate::run_curate_bars::load_provider_mapping_tsv`]. +//! - All decoded [`CeoPost`] rows are passed directly to [`curate_and_write_posts`] (which splits +//! `bot == "1"` newswire vs. retail, enforces the `edited` text `known_at` guard, resolves +//! `provider_mapping` on the Eastern local posting date of `posted_at`, and drops unmapped or +//! unsupported-date rows into stats). +//! - **In-memory accumulation:** [`RawBsonChunkReader`] bounds only the raw BSON chunk buffer +//! (`peak_chunk_bytes`); decoded posts and their text accumulate in memory before +//! [`curate_and_write_posts`] runs, as [`crate::curate_posts::curate_posts`] requires. +//! - **Empty / all-unmapped behavior:** returns `Ok` with `rows_written == 0` and +//! `files_written == 0` without creating `/events`. +//! - **Fail-closed safety:** invalid `out_dir`, pre-existing `/events/year=*` entries, +//! invalid field names, blank `mapping_source`, unreadable inputs, malformed/overlapping +//! `provider_mapping.tsv`, truncated/corrupt BSON framing or element bytes, and curation +//! timestamp overflow errors return a typed [`RunCuratePostsError`] before touching `out_dir`. +//! +//! # Counter Conservation Invariants +//! Every successful [`CuratePostsRunReport`] satisfies: +//! - `docs_framed as usize == decode.docs_in == decode.rows_out + decode.skipped_total()` +//! - `decode.rows_out == curate_stats.builder.input` +//! - `curate_stats.builder.input == curate_stats.builder.newswire + curate_stats.builder.retail + curate_stats.builder.duplicates_dropped + curate_stats.builder.rejected_invalid` +//! - `curate_stats.rows_in == curate_stats.builder.newswire + curate_stats.builder.retail == curate_stats.rows_out + curate_stats.dropped_unmapped + curate_stats.dropped_unsupported_date + curate_stats.listing_duplicate_collapsed` +//! - `write_stats.rows_written == curate_stats.rows_out` + +use std::collections::HashSet; +use std::error::Error; +use std::fmt::{self, Write as _}; +use std::fs::{self, File}; +use std::io; +use std::path::{Component, Path, PathBuf}; +use std::sync::Arc; +use std::time::Instant; + +use crate::bson_ceo_posts::{ + BsonCeoPostsDecodeStats, BsonCeoPostsError, CeoPostsFieldNames, CeoPostsTimestampUnit, +}; +use crate::bson_stream::{ + decode_ceo_posts_chunks, BsonCeoPostsStreamError, BsonStreamError, BsonStreamOptions, + RawBsonChunkReader, +}; +use crate::curate_posts::{curate_and_write_posts, CuratePostsStats, CuratePostsWriteError}; +use crate::parquet_events::{EventsWriteOptions, EventsWriteStats}; +use crate::posts::CeoPost; +use crate::provider_mapping::{ProviderMappingError, ProviderMappingTable}; +use crate::run_curate_bars::{load_provider_mapping_tsv, RunCurateBarsError}; + +/// Default `mapping_source` passed to `provider_mapping` lookups for `ceoPosts`. +pub const DEFAULT_MAPPING_SOURCE: &str = "ceo"; + +/// Arguments for [`run_curate_posts`]. +/// +/// `timestamp_unit` intentionally has no default: callers must explicitly choose +/// [`CeoPostsTimestampUnit::Seconds`] or [`CeoPostsTimestampUnit::Millis`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CuratePostsArgs { + pub ceo_posts: PathBuf, + pub provider_mapping: PathBuf, + pub out_dir: PathBuf, + pub timestamp_unit: CeoPostsTimestampUnit, + pub key_field: String, + pub spiel_id_field: String, + pub timestamp_field: String, + pub edited_field: String, + pub bot_field: String, + pub user_id_field: String, + pub text_field: String, + pub mapping_source: String, +} + +impl CuratePostsArgs { + /// Borrows the configured BSON field names as [`CeoPostsFieldNames`]. + #[inline] + pub fn field_names(&self) -> CeoPostsFieldNames<'_> { + CeoPostsFieldNames { + key: self.key_field.as_str(), + spiel_id: self.spiel_id_field.as_str(), + timestamp: self.timestamp_field.as_str(), + edited: self.edited_field.as_str(), + bot: self.bot_field.as_str(), + user_id: self.user_id_field.as_str(), + text: self.text_field.as_str(), + } + } +} + +/// Full run report produced by [`run_curate_posts`] and [`run_curate_posts_with_reader`]. +#[derive(Debug, Clone, PartialEq)] +pub struct CuratePostsRunReport { + pub docs_framed: u64, + pub bytes_read: u64, + pub peak_chunk_bytes: usize, + pub decode: BsonCeoPostsDecodeStats, + pub curate_stats: CuratePostsStats, + pub write_stats: EventsWriteStats, + pub elapsed_secs: f64, +} + +/// Typed errors returned by [`run_curate_posts`] and [`run_curate_posts_with_reader`]. +/// +/// Every variant's `Display` output is a single line naming the offending path (and line number or +/// byte offset where applicable). +#[derive(Debug)] +pub enum RunCuratePostsError { + InvalidOutDir { + path: PathBuf, + detail: String, + }, + InspectOutDir { + path: PathBuf, + source: io::Error, + }, + EventsDatasetExists { + path: PathBuf, + }, + InvalidFieldNames { + source: BsonCeoPostsError, + }, + EmptyMappingSource, + OpenInput { + label: &'static str, + path: PathBuf, + source: io::Error, + }, + ReadInput { + label: &'static str, + path: PathBuf, + source: io::Error, + }, + TsvParse { + path: PathBuf, + line: usize, + detail: String, + }, + ProviderMapping { + path: PathBuf, + source: ProviderMappingError, + }, + BsonStream { + path: PathBuf, + source: BsonStreamError, + }, + CorruptBson { + path: PathBuf, + offset: u64, + source: BsonCeoPostsError, + }, + CurateWrite { + out_dir: PathBuf, + source: CuratePostsWriteError, + }, +} + +struct SingleLineWriter<'a, 'b> { + f: &'a mut fmt::Formatter<'b>, +} + +impl fmt::Write for SingleLineWriter<'_, '_> { + fn write_str(&mut self, s: &str) -> fmt::Result { + let mut rest = s; + while let Some(idx) = rest.find(['\n', '\r']) { + let (head, tail) = rest.split_at(idx); + if !head.is_empty() { + self.f.write_str(head)?; + } + let mut chars = tail.chars(); + match chars.next() { + Some('\n') => self.f.write_str("\\n")?, + Some('\r') => self.f.write_str("\\r")?, + _ => unreachable!(), + } + rest = chars.as_str(); + } + if !rest.is_empty() { + self.f.write_str(rest)?; + } + Ok(()) + } +} + +impl fmt::Display for RunCuratePostsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut w = SingleLineWriter { f }; + match self { + Self::InvalidOutDir { path, detail } => { + write!(w, "invalid --out '{}': {detail}", path.display()) + } + Self::InspectOutDir { path, source } => { + write!( + w, + "failed to inspect output path '{}': {source}", + path.display() + ) + } + Self::EventsDatasetExists { path } => write!( + w, + "refusing to overwrite existing events partition '{}': use a dedicated --out directory for ceoPosts", + path.display() + ), + Self::InvalidFieldNames { source } => write!(w, "{source}"), + Self::EmptyMappingSource => { + write!(w, "invalid --mapping-source: must not be empty or blank") + } + Self::OpenInput { + label, + path, + source, + } => write!(w, "failed to open {label} '{}': {source}", path.display()), + Self::ReadInput { + label, + path, + source, + } => write!(w, "failed to read {label} '{}': {source}", path.display()), + Self::TsvParse { path, line, detail } => { + write!(w, "{}:{line}: {detail}", path.display()) + } + Self::ProviderMapping { path, source } => { + write!(w, "invalid provider_mapping '{}': {source}", path.display()) + } + Self::BsonStream { path, source } => { + write!(w, "failed reading ceo-posts '{}': {source}", path.display()) + } + Self::CorruptBson { + path, + offset, + source, + } => write!( + w, + "corrupt ceo-posts BSON '{}' at byte offset {offset}: {source}", + path.display() + ), + Self::CurateWrite { out_dir, source } => { + write!(w, "curate/write to '{}' failed: {source}", out_dir.display()) + } + } + } +} + +impl Error for RunCuratePostsError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::InspectOutDir { source, .. } => Some(source), + Self::InvalidFieldNames { source } => Some(source), + Self::OpenInput { source, .. } | Self::ReadInput { source, .. } => Some(source), + Self::ProviderMapping { source, .. } => Some(source), + Self::BsonStream { source, .. } => Some(source), + Self::CorruptBson { source, .. } => Some(source), + Self::CurateWrite { source, .. } => Some(source), + Self::InvalidOutDir { .. } + | Self::EventsDatasetExists { .. } + | Self::EmptyMappingSource + | Self::TsvParse { .. } => None, + } + } +} + +fn validate_out_dir_and_events_guard(out_dir: &Path) -> Result<(), RunCuratePostsError> { + if out_dir.as_os_str().is_empty() { + return Err(RunCuratePostsError::InvalidOutDir { + path: out_dir.to_path_buf(), + detail: "output directory path must not be empty".to_string(), + }); + } + + // Reject `..` after a missing path component: `fs::metadata` reports `NotFound` for the + // unresolved path, but `create_dir_all` would create the missing component and then traverse + // `..` into an existing directory, bypassing the events clobber guard. + let mut prefix = PathBuf::new(); + let mut saw_missing = false; + for component in out_dir.components() { + match component { + Component::ParentDir => { + if saw_missing { + return Err(RunCuratePostsError::InvalidOutDir { + path: out_dir.to_path_buf(), + detail: "output path must not contain '..' after a missing component" + .to_string(), + }); + } + prefix.push(component); + } + Component::CurDir => { + if !saw_missing { + prefix.push(component); + } + } + Component::RootDir | Component::Prefix(_) => { + prefix.push(component); + } + Component::Normal(_) => { + prefix.push(component); + if !saw_missing { + match fs::metadata(&prefix) { + Ok(_) => {} + Err(err) if err.kind() == io::ErrorKind::NotFound => { + saw_missing = true; + } + Err(source) => { + return Err(RunCuratePostsError::InspectOutDir { + path: prefix, + source, + }); + } + } + } + } + } + } + + match fs::metadata(out_dir) { + Ok(meta) if !meta.is_dir() => { + return Err(RunCuratePostsError::InvalidOutDir { + path: out_dir.to_path_buf(), + detail: "path exists and is not a directory".to_string(), + }); + } + Ok(_) => {} + Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()), + Err(source) => { + return Err(RunCuratePostsError::InspectOutDir { + path: out_dir.to_path_buf(), + source, + }); + } + } + + let events_dir = out_dir.join("events"); + match fs::metadata(&events_dir) { + Ok(meta) if !meta.is_dir() => { + return Err(RunCuratePostsError::InvalidOutDir { + path: events_dir, + detail: "events output path exists and is not a directory".to_string(), + }); + } + Ok(_) => {} + Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()), + Err(source) => { + return Err(RunCuratePostsError::InspectOutDir { + path: events_dir, + source, + }); + } + } + + let entries = fs::read_dir(&events_dir).map_err(|source| RunCuratePostsError::InspectOutDir { + path: events_dir.clone(), + source, + })?; + + let mut existing_year_entry: Option = None; + for entry_res in entries { + let entry = entry_res.map_err(|source| RunCuratePostsError::InspectOutDir { + path: events_dir.clone(), + source, + })?; + let name = entry.file_name(); + if name.to_string_lossy().starts_with("year=") { + let candidate = entry.path(); + if existing_year_entry + .as_ref() + .is_none_or(|current| candidate < *current) + { + existing_year_entry = Some(candidate); + } + } + } + + if let Some(path) = existing_year_entry { + return Err(RunCuratePostsError::EventsDatasetExists { path }); + } + + Ok(()) +} + +fn map_tsv_error(path: &Path, err: RunCurateBarsError) -> RunCuratePostsError { + match err { + RunCurateBarsError::OpenInput { + label, + path, + source, + } => RunCuratePostsError::OpenInput { + label, + path, + source, + }, + RunCurateBarsError::ReadInput { + label, + path, + source, + } => RunCuratePostsError::ReadInput { + label, + path, + source, + }, + RunCurateBarsError::TsvParse { path, line, detail } => { + RunCuratePostsError::TsvParse { path, line, detail } + } + RunCurateBarsError::ProviderMapping { path, source } => { + RunCuratePostsError::ProviderMapping { path, source } + } + other => RunCuratePostsError::TsvParse { + path: path.to_path_buf(), + line: 0, + detail: other.to_string(), + }, + } +} + +fn bson_error_offset(err: &BsonCeoPostsError) -> u64 { + match err { + BsonCeoPostsError::TruncatedDocument { offset, .. } + | BsonCeoPostsError::CorruptDocumentLength { offset, .. } + | BsonCeoPostsError::CorruptBson { offset, .. } => *offset, + BsonCeoPostsError::InvalidFieldNames { .. } => 0, + } +} + +struct DecodedPostsInputs { + mapping: ProviderMappingTable, + posts: Vec>>, + docs_framed: u64, + bytes_read: u64, + peak_chunk_bytes: usize, + decode: BsonCeoPostsDecodeStats, +} + +fn decode_inputs_from_opener( + provider_mapping_path: &Path, + mapping_source: &str, + fields: &CeoPostsFieldNames<'_>, + timestamp_unit: CeoPostsTimestampUnit, + ceo_posts_path: &Path, + open_posts: F, +) -> Result +where + R: io::Read, + F: FnOnce() -> Result, +{ + fields + .validate() + .map_err(|source| RunCuratePostsError::InvalidFieldNames { source })?; + + if mapping_source.trim().is_empty() { + return Err(RunCuratePostsError::EmptyMappingSource); + } + + let mapping_rows = load_provider_mapping_tsv(provider_mapping_path) + .map_err(|err| map_tsv_error(provider_mapping_path, err))?; + let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| { + RunCuratePostsError::ProviderMapping { + path: provider_mapping_path.to_path_buf(), + source, + } + })?; + + let stream = open_posts()?; + let mut reader = RawBsonChunkReader::with_options(stream, BsonStreamOptions::default()) + .map_err(|source| RunCuratePostsError::BsonStream { + path: ceo_posts_path.to_path_buf(), + source, + })?; + + let mut key_interner: HashSet> = HashSet::new(); + let mut posts: Vec>> = Vec::new(); + + let decode = decode_ceo_posts_chunks(&mut reader, fields, timestamp_unit, |raw| { + let key = if let Some(existing) = key_interner.get(raw.key) { + Arc::clone(existing) + } else { + let arc: Arc = Arc::from(raw.key); + key_interner.insert(Arc::clone(&arc)); + arc + }; + posts.push(CeoPost { + key, + spiel_id: raw.spiel_id, + timestamp_ms: raw.timestamp_ms, + edited_ms: raw.edited_ms, + bot: raw.bot, + user_id: raw.user_id, + text: raw.text, + }); + }) + .map_err(|err| match err { + BsonCeoPostsStreamError::Stream(source) => RunCuratePostsError::BsonStream { + path: ceo_posts_path.to_path_buf(), + source, + }, + BsonCeoPostsStreamError::Decode(source) => match &source { + BsonCeoPostsError::InvalidFieldNames { .. } => { + RunCuratePostsError::InvalidFieldNames { source } + } + _ => { + let offset = bson_error_offset(&source); + RunCuratePostsError::CorruptBson { + path: ceo_posts_path.to_path_buf(), + offset, + source, + } + } + }, + })?; + + Ok(DecodedPostsInputs { + mapping, + posts, + docs_framed: reader.docs_framed(), + bytes_read: reader.bytes_read(), + peak_chunk_bytes: reader.buffer_capacity(), + decode, + }) +} + +fn run_curate_posts_from_opener( + provider_mapping_path: &Path, + mapping_source: &str, + fields: &CeoPostsFieldNames<'_>, + timestamp_unit: CeoPostsTimestampUnit, + ceo_posts_path: &Path, + open_posts: F, + out_dir: &Path, +) -> Result +where + R: io::Read, + F: FnOnce() -> Result, +{ + let start = Instant::now(); + validate_out_dir_and_events_guard(out_dir)?; + + let decoded = decode_inputs_from_opener( + provider_mapping_path, + mapping_source, + fields, + timestamp_unit, + ceo_posts_path, + open_posts, + )?; + + // Re-check output directory and clobber guard immediately before curating/writing. + validate_out_dir_and_events_guard(out_dir)?; + + let write_report = curate_and_write_posts( + out_dir, + decoded.posts, + mapping_source, + &decoded.mapping, + EventsWriteOptions::default(), + ) + .map_err(|source| RunCuratePostsError::CurateWrite { + out_dir: out_dir.to_path_buf(), + source, + })?; + + Ok(CuratePostsRunReport { + docs_framed: decoded.docs_framed, + bytes_read: decoded.bytes_read, + peak_chunk_bytes: decoded.peak_chunk_bytes, + decode: decoded.decode, + curate_stats: write_report.curate_stats, + write_stats: write_report.write_stats, + elapsed_secs: start.elapsed().as_secs_f64(), + }) +} + +/// Runs the end-to-end `curate-posts` file-to-Parquet pipeline via [`curate_and_write_posts`]. +/// +/// Any validation, clobber-guard, I/O, TSV, mapping, BSON framing/corruption, or curation error +/// returns before touching `args.out_dir`. +pub fn run_curate_posts( + args: &CuratePostsArgs, +) -> Result { + run_curate_posts_from_opener( + &args.provider_mapping, + &args.mapping_source, + &args.field_names(), + args.timestamp_unit, + &args.ceo_posts, + || { + File::open(&args.ceo_posts).map_err(|source| RunCuratePostsError::OpenInput { + label: "ceo-posts", + path: args.ceo_posts.clone(), + source, + }) + }, + &args.out_dir, + ) +} + +/// Runs `curate-posts` from an arbitrary raw-BSON [`io::Read`] stream. +pub fn run_curate_posts_with_reader( + provider_mapping_path: &Path, + mapping_source: &str, + fields: &CeoPostsFieldNames<'_>, + timestamp_unit: CeoPostsTimestampUnit, + ceo_posts_input: (&Path, R), + out_dir: &Path, +) -> Result { + let (ceo_path, stream) = ceo_posts_input; + run_curate_posts_from_opener( + provider_mapping_path, + mapping_source, + fields, + timestamp_unit, + ceo_path, + || Ok(stream), + out_dir, + ) +} + +/// Formats [`CuratePostsRunReport`] into a deterministic machine-readable `key=value` summary. +/// +/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`). +pub fn format_curate_posts_report(report: &CuratePostsRunReport) -> String { + let d = &report.decode; + let b = &report.curate_stats.builder; + let c = &report.curate_stats; + let w = &report.write_stats; + format!( + "curate-etl curate-posts\n\ + \x20 ceo_bson: docs_framed={} bytes_read={} peak_chunk_bytes={} docs_in={} rows_out={} skipped={} (missing_key={} wrong_key_type={} empty_key={} missing_spiel_id={} wrong_spiel_id_type={} empty_spiel_id={} missing_ts={} wrong_ts_type={} invalid_ts={} ts_oor={} invalid_edited={} wrong_text_type={}) emitted=(edited_zero_or_false={} nulled_bot={} nulled_user_id={} empty_text={})\n\ + \x20 builder: input={} newswire={} retail={} edited={} edited_before_posted={} dup_dropped={} rejected_invalid={}\n\ + \x20 curate: rows_in={} rows_out={} newswire_out={} retail_out={} listings_out={} dropped_unmapped={} dropped_unsupported_date={} listing_dup_collapsed={}\n\ + \x20 write: files={} row_groups={} rows_written={} bytes_written={}\n\ + \x20 timing: elapsed_secs={:.6}", + report.docs_framed, + report.bytes_read, + report.peak_chunk_bytes, + d.docs_in, + d.rows_out, + d.skipped_total(), + d.skipped_missing_key, + d.skipped_wrong_key_type, + d.skipped_empty_key, + d.skipped_missing_spiel_id, + d.skipped_wrong_spiel_id_type, + d.skipped_empty_spiel_id, + d.skipped_missing_timestamp, + d.skipped_wrong_timestamp_type, + d.skipped_invalid_timestamp, + d.skipped_timestamp_out_of_range, + d.skipped_invalid_edited, + d.skipped_wrong_text_type, + d.edited_zero_or_false, + d.nulled_wrong_type_bot, + d.nulled_wrong_type_user_id, + d.empty_text, + b.input, + b.newswire, + b.retail, + b.edited, + b.edited_before_posted, + b.duplicates_dropped, + b.rejected_invalid, + c.rows_in, + c.rows_out, + c.newswire_out, + c.retail_out, + c.listings_out, + c.dropped_unmapped, + c.dropped_unsupported_date, + c.listing_duplicate_collapsed, + w.files_written, + w.row_groups_written, + w.rows_written, + w.bytes_written, + report.elapsed_secs, + ) +} + +#[cfg(test)] +#[path = "run_curate_posts_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/run_curate_posts_tests.rs b/tools/curate-etl/src/run_curate_posts_tests.rs new file mode 100644 index 00000000..7456672b --- /dev/null +++ b/tools/curate-etl/src/run_curate_posts_tests.rs @@ -0,0 +1,1450 @@ +use std::borrow::Cow; +use std::fs::{self, File}; +use std::io::{self, Cursor, Read, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use bson::raw::{cstr, RawDocumentBuf}; +use parquet::basic::Compression; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::*; +use crate::bson_ceo_posts::{ + DEFAULT_BOT_FIELD, DEFAULT_EDITED_FIELD, DEFAULT_KEY_FIELD, DEFAULT_SPIEL_ID_FIELD, + DEFAULT_TEXT_FIELD, DEFAULT_TIMESTAMP_FIELD, DEFAULT_USER_ID_FIELD, +}; +use crate::curate_posts::{curate_posts, CuratePostsError, CuratePostsWriteError}; +use crate::parquet_events::EventsParquetRow; +use crate::parquet_posts::{ + EVENT_KIND_POST, KNOWN_AT_SOURCE_POST_EDITED, KNOWN_AT_SOURCE_POST_TIMESTAMP, + POST_SUBTYPE_NEWSWIRE, POST_SUBTYPE_RETAIL, +}; +use crate::posts::PostsError; +use crate::provider_mapping::ProviderMappingRow; +use crate::split::ymd_to_epoch_days; + +static TEMP_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDirGuard { + path: PathBuf, +} + +impl TempDirGuard { + fn new(label: &str) -> Self { + let seq = TEMP_SEQ.fetch_add(1, Ordering::Relaxed); + let pid = std::process::id(); + let path = + std::env::temp_dir().join(format!("curate-etl-run-posts-test-{label}-{pid}-{seq}")); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp dir"); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn utc_ms(year: i32, month: u32, day_num: u32, hour: u8, minute: u8, second: u8) -> i64 { + let epoch_day = day(year, month, day_num); + let secs = i64::from(epoch_day) * 86_400 + + i64::from(hour) * 3_600 + + i64::from(minute) * 60 + + i64::from(second); + secs * 1_000 +} + +fn write_bytes(path: &Path, bytes: &[u8]) { + let mut f = File::create(path).expect("create file"); + f.write_all(bytes).expect("write file"); +} + +fn default_args( + ceo_posts: PathBuf, + provider_mapping: PathBuf, + out_dir: PathBuf, + timestamp_unit: CeoPostsTimestampUnit, +) -> CuratePostsArgs { + CuratePostsArgs { + ceo_posts, + provider_mapping, + out_dir, + timestamp_unit, + key_field: DEFAULT_KEY_FIELD.to_string(), + spiel_id_field: DEFAULT_SPIEL_ID_FIELD.to_string(), + timestamp_field: DEFAULT_TIMESTAMP_FIELD.to_string(), + edited_field: DEFAULT_EDITED_FIELD.to_string(), + bot_field: DEFAULT_BOT_FIELD.to_string(), + user_id_field: DEFAULT_USER_ID_FIELD.to_string(), + text_field: DEFAULT_TEXT_FIELD.to_string(), + mapping_source: DEFAULT_MAPPING_SOURCE.to_string(), + } +} + +#[allow(clippy::too_many_arguments)] +fn make_post_doc( + fields: &CeoPostsFieldNames<'_>, + key: &str, + spiel_id: &str, + timestamp: i64, + edited: Option, + bot: Option<&str>, + user_id: Option<&str>, + text: &str, +) -> Vec { + let cstring = |s: &str| bson::raw::CString::try_from(s.to_owned()).expect("valid BSON key"); + let mut doc = RawDocumentBuf::new(); + doc.append(cstring(fields.key), key); + doc.append(cstring(fields.spiel_id), spiel_id); + doc.append(cstring(fields.timestamp), timestamp); + if let Some(ed) = edited { + doc.append(cstring(fields.edited), ed); + } + if let Some(b) = bot { + doc.append(cstring(fields.bot), b); + } + if let Some(u) = user_id { + doc.append(cstring(fields.user_id), u); + } + doc.append(cstring(fields.text), text); + doc.into_bytes() +} + +fn assert_report_invariants(report: &CuratePostsRunReport) { + assert_eq!(report.docs_framed as usize, report.decode.docs_in); + assert_eq!( + report.decode.docs_in, + report.decode.rows_out + report.decode.skipped_total() + ); + let b = &report.curate_stats.builder; + assert_eq!(report.decode.rows_out, b.input); + assert_eq!( + b.input, + b.newswire + b.retail + b.duplicates_dropped + b.rejected_invalid + ); + let c = &report.curate_stats; + assert_eq!(c.rows_in, b.newswire + b.retail); + assert_eq!( + c.rows_in, + c.rows_out + + c.dropped_unmapped + + c.dropped_unsupported_date + + c.listing_duplicate_collapsed + ); + assert_eq!(c.rows_out, c.newswire_out + c.retail_out); + assert_eq!(report.write_stats.rows_written, c.rows_out); +} + +fn read_events_parquet_and_verify_zstd(path: &Path) -> Vec { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let meta = reader.metadata(); + let mut out = Vec::new(); + + for rg_idx in 0..meta.num_row_groups() { + let rg_meta = meta.row_group(rg_idx); + assert_eq!( + rg_meta.num_columns(), + 7, + "expected 7 columns in events schema" + ); + for col_idx in 0..rg_meta.num_columns() { + let compression = rg_meta.column(col_idx).compression(); + assert!( + matches!(compression, Compression::ZSTD(_)), + "expected ZSTD compression for row_group={rg_idx} col={col_idx}, got {compression:?}" + ); + } + + let rg_rows = rg_meta.num_rows() as usize; + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + + let read_i32_col = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read i32 records"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected INT32 column at index {col_idx}"), + } + vals + }; + + let read_i64_col = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int64ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read i64 records"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected INT64 column at index {col_idx}"), + } + vals + }; + + let read_str_col = |col_idx: usize| -> Vec { + let mut raw = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut raw) + .expect("read byte_array records"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), + } + raw.iter() + .map(|b| { + std::str::from_utf8(b.data()) + .expect("valid utf8") + .to_string() + }) + .collect() + }; + + let listing_ids = read_i32_col(0); + let ts = read_i64_col(1); + let known_at = read_i64_col(2); + let known_at_source = read_str_col(3); + let kind = read_str_col(4); + let subtype = read_str_col(5); + let payload_json = read_str_col(6); + + for i in 0..rg_rows { + out.push(EventsParquetRow { + listing_id: listing_ids[i], + ts_micros: ts[i], + known_at_micros: known_at[i], + known_at_source: Cow::Owned(known_at_source[i].clone()), + kind: Cow::Owned(kind[i].clone()), + subtype: subtype[i].clone(), + payload_json: payload_json[i].clone(), + }); + } + } + + out +} + +fn read_all_event_partitions(out_dir: &Path) -> Vec { + let events_dir = out_dir.join("events"); + let mut year_dirs: Vec = fs::read_dir(&events_dir) + .expect("read events dir") + .map(|e| e.expect("dir entry").path()) + .filter(|p| { + p.file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n.starts_with("year=")) + }) + .collect(); + year_dirs.sort(); + + let mut all = Vec::new(); + for yd in year_dirs { + all.extend(read_events_parquet_and_verify_zstd( + &yd.join("part.parquet"), + )); + } + all.sort_by(|a, b| { + a.listing_id + .cmp(&b.listing_id) + .then_with(|| a.ts_micros.cmp(&b.ts_micros)) + .then_with(|| a.kind.as_ref().cmp(b.kind.as_ref())) + .then_with(|| a.subtype.cmp(&b.subtype)) + .then_with(|| a.payload_json.cmp(&b.payload_json)) + .then_with(|| a.known_at_micros.cmp(&b.known_at_micros)) + .then_with(|| a.known_at_source.as_ref().cmp(b.known_at_source.as_ref())) + }); + all +} + +fn assert_single_line_err(err: &RunCuratePostsError) -> String { + let msg = err.to_string(); + assert!(!msg.is_empty(), "error message must not be empty"); + assert!( + !msg.contains('\n') && !msg.contains('\r'), + "error message must be single-line, got: {msg:?}" + ); + msg +} + +struct FailingReader { + prefix: Vec, + pos: usize, + error_message: String, +} + +impl Read for FailingReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if self.pos < self.prefix.len() { + let n = (self.prefix.len() - self.pos).min(buf.len()); + buf[..n].copy_from_slice(&self.prefix[self.pos..self.pos + n]); + self.pos += n; + return Ok(n); + } + Err(io::Error::new( + io::ErrorKind::BrokenPipe, + self.error_message.clone(), + )) + } +} + +#[test] +fn happy_path_matches_curate_posts_verifies_zstd_edit_time_and_invariants() { + let dir = TempDirGuard::new("happy"); + let bson_path = dir.path().join("ceoPosts.bson"); + let map_path = dir.path().join("provider_mapping.tsv"); + let out_a = dir.path().join("out_a"); + let out_b = dir.path().join("out_b"); + + let mapping_tsv = concat!( + "ceo\tCEO_RY\t2020-01-01\t\t101\n", + "ceo\tCEO_SHOP\t2024-01-01\t\t202\n", + ); + write_bytes(&map_path, mapping_tsv.as_bytes()); + + let fields = CeoPostsFieldNames::default(); + let t_wire = utc_ms(2024, 6, 15, 14, 0, 0); + let t_retail = utc_ms(2024, 6, 15, 14, 5, 0); + let t_edited_post = utc_ms(2024, 6, 15, 15, 0, 0); + let t_edited_at = utc_ms(2024, 6, 15, 18, 30, 0); + let t_2025 = utc_ms(2025, 1, 10, 16, 0, 0); + + // Semantic skip doc: invalid edited (boolean true) + let mut skipped_doc = RawDocumentBuf::new(); + skipped_doc.append(cstr!("ceoId"), "CEO_RY"); + skipped_doc.append(cstr!("spielId"), "sp-skip"); + skipped_doc.append(cstr!("timestamp"), t_wire); + skipped_doc.append(cstr!("edited"), true); + skipped_doc.append(cstr!("spiel"), "should skip"); + + let docs = vec![ + // 1. Newswire (bot == "1") + make_post_doc( + &fields, + "CEO_RY", + "sp-wire-1", + t_wire, + None, + Some("1"), + Some("thenewswire"), + "Royal Bank quarterly release", + ), + // 2. Retail (bot == "0") + make_post_doc( + &fields, + "CEO_RY", + "sp-retail-1", + t_retail, + None, + Some("0"), + Some("trader42"), + "Looking strong today", + ), + // 3. Edited retail post: posted at t_edited_post, edited at t_edited_at + make_post_doc( + &fields, + "CEO_SHOP", + "sp-edited-1", + t_edited_post, + Some(t_edited_at), + None, + Some("analyst99"), + "Updated guidance notes", + ), + // 4. Duplicate spielId (earlier version of sp-edited-1 -> dropped by dedup) + make_post_doc( + &fields, + "CEO_SHOP", + "sp-edited-1", + t_edited_post, + None, + None, + Some("analyst99"), + "Initial draft", + ), + // 5. Unmapped key -> dropped_unmapped + make_post_doc( + &fields, + "UNKNOWN_CH", + "sp-unmapped-1", + t_retail, + None, + None, + Some("anon"), + "Unmapped channel post", + ), + // 6. Second partition year (2025) + make_post_doc( + &fields, + "CEO_SHOP", + "sp-2025-1", + t_2025, + None, + Some("1"), + Some("globenewswire"), + "2025 update", + ), + // 7. Semantic skip + skipped_doc.into_bytes(), + ]; + + let mut forward_bytes = Vec::new(); + for d in &docs { + forward_bytes.extend_from_slice(d); + } + write_bytes(&bson_path, &forward_bytes); + + let args_a = default_args( + bson_path.clone(), + map_path.clone(), + out_a.clone(), + CeoPostsTimestampUnit::Millis, + ); + let report_a = run_curate_posts(&args_a).expect("run forward"); + assert_report_invariants(&report_a); + assert_eq!(report_a.docs_framed, 7); + assert_eq!(report_a.decode.docs_in, 7); + assert_eq!(report_a.decode.rows_out, 6); + assert_eq!(report_a.decode.skipped_invalid_edited, 1); + assert_eq!(report_a.curate_stats.builder.input, 6); + assert_eq!(report_a.curate_stats.builder.duplicates_dropped, 1); + assert_eq!(report_a.curate_stats.dropped_unmapped, 1); + assert_eq!(report_a.curate_stats.rows_out, 4); + assert_eq!(report_a.curate_stats.newswire_out, 2); + assert_eq!(report_a.curate_stats.retail_out, 2); + assert_eq!(report_a.write_stats.files_written, 2); + assert_eq!(report_a.write_stats.rows_written, 4); + + // Baseline comparison against pure curate_posts on equivalent typed inputs. + let baseline_mapping = ProviderMappingTable::from_rows(vec![ + ProviderMappingRow { + source: "ceo".to_string(), + source_id: "CEO_RY".to_string(), + valid_from: day(2020, 1, 1), + valid_to: None, + listing_id: 101, + }, + ProviderMappingRow { + source: "ceo".to_string(), + source_id: "CEO_SHOP".to_string(), + valid_from: day(2024, 1, 1), + valid_to: None, + listing_id: 202, + }, + ]) + .expect("valid mapping"); + let baseline_posts = vec![ + CeoPost { + key: "CEO_RY".to_string(), + spiel_id: "sp-wire-1".to_string(), + timestamp_ms: t_wire, + edited_ms: None, + bot: Some("1".to_string()), + user_id: Some("thenewswire".to_string()), + text: "Royal Bank quarterly release".to_string(), + }, + CeoPost { + key: "CEO_RY".to_string(), + spiel_id: "sp-retail-1".to_string(), + timestamp_ms: t_retail, + edited_ms: None, + bot: Some("0".to_string()), + user_id: Some("trader42".to_string()), + text: "Looking strong today".to_string(), + }, + CeoPost { + key: "CEO_SHOP".to_string(), + spiel_id: "sp-edited-1".to_string(), + timestamp_ms: t_edited_post, + edited_ms: Some(t_edited_at), + bot: None, + user_id: Some("analyst99".to_string()), + text: "Updated guidance notes".to_string(), + }, + CeoPost { + key: "CEO_SHOP".to_string(), + spiel_id: "sp-edited-1".to_string(), + timestamp_ms: t_edited_post, + edited_ms: None, + bot: None, + user_id: Some("analyst99".to_string()), + text: "Initial draft".to_string(), + }, + CeoPost { + key: "UNKNOWN_CH".to_string(), + spiel_id: "sp-unmapped-1".to_string(), + timestamp_ms: t_retail, + edited_ms: None, + bot: None, + user_id: Some("anon".to_string()), + text: "Unmapped channel post".to_string(), + }, + CeoPost { + key: "CEO_SHOP".to_string(), + spiel_id: "sp-2025-1".to_string(), + timestamp_ms: t_2025, + edited_ms: None, + bot: Some("1".to_string()), + user_id: Some("globenewswire".to_string()), + text: "2025 update".to_string(), + }, + ]; + let baseline = curate_posts(baseline_posts, "ceo", &baseline_mapping).expect("baseline"); + let read_back = read_all_event_partitions(&out_a); + assert_eq!(read_back, baseline.rows); + assert_eq!(report_a.curate_stats, baseline.stats); + + // Independent checks on kind, subtype, and edited post's ts vs known_at. + assert!(read_back.iter().all(|r| r.kind.as_ref() == EVENT_KIND_POST)); + let wire_row = read_back + .iter() + .find(|r| r.payload_json.contains("sp-wire-1")) + .expect("newswire row"); + assert_eq!(wire_row.subtype, POST_SUBTYPE_NEWSWIRE); + assert_eq!( + wire_row.known_at_source.as_ref(), + KNOWN_AT_SOURCE_POST_TIMESTAMP + ); + assert_eq!(wire_row.ts_micros, t_wire * 1_000); + assert_eq!(wire_row.known_at_micros, t_wire * 1_000); + + let edited_row = read_back + .iter() + .find(|r| r.payload_json.contains("sp-edited-1")) + .expect("edited row"); + assert_eq!(edited_row.subtype, POST_SUBTYPE_RETAIL); + assert_eq!(edited_row.ts_micros, t_edited_post * 1_000); + assert_eq!(edited_row.known_at_micros, t_edited_at * 1_000); + assert_eq!( + edited_row.known_at_source.as_ref(), + KNOWN_AT_SOURCE_POST_EDITED + ); + + // Reversed input order must yield byte-identical Parquet files and deterministic report. + let bson_rev = dir.path().join("ceoPosts_rev.bson"); + let mut rev_bytes = Vec::new(); + for d in docs.iter().rev() { + rev_bytes.extend_from_slice(d); + } + write_bytes(&bson_rev, &rev_bytes); + + let args_b = CuratePostsArgs { + ceo_posts: bson_rev, + out_dir: out_b.clone(), + ..args_a + }; + let report_b = run_curate_posts(&args_b).expect("run reversed"); + assert_report_invariants(&report_b); + assert_eq!(report_a.curate_stats, report_b.curate_stats); + assert_eq!(report_a.write_stats, report_b.write_stats); + + for year in ["year=2024", "year=2025"] { + let a = fs::read(out_a.join("events").join(year).join("part.parquet")).expect("read a"); + let b = fs::read(out_b.join("events").join(year).join("part.parquet")).expect("read b"); + assert_eq!( + a, b, + "reversed input must produce byte-identical {year}/part.parquet" + ); + } + + let strip_timing = |s: &str| { + s.lines() + .filter(|l| !l.trim_start().starts_with("timing:")) + .collect::>() + .join("\n") + }; + assert_eq!( + strip_timing(&format_curate_posts_report(&report_a)), + strip_timing(&format_curate_posts_report(&report_b)) + ); +} + +#[test] +fn seconds_vs_millis_and_custom_fields_with_reader_work_end_to_end() { + let dir = TempDirGuard::new("units"); + let map_path = dir.path().join("mapping.tsv"); + write_bytes(&map_path, b"ceo_alt\tCH_1\t2020-01-01\t\t555\n"); + + let custom_fields = CeoPostsFieldNames { + key: "channel", + spiel_id: "id", + timestamp: "ts", + edited: "ed", + bot: "isBot", + user_id: "author", + text: "body", + }; + + let ts_sec = 1_718_460_000_i64; // 2024-06-15 14:00:00 UTC + let ed_sec = 1_718_463_600_i64; // 2024-06-15 15:00:00 UTC + let doc_sec = make_post_doc( + &custom_fields, + "CH_1", + "p-1", + ts_sec, + Some(ed_sec), + None, + Some("u1"), + "hello", + ); + let doc_ms = make_post_doc( + &custom_fields, + "CH_1", + "p-1", + ts_sec * 1_000, + Some(ed_sec * 1_000), + None, + Some("u1"), + "hello", + ); + + let out_sec = dir.path().join("out_sec"); + let out_ms = dir.path().join("out_ms"); + + let rep_sec = run_curate_posts_with_reader( + &map_path, + "ceo_alt", + &custom_fields, + CeoPostsTimestampUnit::Seconds, + (Path::new("in-mem-sec.bson"), Cursor::new(doc_sec)), + &out_sec, + ) + .expect("run seconds"); + let rep_ms = run_curate_posts_with_reader( + &map_path, + "ceo_alt", + &custom_fields, + CeoPostsTimestampUnit::Millis, + (Path::new("in-mem-ms.bson"), Cursor::new(doc_ms)), + &out_ms, + ) + .expect("run millis"); + + assert_report_invariants(&rep_sec); + assert_report_invariants(&rep_ms); + let rows_sec = read_all_event_partitions(&out_sec); + let rows_ms = read_all_event_partitions(&out_ms); + assert_eq!(rows_sec, rows_ms); + assert_eq!(rows_sec.len(), 1); + assert_eq!(rows_sec[0].ts_micros, ts_sec * 1_000_000); + assert_eq!(rows_sec[0].known_at_micros, ed_sec * 1_000_000); +} + +#[test] +fn clobber_guard_rejects_existing_year_partitions_and_preserves_bytes() { + let dir = TempDirGuard::new("clobber"); + let map_path = dir.path().join("mapping.tsv"); + write_bytes(&map_path, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); + + let fields = CeoPostsFieldNames::default(); + let bson_path = dir.path().join("posts.bson"); + write_bytes( + &bson_path, + &make_post_doc( + &fields, + "CEO_RY", + "sp-1", + utc_ms(2024, 6, 15, 14, 0, 0), + None, + None, + None, + "hi", + ), + ); + + // 1. Pre-existing events/year=2024/part.parquet with sentinel bytes + let out_a = dir.path().join("out_existing_parquet"); + let year_2024 = out_a.join("events/year=2024"); + fs::create_dir_all(&year_2024).unwrap(); + let sentinel_path = year_2024.join("part.parquet"); + let sentinel_bytes = b"SENTINEL-FILINGS-EARNINGS-EVENTS-PARQUET".to_vec(); + write_bytes(&sentinel_path, &sentinel_bytes); + + let args_a = default_args( + bson_path.clone(), + map_path.clone(), + out_a.clone(), + CeoPostsTimestampUnit::Millis, + ); + let err = run_curate_posts(&args_a).unwrap_err(); + assert!(matches!( + err, + RunCuratePostsError::EventsDatasetExists { .. } + )); + let msg = assert_single_line_err(&err); + assert!(msg.contains("year=2024"), "expected year=2024 in {msg}"); + assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes); + let entries: Vec<_> = fs::read_dir(out_a.join("events")) + .unwrap() + .map(|e| e.unwrap().file_name()) + .collect(); + assert_eq!(entries.len(), 1); + + // 2. Pre-existing year=* directory without a Parquet file must also fail closed + let out_b = dir.path().join("out_empty_year_dir"); + let year_2025 = out_b.join("events/year=2025"); + fs::create_dir_all(&year_2025).unwrap(); + let args_b = default_args( + bson_path, + map_path, + out_b.clone(), + CeoPostsTimestampUnit::Millis, + ); + let err = run_curate_posts(&args_b).unwrap_err(); + assert!(matches!( + err, + RunCuratePostsError::EventsDatasetExists { .. } + )); + let msg = assert_single_line_err(&err); + assert!(msg.contains("year=2025"), "expected year=2025 in {msg}"); + assert_eq!(fs::read_dir(&year_2025).unwrap().count(), 0); +} + +#[test] +fn clobber_guard_rejects_parent_dir_after_missing_component_and_preserves_tree() { + let dir = TempDirGuard::new("clobber-parent-dir"); + let map_path = dir.path().join("mapping.tsv"); + write_bytes(&map_path, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); + + let fields = CeoPostsFieldNames::default(); + let bson_path = dir.path().join("posts.bson"); + write_bytes( + &bson_path, + &make_post_doc( + &fields, + "CEO_RY", + "sp-1", + utc_ms(2024, 6, 15, 14, 0, 0), + None, + None, + None, + "hi", + ), + ); + + // Seed exports/shared/events/year=2024/part.parquet while exports/scratch is absent. + let exports_dir = dir.path().join("exports"); + let shared_dir = exports_dir.join("shared"); + let year_2024 = shared_dir.join("events/year=2024"); + fs::create_dir_all(&year_2024).unwrap(); + let sentinel_path = year_2024.join("part.parquet"); + let sentinel_bytes = b"SENTINEL-FILINGS-EARNINGS-2024".to_vec(); + write_bytes(&sentinel_path, &sentinel_bytes); + + let bypass_out = exports_dir.join("scratch").join("..").join("shared"); + assert!(!exports_dir.join("scratch").exists()); + + let args = default_args( + bson_path, + map_path, + bypass_out, + CeoPostsTimestampUnit::Millis, + ); + let err = run_curate_posts(&args).unwrap_err(); + assert!(matches!(err, RunCuratePostsError::InvalidOutDir { .. })); + let msg = assert_single_line_err(&err); + assert!(msg.contains(".."), "expected '..' detail in {msg}"); + + // The missing scratch component must not have been created, and the target partition + // and surrounding directory tree must be completely unchanged. + assert!(!exports_dir.join("scratch").exists()); + assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes); + + let list_names = |p: &Path| -> Vec { + let mut names: Vec = fs::read_dir(p) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + names + }; + assert_eq!(list_names(&exports_dir), vec!["shared"]); + assert_eq!(list_names(&shared_dir), vec!["events"]); + assert_eq!(list_names(&shared_dir.join("events")), vec!["year=2024"]); + assert_eq!(list_names(&year_2024), vec!["part.parquet"]); +} + +#[test] +fn fail_closed_errors_are_typed_single_line_and_leave_out_dir_untouched() { + let dir = TempDirGuard::new("fail-closed"); + let out_dir = dir.path().join("out"); + fs::create_dir_all(&out_dir).unwrap(); + let marker = out_dir.join("keep.txt"); + let marker_bytes = b"DO-NOT-TOUCH".to_vec(); + write_bytes(&marker, &marker_bytes); + + let assert_out_untouched = || { + assert!( + !out_dir.join("events").exists(), + "events dir must not be created" + ); + assert_eq!(fs::read(&marker).unwrap(), marker_bytes); + let entries: Vec<_> = fs::read_dir(&out_dir) + .unwrap() + .map(|e| e.unwrap().file_name()) + .collect(); + assert_eq!(entries.len(), 1); + }; + + let valid_map = dir.path().join("valid_map.tsv"); + write_bytes(&valid_map, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); + + let fields = CeoPostsFieldNames::default(); + let valid_doc = make_post_doc( + &fields, + "CEO_RY", + "sp-valid", + utc_ms(2024, 6, 15, 14, 0, 0), + None, + None, + None, + "valid post", + ); + let valid_bson = dir.path().join("valid.bson"); + write_bytes(&valid_bson, &valid_doc); + + let base_args = default_args( + valid_bson.clone(), + valid_map.clone(), + out_dir.clone(), + CeoPostsTimestampUnit::Millis, + ); + + // 1. Invalid output paths: regular file as out_dir, empty out_dir, regular file as out/events + let file_as_out = dir.path().join("file_out"); + write_bytes(&file_as_out, b"not-a-dir"); + let err = run_curate_posts(&CuratePostsArgs { + out_dir: file_as_out.clone(), + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::InvalidOutDir { .. })); + assert_single_line_err(&err); + assert_eq!(fs::read(&file_as_out).unwrap(), b"not-a-dir"); + + let err = run_curate_posts(&CuratePostsArgs { + out_dir: PathBuf::new(), + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::InvalidOutDir { .. })); + assert_single_line_err(&err); + + let out_with_file_events = dir.path().join("out_file_events"); + fs::create_dir_all(&out_with_file_events).unwrap(); + write_bytes(&out_with_file_events.join("events"), b"file-not-dir"); + let err = run_curate_posts(&CuratePostsArgs { + out_dir: out_with_file_events.clone(), + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::InvalidOutDir { .. })); + assert_single_line_err(&err); + assert_eq!( + fs::read(out_with_file_events.join("events")).unwrap(), + b"file-not-dir" + ); + + // 2. Blank field name + let err = run_curate_posts(&CuratePostsArgs { + key_field: " ".to_string(), + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::InvalidFieldNames { .. })); + assert_single_line_err(&err); + assert_out_untouched(); + + // 3. Duplicate field names + let err = run_curate_posts(&CuratePostsArgs { + spiel_id_field: DEFAULT_KEY_FIELD.to_string(), + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::InvalidFieldNames { .. })); + assert_single_line_err(&err); + assert_out_untouched(); + + // 4. Blank mapping_source + let err = run_curate_posts(&CuratePostsArgs { + mapping_source: " \t ".to_string(), + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::EmptyMappingSource)); + assert_single_line_err(&err); + assert_out_untouched(); + + // 5. Missing input file + let err = run_curate_posts(&CuratePostsArgs { + ceo_posts: dir.path().join("missing.bson"), + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::OpenInput { .. })); + assert_single_line_err(&err); + assert_out_untouched(); + + // 6. Injected reader I/O error (valid doc followed by multiline BrokenPipe) + let multiline_cause = "decompression failed\ncaused by: corrupt zstd frame\r\nstream aborted"; + let err = run_curate_posts_with_reader( + &valid_map, + DEFAULT_MAPPING_SOURCE, + &fields, + CeoPostsTimestampUnit::Millis, + ( + Path::new("failing.bson"), + FailingReader { + prefix: valid_doc.clone(), + pos: 0, + error_message: multiline_cause.to_string(), + }, + ), + &out_dir, + ) + .unwrap_err(); + match &err { + RunCuratePostsError::BsonStream { + source: BsonStreamError::Io { offset, source }, + .. + } => { + assert_eq!(*offset, valid_doc.len() as u64); + // Typed cause is preserved intact. + assert_eq!(source.kind(), io::ErrorKind::BrokenPipe); + assert_eq!(source.to_string(), multiline_cause); + } + other => panic!("expected BsonStream::Io, got {other:?}"), + } + let msg = assert_single_line_err(&err); + assert!(msg.contains("failing.bson"), "expected path in {msg}"); + assert!( + msg.contains(&valid_doc.len().to_string()), + "expected byte offset in {msg}" + ); + assert!( + msg.contains("decompression failed\\ncaused by: corrupt zstd frame\\r\\nstream aborted"), + "expected escaped multiline cause in {msg}" + ); + assert_out_untouched(); + + // 6b. Path containing a newline is also escaped to a single line + let err = run_curate_posts_with_reader( + &valid_map, + DEFAULT_MAPPING_SOURCE, + &fields, + CeoPostsTimestampUnit::Millis, + ( + Path::new("dir/bad\nname.bson"), + FailingReader { + prefix: Vec::new(), + pos: 0, + error_message: "boom\nline2".to_string(), + }, + ), + &out_dir, + ) + .unwrap_err(); + assert!(matches!( + err, + RunCuratePostsError::BsonStream { + source: BsonStreamError::Io { offset: 0, .. }, + .. + } + )); + let msg = assert_single_line_err(&err); + assert!( + msg.contains("dir/bad\\nname.bson"), + "expected escaped path in {msg}" + ); + assert!( + msg.contains("boom\\nline2"), + "expected escaped cause in {msg}" + ); + assert_out_untouched(); + + // 7. Malformed TSV (line 2) + let bad_tsv = dir.path().join("bad.tsv"); + write_bytes( + &bad_tsv, + b"ceo\tCEO_RY\t2020-01-01\t\t101\nceo\tCEO_SHOP\tnot-a-date\t\t202\n", + ); + let err = run_curate_posts(&CuratePostsArgs { + provider_mapping: bad_tsv, + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::TsvParse { line: 2, .. })); + let msg = assert_single_line_err(&err); + assert!(msg.contains(":2:"), "expected :2: in {msg}"); + assert_out_untouched(); + + // 8. Overlapping provider_mapping.tsv + let overlap_tsv = dir.path().join("overlap.tsv"); + write_bytes( + &overlap_tsv, + b"ceo\tCEO_RY\t2020-01-01\t2024-06-01\t101\nceo\tCEO_RY\t2024-06-01\t\t102\n", + ); + let err = run_curate_posts(&CuratePostsArgs { + provider_mapping: overlap_tsv, + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::ProviderMapping { .. })); + let msg = assert_single_line_err(&err); + assert!(msg.contains("CEO_RY"), "expected conflicting key in {msg}"); + assert_out_untouched(); + + // 9. Truncated BSON after valid doc + let trunc_bson = dir.path().join("trunc.bson"); + let mut trunc_bytes = valid_doc.clone(); + let trunc_offset = trunc_bytes.len() as u64; + trunc_bytes.extend_from_slice(&[30, 0, 0, 0, 0x02, b'a']); + write_bytes(&trunc_bson, &trunc_bytes); + let err = run_curate_posts(&CuratePostsArgs { + ceo_posts: trunc_bson, + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!( + err, + RunCuratePostsError::BsonStream { + source: BsonStreamError::TruncatedDocument { offset, .. }, + .. + } if offset == trunc_offset + )); + let msg = assert_single_line_err(&err); + assert!(msg.contains(&trunc_offset.to_string())); + assert_out_untouched(); + + // 10. Corrupt BSON element after valid doc + let corrupt_bson = dir.path().join("corrupt.bson"); + let mut corrupt_doc = RawDocumentBuf::new(); + corrupt_doc.append(cstr!("ceoId"), "CEO_RY"); + corrupt_doc.append(cstr!("z"), 1_i32); + let mut bad_doc_bytes = corrupt_doc.into_bytes(); + let z_pos = bad_doc_bytes + .windows(3) + .position(|w| w == [0x10, b'z', 0x00]) + .unwrap(); + bad_doc_bytes[z_pos] = 0x7e; + + let mut combined_corrupt = valid_doc.clone(); + let corrupt_offset = combined_corrupt.len() as u64; + combined_corrupt.extend_from_slice(&bad_doc_bytes); + write_bytes(&corrupt_bson, &combined_corrupt); + let err = run_curate_posts(&CuratePostsArgs { + ceo_posts: corrupt_bson, + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!( + err, + RunCuratePostsError::CorruptBson { offset, .. } if offset == corrupt_offset + )); + let msg = assert_single_line_err(&err); + assert!(msg.contains(&corrupt_offset.to_string())); + assert_out_untouched(); + + // 11. Curation timestamp overflow after valid doc -> late failure publishes nothing + let overflow_bson = dir.path().join("overflow.bson"); + let mut overflow_bytes = valid_doc; + overflow_bytes.extend_from_slice(&make_post_doc( + &fields, + "CEO_RY", + "sp-overflow", + i64::MAX, + None, + None, + None, + "overflow ts", + )); + write_bytes(&overflow_bson, &overflow_bytes); + let err = run_curate_posts(&CuratePostsArgs { + ceo_posts: overflow_bson, + ..base_args + }) + .unwrap_err(); + assert!(matches!( + err, + RunCuratePostsError::CurateWrite { + source: CuratePostsWriteError::Curate(CuratePostsError::Posts( + PostsError::TimestampOverflow { .. } + )), + .. + } + )); + assert_single_line_err(&err); + assert_out_untouched(); +} + +#[test] +fn empty_and_all_unmapped_inputs_return_zero_rows_without_creating_events_dir() { + let dir = TempDirGuard::new("zero-rows"); + let map_path = dir.path().join("mapping.tsv"); + write_bytes(&map_path, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); + + // 1. Empty BSON input + let empty_bson = dir.path().join("empty.bson"); + write_bytes(&empty_bson, &[]); + let out_empty = dir.path().join("out_empty"); + let rep_empty = run_curate_posts(&default_args( + empty_bson, + map_path.clone(), + out_empty.clone(), + CeoPostsTimestampUnit::Millis, + )) + .expect("empty succeeds"); + assert_report_invariants(&rep_empty); + assert_eq!(rep_empty.docs_framed, 0); + assert_eq!(rep_empty.write_stats.rows_written, 0); + assert_eq!(rep_empty.write_stats.files_written, 0); + assert!(!out_empty.join("events").exists()); + + // 2. All-unmapped BSON input + let fields = CeoPostsFieldNames::default(); + let unmapped_bson = dir.path().join("unmapped.bson"); + write_bytes( + &unmapped_bson, + &make_post_doc( + &fields, + "NO_MATCH", + "sp-unmapped", + utc_ms(2024, 6, 15, 14, 0, 0), + None, + None, + None, + "unmapped", + ), + ); + let out_unmapped = dir.path().join("out_unmapped"); + let rep_unmapped = run_curate_posts(&default_args( + unmapped_bson, + map_path, + out_unmapped.clone(), + CeoPostsTimestampUnit::Millis, + )) + .expect("all-unmapped succeeds"); + assert_report_invariants(&rep_unmapped); + assert_eq!(rep_unmapped.docs_framed, 1); + assert_eq!(rep_unmapped.curate_stats.dropped_unmapped, 1); + assert_eq!(rep_unmapped.write_stats.rows_written, 0); + assert_eq!(rep_unmapped.write_stats.files_written, 0); + assert!(!out_unmapped.join("events").exists()); +} + +/// Reader that serves `bytes` and, on the first EOF, runs `on_eof` once (used to simulate another +/// publisher creating an `events/year=*` partition while the dump is still being decoded). +struct EofHookReader { + bytes: Vec, + pos: usize, + on_eof: Option, +} + +impl Read for EofHookReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if self.pos < self.bytes.len() { + let n = (self.bytes.len() - self.pos).min(buf.len()); + buf[..n].copy_from_slice(&self.bytes[self.pos..self.pos + n]); + self.pos += n; + return Ok(n); + } + if let Some(mut hook) = self.on_eof.take() { + hook(); + } + Ok(0) + } +} + +fn sorted_names(p: &Path) -> Vec { + let mut names: Vec = fs::read_dir(p) + .expect("read dir") + .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + names +} + +#[test] +fn post_decode_guard_rejects_partition_created_during_decode_and_preserves_bytes() { + let dir = TempDirGuard::new("guard-recheck"); + let map_path = dir.path().join("mapping.tsv"); + write_bytes(&map_path, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); + let fields = CeoPostsFieldNames::default(); + let doc = make_post_doc( + &fields, + "CEO_RY", + "sp-1", + utc_ms(2024, 6, 15, 14, 0, 0), + None, + None, + None, + "hi", + ); + + let out_dir = dir.path().join("out"); + let partition = out_dir.join("events").join("year=2024"); + let sentinel_path = partition.join("part.parquet"); + let sentinel = b"SENTINEL-CONCURRENT-FILINGS".to_vec(); + assert!( + !out_dir.exists(), + "first guard must see a fresh output root" + ); + + let hook_partition = partition.clone(); + let hook_sentinel_path = sentinel_path.clone(); + let hook_sentinel = sentinel.clone(); + let err = run_curate_posts_with_reader( + &map_path, + DEFAULT_MAPPING_SOURCE, + &fields, + CeoPostsTimestampUnit::Millis, + ( + Path::new("hooked.bson"), + EofHookReader { + bytes: doc, + pos: 0, + on_eof: Some(move || { + fs::create_dir_all(&hook_partition).expect("create concurrent partition"); + write_bytes(&hook_sentinel_path, &hook_sentinel); + }), + }, + ), + &out_dir, + ) + .unwrap_err(); + + assert!( + matches!(&err, RunCuratePostsError::EventsDatasetExists { path } if path == &partition), + "expected EventsDatasetExists for {partition:?}, got {err:?}" + ); + assert_single_line_err(&err); + assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel); + assert_eq!(sorted_names(&out_dir.join("events")), vec!["year=2024"]); + assert_eq!(sorted_names(&partition), vec!["part.parquet"]); +} + +#[test] +fn events_dir_with_only_non_year_entries_is_published_and_non_year_entries_preserved() { + let dir = TempDirGuard::new("non-year-entries"); + let map_path = dir.path().join("mapping.tsv"); + write_bytes(&map_path, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); + let fields = CeoPostsFieldNames::default(); + let bson_path = dir.path().join("posts.bson"); + write_bytes( + &bson_path, + &make_post_doc( + &fields, + "CEO_RY", + "sp-1", + utc_ms(2024, 6, 15, 14, 0, 0), + None, + None, + None, + "hi", + ), + ); + + let out_dir = dir.path().join("out"); + let events_dir = out_dir.join("events"); + fs::create_dir_all(&events_dir).unwrap(); + let readme = events_dir.join("README.txt"); + write_bytes(&readme, b"not a partition"); + + let report = run_curate_posts(&default_args( + bson_path, + map_path, + out_dir.clone(), + CeoPostsTimestampUnit::Millis, + )) + .expect("non-year entries must not trip the clobber guard"); + + assert_report_invariants(&report); + assert_eq!(report.write_stats.rows_written, 1); + assert_eq!(fs::read(&readme).unwrap(), b"not a partition"); + assert_eq!(sorted_names(&events_dir), vec!["README.txt", "year=2024"]); +} + +#[test] +fn parent_dir_through_existing_components_still_hits_events_guard() { + let dir = TempDirGuard::new("parent-existing"); + let map_path = dir.path().join("mapping.tsv"); + write_bytes(&map_path, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); + let fields = CeoPostsFieldNames::default(); + let bson_path = dir.path().join("posts.bson"); + write_bytes( + &bson_path, + &make_post_doc( + &fields, + "CEO_RY", + "sp-1", + utc_ms(2024, 6, 15, 14, 0, 0), + None, + None, + None, + "hi", + ), + ); + + let exports = dir.path().join("exports"); + let shared_partition = exports.join("shared/events/year=2024"); + fs::create_dir_all(&shared_partition).unwrap(); + fs::create_dir_all(exports.join("scratch")).unwrap(); + let sentinel_path = shared_partition.join("part.parquet"); + write_bytes(&sentinel_path, b"SENTINEL"); + + // `scratch` exists, so `..` resolves consistently and the guard must inspect `shared`. + let out = exports.join("scratch").join("..").join("shared"); + let err = run_curate_posts(&default_args( + bson_path, + map_path, + out, + CeoPostsTimestampUnit::Millis, + )) + .unwrap_err(); + assert!( + matches!(err, RunCuratePostsError::EventsDatasetExists { .. }), + "got {err:?}" + ); + assert_single_line_err(&err); + assert_eq!(fs::read(&sentinel_path).unwrap(), b"SENTINEL"); + assert_eq!(sorted_names(&exports), vec!["scratch", "shared"]); + assert!(sorted_names(&exports.join("scratch")).is_empty()); +} + +#[test] +fn eastern_posting_date_mapping_and_edit_clamp_match_curate_posts_baseline() { + let dir = TempDirGuard::new("eastern-pit"); + let map_path = dir.path().join("mapping.tsv"); + // Listing switch at the Eastern calendar boundary 2023-12-31 -> 2024-01-01 (valid_to inclusive). + write_bytes( + &map_path, + b"ceo\tCEO_RY\t2020-01-01\t2023-12-31\t101\nceo\tCEO_RY\t2024-01-01\t\t102\n", + ); + let fields = CeoPostsFieldNames::default(); + + // 2024-01-01 03:00 UTC == 2023-12-31 22:00 EST -> listing 101 (UTC date would give 102). + let t_late_eve = utc_ms(2024, 1, 1, 3, 0, 0); + // 2024-01-01 06:00 UTC == 2024-01-01 01:00 EST -> listing 102. + let t_new_year = utc_ms(2024, 1, 1, 6, 0, 0); + // Posted 2023-12-31 23:30 EST, edited after the switch: mapping must follow posted date. + let t_edit_posted = utc_ms(2024, 1, 1, 4, 30, 0); + let t_edit_at = utc_ms(2024, 1, 2, 15, 0, 0); + // Edit earlier than posting (clock skew): known_at clamps to posted_at. + let t_skew_posted = utc_ms(2024, 3, 5, 15, 0, 0); + let t_skew_edit = utc_ms(2024, 3, 5, 14, 0, 0); + + let inputs: Vec<(&str, i64, Option, Option<&str>)> = vec![ + ("sp-eve", t_late_eve, None, Some("1")), + ("sp-ny", t_new_year, None, None), + ("sp-edit", t_edit_posted, Some(t_edit_at), None), + ("sp-skew", t_skew_posted, Some(t_skew_edit), Some("0")), + ]; + let mut bytes = Vec::new(); + let mut baseline_posts = Vec::new(); + for (spiel, ts, ed, bot) in &inputs { + bytes.extend_from_slice(&make_post_doc( + &fields, + "CEO_RY", + spiel, + *ts, + *ed, + *bot, + Some("u"), + spiel, + )); + baseline_posts.push(CeoPost { + key: "CEO_RY".to_string(), + spiel_id: spiel.to_string(), + timestamp_ms: *ts, + edited_ms: *ed, + bot: bot.map(str::to_string), + user_id: Some("u".to_string()), + text: spiel.to_string(), + }); + } + let bson_path = dir.path().join("posts.bson"); + write_bytes(&bson_path, &bytes); + let out_dir = dir.path().join("out"); + + let report = run_curate_posts(&default_args( + bson_path, + map_path.clone(), + out_dir.clone(), + CeoPostsTimestampUnit::Millis, + )) + .expect("run"); + assert_report_invariants(&report); + assert_eq!(report.curate_stats.builder.edited, 2); + assert_eq!(report.curate_stats.builder.edited_before_posted, 1); + assert_eq!(report.write_stats.rows_written, 4); + + let mapping = ProviderMappingTable::from_rows(vec![ + ProviderMappingRow { + source: "ceo".to_string(), + source_id: "CEO_RY".to_string(), + valid_from: day(2020, 1, 1), + valid_to: Some(day(2023, 12, 31)), + listing_id: 101, + }, + ProviderMappingRow { + source: "ceo".to_string(), + source_id: "CEO_RY".to_string(), + valid_from: day(2024, 1, 1), + valid_to: None, + listing_id: 102, + }, + ]) + .unwrap(); + let baseline = curate_posts(baseline_posts, "ceo", &mapping).expect("baseline"); + let rows = read_all_event_partitions(&out_dir); + assert_eq!(rows, baseline.rows); + assert_eq!(report.curate_stats, baseline.stats); + + let find = |spiel: &str| { + rows.iter() + .find(|r| r.payload_json.contains(spiel)) + .unwrap_or_else(|| panic!("row {spiel}")) + }; + assert_eq!(find("sp-eve").listing_id, 101); + assert_eq!(find("sp-ny").listing_id, 102); + let edit = find("sp-edit"); + assert_eq!(edit.listing_id, 101); + assert_eq!(edit.ts_micros, t_edit_posted * 1_000); + assert_eq!(edit.known_at_micros, t_edit_at * 1_000); + let skew = find("sp-skew"); + assert_eq!(skew.ts_micros, t_skew_posted * 1_000); + assert_eq!(skew.known_at_micros, t_skew_posted * 1_000); + // No row may become visible before it was posted. + assert!(rows.iter().all(|r| r.known_at_micros >= r.ts_micros)); + // All four posts land in the UTC-2024 partition only. + assert_eq!(sorted_names(&out_dir.join("events")), vec!["year=2024"]); +} diff --git a/tools/curate-etl/tests/curate_posts.rs b/tools/curate-etl/tests/curate_posts.rs new file mode 100644 index 00000000..c349ceec --- /dev/null +++ b/tools/curate-etl/tests/curate_posts.rs @@ -0,0 +1,191 @@ +//! End-to-end tests for the file-mode curate-posts CLI. + +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; + +use bson::{doc, Document}; +use curate_etl::bson_ceo_posts::CeoPostsTimestampUnit; +use curate_etl::run_curate_posts::{format_curate_posts_report, run_curate_posts, CuratePostsArgs}; +use parquet::file::reader::{FileReader, SerializedFileReader}; +use parquet::record::RowAccessor; + +const POSTED: i64 = 1_718_460_000; +const EDITED: i64 = POSTED + 3_600; +const PARTITION: &str = "events/year=2024/part.parquet"; +const MAPPING: &str = "ceo_alt\tCH_1\t2020-01-01\t\t555\nceo_alt\tCH_2\t2020-01-01\t\t556\n"; +const CUSTOM_FLAGS: &[&str] = &[ + "--key-field=channel", + "--spiel-id-field=id", + "--timestamp-field=ts", + "--edited-field=ed", + "--bot-field=isBot", + "--user-id-field=author", + "--text-field=body", + "--mapping-source=ceo_alt", +]; + +struct TempDir(PathBuf); + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn cli() -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_curate-etl")); + command.arg("curate-posts"); + command +} + +fn curate(dir: &Path, out: &str, unit: &str) -> Output { + cli() + .current_dir(dir) + .args([ + "--ceo-posts", + "posts.bson", + "--provider-mapping=mapping.tsv", + ]) + .args(["--out", out, "--timestamp-unit", unit]) + .args(CUSTOM_FLAGS) + .output() + .expect("run curate-posts") +} + +fn write_posts(path: &Path, scale: i64, edited_text: &str) { + let posts: [Document; 3] = [ + doc! { + "channel": "CH_1", "id": "p-1", "ts": POSTED * scale, + "ed": EDITED * scale, "author": "u1", "body": edited_text, + }, + doc! { + "channel": "CH_2", "id": "wire-1", "ts": POSTED * scale, + "isBot": "1", "body": "wire release", + }, + doc! { + "channel": "unmapped", "id": "p-2", "ts": POSTED * scale, + "body": "unmapped post", + }, + ]; + let bytes: Vec = posts + .iter() + .flat_map(|post| post.to_vec().unwrap()) + .collect(); + fs::write(path, bytes).expect("write concatenated BSON"); +} + +#[test] +fn cli_publishes_runner_equivalent_posts_and_preserves_an_existing_partition() { + // Use the runner's fixed custom-field and edited-post fixture, plus a wire and an unmapped row. + let path = std::env::temp_dir().join(format!("curate-posts-cli-{}", std::process::id())); + fs::create_dir(&path).expect("create isolated test directory"); + let dir = TempDir(path); + let bson = dir.0.join("posts.bson"); + let mapping = dir.0.join("mapping.tsv"); + write_posts(&bson, 1, "hello"); + fs::write(&mapping, MAPPING).unwrap(); + + let baseline_dir = dir.0.join("baseline"); + let baseline_report = run_curate_posts(&CuratePostsArgs { + ceo_posts: bson.clone(), + provider_mapping: mapping, + out_dir: baseline_dir.clone(), + timestamp_unit: CeoPostsTimestampUnit::Seconds, + key_field: "channel".into(), + spiel_id_field: "id".into(), + timestamp_field: "ts".into(), + edited_field: "ed".into(), + bot_field: "isBot".into(), + user_id_field: "author".into(), + text_field: "body".into(), + mapping_source: "ceo_alt".into(), + }) + .expect("run library baseline"); + let baseline = fs::read(baseline_dir.join(PARTITION)).unwrap(); + let expected_report = format_curate_posts_report(&baseline_report); + + for (unit, scale) in [("seconds", 1), ("millis", 1_000)] { + write_posts(&bson, scale, "hello"); + let result = curate(&dir.0, unit, unit); + assert!(result.status.success(), "{unit}: {:?}", result); + assert!(result.stderr.is_empty()); + let stdout = String::from_utf8(result.stdout).unwrap(); + assert_eq!( + stdout.lines().take(5).collect::>(), + expected_report.lines().take(5).collect::>() + ); + assert!(stdout.contains("docs_framed=3")); + assert!(stdout.contains("dropped_unmapped=1")); + assert!(stdout.contains("rows_written=2")); + assert!(stdout.lines().last().unwrap().contains("timing:")); + assert_eq!( + fs::read(dir.0.join(unit).join(PARTITION)).unwrap(), + baseline + ); + } + + let partition = dir.0.join("millis").join(PARTITION); + let reader = SerializedFileReader::new(File::open(&partition).unwrap()).unwrap(); + let rows: Vec<_> = reader + .get_row_iter(None) + .unwrap() + .map(Result::unwrap) + .collect(); + assert_eq!(rows.len(), 2); + for (row, listing, subtype, known_at) in [ + (&rows[0], 555, "retail", EDITED), + (&rows[1], 556, "newswire", POSTED), + ] { + assert_eq!(row.get_int(0).unwrap(), listing); + assert_eq!(row.get_timestamp_micros(1).unwrap(), POSTED * 1_000_000); + assert_eq!(row.get_timestamp_micros(2).unwrap(), known_at * 1_000_000); + assert_eq!(row.get_string(4).unwrap(), "post"); + assert_eq!(row.get_string(5).unwrap(), subtype); + } + + let edited_text_visible = |cutoff| { + rows.iter().any(|row| { + row.get_timestamp_micros(2).unwrap() <= cutoff + && row.get_string(6).unwrap().contains(r#""text":"hello""#) + }) + }; + assert!(!edited_text_visible(EDITED * 1_000_000 - 1)); + assert!(edited_text_visible(EDITED * 1_000_000)); + + write_posts(&bson, 1_000, "replacement"); + let retry = curate(&dir.0, "millis", "millis"); + assert_eq!(retry.status.code(), Some(1)); + assert!(retry.stdout.is_empty()); + assert!(String::from_utf8_lossy(&retry.stderr) + .starts_with("error: refusing to overwrite existing events partition")); + assert_eq!(fs::read(partition).unwrap(), baseline); +} + +#[test] +fn cli_reports_usage_for_invalid_posts_flags() { + for (args, error) in [ + ( + &["--from-mongo"][..], + "unknown flag '--from-mongo' for curate-posts", + ), + ( + &["--timestamp-unit", "--out=x"][..], + "missing value for flag '--timestamp-unit'", + ), + ( + &["--text-field=first", "--text-field", "second"][..], + "duplicate flag '--text-field'", + ), + ] { + let result = cli().args(args).output().expect("run curate-posts"); + assert_eq!(result.status.code(), Some(1), "{args:?}"); + assert!(result.stdout.is_empty(), "{args:?}"); + let stderr = String::from_utf8(result.stderr).unwrap(); + assert_eq!( + stderr.lines().next(), + Some(format!("error: {error}").as_str()) + ); + assert!(stderr.contains("curate-posts --ceo-posts"), "{stderr}"); + } +}