diff --git a/libs/research/README.md b/libs/research/README.md index a0f15120..44c85510 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -278,6 +278,12 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported - **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. - **Bar-derived `SessionDatesPort` (`createBarSessionDatesPort({ store, referenceListingIds })`):** Exported from `@stock-bot/research/mcp` alongside `BarSessionDatesPortOptions` and `BarSessionDatesError`. Keys in `referenceListingIds` are exact `exchange.calendar_code` strings (e.g. `XNYS`, `XTSE`) mapped to non-empty, duplicate-free arrays of positive INT32 reference listing IDs whose daily bars define that exchange's session dates; the caller owns reference-listing coverage so gaps do not omit real sessions. Each `listSessionDates` call queries `store.bars({ listingIds, timeframe: '1d', from, to, adjustment: 'raw' })` once with `scope` and `asOf` omitted so the store's default `'vault_fenced'` scope applies (`'vault_evaluation_only'` is never passed), propagates store errors (including `VaultHoldoutFenceError`) unchanged, derives UTC session dates from `BarRecord.ts` (`Math.floor(ts / MS_PER_DAY)`), and fails closed on unknown calendars, malformed queries, or invalid bars. +### 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/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-trial-ref.ts b/libs/research/src/mcp/adapters/postgres-trial-ref.ts index adeb9825..bc6ac3f7 100644 --- a/libs/research/src/mcp/adapters/postgres-trial-ref.ts +++ b/libs/research/src/mcp/adapters/postgres-trial-ref.ts @@ -6,17 +6,20 @@ * injected via {@link TrialRefExecutor}. */ -import { MarketDataStoreValidationError } from '../../market-data-store'; import type { TrialRefLookupPort } from '../tools/file-finding'; import { utcDateOf, validateVaultCutoffTs } from '../tools/vault-fenced-input'; const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/; -const CANONICAL_TRIAL_ID_RE = /^[1-9][0-9]{0,18}$/; -const MAX_PG_BIGINT_STR = '9223372036854775807'; -const PG_ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/; +const FOUR_DIGIT_DATE_RE = /^\d{4}-\d{2}-\d{2}$/; +const CANONICAL_POSITIVE_BIGINT_RE = /^[1-9][0-9]{0,18}$/; +const MAX_SIGNED_BIGINT_STR = '9223372036854775807'; /** Error codes thrown by {@link PostgresTrialRefError}. */ -export type PostgresTrialRefErrorCode = 'INVALID_EXECUTOR' | 'INVALID_SCHEMA' | 'INVALID_ROW'; +export type PostgresTrialRefErrorCode = + | 'INVALID_EXECUTOR' + | 'INVALID_SCHEMA' + | 'INVALID_VAULT_CUTOFF' + | 'INVALID_ROW'; /** Typed validation error thrown by the PostgreSQL trial-ref lookup adapter. */ export class PostgresTrialRefError extends RangeError { @@ -41,37 +44,40 @@ export interface TrialRefExecutor { ): Promise<{ readonly rows: readonly Row[] }>; } -/** Factory options for {@link createPostgresTrialRefPort}. */ -export interface PostgresTrialRefPortOptions { +/** Factory options for {@link createPostgresTrialRefLookupPort} / {@link createPostgresTrialRefPort}. */ +export interface PostgresTrialRefLookupPortOptions { readonly executor: TrialRefExecutor; - /** Server-injected Vault cutoff epoch-ms timestamp; trials with `sample_end < utcDate(vaultCutoffTs)` are visible. */ + /** Authoritative UTC epoch-ms Vault cutoff; trials with `sample_end < cutoffDate` are research-visible. */ readonly vaultCutoffTs: number; /** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */ readonly schema?: string; } +/** Alias for {@link PostgresTrialRefLookupPortOptions}. */ +export type PostgresTrialRefPortOptions = PostgresTrialRefLookupPortOptions; + interface RawTrialRefVisibilityRow { - readonly visible: unknown; + readonly visible?: unknown; } function isCanonicalPositiveBigInt(value: unknown): value is string { - if (typeof value !== 'string' || !CANONICAL_TRIAL_ID_RE.test(value)) { + if (typeof value !== 'string' || !CANONICAL_POSITIVE_BIGINT_RE.test(value)) { return false; } - if (value.length === MAX_PG_BIGINT_STR.length && value > MAX_PG_BIGINT_STR) { + if (value.length === MAX_SIGNED_BIGINT_STR.length && value > MAX_SIGNED_BIGINT_STR) { return false; } return true; } -function buildTrialRefVisibilitySql(schemaPrefix: string): string { +function buildTrialVisibilitySql(schemaPrefix: string): string { return `SELECT 1 AS visible FROM ${schemaPrefix}trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1`; } -function validateFactoryOptions(options: PostgresTrialRefPortOptions): { +function validateFactoryOptions(options: PostgresTrialRefLookupPortOptions): { readonly executor: TrialRefExecutor; + readonly cutoffDate: string; readonly schemaPrefix: string; - readonly vaultCutoffDate: string; } { if (typeof options !== 'object' || options === null) { throw new PostgresTrialRefError( @@ -99,28 +105,39 @@ function validateFactoryOptions(options: PostgresTrialRefPortOptions): { schemaPrefix = `"${schema}".`; } - const cutoffTs = validateVaultCutoffTs(vaultCutoffTs); - const vaultCutoffDate = utcDateOf(cutoffTs); - if (!PG_ISO_DATE_RE.test(vaultCutoffDate) || vaultCutoffDate.startsWith('0000-')) { - throw new MarketDataStoreValidationError( - `Invalid \`vaultCutoffTs\`: ${String(vaultCutoffTs)} does not produce a PostgreSQL YYYY-MM-DD date.`, - 'vaultCutoffTs' + let validatedCutoffTs: number; + try { + validatedCutoffTs = validateVaultCutoffTs(vaultCutoffTs); + } catch { + throw new PostgresTrialRefError( + 'INVALID_VAULT_CUTOFF', + 'Invalid vaultCutoffTs: expected a finite safe-integer epoch-ms timestamp within ECMAScript Date bounds.' ); } - return { executor, schemaPrefix, vaultCutoffDate }; + const cutoffDate = utcDateOf(validatedCutoffTs); + if (!FOUR_DIGIT_DATE_RE.test(cutoffDate) || cutoffDate.startsWith('0000-')) { + throw new PostgresTrialRefError( + 'INVALID_VAULT_CUTOFF', + 'Invalid vaultCutoffTs: resolved UTC date must be a four-digit PostgreSQL calendar date (0001-01-01 through 9999-12-31).' + ); + } + + return { executor, cutoffDate, schemaPrefix }; } /** * Creates a read-only PostgreSQL {@link TrialRefLookupPort} backed by `trial_ledger` - * (`36-trial-ledger.sql`), enforcing `sample_end < vaultCutoffDate` so unknown and - * Vault-only trial references are indistinguishable. + * (`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`. */ -export function createPostgresTrialRefPort( - options: PostgresTrialRefPortOptions +export function createPostgresTrialRefLookupPort( + options: PostgresTrialRefLookupPortOptions ): TrialRefLookupPort { - const { executor, schemaPrefix, vaultCutoffDate } = validateFactoryOptions(options); - const sql = buildTrialRefVisibilitySql(schemaPrefix); + const { executor, cutoffDate, schemaPrefix } = validateFactoryOptions(options); + const sql = buildTrialVisibilitySql(schemaPrefix); return { async hasResearchVisibleTrial(trialRef: string): Promise { @@ -128,11 +145,7 @@ export function createPostgresTrialRefPort( return false; } - const result = await executor.query(sql, [ - trialRef, - vaultCutoffDate, - ]); - + const result = await executor.query(sql, [trialRef, cutoffDate]); if (typeof result !== 'object' || result === null || !Array.isArray(result.rows)) { throw new PostgresTrialRefError( 'INVALID_ROW', @@ -163,3 +176,6 @@ export function createPostgresTrialRefPort( }, }; } + +/** 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 ec6e21b0..9ffe9a0a 100644 --- a/libs/research/src/mcp/index.ts +++ b/libs/research/src/mcp/index.ts @@ -1,3 +1,4 @@ +export * from './adapters/library-cards'; export * from './adapters/postgres-findings'; export * from './adapters/postgres-symbol-search'; export * from './adapters/postgres-trial-ref'; 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-trial-ref.test.ts b/libs/research/test/mcp-postgres-trial-ref.test.ts index cffaf1a8..f3f4186c 100644 --- a/libs/research/test/mcp-postgres-trial-ref.test.ts +++ b/libs/research/test/mcp-postgres-trial-ref.test.ts @@ -1,10 +1,20 @@ import { describe, expect, test } from 'bun:test'; -import { MarketDataStoreValidationError } from '../src/market-data-store'; import { + type AppendFindingResult, + FILE_FINDING_ERROR_FILING_FAILED, + FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, + FILE_FINDING_INITIAL_STATUS, + type FileFindingResultPayload, + type FiledFindingRecord, + type FindingWritePort, PostgresTrialRefError, type TrialRefExecutor, + createFileFindingTool, + createMcpServer, + createPostgresTrialRefLookupPort, createPostgresTrialRefPort, } from '../src/mcp/index'; +import { utcDateOf } from '../src/mcp/tools/vault-fenced-input'; interface RecordedCall { readonly text: string; @@ -28,92 +38,67 @@ function createFakeExecutor(rows: readonly Record[] = []): { return { calls, executor }; } -const CUTOFF_TS = Date.UTC(2025, 5, 30, 15, 45, 30, 500); // 2025-06-30T15:45:30.500Z -const CUTOFF_DATE = '2025-06-30'; +function createFakeWritePort(): { + readonly appended: FiledFindingRecord[]; + readonly port: FindingWritePort; +} { + const appended: FiledFindingRecord[] = []; + const port: FindingWritePort = { + async appendFinding(record: FiledFindingRecord): Promise { + appended.push(record); + return { + status: 'created', + id: record.id, + createdAt: record.createdAt, + }; + }, + }; + return { appended, port }; +} -describe('createPostgresTrialRefPort (fake executor)', () => { - test('issues exact parameterized SELECT with default search_path and explicit quoted schema', async () => { - const fakeDefault = createFakeExecutor([{ visible: 1 }]); - const defaultPort = createPostgresTrialRefPort({ - executor: fakeDefault.executor, - vaultCutoffTs: CUTOFF_TS, - }); +const CUTOFF_MIDNIGHT_TS = Date.UTC(2025, 5, 30, 0, 0, 0, 0); // 2025-06-30T00:00:00.000Z - expect(await defaultPort.hasResearchVisibleTrial('42')).toBe(true); - expect(fakeDefault.calls).toEqual([ - { - text: 'SELECT 1 AS visible FROM trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1', - params: ['42', CUTOFF_DATE], - }, - ]); - - const fakeScoped = createFakeExecutor([{ visible: 1 }]); - const scopedPort = createPostgresTrialRefPort({ - executor: fakeScoped.executor, - vaultCutoffTs: CUTOFF_TS, - schema: 'research_iso_1', - }); - - expect(await scopedPort.hasResearchVisibleTrial('42')).toBe(true); - expect(fakeScoped.calls).toEqual([ - { - text: 'SELECT 1 AS visible FROM "research_iso_1".trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1', - params: ['42', CUTOFF_DATE], - }, - ]); +describe('createPostgresTrialRefLookupPort', () => { + test('exposes createPostgresTrialRefPort as an alias', () => { + expect(createPostgresTrialRefPort).toBe(createPostgresTrialRefLookupPort); }); - test('converts vaultCutoffTs once to UTC calendar date across midnight boundaries', async () => { - const lateFake = createFakeExecutor([]); - // 2025-06-30T23:30:00.000Z is already 2025-07-01 in UTC+1 zones; must bind UTC date 2025-06-30. - const latePort = createPostgresTrialRefPort({ - executor: lateFake.executor, - vaultCutoffTs: Date.UTC(2025, 5, 30, 23, 30, 0, 0), - }); - expect(await latePort.hasResearchVisibleTrial('7')).toBe(false); - expect(lateFake.calls[0]?.params).toEqual(['7', '2025-06-30']); - - const nextFake = createFakeExecutor([]); - const nextPort = createPostgresTrialRefPort({ - executor: nextFake.executor, - vaultCutoffTs: Date.UTC(2025, 6, 1, 0, 0, 0, 0), - }); - expect(await nextPort.hasResearchVisibleTrial('7')).toBe(false); - expect(nextFake.calls[0]?.params).toEqual(['7', '2025-07-01']); - }); - - test('rejects invalid options and executors with INVALID_EXECUTOR before any query', () => { + test('rejects missing or non-callable executor with INVALID_EXECUTOR', () => { const invalidOptions: unknown[] = [ null, undefined, {}, - { executor: null, vaultCutoffTs: CUTOFF_TS }, - { executor: {}, vaultCutoffTs: CUTOFF_TS }, - { executor: { query: 'not-a-fn' }, vaultCutoffTs: CUTOFF_TS }, + { executor: null, vaultCutoffTs: CUTOFF_MIDNIGHT_TS }, + { executor: {}, vaultCutoffTs: CUTOFF_MIDNIGHT_TS }, + { executor: { query: 'not-a-fn' }, vaultCutoffTs: CUTOFF_MIDNIGHT_TS }, ]; for (const opts of invalidOptions) { let caught: unknown; try { - createPostgresTrialRefPort(opts as Parameters[0]); + createPostgresTrialRefLookupPort( + opts as Parameters[0] + ); } catch (err) { caught = err; } expect(caught).toBeInstanceOf(PostgresTrialRefError); + expect(caught).toBeInstanceOf(RangeError); expect((caught as PostgresTrialRefError).code).toBe('INVALID_EXECUTOR'); } }); - test('rejects invalid schema identifiers with INVALID_SCHEMA before any query', () => { + test('rejects invalid schema names with INVALID_SCHEMA before any query', () => { const fake = createFakeExecutor([]); const badSchemas: unknown[] = [ '', 'Public', + 'Bad-Schema', + 'a;drop', '1schema', - 'bad-name', 'bad.name', - 'public"; DROP TABLE trial_ledger; --', 'space name', + 'public"; DROP TABLE trial_ledger; --', 123, null, ]; @@ -121,9 +106,9 @@ describe('createPostgresTrialRefPort (fake executor)', () => { for (const schema of badSchemas) { let caught: unknown; try { - createPostgresTrialRefPort({ + createPostgresTrialRefLookupPort({ executor: fake.executor, - vaultCutoffTs: CUTOFF_TS, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, schema: schema as string, }); } catch (err) { @@ -136,150 +121,172 @@ describe('createPostgresTrialRefPort (fake executor)', () => { expect(fake.calls).toHaveLength(0); }); - test('accepts minimal valid schema identifiers and prototype-method pg.Pool-shaped executors', async () => { - for (const schema of ['_', 'a', 'stock_bot_safety_0abc']) { - const fake = createFakeExecutor([]); - const port = createPostgresTrialRefPort({ - executor: fake.executor, - vaultCutoffTs: CUTOFF_TS, - schema, - }); - await port.hasResearchVisibleTrial('1'); - expect(fake.calls[0]?.text).toContain(`FROM "${schema}".trial_ledger `); - } - - class PrototypeExecutor { - readonly calls: RecordedCall[] = []; - async query>( - text: string, - params?: readonly unknown[] - ): Promise<{ readonly rows: readonly Row[] }> { - this.calls.push({ text, params }); - return { rows: [{ visible: 1 }] as unknown as readonly Row[] }; - } - } - - const executor = new PrototypeExecutor(); - const port = createPostgresTrialRefPort({ executor, vaultCutoffTs: CUTOFF_TS }); - expect(await port.hasResearchVisibleTrial('101')).toBe(true); - expect(executor.calls).toHaveLength(1); - }); - - test('rejects invalid or non-PostgreSQL-date vaultCutoffTs with MarketDataStoreValidationError', () => { + test('rejects invalid or extended-year vaultCutoffTs with INVALID_VAULT_CUTOFF', () => { const fake = createFakeExecutor([]); - const yearZeroTs = new Date('0000-06-15T00:00:00.000Z').getTime(); - const negativeYearTs = new Date('-000001-01-01T00:00:00.000Z').getTime(); - const fiveDigitYearTs = new Date('+010000-01-01T00:00:00.000Z').getTime(); - - const invalidCutoffs: unknown[] = [ - undefined, - null, - '2025-06-30', + const badCutoffs: unknown[] = [ Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, - 1.5, + '2025-06-30', + null, + undefined, + 123.45, Number.MAX_SAFE_INTEGER + 1, 8_640_000_000_000_000, -8_640_000_000_000_000, - yearZeroTs, - negativeYearTs, - fiveDigitYearTs, + Date.parse('+010000-01-01T00:00:00.000Z'), + Date.parse('-000001-01-01T00:00:00.000Z'), + Date.parse('0000-01-01T00:00:00.000Z'), ]; - for (const vaultCutoffTs of invalidCutoffs) { + for (const vaultCutoffTs of badCutoffs) { let caught: unknown; try { - createPostgresTrialRefPort({ + createPostgresTrialRefLookupPort({ executor: fake.executor, vaultCutoffTs: vaultCutoffTs as number, }); } catch (err) { caught = err; } - expect(caught).toBeInstanceOf(MarketDataStoreValidationError); - expect((caught as MarketDataStoreValidationError).field).toBe('vaultCutoffTs'); + expect(caught).toBeInstanceOf(PostgresTrialRefError); + expect((caught as PostgresTrialRefError).code).toBe('INVALID_VAULT_CUTOFF'); } expect(fake.calls).toHaveLength(0); }); - test('returns false with zero executor calls for every invalid, non-canonical, overflow, or injection-shaped ref', async () => { + test('returns true for a visible trial with one parameterized read-only SELECT and exact params', async () => { const fake = createFakeExecutor([{ visible: 1 }]); - const port = createPostgresTrialRefPort({ + const port = createPostgresTrialRefLookupPort({ executor: fake.executor, - vaultCutoffTs: CUTOFF_TS, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, + }); + + const visible = await port.hasResearchVisibleTrial('42'); + + expect(visible).toBe(true); + expect(fake.calls).toHaveLength(1); + const call = fake.calls[0]!; + 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).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'); + }); + + test('returns false when the executor returns empty rows (unknown or Vault-only trial)', async () => { + const fake = createFakeExecutor([]); + const port = createPostgresTrialRefLookupPort({ + executor: fake.executor, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, + }); + + const visible = await port.hasResearchVisibleTrial('42'); + + expect(visible).toBe(false); + expect(fake.calls).toHaveLength(1); + expect(fake.calls[0]!.params).toEqual(['42', '2025-06-30']); + }); + + test('maps midnight and non-midnight UTC vaultCutoffTs to the same UTC date as utcDateOf', async () => { + const nonMidnightTs = Date.UTC(2025, 5, 30, 23, 59, 59, 999); + const nextDayTs = Date.UTC(2025, 6, 1, 0, 0, 0, 0); + + const fakeSameDay = createFakeExecutor([{ visible: 1 }]); + const sameDayPort = createPostgresTrialRefLookupPort({ + executor: fakeSameDay.executor, + vaultCutoffTs: nonMidnightTs, + }); + await sameDayPort.hasResearchVisibleTrial('7'); + expect(fakeSameDay.calls[0]!.params).toEqual(['7', utcDateOf(nonMidnightTs)]); + expect(fakeSameDay.calls[0]!.params?.[1]).toBe('2025-06-30'); + + const fakeNextDay = createFakeExecutor([{ visible: 1 }]); + const nextDayPort = createPostgresTrialRefLookupPort({ + executor: fakeNextDay.executor, + vaultCutoffTs: nextDayTs, + }); + await nextDayPort.hasResearchVisibleTrial('7'); + expect(fakeNextDay.calls[0]!.params).toEqual(['7', '2025-07-01']); + }); + + test('returns false with zero executor calls for malformed, injection-shaped, overflowing, and non-string refs', async () => { + const fake = createFakeExecutor([{ visible: 1 }]); + const port = createPostgresTrialRefLookupPort({ + executor: fake.executor, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, }); const invalidRefs: unknown[] = [ '', - ' ', - ' 1', - '1 ', - '\t1', - '1\n', + ' 42', + '42 ', + '042', '0', '-1', '+1', - '01', - '0001', '1.0', - '1e2', - '1E2', + '1e3', '0x10', '1_000', - 'abc', - '1; DROP TABLE trial_ledger', - '1 OR 1=1', + '42; DROP TABLE trial_ledger', '9223372036854775808', - '9999999999999999999', '10000000000000000000', - 1, - 0, + 42, + 42n, null, undefined, {}, [], - 1n, ]; for (const ref of invalidRefs) { - expect(await port.hasResearchVisibleTrial(ref as string)).toBe(false); + const result = await port.hasResearchVisibleTrial(ref as string); + expect(result).toBe(false); } expect(fake.calls).toHaveLength(0); }); - test('passes 9223372036854775807 as an exact string without Number coercion and skips 9223372036854775808', async () => { + test('queries the maximum signed 64-bit BIGINT verbatim as a string without numeric coercion', async () => { + const maxBigIntRef = '9223372036854775807'; const fake = createFakeExecutor([{ visible: 1 }]); - const port = createPostgresTrialRefPort({ + const port = createPostgresTrialRefLookupPort({ executor: fake.executor, - vaultCutoffTs: CUTOFF_TS, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, }); - expect(await port.hasResearchVisibleTrial('9223372036854775807')).toBe(true); - expect(fake.calls).toHaveLength(1); - expect(fake.calls[0]?.params).toEqual(['9223372036854775807', CUTOFF_DATE]); - expect(typeof fake.calls[0]?.params?.[0]).toBe('string'); + const visible = await port.hasResearchVisibleTrial(maxBigIntRef); - expect(await port.hasResearchVisibleTrial('9223372036854775808')).toBe(false); + expect(visible).toBe(true); expect(fake.calls).toHaveLength(1); + expect(fake.calls[0]!.text).not.toContain(maxBigIntRef); + expect(fake.calls[0]!.params).toEqual([maxBigIntRef, '2025-06-30']); }); - test('returns false for zero rows and true for exactly one valid visibility row', async () => { - const emptyFake = createFakeExecutor([]); - const emptyPort = createPostgresTrialRefPort({ - executor: emptyFake.executor, - vaultCutoffTs: CUTOFF_TS, + test('quotes validated optional schema and leaves table unqualified when omitted', async () => { + const fakeDefault = createFakeExecutor([]); + const defaultPort = createPostgresTrialRefLookupPort({ + executor: fakeDefault.executor, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, }); - expect(await emptyPort.hasResearchVisibleTrial('123')).toBe(false); + await defaultPort.hasResearchVisibleTrial('1'); + expect(fakeDefault.calls[0]!.text).toContain('FROM trial_ledger '); - const hitFake = createFakeExecutor([{ visible: 1 }]); - const hitPort = createPostgresTrialRefPort({ - executor: hitFake.executor, - vaultCutoffTs: CUTOFF_TS, - }); - expect(await hitPort.hasResearchVisibleTrial('123')).toBe(true); + 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('throws INVALID_ROW for malformed envelopes, invalid singleton rows, and multiple rows (regression)', async () => { @@ -309,9 +316,9 @@ describe('createPostgresTrialRefPort (fake executor)', () => { return response as { readonly rows: readonly never[] }; }, }; - const port = createPostgresTrialRefPort({ + const port = createPostgresTrialRefLookupPort({ executor, - vaultCutoffTs: CUTOFF_TS, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, }); let caught: unknown; @@ -326,7 +333,7 @@ describe('createPostgresTrialRefPort (fake executor)', () => { }); test('propagates rejected and synchronously thrown executor errors unchanged without retrying', async () => { - const asyncFailure = new Error('connection terminated'); + const asyncFailure = new Error('postgres connection lost'); let asyncAttempts = 0; const asyncExecutor: TrialRefExecutor = { async query() { @@ -334,28 +341,225 @@ describe('createPostgresTrialRefPort (fake executor)', () => { throw asyncFailure; }, }; - const asyncPort = createPostgresTrialRefPort({ + const asyncPort = createPostgresTrialRefLookupPort({ executor: asyncExecutor, - vaultCutoffTs: CUTOFF_TS, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, }); - await expect(asyncPort.hasResearchVisibleTrial('101')).rejects.toBe(asyncFailure); + await expect(asyncPort.hasResearchVisibleTrial('42')).rejects.toBe(asyncFailure); expect(asyncAttempts).toBe(1); - const syncFailure = new Error('sync driver failure'); + const syncFailure = new Error('pool exhausted'); let syncAttempts = 0; - const syncExecutor: TrialRefExecutor = { + const syncExecutor = { query() { syncAttempts += 1; throw syncFailure; }, - }; - const syncPort = createPostgresTrialRefPort({ + } as unknown as TrialRefExecutor; + const syncPort = createPostgresTrialRefLookupPort({ executor: syncExecutor, - vaultCutoffTs: CUTOFF_TS, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, }); - await expect(syncPort.hasResearchVisibleTrial('101')).rejects.toBe(syncFailure); + 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 () => { + class PoolLikeExecutor { + readonly calls: RecordedCall[] = []; + async query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + this.calls.push({ text, params }); + return { rows: [{ visible: 1 }] as unknown as readonly Row[] }; + } + } + + const executor = new PoolLikeExecutor(); + const port = createPostgresTrialRefLookupPort({ + executor, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, + }); + + expect(await port.hasResearchVisibleTrial('99')).toBe(true); + expect(executor.calls).toHaveLength(1); + }); +}); + +describe('createPostgresTrialRefLookupPort wired into createFileFindingTool', () => { + async function callFileFinding( + executor: TrialRefExecutor, + trialRefs: readonly string[] + ): Promise<{ + readonly appended: FiledFindingRecord[]; + readonly result: { readonly content: readonly { type: string; text: string }[]; readonly isError?: boolean }; + }> { + const trialLookup = createPostgresTrialRefLookupPort({ + executor, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, + }); + const { appended, port } = createFakeWritePort(); + const tool = createFileFindingTool({ + port, + trialLookup, + newId: () => 'finding-0001', + now: () => Date.UTC(2025, 5, 29, 12, 0, 0, 0), + }); + const server = createMcpServer({ + name: 'test-copilot', + version: '0.1.0', + tools: [tool], + }); + + const rawResponse = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { + name: 'file_finding', + arguments: { + kind: 'finding', + title: 'Pre-vault momentum signal', + summary: 'Observed stable rank IC across US equities prior to cutoff.', + trialRefs, + }, + }, + }) + ); + + const parsed = JSON.parse(rawResponse!) as { + readonly result: { + readonly content: readonly { type: string; text: string }[]; + readonly isError?: boolean; + }; + }; + return { appended, result: parsed.result }; + } + + test('files a pending_review finding and returns a created receipt when the trial is visible', async () => { + const fake = createFakeExecutor([{ visible: 1 }]); + const { appended, result } = await callFileFinding(fake.executor, ['42']); + + expect(result.isError).toBeUndefined(); + const payload = JSON.parse(result.content[0]!.text) as FileFindingResultPayload; + expect(payload).toEqual({ + id: 'finding-0001', + createdAt: '2025-06-29T12:00:00.000Z', + created: true, + }); + expect(appended).toHaveLength(1); + expect(appended[0]).toEqual({ + id: 'finding-0001', + kind: 'finding', + title: 'Pre-vault momentum signal', + status: FILE_FINDING_INITIAL_STATUS, + createdAt: '2025-06-29T12:00:00.000Z', + summary: 'Observed stable rank IC across US equities prior to cutoff.', + trialRefs: ['42'], + evidenceRefs: [], + }); + expect(fake.calls).toHaveLength(1); + expect(fake.calls[0]!.params).toEqual(['42', '2025-06-30']); + }); + + test('returns FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF with zero appends when executor returns no rows', async () => { + const fake = createFakeExecutor([]); + const { appended, result } = await callFileFinding(fake.executor, ['42']); + + expect(result.isError).toBe(true); + expect(result.content[0]!.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); + expect(appended).toHaveLength(0); + expect(fake.calls).toHaveLength(1); + }); + + test('returns FILE_FINDING_ERROR_FILING_FAILED with zero appends when executor rejects', async () => { + const executor: TrialRefExecutor = { + async query() { + throw new Error('database unavailable'); + }, + }; + const { appended, result } = await callFileFinding(executor, ['42']); + + expect(result.isError).toBe(true); + expect(result.content[0]!.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); + expect(appended).toHaveLength(0); + }); +}); + +describe('createPostgresTrialRefLookupPort (QA edge cases)', () => { + test('queries in-range 19-digit refs and rejects 19-digit refs above the signed BIGINT max', async () => { + const fake = createFakeExecutor([{ visible: 1 }]); + const port = createPostgresTrialRefLookupPort({ + executor: fake.executor, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, + }); + + expect(await port.hasResearchVisibleTrial('1000000000000000000')).toBe(true); + expect(await port.hasResearchVisibleTrial('9223372036854775806')).toBe(true); + expect(await port.hasResearchVisibleTrial('9223372036854775900')).toBe(false); + expect(await port.hasResearchVisibleTrial('9999999999999999999')).toBe(false); + + expect(fake.calls.map(c => c.params?.[0])).toEqual([ + '1000000000000000000', + '9223372036854775806', + ]); + }); + + test('rejects trailing-newline, tab, fullwidth-digit, and boxed-String refs without querying', async () => { + const fake = createFakeExecutor([{ visible: 1 }]); + const port = createPostgresTrialRefLookupPort({ + executor: fake.executor, + vaultCutoffTs: CUTOFF_MIDNIGHT_TS, + }); + + for (const ref of ['42\n', '\n42', '4\t2', '42', '42\u0000', new String('42')] as unknown[]) { + expect(await port.hasResearchVisibleTrial(ref as string)).toBe(false); + } + expect(fake.calls).toHaveLength(0); + }); + + test('accepts the four-digit PostgreSQL calendar bounds 0001-01-01 and 9999-12-31 as cutoff dates', async () => { + const earliest = Date.parse('0001-01-01T00:00:00.000Z'); + const latest = Date.parse('9999-12-31T23:59:59.999Z'); + + for (const [ts, expected] of [ + [earliest, '0001-01-01'], + [latest, '9999-12-31'], + [Date.UTC(1969, 11, 31, 23, 59, 59, 999), '1969-12-31'], + ] as const) { + const fake = createFakeExecutor([]); + const port = createPostgresTrialRefLookupPort({ executor: fake.executor, vaultCutoffTs: ts }); + await port.hasResearchVisibleTrial('5'); + expect(fake.calls[0]!.params).toEqual(['5', expected]); + } + + let caught: unknown; + try { + createPostgresTrialRefLookupPort({ + executor: createFakeExecutor().executor, + vaultCutoffTs: latest + 1, + }); + } catch (err) { + caught = err; + } + expect((caught as PostgresTrialRefError).code).toBe('INVALID_VAULT_CUTOFF'); + }); + + test('freezes the cutoff date and SQL text at construction across repeated lookups', async () => { + const fake = createFakeExecutor([]); + const options = { executor: fake.executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS }; + const port = createPostgresTrialRefLookupPort(options); + + await port.hasResearchVisibleTrial('1'); + (options as { vaultCutoffTs: number }).vaultCutoffTs = Date.UTC(2030, 0, 1); + await port.hasResearchVisibleTrial('2'); + + expect(fake.calls).toHaveLength(2); + expect(fake.calls[0]!.text).toBe(fake.calls[1]!.text); + expect(fake.calls[1]!.params).toEqual(['2', '2025-06-30']); + }); }); diff --git a/test/postgres/mcp-trial-ref-adapter.test.ts b/test/postgres/mcp-trial-ref-adapter.test.ts index 371f583d..2a91334f 100644 --- a/test/postgres/mcp-trial-ref-adapter.test.ts +++ b/test/postgres/mcp-trial-ref-adapter.test.ts @@ -6,13 +6,15 @@ 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, - createPostgresTrialRefPort, + createPostgresTrialRefLookupPort, } from '../../libs/research/src/mcp/index'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); @@ -20,9 +22,13 @@ const logger = getLogger('mcp-trial-ref-adapter-pg-test'); const url = process.env.PIPELINE_TEST_DATABASE_URL; const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); -// Non-midnight UTC cutoff on 2025-06-30; research-visible requires sample_end < 2025-06-30. -const VAULT_CUTOFF_TS = Date.UTC(2025, 5, 30, 15, 45, 30, 500); +// 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'; +const ABOVE_SAFE_INT_NEIGHBOR_REF = '9007199254740992'; const cleanup: (() => Promise | void)[] = []; afterEach(async () => { @@ -83,7 +89,11 @@ function createPgExecutor( }; } -function buildIsolatedPoolConfig(connectionString: string | undefined, schema: string): PoolConfig { +function buildIsolatedPoolConfig( + connectionString: string | undefined, + schema: string, + extraOptions?: string +): PoolConfig { const safeUrl = assertSafetyDatabaseUrl(connectionString); const parsed = new URL(safeUrl); const existingOptions = parsed.searchParams @@ -92,7 +102,9 @@ function buildIsolatedPoolConfig(connectionString: string | undefined, schema: s .filter(value => value.length > 0); parsed.searchParams.delete('options'); - const schemaOptions = `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`; + 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 { @@ -111,6 +123,14 @@ async function createIsolatedFixture(connectionString: string | undefined = url) 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' @@ -141,48 +161,31 @@ async function createIsolatedFixture(connectionString: string | undefined = url) }); await runPostgresMigrations(postgres, { track: 'research' }); + await seedTrials(pool); - return { admin, pool, schema }; + return { admin, pool, readOnlyPool, schema }; } -async function insertTrialRow( - pool: Pool, - sampleEnd: string, - hashChar: string -): Promise { - const { rows } = await pool.query<{ trial_id: string }>( - `INSERT INTO trial_ledger ( - principal_id, - stage, - universe_market, - horizon_bucket, - expression_hash, - sample_start, - sample_end, - n_obs, - sharpe_unann, - skewness, - kurtosis, - daily_series - ) - VALUES ( - 'operator', - 'signal_ic', - 'US_EQ', - 'swing_1_10d', - $1, - '2024-01-02'::date, - $2::date, - 252, - 0.05, - -0.1, - 3.2, - ARRAY[0.01, -0.005]::real[] - ) - RETURNING trial_id::text AS trial_id`, - [hashChar.repeat(64), sampleEnd] - ); - return rows[0]!.trial_id; +async function seedTrials(pool: Pool): Promise { + const trials: readonly (readonly [string, string])[] = [ + ['1', '2025-06-29'], // last research-visible day + ['2', '2025-06-30'], // sample_end == cutoff: Vault-only + ['3', '2025-07-15'], // sample_end after cutoff: Vault-only + [ABOVE_SAFE_INT_REF, '2024-01-31'], + [MAX_BIGINT_REF, '2020-01-31'], + ]; + for (const [trialId, sampleEnd] of trials) { + await pool.query( + `INSERT INTO trial_ledger ( + trial_id, principal_id, stage, universe_market, horizon_bucket, expression_hash, + sample_start, sample_end, n_obs, sharpe_unann, skewness, kurtosis, daily_series + ) + OVERRIDING SYSTEM VALUE + VALUES ($1::bigint, 'operator', 'signal_ic', 'US_EQ', 'swing_1_10d', repeat('a', 64), + '2020-01-01'::date, $2::date, 2, 0, 0, 3, ARRAY[0.1, 0.2]::real[])`, + [trialId, sampleEnd] + ); + } } describe('PostgreSQL trial-ref adapter safety guard', () => { @@ -227,53 +230,170 @@ describe('PostgreSQL trial-ref adapter safety guard', () => { }); }); -describe.skipIf(!url)('PostgreSQL MCP trial-ref adapter', () => { - test('enforces strict sample_end < vaultCutoffDate across default search_path and explicit schema', async () => { +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(); - - const beforeCutoffId = await insertTrialRow(f.pool, '2025-06-29', 'a'); - const onCutoffId = await insertTrialRow(f.pool, '2025-06-30', 'b'); - const afterCutoffId = await insertTrialRow(f.pool, '2025-07-01', 'c'); - - const defaultPort = createPostgresTrialRefPort({ + const port = createPostgresTrialRefLookupPort({ executor: createPgExecutor(f.pool), vaultCutoffTs: VAULT_CUTOFF_TS, }); - expect(await defaultPort.hasResearchVisibleTrial(beforeCutoffId)).toBe(true); - expect(await defaultPort.hasResearchVisibleTrial(onCutoffId)).toBe(false); - expect(await defaultPort.hasResearchVisibleTrial(afterCutoffId)).toBe(false); - expect(await defaultPort.hasResearchVisibleTrial('999999999')).toBe(false); - expect(await defaultPort.hasResearchVisibleTrial('1; DROP TABLE trial_ledger')).toBe(false); - // Largest bigint binds through $1::bigint without overflow and is simply unknown. - expect(await defaultPort.hasResearchVisibleTrial('9223372036854775807')).toBe(false); - const { rows: ledgerCount } = await f.pool.query<{ c: number }>( - 'SELECT count(*)::int AS c FROM trial_ledger' - ); - expect(ledgerCount[0]?.c).toBe(3); + expect(await port.hasResearchVisibleTrial('1')).toBe(true); + expect(await port.hasResearchVisibleTrial('2')).toBe(false); + expect(await port.hasResearchVisibleTrial('3')).toBe(false); + expect(await port.hasResearchVisibleTrial('4')).toBe(false); // unknown + expect(await port.hasResearchVisibleTrial(MAX_BIGINT_REF)).toBe(true); + }); - // Explicit schema option against the admin pool (default search_path) - const scopedPort = createPostgresTrialRefPort({ - executor: createPgExecutor(f.admin), + test('matches BIGINT ids above 2^53 exactly without numeric coercion', async () => { + const f = await createIsolatedFixture(); + const port = createPostgresTrialRefLookupPort({ + executor: createPgExecutor(f.pool), vaultCutoffTs: VAULT_CUTOFF_TS, - schema: f.schema, }); - expect(await scopedPort.hasResearchVisibleTrial(beforeCutoffId)).toBe(true); - expect(await scopedPort.hasResearchVisibleTrial(onCutoffId)).toBe(false); - expect(await scopedPort.hasResearchVisibleTrial(afterCutoffId)).toBe(false); - expect(await scopedPort.hasResearchVisibleTrial('999999999')).toBe(false); + expect(await port.hasResearchVisibleTrial(ABOVE_SAFE_INT_REF)).toBe(true); + expect(await port.hasResearchVisibleTrial(ABOVE_SAFE_INT_NEIGHBOR_REF)).toBe(false); + }); + + test('moves the visibility boundary with the cutoff date, including a near-midnight UTC instant', async () => { + const f = await createIsolatedFixture(); + const executor = createPgExecutor(f.pool); + const lastMsOfCutoffDay = createPostgresTrialRefLookupPort({ + executor, + vaultCutoffTs: Date.UTC(2025, 5, 30, 23, 59, 59, 999), + }); + const nextDay = createPostgresTrialRefLookupPort({ + executor, + vaultCutoffTs: Date.UTC(2025, 6, 1, 0, 0, 0, 0), + }); + + expect(await lastMsOfCutoffDay.hasResearchVisibleTrial('2')).toBe(false); + expect(await nextDay.hasResearchVisibleTrial('2')).toBe(true); + expect(await nextDay.hasResearchVisibleTrial('3')).toBe(false); + }); + + test('runs in a read-only session and is unaffected by the session TimeZone', async () => { + const f = await createIsolatedFixture(); + const client = await f.readOnlyPool.connect(); + try { + await client.query("SET TimeZone = 'Pacific/Kiritimati'"); + const port = createPostgresTrialRefLookupPort({ + executor: createPgExecutor(client), + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + expect(await port.hasResearchVisibleTrial('1')).toBe(true); + expect(await port.hasResearchVisibleTrial('2')).toBe(false); + } finally { + await client.query('RESET TimeZone'); + client.release(); + } + }); + + test('qualifies trial_ledger with an explicit schema when the session search_path does not include it', async () => { + const f = await createIsolatedFixture(); + const client = await f.admin.connect(); + try { + // Pin a search_path that cannot contain trial_ledger, independent of the shared public schema. + await client.query('SET search_path TO pg_catalog'); + const unqualified = createPostgresTrialRefLookupPort({ + executor: createPgExecutor(client), + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + const qualified = createPostgresTrialRefLookupPort({ + executor: createPgExecutor(client), + vaultCutoffTs: VAULT_CUTOFF_TS, + schema: f.schema, + }); + + expect(await qualified.hasResearchVisibleTrial('1')).toBe(true); + expect(await qualified.hasResearchVisibleTrial('2')).toBe(false); + // Missing relation must surface as a rejection, never as "not visible". + await expect(unqualified.hasResearchVisibleTrial('1')).rejects.toMatchObject({ + code: '42P01', + }); + } finally { + await client.query('RESET search_path'); + client.release(); + } + }); + + test('leaves trial_ledger untouched and never executes an injection-shaped ref', async () => { + const f = await createIsolatedFixture(); + const port = createPostgresTrialRefLookupPort({ + executor: createPgExecutor(f.pool), + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + expect(await port.hasResearchVisibleTrial('1 OR 1=1')).toBe(false); + expect(await port.hasResearchVisibleTrial("1'; DELETE FROM trial_ledger; --")).toBe(false); + + const { rows } = await f.pool.query<{ n: string }>('SELECT count(*)::text AS n FROM trial_ledger'); + expect(rows[0]!.n).toBe('5'); + }); + + test('files through createFileFindingTool only when every trial ref is research-visible', async () => { + const f = await createIsolatedFixture(); + const trialLookup = createPostgresTrialRefLookupPort({ + executor: createPgExecutor(f.pool), + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + const appended: FiledFindingRecord[] = []; + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: { + async appendFinding(record: FiledFindingRecord): Promise { + appended.push(record); + return { status: 'created', id: record.id, createdAt: record.createdAt }; + }, + }, + trialLookup, + newId: () => 'finding-pg-0001', + now: () => Date.UTC(2025, 5, 29, 12, 0, 0, 0), + }), + ], + }); + + const call = async (trialRefs: readonly string[]) => { + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { + name: 'file_finding', + arguments: { + kind: 'finding', + title: 'Pre-vault signal', + summary: 'Research-visible evidence only.', + trialRefs, + }, + }, + }) + ); + return (JSON.parse(raw!) as { result: { isError?: boolean; content: { text: string }[] } }) + .result; + }; + + const mixed = await call(['1', '2']); + expect(mixed.isError).toBe(true); + expect(mixed.content[0]!.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); + expect(appended).toHaveLength(0); + + const visible = await call(['1', MAX_BIGINT_REF]); + expect(visible.isError).toBeUndefined(); + 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 visibleTrialId = await insertTrialRow(f.pool, '2025-06-29', '1'); - const equalCutoffTrialId = await insertTrialRow(f.pool, '2025-06-30', '2'); - const afterCutoffTrialId = await insertTrialRow(f.pool, '2025-07-01', '3'); - const executor = createPgExecutor(f.pool); - const trialLookup = createPostgresTrialRefPort({ + const trialLookup = createPostgresTrialRefLookupPort({ executor, vaultCutoffTs: VAULT_CUTOFF_TS, }); @@ -320,7 +440,7 @@ describe.skipIf(!url)('PostgreSQL MCP trial-ref adapter', () => { kind: 'finding', title: 'Pre-cutoff signal holds across US equities', summary: 'Positive IC verified strictly before the Vault cutoff.', - trialRefs: [visibleTrialId], + trialRefs: ['1'], evidenceRefs: ['snap:2025-06-29:ic'], }); expect(okRes.isError).toBeUndefined(); @@ -340,12 +460,12 @@ describe.skipIf(!url)('PostgreSQL MCP trial-ref adapter', () => { { id: 'finding-trial-ref-1', status: 'pending_review', - trial_refs: [visibleTrialId], + 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 [equalCutoffTrialId, afterCutoffTrialId, '999999999']) { + for (const deniedRef of ['2', '3', '999999999']) { const deniedRes = await callFileFinding({ kind: 'dead_end', title: 'Should be rejected by Vault fence', diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 09c40ff5..ec632373 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -142,7 +142,7 @@ 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`: `curate-posts` CLI subcommand, benchmark, live `ceoPosts` verification (including live `edited` BSON type verification), 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`, and the file-to-file runner in `src/run_curate_posts.rs`). +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`) @@ -922,7 +922,7 @@ Command (`2026-11-28`, two back-to-back runs with identical checksum `0x0a1b7ace - **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:** the `curate-posts` CLI subcommand, benchmark, live `ceoPosts` run/verification, and co-publishing posts with `curate-events` output remain deferred to follow-up tasks. + - **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`) @@ -1540,6 +1540,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. @@ -1733,7 +1764,7 @@ curate-etl curate-fx-1m \ - **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: `teData` BSON decoding, runner, CLI command, `macroAsOf` DuckDB reader, and live MongoDB access. +- **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`) @@ -1742,3 +1773,10 @@ curate-etl curate-fx-1m \ - **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/cli.rs b/tools/curate-etl/src/cli.rs index 625fdea9..f59c8445 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::{ @@ -48,6 +57,9 @@ 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_fx_1m::CurateFx1mArgs; +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, @@ -74,6 +86,7 @@ pub enum CliAction { CurateEventsMongo(CurateEventsMongoArgs), CurateBars1m(CurateBars1mArgs), CurateFx1m(CurateFx1mArgs), + CuratePosts(CuratePostsArgs), BenchSplit(usize), BenchAdj(usize), BenchCorporateActions(usize), @@ -139,6 +152,8 @@ pub fn format_usage(name: &str, version: &str) -> String { Curate split-unadjusted 1-minute bars from eodIntraday1M + qmSplits BSON + provider_mapping TSV into bars_1m.shard-.ilp (default --mapping-source: {DEFAULT_BARS_1M_MAPPING_SOURCE})\n\ {name} curate-fx-1m --eod-intraday --out --shards \n\ Curate USD/CAD 1-minute FX bars from eodIntraday1M BSON into fx_1m.shard-.ilp\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\ @@ -189,6 +204,7 @@ pub fn format_usage_stderr(name: &str) -> String { {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-bars-1m --eod-intraday --qm-splits --provider-mapping --out --shards --known-at-micros [--mapping-source ]\n\ {name} curate-fx-1m --eod-intraday --out --shards \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\ @@ -1004,6 +1020,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; @@ -1052,28 +1090,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)?, @@ -1161,6 +1177,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; @@ -1706,6 +1835,7 @@ pub fn parse_args(args: &[String]) -> Result { ["curate-events", rest @ ..] => parse_curate_events_args(rest), ["curate-bars-1m", rest @ ..] => parse_curate_bars_1m_args(rest), ["curate-fx-1m", rest @ ..] => parse_curate_fx_1m_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)), @@ -4298,4 +4428,390 @@ mod tests { ); } } + + #[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_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/lib.rs b/tools/curate-etl/src/lib.rs index fbc39ed1..a351d5e4 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -277,6 +277,12 @@ pub use curate_fundamentals::{ 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, diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index 4f08f450..c23b3457 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -30,6 +30,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_fx_1m::{format_curate_fx_1m_report, run_curate_fx_1m}; +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, @@ -219,6 +220,16 @@ fn main() -> ExitCode { ExitCode::FAILURE } }, + 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_fundamentals.rs b/tools/curate-etl/src/parquet_fundamentals.rs index 0bc2a9b4..38000652 100644 --- a/tools/curate-etl/src/parquet_fundamentals.rs +++ b/tools/curate-etl/src/parquet_fundamentals.rs @@ -17,11 +17,11 @@ //! 12. `total_assets` (`DOUBLE`, `OPTIONAL`) //! 13. `total_equity` (`DOUBLE`, `OPTIONAL`) //! 14. `shares_outstanding` (`DOUBLE`, `OPTIONAL`) -//! 15. `ttm_period_end` (`INT32`, `OPTIONAL`, `DATE`) -//! 16. `ttm_currency` (`BYTE_ARRAY`, `OPTIONAL`, `STRING`) -//! 17. `ttm_revenue` (`DOUBLE`, `OPTIONAL`) -//! 18. `ttm_net_income` (`DOUBLE`, `OPTIONAL`) -//! 19. `ttm_operating_cash_flow` (`DOUBLE`, `OPTIONAL`) +//! 15. `ttm_revenue` (`DOUBLE`, `OPTIONAL`) +//! 16. `ttm_net_income` (`DOUBLE`, `OPTIONAL`) +//! 17. `ttm_operating_cash_flow` (`DOUBLE`, `OPTIONAL`) +//! 18. `ttm_period_end` (`INT32`, `OPTIONAL`, `DATE`) +//! 19. `ttm_currency` (`BYTE_ARRAY`, `OPTIONAL`, `STRING`) //! 20. `ttm_has_estimated_lag` (`BOOLEAN`, `OPTIONAL`) //! //! Each physical row flattens `periods[0]` (the latest visible resolved period) and the @@ -500,21 +500,7 @@ pub fn fundamentals_pit_parquet_schema() -> Result { .with_repetition(Repetition::OPTIONAL) .build()?, ), - // 15. ttm_period_end INT32 DATE OPTIONAL - Arc::new( - Type::primitive_type_builder("ttm_period_end", PhysicalType::INT32) - .with_repetition(Repetition::OPTIONAL) - .with_logical_type(Some(LogicalType::Date)) - .build()?, - ), - // 16. ttm_currency STRING OPTIONAL - Arc::new( - Type::primitive_type_builder("ttm_currency", PhysicalType::BYTE_ARRAY) - .with_repetition(Repetition::OPTIONAL) - .with_logical_type(Some(LogicalType::String)) - .build()?, - ), - // 17-19. TTM flow sums DOUBLE OPTIONAL + // 15-17. TTM flow sums DOUBLE OPTIONAL Arc::new( Type::primitive_type_builder("ttm_revenue", PhysicalType::DOUBLE) .with_repetition(Repetition::OPTIONAL) @@ -530,6 +516,20 @@ pub fn fundamentals_pit_parquet_schema() -> Result { .with_repetition(Repetition::OPTIONAL) .build()?, ), + // 18. ttm_period_end INT32 DATE OPTIONAL + Arc::new( + Type::primitive_type_builder("ttm_period_end", PhysicalType::INT32) + .with_repetition(Repetition::OPTIONAL) + .with_logical_type(Some(LogicalType::Date)) + .build()?, + ), + // 19. ttm_currency STRING OPTIONAL + Arc::new( + Type::primitive_type_builder("ttm_currency", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::OPTIONAL) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), // 20. ttm_has_estimated_lag BOOLEAN OPTIONAL Arc::new( Type::primitive_type_builder("ttm_has_estimated_lag", PhysicalType::BOOLEAN) @@ -998,43 +998,43 @@ impl YearWriter { &self.buf.shares_outstanding_def, ) .map_err(map_pq)?; - // 15. ttm_period_end (INT32, OPTIONAL, DATE) - write_optional_i32_col( - &mut rg_writer, - &self.buf.ttm_period_end_values, - &self.buf.ttm_period_end_def, - ) - .map_err(map_pq)?; - // 16. ttm_currency (BYTE_ARRAY, OPTIONAL, STRING) - write_optional_interned_str_col( - &mut rg_writer, - &self.buf.ttm_currency_ids, - &self.buf.ttm_currency_def, - &self.buf.ttm_currency_interner, - scratch, - ) - .map_err(map_pq)?; - // 17. ttm_revenue (DOUBLE, OPTIONAL) + // 15. ttm_revenue (DOUBLE, OPTIONAL) write_optional_f64_col( &mut rg_writer, &self.buf.ttm_revenue_values, &self.buf.ttm_revenue_def, ) .map_err(map_pq)?; - // 18. ttm_net_income (DOUBLE, OPTIONAL) + // 16. ttm_net_income (DOUBLE, OPTIONAL) write_optional_f64_col( &mut rg_writer, &self.buf.ttm_net_income_values, &self.buf.ttm_net_income_def, ) .map_err(map_pq)?; - // 19. ttm_operating_cash_flow (DOUBLE, OPTIONAL) + // 17. ttm_operating_cash_flow (DOUBLE, OPTIONAL) write_optional_f64_col( &mut rg_writer, &self.buf.ttm_operating_cash_flow_values, &self.buf.ttm_operating_cash_flow_def, ) .map_err(map_pq)?; + // 18. ttm_period_end (INT32, OPTIONAL, DATE) + write_optional_i32_col( + &mut rg_writer, + &self.buf.ttm_period_end_values, + &self.buf.ttm_period_end_def, + ) + .map_err(map_pq)?; + // 19. ttm_currency (BYTE_ARRAY, OPTIONAL, STRING) + write_optional_interned_str_col( + &mut rg_writer, + &self.buf.ttm_currency_ids, + &self.buf.ttm_currency_def, + &self.buf.ttm_currency_interner, + scratch, + ) + .map_err(map_pq)?; // 20. ttm_has_estimated_lag (BOOLEAN, OPTIONAL) write_bool_col( &mut rg_writer, diff --git a/tools/curate-etl/src/parquet_fundamentals_tests.rs b/tools/curate-etl/src/parquet_fundamentals_tests.rs index de8b46e2..922f4435 100644 --- a/tools/curate-etl/src/parquet_fundamentals_tests.rs +++ b/tools/curate-etl/src/parquet_fundamentals_tests.rs @@ -23,7 +23,8 @@ use crate::events::{ }; use crate::fundamentals::{ build_fundamentals_rows, build_fundamentals_snapshots, FinancialObservation, FiscalPeriod, - FundamentalsFields, FundamentalsSnapshot, FundamentalsTtm, StatutoryLagVenue, TtmFlowFields, + FundamentalsFields, FundamentalsPeriodSlot, FundamentalsSnapshot, FundamentalsTtm, + StatutoryLagVenue, TtmFlowFields, }; use crate::split::ymd_to_epoch_days; @@ -113,11 +114,11 @@ struct DecodedFundamentalsPitRow { 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_period_end: Option, + ttm_currency: Option, ttm_has_estimated_lag: Option, } @@ -345,11 +346,11 @@ fn read_parquet_rows(path: &Path) -> Vec { let total_assets = read_opt_f64(11); let total_equity = read_opt_f64(12); let shares_outstanding = read_opt_f64(13); - let ttm_period_end = read_opt_i32(14); - let ttm_currency = read_opt_str(15); - let ttm_revenue = read_opt_f64(16); - let ttm_net_income = read_opt_f64(17); - let ttm_operating_cash_flow = read_opt_f64(18); + let ttm_revenue = read_opt_f64(14); + let ttm_net_income = read_opt_f64(15); + let ttm_operating_cash_flow = read_opt_f64(16); + let ttm_period_end = read_opt_i32(17); + let ttm_currency = read_opt_str(18); let ttm_has_estimated_lag = read_opt_bool(19); for i in 0..rg_rows { @@ -368,11 +369,11 @@ fn read_parquet_rows(path: &Path) -> Vec { 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_period_end: ttm_period_end[i], + ttm_currency: ttm_currency[i].clone(), ttm_has_estimated_lag: ttm_has_estimated_lag[i], }); } @@ -381,6 +382,80 @@ fn read_parquet_rows(path: &Path) -> Vec { out } +fn assert_decoded_matches_snapshot_bit_for_bit( + actual: &DecodedFundamentalsPitRow, + snapshot: &FundamentalsSnapshot, +) { + let latest = snapshot + .periods + .first() + .expect("snapshot must have at least one period"); + assert_eq!(actual.listing_id, snapshot.key); + assert_eq!( + actual.effective_known_at, + snapshot.effective_known_at_utc_micros + ); + assert_eq!(actual.known_at_source, snapshot.known_at_source); + assert_eq!(actual.has_estimated_lag, snapshot.has_estimated_lag); + assert_eq!(actual.period_end, latest.period_end); + assert_eq!(actual.fiscal_period, latest.fiscal_period.as_str()); + assert_eq!(actual.currency, latest.currency); + assert_eq!(actual.period_known_at, latest.known_at_utc_micros); + + assert_eq!( + actual.revenue.map(f64::to_bits), + latest.fields.revenue.map(f64::to_bits) + ); + assert_eq!( + actual.net_income.map(f64::to_bits), + latest.fields.net_income.map(f64::to_bits) + ); + assert_eq!( + actual.operating_cash_flow.map(f64::to_bits), + latest.fields.operating_cash_flow.map(f64::to_bits) + ); + assert_eq!( + actual.total_assets.map(f64::to_bits), + latest.fields.total_assets.map(f64::to_bits) + ); + assert_eq!( + actual.total_equity.map(f64::to_bits), + latest.fields.total_equity.map(f64::to_bits) + ); + assert_eq!( + actual.shares_outstanding.map(f64::to_bits), + latest.fields.shares_outstanding.map(f64::to_bits) + ); + + match &snapshot.ttm { + Some(ttm) => { + assert_eq!( + actual.ttm_revenue.map(f64::to_bits), + ttm.flows.revenue.map(f64::to_bits) + ); + assert_eq!( + actual.ttm_net_income.map(f64::to_bits), + ttm.flows.net_income.map(f64::to_bits) + ); + assert_eq!( + actual.ttm_operating_cash_flow.map(f64::to_bits), + ttm.flows.operating_cash_flow.map(f64::to_bits) + ); + assert_eq!(actual.ttm_period_end, Some(ttm.ending_period_end)); + assert_eq!(actual.ttm_currency.as_deref(), Some(ttm.currency.as_str())); + assert_eq!(actual.ttm_has_estimated_lag, Some(ttm.has_estimated_lag)); + } + None => { + assert_eq!(actual.ttm_revenue, None); + assert_eq!(actual.ttm_net_income, None); + assert_eq!(actual.ttm_operating_cash_flow, None); + assert_eq!(actual.ttm_period_end, None); + assert_eq!(actual.ttm_currency, None); + assert_eq!(actual.ttm_has_estimated_lag, None); + } + } +} + fn assert_no_transient_files(dir: &Path) { if !dir.exists() { return; @@ -654,20 +729,6 @@ fn schema_matches_contract_zstd_null_ttm_and_nullable_booleans() { None, ConvertedType::NONE, ), - ( - "ttm_period_end", - PhysicalType::INT32, - Repetition::OPTIONAL, - Some(LogicalType::Date), - ConvertedType::DATE, - ), - ( - "ttm_currency", - PhysicalType::BYTE_ARRAY, - Repetition::OPTIONAL, - Some(LogicalType::String), - ConvertedType::UTF8, - ), ( "ttm_revenue", PhysicalType::DOUBLE, @@ -689,6 +750,20 @@ fn schema_matches_contract_zstd_null_ttm_and_nullable_booleans() { None, ConvertedType::NONE, ), + ( + "ttm_period_end", + PhysicalType::INT32, + Repetition::OPTIONAL, + Some(LogicalType::Date), + ConvertedType::DATE, + ), + ( + "ttm_currency", + PhysicalType::BYTE_ARRAY, + Repetition::OPTIONAL, + Some(LogicalType::String), + ConvertedType::UTF8, + ), ( "ttm_has_estimated_lag", PhysicalType::BOOLEAN, @@ -741,19 +816,19 @@ fn schema_matches_contract_zstd_null_ttm_and_nullable_booleans() { assert_eq!(decoded[0].total_assets, None); assert_eq!(decoded[0].total_equity, Some(220.0)); assert_eq!(decoded[0].shares_outstanding, None); - assert_eq!(decoded[0].ttm_period_end, None); - assert_eq!(decoded[0].ttm_currency, None); assert_eq!(decoded[0].ttm_revenue, None); assert_eq!(decoded[0].ttm_net_income, None); assert_eq!(decoded[0].ttm_operating_cash_flow, None); + assert_eq!(decoded[0].ttm_period_end, None); + assert_eq!(decoded[0].ttm_currency, None); assert_eq!(decoded[0].ttm_has_estimated_lag, None); // Row 1: ttm_has_estimated_lag = Some(false) - assert_eq!(decoded[1].ttm_period_end, Some(day(2024, 6, 30))); - assert_eq!(decoded[1].ttm_currency.as_deref(), Some("USD")); assert_eq!(decoded[1].ttm_revenue, Some(370.0)); assert_eq!(decoded[1].ttm_net_income, Some(37.0)); assert_eq!(decoded[1].ttm_operating_cash_flow, Some(55.0)); + assert_eq!(decoded[1].ttm_period_end, Some(day(2024, 6, 30))); + assert_eq!(decoded[1].ttm_currency.as_deref(), Some("USD")); assert_eq!(decoded[1].ttm_has_estimated_lag, Some(false)); // Row 2: ttm_has_estimated_lag = Some(true), partial missing TTM flow, statutory lag source. @@ -761,16 +836,273 @@ fn schema_matches_contract_zstd_null_ttm_and_nullable_booleans() { assert!(decoded[2].has_estimated_lag); assert_eq!(decoded[2].fiscal_period, "FY"); assert_eq!(decoded[2].currency, "CAD"); - assert_eq!(decoded[2].ttm_period_end, Some(day(2024, 9, 30))); - assert_eq!(decoded[2].ttm_currency.as_deref(), Some("CAD")); assert_eq!(decoded[2].ttm_revenue, Some(450.0)); assert_eq!(decoded[2].ttm_net_income, None); assert_eq!(decoded[2].ttm_operating_cash_flow, Some(60.0)); + assert_eq!(decoded[2].ttm_period_end, Some(day(2024, 9, 30))); + assert_eq!(decoded[2].ttm_currency.as_deref(), Some("CAD")); assert_eq!(decoded[2].ttm_has_estimated_lag, Some(true)); assert_no_transient_files(&tmp.path().join("fundamentals_pit")); } +#[test] +fn builder_snapshots_round_trip_bit_for_bit_including_nulls_ttm_and_signed_zero() { + let tmp = TempDirGuard::new("builder-roundtrip-bits"); + + let venues = BTreeMap::from([ + (10_i32, StatutoryLagVenue::UsTsx), + (20_i32, StatutoryLagVenue::TsxvCse), + ]); + + let observations = vec![ + // Listing 10: 5 consecutive quarters (Q1 2023 .. Q1 2024). + // Q1..Q4 2023 all have distinct non-null flow values so Q4 2023's snapshot carries + // three distinct non-null TTM flows (catching any positional TTM column transposition). + // Q1 2024 omits operating_cash_flow so its snapshot has ttm_operating_cash_flow = None + // while ttm_revenue and ttm_net_income remain populated and distinct. + obs( + 10, + day(2023, 3, 31), + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 5, 2)), + FundamentalsFields { + revenue: Some(95.5), + net_income: Some(9.25), + operating_cash_flow: Some(17.75), + total_assets: Some(960.0), + total_equity: Some(380.0), + shares_outstanding: Some(49_500_000.0), + }, + ), + obs( + 10, + day(2023, 6, 30), + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 8, 2)), + FundamentalsFields { + revenue: Some(101.25), + net_income: Some(11.5), + operating_cash_flow: Some(19.75), + total_assets: Some(1_000.0), + total_equity: Some(400.0), + shares_outstanding: Some(50_000_000.0), + }, + ), + obs( + 10, + day(2023, 9, 30), + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 11, 3)), + FundamentalsFields { + revenue: Some(110.5), + net_income: Some(12.25), + operating_cash_flow: Some(21.0), + total_assets: None, + total_equity: Some(415.0), + shares_outstanding: Some(50_100_000.0), + }, + ), + obs( + 10, + day(2023, 12, 31), + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 2, 14)), + FundamentalsFields { + revenue: Some(125.0), + net_income: Some(14.0), + operating_cash_flow: Some(22.5), + total_assets: Some(1_120.0), + total_equity: None, + shares_outstanding: Some(50_200_000.0), + }, + ), + obs( + 10, + day(2024, 3, 31), + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 1)), + FundamentalsFields { + revenue: Some(130.75), + net_income: Some(16.5), + operating_cash_flow: None, + total_assets: Some(1_150.0), + total_equity: Some(440.0), + shares_outstanding: None, + }, + ), + // Listing 20: unlinked observation -> statutory_lag_estimate (+60d for TSXV/CSE), + // ttm == None. + obs( + 20, + day(2024, 3, 31), + FiscalPeriod::Quarterly, + "CAD", + None, + FundamentalsFields { + revenue: Some(42.5), + net_income: Some(-3.5), + operating_cash_flow: None, + total_assets: Some(25.0), + total_equity: Some(12.5), + shares_outstanding: Some(8_000_000.0), + }, + ), + ]; + + let filings = vec![ + filing(10, "2023-05-02T16:05:00 EDT", "10-Q"), + filing(10, "2023-08-02T16:10:00 EDT", "10-Q"), + filing(10, "2023-11-03T16:05:00 EDT", "10-Q"), + filing(10, "2024-02-14T16:15:00 EST", "10-Q"), + filing(10, "2024-05-01T16:20:00 EDT", "10-Q"), + ]; + + let built = build_fundamentals_rows(observations, filings, &venues); + let mut snapshots = build_fundamentals_snapshots(&built.rows, 4).expect("build snapshots"); + assert_eq!(snapshots.len(), 6); + + // Append a direct snapshot carrying signed negative zero (-0.0) vs positive zero (+0.0) in + // statement fields (builder normalizes -0.0; this verifies the Parquet writer preserves exact + // IEEE-754 bit patterns without altering them). + snapshots.push(FundamentalsSnapshot { + key: 30_i32, + effective_known_at_utc_micros: utc_micros(2024, 6, 15, 20, 5, 0, 0), + known_at_source: KNOWN_AT_SOURCE_STATUTORY_LAG, + has_estimated_lag: true, + periods: vec![FundamentalsPeriodSlot { + period_end: day(2024, 3, 31), + fiscal_period: FiscalPeriod::Quarterly, + currency: "CAD".to_string(), + known_at_utc_micros: utc_micros(2024, 6, 15, 20, 5, 0, 0), + known_at_source: KNOWN_AT_SOURCE_STATUTORY_LAG, + has_estimated_lag: true, + fields: FundamentalsFields { + revenue: Some(-0.0_f64), + net_income: Some(0.0_f64), + operating_cash_flow: None, + total_assets: Some(10.0), + total_equity: None, + shares_outstanding: Some(1_000_000.0), + }, + }], + ttm: None, + }); + + let rows_from_ref: Vec = snapshots + .iter() + .map(FundamentalsPitParquetRow::from) + .collect(); + let rows_from_owned: Vec = snapshots + .clone() + .into_iter() + .map(FundamentalsPitParquetRow::from) + .collect(); + assert_eq!(rows_from_ref, rows_from_owned); + + let stats = write_fundamentals_pit_dataset( + tmp.path(), + &rows_from_ref, + FundamentalsPitWriteOptions { + row_group_rows: 2, + zstd_level: DEFAULT_ZSTD_LEVEL, + }, + ) + .expect("write builder snapshots"); + + let expected_by_year = BTreeMap::from([(2023, 3), (2024, 4)]); + assert_eq!(stats.rows_written, 7); + assert_eq!(stats.files_written, 2); + assert_eq!(stats.row_groups_written, 4); + assert_eq!(stats.rows_by_year, expected_by_year); + + let mut total_bytes = 0u64; + for (&year, &expected_count) in &expected_by_year { + let path = tmp + .path() + .join(format!("fundamentals_pit/year={year:04}/part.parquet")); + assert!(path.is_file(), "missing {}", path.display()); + total_bytes += fs::metadata(&path).expect("metadata").len(); + + let decoded = read_parquet_rows(&path); + let expected_snapshots: Vec<&FundamentalsSnapshot> = snapshots + .iter() + .filter(|s| partition_year_utc(s.effective_known_at_utc_micros) == year) + .collect(); + assert_eq!(decoded.len(), expected_count); + assert_eq!(decoded.len(), expected_snapshots.len()); + for (actual_row, snap) in decoded.iter().zip(expected_snapshots.iter()) { + assert_decoded_matches_snapshot_bit_for_bit(actual_row, snap); + } + + if year == 2024 { + // Q4 2023 snapshot (filed 2024-02-14): all three TTM flows present and distinct. + let full_ttm = decoded + .iter() + .find(|r| r.listing_id == 10 && r.period_end == day(2023, 12, 31)) + .expect("listing 10 Q4 2023 row"); + assert_eq!(full_ttm.ttm_revenue, Some(432.25)); + assert_eq!(full_ttm.ttm_net_income, Some(47.0)); + assert_eq!(full_ttm.ttm_operating_cash_flow, Some(81.0)); + assert_eq!(full_ttm.ttm_period_end, Some(day(2023, 12, 31))); + assert_eq!(full_ttm.ttm_currency.as_deref(), Some("USD")); + assert_eq!(full_ttm.ttm_has_estimated_lag, Some(false)); + + // Q1 2024 snapshot (filed 2024-05-01): partial null TTM flow. + let partial_ttm = decoded + .iter() + .find(|r| r.listing_id == 10 && r.period_end == day(2024, 3, 31)) + .expect("listing 10 Q1 2024 row"); + assert_eq!(partial_ttm.ttm_revenue, Some(467.5)); + assert_eq!(partial_ttm.ttm_net_income, Some(54.25)); + assert_eq!(partial_ttm.ttm_operating_cash_flow, None); + assert_eq!(partial_ttm.ttm_period_end, Some(day(2024, 3, 31))); + assert_eq!(partial_ttm.ttm_currency.as_deref(), Some("USD")); + assert_eq!(partial_ttm.ttm_has_estimated_lag, Some(false)); + + // Listing 20: statutory lag provenance and ttm == None. + let est_row = decoded + .iter() + .find(|r| r.listing_id == 20) + .expect("listing 20 row"); + assert_eq!(est_row.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + assert!(est_row.has_estimated_lag); + assert_eq!(est_row.ttm_revenue, None); + assert_eq!(est_row.ttm_net_income, None); + assert_eq!(est_row.ttm_operating_cash_flow, None); + assert_eq!(est_row.ttm_period_end, None); + assert_eq!(est_row.ttm_currency, None); + assert_eq!(est_row.ttm_has_estimated_lag, None); + + // Listing 30: exact IEEE-754 -0.0 vs +0.0 bit preservation across Parquet write/read. + let signed_zero_row = decoded + .iter() + .find(|r| r.listing_id == 30) + .expect("listing 30 row"); + assert_eq!( + signed_zero_row.revenue.map(f64::to_bits), + Some((-0.0_f64).to_bits()) + ); + assert_ne!( + signed_zero_row.revenue.map(f64::to_bits), + Some(0.0_f64.to_bits()) + ); + assert_eq!( + signed_zero_row.net_income.map(f64::to_bits), + Some(0.0_f64.to_bits()) + ); + } + } + + assert_eq!(stats.bytes_written, total_bytes); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); +} + #[test] fn restatement_of_q1_after_q2_preserves_q2_on_disk_and_updates_ttm() { let listing_id = 42_i32; @@ -1033,6 +1365,11 @@ fn utc_year_partitioning_interleaved_listings_and_midnight_boundary() { let path_2024 = tmp.path().join("fundamentals_pit/year=2024/part.parquet"); assert!(path_2023.is_file()); assert!(path_2024.is_file()); + assert_eq!( + stats.bytes_written, + fs::metadata(&path_2023).expect("meta 2023").len() + + fs::metadata(&path_2024).expect("meta 2024").len() + ); let decoded_2023 = read_parquet_rows(&path_2023); let decoded_2024 = read_parquet_rows(&path_2024); @@ -1264,7 +1601,6 @@ fn publish_failure_on_later_year_rolls_back_replaced_and_new_partitions() { assert_no_transient_files(&tmp.path().join("fundamentals_pit")); } - // --------------------------------------------------------------------------------------------- // QA additions (T-143): full-row round-trip equality, builder estimated-lag provenance, // partial-rewrite semantics, deterministic bytes, and remaining typed validation errors. @@ -1291,11 +1627,11 @@ fn expected_decoded(row: &FundamentalsPitParquetRow) -> DecodedFundamentalsPitRo total_assets: latest.fields.total_assets, total_equity: latest.fields.total_equity, shares_outstanding: latest.fields.shares_outstanding, - ttm_period_end: ttm.map(|t| t.ending_period_end), - ttm_currency: ttm.map(|t| t.currency.clone()), ttm_revenue: ttm.and_then(|t| t.flows.revenue), ttm_net_income: ttm.and_then(|t| t.flows.net_income), ttm_operating_cash_flow: ttm.and_then(|t| t.flows.operating_cash_flow), + ttm_period_end: ttm.map(|t| t.ending_period_end), + ttm_currency: ttm.map(|t| t.currency.clone()), ttm_has_estimated_lag: ttm.map(|t| t.has_estimated_lag), } } @@ -1594,11 +1930,11 @@ fn builder_statutory_lag_snapshots_keep_estimated_provenance_on_disk() { assert_eq!(decoded[1].operating_cash_flow, None); // Only two quarters exist, so TTM is unavailable and every ttm_* column is null. for r in &decoded { - assert_eq!(r.ttm_period_end, None); - assert_eq!(r.ttm_currency, None); assert_eq!(r.ttm_revenue, None); assert_eq!(r.ttm_net_income, None); assert_eq!(r.ttm_operating_cash_flow, None); + assert_eq!(r.ttm_period_end, None); + assert_eq!(r.ttm_currency, None); assert_eq!(r.ttm_has_estimated_lag, None); } } 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}"); + } +}