From 4e4be190df7928221d41004d44e8070ffcb36e7e Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 08:49:30 -0500 Subject: [PATCH 01/21] =?UTF-8?q?T-158:=20M2.1k=20=E2=80=94=20PostgreSQL?= =?UTF-8?q?=20security-master=20adapter=20for=20the=20MCP=20copilot=20`sea?= =?UTF-8?q?rch=5Fsymbols`=20tool:=20`SymbolSearchPort`=20over=20an=20injec?= =?UTF-8?q?ted=20executor=20in=20`libs/research/src/mcp/adapters/postgres-?= =?UTF-8?q?symbol-search.ts`=20(as-of-cutoff=20ticker=20resolution,=20para?= =?UTF-8?q?meterized=20SQL,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/README.md | 8 + .../mcp/adapters/postgres-symbol-search.ts | 355 ++++++++++++++ libs/research/src/mcp/index.ts | 1 + .../test/mcp-postgres-symbol-search.test.ts | 413 ++++++++++++++++ .../mcp-symbol-search-adapter.test.ts | 447 ++++++++++++++++++ 5 files changed, 1224 insertions(+) create mode 100644 libs/research/src/mcp/adapters/postgres-symbol-search.ts create mode 100644 libs/research/test/mcp-postgres-symbol-search.test.ts create mode 100644 test/postgres/mcp-symbol-search-adapter.test.ts diff --git a/libs/research/README.md b/libs/research/README.md index 93e29a1d..cf49f406 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -256,6 +256,14 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported - **Review status & Vault safety:** Server-controlled metadata (`id`, UTC ISO `createdAt`, and initial `status: 'pending_review'`) cannot be supplied by callers; director approval occurs out-of-band. Every unique `trialRef` is verified via the injected read-only `trialLookup.hasResearchVisibleTrial(ref)` before generating metadata or writing (treating unknown and Vault-only refs identically). Callers must describe research-visible evidence only in `title` and `summary` and keep Vault holdout observations out of filing text. - **Idempotency & receipts:** `FindingWritePort` exposes only `appendFinding(record, idempotencyKey?)` with atomic `created` / `replayed` / `conflict` semantics comparing normalized `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs`. Retries with the same key and normalized payload return the original `{ id, createdAt, created: false }` without appending; key reuse with a different payload returns a fixed `isError: true` conflict error with zero writes; unkeyed calls are independent. Filed records extend `FindingRecord` and can be read back by receipt ID via `read_knowledge`. +### PostgreSQL Symbol Search Adapter + +- **`createPostgresSymbolSearchPort({ executor, schema? })`** (exported from `@stock-bot/research/mcp` alongside `SymbolSearchExecutor` and `PostgresSymbolSearchError`) implements `SymbolSearchPort` over the M1 PostgreSQL security master (`listing`, `instrument`, `exchange`, `listing_symbol_history`) in one read-only parameterized `SELECT` with zero runtime `pg` dependency. +- **Inputs & schema:** Validates that `executor` exposes a callable `query(text, params?)` method (`INVALID_EXECUTOR`), validates optional `schema` against `^[a-z_][a-z0-9_]*$` before quoting table identifiers (`INVALID_SCHEMA`; defaults to the executor's `search_path`), validates `q.vaultCutoffTs` (epoch milliseconds) and converts it to a UTC calendar date (`YYYY-MM-DD`), escapes `%`, `_`, and `\` before building the `ILIKE` pattern, and rejects malformed/non-integer IDs or invalid/impossible `YYYY-MM-DD` dates returned by the executor (`INVALID_ROW`). +- **As-of ticker resolution & root suppression:** Excludes listings with `listed_from > cutoff` (retaining `listed_from IS NULL`). Defines `root_is_future` per listing when `listing_symbol_history` has at least one row with `upper(ticker) = upper(listing.ticker_root)` and none with `valid_from <= cutoff`. Resolves one ticker per listing (breaking same-`valid_from` ties by `ticker ASC`) in strict order: (1) latest history row valid at cutoff (`valid_from <= cutoff AND (valid_to IS NULL OR valid_to >= cutoff)`), (2) `listing.ticker_root` when `NOT root_is_future`, (3) latest history row with `valid_from <= cutoff` even if its `valid_to < cutoff`, (4) otherwise excludes the listing so future tickers never leak via fallback or name/ISIN lookup. +- **`delistedAt` derivation:** Projects `delistedAt` as `listing.listed_to` (`YYYY-MM-DD`) when `delist_reason IS NOT NULL AND delist_reason <> 'active'`, else `null`. When `q.includeDelisted === false`, rows with non-null `delistedAt <= cutoff` are filtered out while future delistings (`delistedAt > cutoff`) remain eligible as of the cutoff. +- **Port matching vs. MCP ranking:** The adapter matches on resolved as-of ticker (`ILIKE`), `listing.ticker_root` (`ILIKE`, gated by `NOT root_is_future`), `instrument.canonical_name` (`ILIKE`), or case-insensitive exact `instrument.primary_isin`, ignores `q.limit`, and returns all candidates ordered by `listing_id ASC`. When composed with `createSearchSymbolsTool`, the MCP tool applies Vault clamping/masking, ranks by exact ticker > ticker prefix > company name substring (tie-breaking by `listingId ASC`), and truncates to `limit` — so callers needing ticker-substring, root-only, or exact-ISIN lookups should call the port directly, while MCP tool callers should query by ticker or company name. + ### 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/postgres-symbol-search.ts b/libs/research/src/mcp/adapters/postgres-symbol-search.ts new file mode 100644 index 00000000..c2e7b9ae --- /dev/null +++ b/libs/research/src/mcp/adapters/postgres-symbol-search.ts @@ -0,0 +1,355 @@ +/** + * Read-only PostgreSQL security-master adapter implementing {@link SymbolSearchPort} + * for the MCP copilot `search_symbols` tool. + * + * Dependency-free (no `pg`, no `node:*`, no bare `process`): SQL execution is + * injected via {@link SymbolSearchExecutor}. + */ + +import type { SymbolSearchPort, SymbolSearchQuery, SymbolSearchRow } from '../tools/search-symbols'; +import { utcDateOf, validateVaultCutoffTs } from '../tools/vault-fenced-input'; + +const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/; +const CALENDAR_DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/; +const DAYS_IN_MONTH: readonly number[] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + +/** Error codes thrown by {@link PostgresSymbolSearchError}. */ +export type PostgresSymbolSearchErrorCode = + | 'INVALID_EXECUTOR' + | 'INVALID_SCHEMA' + | 'INVALID_ROW'; + +/** Typed validation error thrown by the PostgreSQL symbol-search adapter. */ +export class PostgresSymbolSearchError extends RangeError { + readonly code: PostgresSymbolSearchErrorCode; + + constructor(code: PostgresSymbolSearchErrorCode, message: string) { + super(message); + this.name = 'PostgresSymbolSearchError'; + this.code = code; + Object.setPrototypeOf(this, new.target.prototype); + } +} + +/** + * Structural `pg.Pool` / `pg.PoolClient`-compatible query interface so this module + * has no runtime dependency on `pg` and is unit-testable with a fake executor. + */ +export interface SymbolSearchExecutor { + query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }>; +} + +/** Factory options for {@link createPostgresSymbolSearchPort}. */ +export interface PostgresSymbolSearchPortOptions { + readonly executor: SymbolSearchExecutor; + /** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */ + readonly schema?: string; +} + +interface RawSymbolSearchRow { + readonly listing_id: unknown; + readonly instrument_id: unknown; + readonly ticker: unknown; + readonly class_suffix: unknown; + readonly name: unknown; + readonly mic: unknown; + readonly currency: unknown; + readonly isin: unknown; + readonly first_bar_date: unknown; + readonly last_bar_date: unknown; + readonly delisted_at: unknown; +} + +function isLeapYear(year: number): boolean { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +function daysInUtcMonth(year: number, monthIndex: number): number { + if (monthIndex === 1 && isLeapYear(year)) { + return 29; + } + return DAYS_IN_MONTH[monthIndex] ?? 0; +} + +function isValidCalendarDate(value: unknown): value is string { + if (typeof value !== 'string') { + return false; + } + const match = CALENDAR_DATE_RE.exec(value); + if (match === null) { + return false; + } + const year = Number(match[1]); + const month = Number(match[2]); + const day = Number(match[3]); + if (month < 1 || month > 12) { + return false; + } + return day >= 1 && day <= daysInUtcMonth(year, month - 1); +} + +function escapeLikePattern(value: string): string { + return value.replace(/[\\%_]/g, '\\$&'); +} + +function quoteTable(schemaPrefix: string, table: string): string { + return `${schemaPrefix}${table}`; +} + +function buildSearchSymbolsSql(schemaPrefix: string): string { + const listingTable = quoteTable(schemaPrefix, 'listing'); + const instrumentTable = quoteTable(schemaPrefix, 'instrument'); + const exchangeTable = quoteTable(schemaPrefix, 'exchange'); + const historyTable = quoteTable(schemaPrefix, 'listing_symbol_history'); + + return [ + 'SELECT', + ' l.listing_id AS listing_id,', + ' l.instrument_id AS instrument_id,', + ' resolved.ticker AS ticker,', + " NULLIF(l.class_suffix, '') AS class_suffix,", + ' i.canonical_name AS name,', + ' l.mic AS mic,', + ' btrim(l.currency) AS currency,', + " NULLIF(btrim(i.primary_isin), '') AS isin,", + " to_char(l.listed_from, 'YYYY-MM-DD') AS first_bar_date,", + " to_char(l.listed_to, 'YYYY-MM-DD') AS last_bar_date,", + " to_char(delisted.delisted_at, 'YYYY-MM-DD') AS delisted_at", + `FROM ${listingTable} l`, + `INNER JOIN ${instrumentTable} i ON i.instrument_id = l.instrument_id`, + `INNER JOIN ${exchangeTable} e ON e.mic = l.mic`, + 'CROSS JOIN LATERAL (', + ' SELECT (', + ' EXISTS (', + ' SELECT 1', + ` FROM ${historyTable} h_any`, + ' WHERE h_any.listing_id = l.listing_id', + ' AND upper(h_any.ticker) = upper(l.ticker_root)', + ' )', + ' AND NOT EXISTS (', + ' SELECT 1', + ` FROM ${historyTable} h_past`, + ' WHERE h_past.listing_id = l.listing_id', + ' AND upper(h_past.ticker) = upper(l.ticker_root)', + ' AND h_past.valid_from <= $1::date', + ' )', + ' ) AS is_future', + ') root_state', + 'LEFT JOIN LATERAL (', + ' SELECT h.ticker', + ` FROM ${historyTable} h`, + ' WHERE h.listing_id = l.listing_id', + ' AND h.valid_from <= $1::date', + ' AND (h.valid_to IS NULL OR h.valid_to >= $1::date)', + ' ORDER BY h.valid_from DESC, h.ticker ASC', + ' LIMIT 1', + ') hist_active ON TRUE', + 'LEFT JOIN LATERAL (', + ' SELECT h.ticker', + ` FROM ${historyTable} h`, + ' WHERE h.listing_id = l.listing_id', + ' AND h.valid_from <= $1::date', + ' ORDER BY h.valid_from DESC, h.ticker ASC', + ' LIMIT 1', + ') hist_prior ON TRUE', + 'CROSS JOIN LATERAL (', + ' SELECT CASE', + ' WHEN hist_active.ticker IS NOT NULL THEN hist_active.ticker', + ' WHEN NOT root_state.is_future THEN l.ticker_root', + ' ELSE hist_prior.ticker', + ' END AS ticker', + ') resolved', + 'CROSS JOIN LATERAL (', + ' SELECT CASE', + " WHEN l.delist_reason IS NOT NULL AND l.delist_reason <> 'active' THEN l.listed_to", + ' ELSE NULL', + ' END AS delisted_at', + ') delisted', + 'WHERE (l.listed_from IS NULL OR l.listed_from <= $1::date)', + ' AND resolved.ticker IS NOT NULL', + " AND resolved.ticker <> ''", + ' AND ($4::text IS NULL OR btrim(e.country_iso) = $4::text)', + ' AND ($5::boolean OR delisted.delisted_at IS NULL OR delisted.delisted_at > $1::date)', + ' AND (', + " resolved.ticker ILIKE $2::text ESCAPE '\\'", + " OR (NOT root_state.is_future AND l.ticker_root ILIKE $2::text ESCAPE '\\')", + " OR i.canonical_name ILIKE $2::text ESCAPE '\\'", + ' OR (i.primary_isin IS NOT NULL AND upper(btrim(i.primary_isin)) = upper($3::text))', + ' )', + 'ORDER BY l.listing_id ASC', + ].join('\n'); +} + +function parseSafeInt(value: unknown, field: string): number { + if (typeof value !== 'number' || !Number.isSafeInteger(value)) { + throw new PostgresSymbolSearchError( + 'INVALID_ROW', + `Invalid security-master row: "${field}" must be a safe integer.` + ); + } + return value; +} + +function parseNonEmptyString(value: unknown, field: string): string { + if (typeof value !== 'string' || value.trim().length === 0) { + throw new PostgresSymbolSearchError( + 'INVALID_ROW', + `Invalid security-master row: "${field}" must be a non-empty string.` + ); + } + return value; +} + +function parseNullableClassSuffix(value: unknown): string | null { + if (value === null) { + return null; + } + if (typeof value !== 'string') { + throw new PostgresSymbolSearchError( + 'INVALID_ROW', + 'Invalid security-master row: "class_suffix" must be a string or null.' + ); + } + return value === '' ? null : value; +} + +function parseNullableIsin(value: unknown): string | null { + if (value === null) { + return null; + } + if (typeof value !== 'string') { + throw new PostgresSymbolSearchError( + 'INVALID_ROW', + 'Invalid security-master row: "isin" must be a string or null.' + ); + } + const trimmed = value.trim(); + return trimmed === '' ? null : trimmed; +} + +function parseNullableDate(value: unknown, field: string): string | null { + if (value === null) { + return null; + } + if (!isValidCalendarDate(value)) { + throw new PostgresSymbolSearchError( + 'INVALID_ROW', + `Invalid security-master row: "${field}" must be a valid YYYY-MM-DD calendar date or null.` + ); + } + return value; +} + +function mapRawRow(raw: unknown): SymbolSearchRow { + if (typeof raw !== 'object' || raw === null) { + throw new PostgresSymbolSearchError( + 'INVALID_ROW', + 'Invalid security-master row: expected a non-null object.' + ); + } + + const row = raw as RawSymbolSearchRow; + const listingId = parseSafeInt(row.listing_id, 'listing_id'); + const instrumentId = parseSafeInt(row.instrument_id, 'instrument_id'); + const ticker = parseNonEmptyString(row.ticker, 'ticker'); + const classSuffix = parseNullableClassSuffix(row.class_suffix); + const name = parseNonEmptyString(row.name, 'name'); + const mic = parseNonEmptyString(row.mic, 'mic'); + const currency = parseNonEmptyString(row.currency, 'currency').trim(); + const isin = parseNullableIsin(row.isin); + const firstBarDate = parseNullableDate(row.first_bar_date, 'first_bar_date'); + const lastBarDate = parseNullableDate(row.last_bar_date, 'last_bar_date'); + const delistedAt = parseNullableDate(row.delisted_at, 'delisted_at'); + + return { + listingId, + instrumentId, + ticker, + classSuffix, + name, + mic, + currency, + isin, + firstBarDate, + lastBarDate, + delistedAt, + }; +} + +function validateFactoryOptions(options: PostgresSymbolSearchPortOptions): { + readonly executor: SymbolSearchExecutor; + readonly schemaPrefix: string; +} { + if (typeof options !== 'object' || options === null) { + throw new PostgresSymbolSearchError( + 'INVALID_EXECUTOR', + 'Invalid options: expected an object with a SymbolSearchExecutor.' + ); + } + + const { executor, schema } = options; + if (typeof executor !== 'object' || executor === null || typeof executor.query !== 'function') { + throw new PostgresSymbolSearchError( + 'INVALID_EXECUTOR', + 'Invalid executor: expected an object with a callable query(text, params?) method.' + ); + } + + if (schema === undefined) { + return { executor, schemaPrefix: '' }; + } + + if (typeof schema !== 'string' || !SCHEMA_IDENT_RE.test(schema)) { + throw new PostgresSymbolSearchError( + 'INVALID_SCHEMA', + 'Invalid schema: expected an identifier matching ^[a-z_][a-z0-9_]*$.' + ); + } + + return { executor, schemaPrefix: `"${schema}".` }; +} + +/** + * Creates a read-only PostgreSQL {@link SymbolSearchPort} backed by the M1 + * security master (`listing`, `instrument`, `exchange`, `listing_symbol_history`). + */ +export function createPostgresSymbolSearchPort( + options: PostgresSymbolSearchPortOptions +): SymbolSearchPort { + const { executor, schemaPrefix } = validateFactoryOptions(options); + const sql = buildSearchSymbolsSql(schemaPrefix); + + return { + async searchSymbols(q: SymbolSearchQuery): Promise { + const cutoffTs = validateVaultCutoffTs(q.vaultCutoffTs); + const cutoffDate = utcDateOf(cutoffTs); + const ilikePattern = `%${escapeLikePattern(q.query)}%`; + const country = q.country ?? null; + const includeDelisted = q.includeDelisted; + + const result = await executor.query(sql, [ + cutoffDate, + ilikePattern, + q.query, + country, + includeDelisted, + ]); + + if (typeof result !== 'object' || result === null || !Array.isArray(result.rows)) { + throw new PostgresSymbolSearchError( + 'INVALID_ROW', + 'Invalid executor response: expected an object with a rows array.' + ); + } + + const mapped: SymbolSearchRow[] = []; + for (let i = 0; i < result.rows.length; i += 1) { + mapped.push(mapRawRow(result.rows[i])); + } + return mapped; + }, + }; +} diff --git a/libs/research/src/mcp/index.ts b/libs/research/src/mcp/index.ts index 3ab56692..f8f50f75 100644 --- a/libs/research/src/mcp/index.ts +++ b/libs/research/src/mcp/index.ts @@ -1,3 +1,4 @@ +export * from './adapters/postgres-symbol-search'; export * from './copilot-server'; export * from './protocol'; export * from './server'; diff --git a/libs/research/test/mcp-postgres-symbol-search.test.ts b/libs/research/test/mcp-postgres-symbol-search.test.ts new file mode 100644 index 00000000..ea9a3edd --- /dev/null +++ b/libs/research/test/mcp-postgres-symbol-search.test.ts @@ -0,0 +1,413 @@ +import { describe, expect, test } from 'bun:test'; +import { MarketDataStoreValidationError } from '../src/market-data-store'; +import { + PostgresSymbolSearchError, + type SymbolSearchExecutor, + type SymbolSearchQuery, + createPostgresSymbolSearchPort, +} from '../src/mcp/index'; + +interface RecordedCall { + readonly text: string; + readonly params: readonly unknown[] | undefined; +} + +function createFakeExecutor(rows: readonly Record[] = []): { + readonly calls: RecordedCall[]; + readonly executor: SymbolSearchExecutor; +} { + const calls: RecordedCall[] = []; + const executor: SymbolSearchExecutor = { + async query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + calls.push({ text, params }); + return { rows: rows as readonly Row[] }; + }, + }; + return { calls, executor }; +} + +function makeRawRow(overrides: Record = {}): Record { + return { + listing_id: 101, + instrument_id: 1001, + ticker: 'ACME', + class_suffix: '', + name: 'Acme Corporation', + mic: 'XNAS', + currency: 'USD', + isin: 'US0000001015', + first_bar_date: '2018-01-02', + last_bar_date: '2024-06-28', + delisted_at: null, + ...overrides, + }; +} + +const BASE_QUERY: SymbolSearchQuery = { + query: 'ACME', + limit: 20, + includeDelisted: true, + vaultCutoffTs: Date.UTC(2024, 5, 30, 0, 0, 0, 0), // 2024-06-30T00:00:00.000Z +}; + +describe('createPostgresSymbolSearchPort (fake executor)', () => { + test('issues a single parameterized SELECT and never interpolates injection-shaped queries', async () => { + const injection = "'; DROP TABLE listing; --"; + const fake = createFakeExecutor([makeRawRow()]); + const port = createPostgresSymbolSearchPort({ executor: fake.executor }); + + await port.searchSymbols({ + ...BASE_QUERY, + query: injection, + }); + + 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.toContain(injection); + expect(call.text).not.toContain('DROP TABLE'); + expect(call.params).toEqual([ + '2024-06-30', + `%${injection}%`, + injection, + null, + true, + ]); + }); + + test('escapes %, _, and backslash literals in the ILIKE pattern while preserving raw query for ISIN', async () => { + const fake = createFakeExecutor([]); + const port = createPostgresSymbolSearchPort({ executor: fake.executor }); + + await port.searchSymbols({ + ...BASE_QUERY, + query: 'A%B_C\\D', + }); + + expect(fake.calls).toHaveLength(1); + const call = fake.calls[0]!; + expect(call.text).toContain("ESCAPE '\\'"); + expect(call.params).toEqual([ + '2024-06-30', + '%A\\%B\\_C\\\\D%', + 'A%B_C\\D', + null, + true, + ]); + }); + + test('converts vaultCutoffTs epoch-ms to UTC calendar date across midnight boundaries', async () => { + const fake = createFakeExecutor([]); + const port = createPostgresSymbolSearchPort({ executor: fake.executor }); + + await port.searchSymbols({ + ...BASE_QUERY, + vaultCutoffTs: Date.UTC(2024, 5, 30, 23, 59, 59, 999), + }); + await port.searchSymbols({ + ...BASE_QUERY, + vaultCutoffTs: Date.UTC(2024, 6, 1, 0, 0, 0, 0), + }); + + expect(fake.calls).toHaveLength(2); + expect(fake.calls[0]!.params?.[0]).toBe('2024-06-30'); + expect(fake.calls[1]!.params?.[0]).toBe('2024-07-01'); + }); + + test('binds optional country filter and both includeDelisted flags', async () => { + const fake = createFakeExecutor([]); + const port = createPostgresSymbolSearchPort({ executor: fake.executor }); + + await port.searchSymbols({ + ...BASE_QUERY, + country: 'CA', + includeDelisted: false, + }); + await port.searchSymbols({ + ...BASE_QUERY, + country: 'US', + includeDelisted: true, + }); + + expect(fake.calls).toHaveLength(2); + expect(fake.calls[0]!.params?.[3]).toBe('CA'); + expect(fake.calls[0]!.params?.[4]).toBe(false); + expect(fake.calls[1]!.params?.[3]).toBe('US'); + expect(fake.calls[1]!.params?.[4]).toBe(true); + }); + + test('ignores q.limit in SQL and returns all candidates without truncation', async () => { + const rows = [ + makeRawRow({ listing_id: 1, instrument_id: 10, ticker: 'AA' }), + makeRawRow({ listing_id: 2, instrument_id: 20, ticker: 'AAB' }), + makeRawRow({ listing_id: 3, instrument_id: 30, ticker: 'AAC' }), + ]; + const fake = createFakeExecutor(rows); + const port = createPostgresSymbolSearchPort({ executor: fake.executor }); + + const r1 = await port.searchSymbols({ ...BASE_QUERY, limit: 1 }); + const r2 = await port.searchSymbols({ ...BASE_QUERY, limit: 100 }); + + expect(r1).toHaveLength(3); + expect(r2).toHaveLength(3); + expect(fake.calls[0]!.text).toBe(fake.calls[1]!.text); + expect(fake.calls[0]!.params).toEqual(fake.calls[1]!.params); + // Outer query has ORDER BY listing_id ASC with no outer LIMIT clause + expect(fake.calls[0]!.text.trimEnd().endsWith('ORDER BY l.listing_id ASC')).toBe(true); + }); + + test('gates ticker_root fallback and matching on cutoff-aware history suppression and derives delisted_at', async () => { + const fake = createFakeExecutor([]); + const port = createPostgresSymbolSearchPort({ executor: fake.executor }); + + await port.searchSymbols(BASE_QUERY); + + const sql = fake.calls[0]!.text; + // Root-suppression subquery checks upper(ticker) = upper(ticker_root) and cutoff $1::date + expect(sql).toContain('upper(h_any.ticker) = upper(l.ticker_root)'); + expect(sql).toContain('upper(h_past.ticker) = upper(l.ticker_root)'); + expect(sql).toContain('h_past.valid_from <= $1::date'); + // Both fallback resolution and root ILIKE predicate are gated by NOT root_state.is_future + expect(sql).toContain('WHEN NOT root_state.is_future THEN l.ticker_root'); + expect(sql).toContain("OR (NOT root_state.is_future AND l.ticker_root ILIKE $2::text ESCAPE '\\')"); + // delisted_at derivation and $5 filter + expect(sql).toContain("WHEN l.delist_reason IS NOT NULL AND l.delist_reason <> 'active' THEN l.listed_to"); + expect(sql).toContain('($5::boolean OR delisted.delisted_at IS NULL OR delisted.delisted_at > $1::date)'); + }); + + test('quotes optional validated schema on all security-master tables and omits prefix when unset', async () => { + const fakeDefault = createFakeExecutor([]); + const defaultPort = createPostgresSymbolSearchPort({ executor: fakeDefault.executor }); + await defaultPort.searchSymbols(BASE_QUERY); + expect(fakeDefault.calls[0]!.text).toContain('FROM listing l'); + expect(fakeDefault.calls[0]!.text).toContain('INNER JOIN instrument i'); + expect(fakeDefault.calls[0]!.text).toContain('INNER JOIN exchange e'); + expect(fakeDefault.calls[0]!.text).toContain('FROM listing_symbol_history'); + + const fakeScoped = createFakeExecutor([]); + const scopedPort = createPostgresSymbolSearchPort({ + executor: fakeScoped.executor, + schema: 'custom_master_1', + }); + await scopedPort.searchSymbols(BASE_QUERY); + expect(fakeScoped.calls[0]!.text).toContain('FROM "custom_master_1".listing l'); + expect(fakeScoped.calls[0]!.text).toContain('INNER JOIN "custom_master_1".instrument i'); + expect(fakeScoped.calls[0]!.text).toContain('INNER JOIN "custom_master_1".exchange e'); + expect(fakeScoped.calls[0]!.text).toContain('FROM "custom_master_1".listing_symbol_history'); + }); + + test('maps raw rows into SymbolSearchRow with classSuffix, ISIN trimming, nullable dates, and delistedAt', async () => { + const fake = createFakeExecutor([ + makeRawRow({ + listing_id: 101, + instrument_id: 501, + ticker: 'ACME', + class_suffix: '', + name: 'Acme Corp', + mic: 'XNAS', + currency: 'USD ', + isin: ' US0000001015 ', + first_bar_date: '2020-02-29', + last_bar_date: '2024-06-28', + delisted_at: null, + }), + makeRawRow({ + listing_id: 102, + instrument_id: 502, + ticker: 'BRK', + class_suffix: 'B', + name: 'Berkshire Example', + mic: 'XNYS', + currency: 'USD', + isin: ' ', + first_bar_date: null, + last_bar_date: '2023-12-15', + delisted_at: '2023-12-15', + }), + makeRawRow({ + listing_id: 103, + instrument_id: 503, + ticker: 'NULLY', + class_suffix: null, + name: 'Nullable Fields Co', + mic: 'XTSE', + currency: 'CAD', + isin: null, + first_bar_date: null, + last_bar_date: null, + delisted_at: null, + }), + ]); + + const port = createPostgresSymbolSearchPort({ executor: fake.executor }); + const rows = await port.searchSymbols(BASE_QUERY); + + expect(rows).toEqual([ + { + listingId: 101, + instrumentId: 501, + ticker: 'ACME', + classSuffix: null, + name: 'Acme Corp', + mic: 'XNAS', + currency: 'USD', + isin: 'US0000001015', + firstBarDate: '2020-02-29', + lastBarDate: '2024-06-28', + delistedAt: null, + }, + { + listingId: 102, + instrumentId: 502, + ticker: 'BRK', + classSuffix: 'B', + name: 'Berkshire Example', + mic: 'XNYS', + currency: 'USD', + isin: null, + firstBarDate: null, + lastBarDate: '2023-12-15', + delistedAt: '2023-12-15', + }, + { + listingId: 103, + instrumentId: 503, + ticker: 'NULLY', + classSuffix: null, + name: 'Nullable Fields Co', + mic: 'XTSE', + currency: 'CAD', + isin: null, + firstBarDate: null, + lastBarDate: null, + delistedAt: null, + }, + ]); + }); + + test('rejects invalid executors and options with INVALID_EXECUTOR before any query', () => { + const invalidOptions: unknown[] = [ + null, + undefined, + {}, + { executor: null }, + { executor: {} }, + { executor: { query: 'not-a-fn' } }, + ]; + + for (const opts of invalidOptions) { + let caught: unknown; + try { + createPostgresSymbolSearchPort(opts as Parameters[0]); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresSymbolSearchError); + expect((caught as PostgresSymbolSearchError).code).toBe('INVALID_EXECUTOR'); + } + }); + + test('rejects invalid schema names with INVALID_SCHEMA before any query', () => { + const fake = createFakeExecutor([]); + const badSchemas: unknown[] = [ + '', + 'Public', + '1schema', + 'bad-name', + 'bad.name', + 'public"; DROP TABLE listing; --', + 'space name', + 123, + null, + ]; + + for (const schema of badSchemas) { + let caught: unknown; + try { + createPostgresSymbolSearchPort({ + executor: fake.executor, + schema: schema as string, + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresSymbolSearchError); + expect((caught as PostgresSymbolSearchError).code).toBe('INVALID_SCHEMA'); + } + + expect(fake.calls).toHaveLength(0); + }); + + test('rejects invalid vaultCutoffTs before executing any query', async () => { + const fake = createFakeExecutor([]); + const port = createPostgresSymbolSearchPort({ executor: fake.executor }); + + await expect( + port.searchSymbols({ ...BASE_QUERY, vaultCutoffTs: Number.NaN }) + ).rejects.toBeInstanceOf(MarketDataStoreValidationError); + expect(fake.calls).toHaveLength(0); + }); + + test('rejects malformed rows (fractional/unsafe IDs, malformed/impossible dates, invalid types) with INVALID_ROW', async () => { + const badRows: readonly Record[] = [ + makeRawRow({ listing_id: 1.5 }), + makeRawRow({ listing_id: Number.MAX_SAFE_INTEGER + 1 }), + makeRawRow({ listing_id: '101' }), + makeRawRow({ listing_id: Number.NaN }), + makeRawRow({ instrument_id: 2.25 }), + makeRawRow({ instrument_id: Number.POSITIVE_INFINITY }), + makeRawRow({ ticker: '' }), + makeRawRow({ ticker: null }), + makeRawRow({ name: '' }), + makeRawRow({ mic: null }), + makeRawRow({ currency: '' }), + makeRawRow({ class_suffix: 42 }), + makeRawRow({ isin: 12345 }), + makeRawRow({ first_bar_date: '2024-6-1' }), + makeRawRow({ first_bar_date: '2023-02-29' }), + makeRawRow({ last_bar_date: '2024-02-30' }), + makeRawRow({ last_bar_date: '2024-13-01' }), + makeRawRow({ delisted_at: '2024-06-30T00:00:00Z' }), + makeRawRow({ delisted_at: new Date('2024-06-30T00:00:00Z') }), + ]; + + for (const badRow of badRows) { + const fake = createFakeExecutor([badRow]); + const port = createPostgresSymbolSearchPort({ executor: fake.executor }); + + let caught: unknown; + try { + await port.searchSymbols(BASE_QUERY); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresSymbolSearchError); + expect((caught as PostgresSymbolSearchError).code).toBe('INVALID_ROW'); + } + + // Non-object row / invalid result shape + const nullRowExecutor: SymbolSearchExecutor = { + async query>() { + return { rows: [null as unknown as Row] }; + }, + }; + const portNullRow = createPostgresSymbolSearchPort({ executor: nullRowExecutor }); + await expect(portNullRow.searchSymbols(BASE_QUERY)).rejects.toBeInstanceOf( + PostgresSymbolSearchError + ); + + const badResultExecutor: SymbolSearchExecutor = { + async query() { + return { rows: 'not-an-array' as unknown as readonly never[] }; + }, + }; + const portBadResult = createPostgresSymbolSearchPort({ executor: badResultExecutor }); + await expect(portBadResult.searchSymbols(BASE_QUERY)).rejects.toBeInstanceOf( + PostgresSymbolSearchError + ); + }); +}); diff --git a/test/postgres/mcp-symbol-search-adapter.test.ts b/test/postgres/mcp-symbol-search-adapter.test.ts new file mode 100644 index 00000000..a66a0b8c --- /dev/null +++ b/test/postgres/mcp-symbol-search-adapter.test.ts @@ -0,0 +1,447 @@ +import { randomUUID } from 'node:crypto'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Pool } from 'pg'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; +import { + type SearchSymbolsResultPayload, + type SymbolSearchExecutor, + createMcpServer, + createPostgresSymbolSearchPort, + createSearchSymbolsTool, +} from '../../libs/research/src/mcp/index'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('mcp-symbol-search-adapter-pg-test'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; + +const VAULT_CUTOFF_DATE = '2024-06-30'; +const VAULT_CUTOFF_TS = Date.UTC(2024, 5, 30, 0, 0, 0, 0); + +const cleanup: (() => Promise | void)[] = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); + +function assertSafetyDatabaseUrl(connectionString: string | undefined): string { + if (!connectionString || !new URL(connectionString).pathname.startsWith('/stock_bot_safety')) { + throw new Error('Dedicated stock_bot_safety database required'); + } + return connectionString; +} + +function createPgExecutor(pool: Pool): SymbolSearchExecutor { + return { + query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + return pool.query( + text, + params === undefined ? undefined : [...params] + ) as unknown as Promise<{ readonly rows: readonly Row[] }>; + }, + }; +} + +async function createIsolatedFixture() { + const safeUrl = assertSafetyDatabaseUrl(url); + const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; + const admin = new Pool({ connectionString: safeUrl }); + await admin.query(`CREATE SCHEMA ${schema}`); + const pool = new Pool({ + connectionString: safeUrl, + options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`, + }); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + + const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, + logger + ); + Object.defineProperty(postgres, 'connectionPool', { + get: () => ({ + connect: () => pool.connect(), + }), + }); + + await runPostgresMigrations(postgres, { track: 'master' }); + await seedFixture(pool); + + return { admin, pool, schema }; +} + +async function seedFixture(pool: Pool): Promise { + const client = await pool.connect(); + try { + await client.query('BEGIN'); + + await client.query(` + INSERT INTO exchange (mic, operating_mic, name, country_iso, currency, timezone, calendar_code, board_lot_policy) + VALUES + ('XNAS', 'XNAS', 'NASDAQ', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'), + ('XNYS', 'XNYS', 'NYSE', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'), + ('XTSE', 'XTSE', 'TSX', 'CA', 'CAD', 'America/Toronto', 'XTSE', 'tsx_tiered') + ON CONFLICT (mic) DO NOTHING + `); + + await client.query(` + INSERT INTO instrument (instrument_id, primary_isin, canonical_name, security_type, issuer_country) + OVERRIDING SYSTEM VALUE + VALUES + (101, 'US1010000001', 'Renamed Holdings Inc', 'common', 'US'), + (102, 'US1020000002', 'Gap Rename Corp', 'common', 'US'), + (103, 'US1030000003', 'Stealth Future Ventures', 'common', 'US'), + (104, 'CA1040000004', 'No History Metals', 'common', 'CA'), + (105, 'US1050000005', 'Overlap Equity Inc', 'common', 'US'), + (106, 'US1060000006', 'Post Cutoff IPO Inc', 'common', 'US'), + (107, 'CA1070000007', 'Unknown Start Corp', 'common', 'CA'), + (108, 'US1080000008', 'Delist Boundary Co', 'common', 'US'), + (109, 'US1090000009', 'Delist Boundary Active', 'common', 'US'), + (110, 'US1100000010', 'Delist Boundary Unspecified', 'common', 'US'), + (111, 'US1110000011', 'Delist Boundary Future', 'common', 'US'), + (112, 'US1120000012', '100% Pure_Wild\\Co', 'common', 'US'), + (113, 'US1130000013', 'Second Oldco Group', 'common', 'US'), + (114, 'CA1140000014', 'Alpha Oldco Canada', 'common', 'CA') + `); + + await client.query(` + INSERT INTO listing ( + listing_id, instrument_id, mic, ticker_root, class_suffix, currency, + listed_from, listed_to, delist_reason + ) + OVERRIDING SYSTEM VALUE + VALUES + (101, 101, 'XNAS', 'NEWCO', '', 'USD', '2018-01-02', '2024-12-31', 'active'), + (102, 102, 'XNYS', 'GAPNEW', '', 'USD', '2019-01-01', '2024-12-31', 'active'), + (103, 103, 'XNAS', 'FUTROOT', '', 'USD', '2020-01-01', NULL, NULL), + (104, 104, 'XTSE', 'NOHIST', 'A', 'CAD', '2021-03-15', '2024-06-28', 'active'), + (105, 105, 'XNYS', 'OVLP', '', 'USD', '2018-01-01', '2024-06-28', 'active'), + (106, 106, 'XNAS', 'IPO25', '', 'USD', '2024-07-01', NULL, 'active'), + (107, 107, 'XTSE', 'NULLSTART', '', 'CAD', NULL, NULL, NULL), + (108, 108, 'XNAS', 'DLST1', '', 'USD', '2015-01-01', '2024-06-30', 'merger_cash'), + (109, 109, 'XNAS', 'DLST2', '', 'USD', '2015-01-01', '2024-06-28', 'active'), + (110, 110, 'XNAS', 'DLST3', '', 'USD', '2015-01-01', '2024-06-28', NULL), + (111, 111, 'XNAS', 'DLST4', '', 'USD', '2015-01-01', '2024-09-15', 'bankruptcy_cancelled'), + (112, 112, 'XNYS', 'WILD', '', 'USD', '2020-01-01', '2024-06-28', 'active'), + (113, 113, 'XNAS', 'OLDCO2', '', 'USD', '2020-01-01', '2024-06-28', 'active'), + (114, 114, 'XTSE', 'ZOLD', '', 'CAD', '2020-01-01', '2024-06-28', 'active') + `); + + await client.query(` + INSERT INTO listing_symbol_history (listing_id, ticker, valid_from, valid_to, source) + VALUES + (101, 'OLDCO', '2018-01-02', '2024-06-30', 'eod'), + (101, 'NEWCO', '2024-07-01', NULL, 'eod'), + (102, 'GAPOLD', '2019-01-01', '2024-05-31', 'eod'), + (102, 'GAPNEW', '2024-07-01', NULL, 'eod'), + (103, 'FUTROOT', '2024-07-15', NULL, 'eod'), + (105, 'OVLP1', '2018-01-01', NULL, 'eod'), + (105, 'OVLPZ', '2023-01-01', NULL, 'eod'), + (105, 'OVLPA', '2023-01-01', NULL, 'eod') + `); + + await client.query('COMMIT'); + } catch (err) { + await client.query('ROLLBACK'); + throw err; + } finally { + client.release(); + } +} + +describe('PostgreSQL symbol search safety guard', () => { + test('rejects unsafe database targets before connecting', () => { + expect(() => assertSafetyDatabaseUrl(undefined)).toThrow('Dedicated stock_bot_safety database required'); + expect(() => + assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/trading_bot') + ).toThrow('Dedicated stock_bot_safety database required'); + expect(() => + assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5433/trading_bot_dev') + ).toThrow('Dedicated stock_bot_safety database required'); + expect( + assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test') + ).toBe('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test'); + }); +}); + +describe.skipIf(!url)('PostgreSQL MCP symbol search adapter', () => { + test('enforces as-of-cutoff ticker resolution, root suppression, and listed_from bounds', async () => { + const f = await createIsolatedFixture(); + const port = createPostgresSymbolSearchPort({ executor: createPgExecutor(f.pool) }); + + // (a)/(g) Post-cutoff rename: OLDCO is valid on 2024-06-30; NEWCO starts 2024-07-01 and is invisible even as ticker_root + const oldcoRows = await port.searchSymbols({ + query: 'OLDCO', + limit: 1, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(oldcoRows.map(r => r.listingId)).toEqual([101, 113, 114]); + expect(oldcoRows[0]).toEqual({ + listingId: 101, + instrumentId: 101, + ticker: 'OLDCO', + classSuffix: null, + name: 'Renamed Holdings Inc', + mic: 'XNAS', + currency: 'USD', + isin: 'US1010000001', + firstBarDate: '2018-01-02', + lastBarDate: '2024-12-31', + delistedAt: null, + }); + + const newcoRows = await port.searchSymbols({ + query: 'NEWCO', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(newcoRows).toEqual([]); + + // Expired-but-known fallback (step 3c): GAPNEW is future-only root, falls back to GAPOLD + const gapOldRows = await port.searchSymbols({ + query: 'GAPOLD', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(gapOldRows.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([ + { id: 102, ticker: 'GAPOLD' }, + ]); + const gapNewRows = await port.searchSymbols({ + query: 'GAPNEW', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(gapNewRows).toEqual([]); + + // (h) Future-only root with no prior history: excluded by root, name, and ISIN searches + expect( + await port.searchSymbols({ + query: 'FUTROOT', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }) + ).toEqual([]); + expect( + await port.searchSymbols({ + query: 'Stealth Future', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }) + ).toEqual([]); + expect( + await port.searchSymbols({ + query: 'US1030000003', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }) + ).toEqual([]); + + // (i) No history rows at all: falls back to ticker_root + const noHistRows = await port.searchSymbols({ + query: 'NOHIST', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(noHistRows).toEqual([ + { + listingId: 104, + instrumentId: 104, + ticker: 'NOHIST', + classSuffix: 'A', + name: 'No History Metals', + mic: 'XTSE', + currency: 'CAD', + isin: 'CA1040000004', + firstBarDate: '2021-03-15', + lastBarDate: '2024-06-28', + delistedAt: null, + }, + ]); + + // Overlapping valid history: latest valid_from wins, tie-breaking by ticker ASC (OVLPA < OVLPZ) + const overlapRows = await port.searchSymbols({ + query: 'Overlap Equity', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(overlapRows).toHaveLength(1); + expect(overlapRows[0]!.listingId).toBe(105); + expect(overlapRows[0]!.ticker).toBe('OVLPA'); + + // (b) listed_from > cutoff excluded + expect( + await port.searchSymbols({ + query: 'IPO25', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }) + ).toEqual([]); + + // (c) listed_from IS NULL included + const nullStartRows = await port.searchSymbols({ + query: 'NULLSTART', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(nullStartRows).toHaveLength(1); + expect(nullStartRows[0]!.listingId).toBe(107); + expect(nullStartRows[0]!.firstBarDate).toBeNull(); + expect(nullStartRows[0]!.lastBarDate).toBeNull(); + expect(nullStartRows[0]!.delistedAt).toBeNull(); + }); + + test('supports country filter, case-insensitive exact ISIN, literal wildcards, delisting semantics, explicit schema, and deterministic ordering', async () => { + const f = await createIsolatedFixture(); + // Use admin pool (default search_path) with explicit schema option to verify schema quoting + const port = createPostgresSymbolSearchPort({ + executor: createPgExecutor(f.admin), + schema: f.schema, + }); + + // (d) country: 'CA' returns only CA-venue listings + const caRows = await port.searchSymbols({ + query: 'OLDCO', + limit: 20, + country: 'CA', + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(caRows.map(r => ({ id: r.listingId, mic: r.mic }))).toEqual([ + { id: 114, mic: 'XTSE' }, + ]); + + // (e) Case-insensitive exact ISIN match with partial-ISIN negative + const isinRows = await port.searchSymbols({ + query: 'ca1040000004', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(isinRows.map(r => r.listingId)).toEqual([104]); + + const partialIsinRows = await port.searchSymbols({ + query: 'CA104000', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(partialIsinRows).toEqual([]); + + // Literal wildcard matching: %, _, and \ are escaped + const wildRows = await port.searchSymbols({ + query: '100% Pure_Wild\\', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(wildRows.map(r => r.listingId)).toEqual([112]); + + // Delisting boundary: 108 confirmed delisted on cutoff (2024-06-30), 109 active, 110 null reason, 111 future delist (2024-09-15) + const allDelist = await port.searchSymbols({ + query: 'Delist Boundary', + limit: 1, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(allDelist.map(r => ({ id: r.listingId, delistedAt: r.delistedAt }))).toEqual([ + { id: 108, delistedAt: '2024-06-30' }, + { id: 109, delistedAt: null }, + { id: 110, delistedAt: null }, + { id: 111, delistedAt: '2024-09-15' }, + ]); + + const activeAsOfCutoff = await port.searchSymbols({ + query: 'Delist Boundary', + limit: 20, + includeDelisted: false, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(activeAsOfCutoff.map(r => r.listingId)).toEqual([109, 110, 111]); + + // Repeated pinned query produces identical deterministic rows + const repeat = await port.searchSymbols({ + query: 'Delist Boundary', + limit: 1, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(repeat).toEqual(allDelist); + }); + + test('composes with createSearchSymbolsTool through MCP for ranking, truncation, clamping, and future delisting masking', async () => { + const f = await createIsolatedFixture(); + const port = createPostgresSymbolSearchPort({ executor: createPgExecutor(f.pool) }); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createSearchSymbolsTool({ + port, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + }), + ], + }); + + const callTool = async (args: Record): Promise => { + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'mcp-pg-1', + method: 'tools/call', + params: { + name: 'search_symbols', + arguments: args, + }, + }) + ); + expect(raw).not.toBeNull(); + const parsed = JSON.parse(raw!) as { + result: { isError?: boolean; content: Array<{ text: string }> }; + }; + expect(parsed.result.isError).toBeUndefined(); + return JSON.parse(parsed.result.content[0]!.text) as SearchSymbolsResultPayload; + }; + + // Ranking & truncation: exact ticker OLDCO (101) > prefix OLDCO2 (113) > name Alpha Oldco Canada (114) + const oldcoPayload = await callTool({ query: 'OLDCO', limit: 2 }); + expect(oldcoPayload.scope).toBe('vault_fenced'); + expect(oldcoPayload.vaultCutoffTs).toBe(VAULT_CUTOFF_TS); + expect(oldcoPayload.truncated).toBe(true); + expect(oldcoPayload.rowCount).toBe(2); + expect(oldcoPayload.rows.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([ + { id: 101, ticker: 'OLDCO' }, + { id: 113, ticker: 'OLDCO2' }, + ]); + // Post-cutoff lastBarDate (2024-12-31) is clamped to vaultCutoffDate (2024-06-30) + expect(oldcoPayload.rows[0]!.lastBarDate).toBe(VAULT_CUTOFF_DATE); + + // Future delisting (111: listed_to=2024-09-15, delist_reason=bankruptcy_cancelled) is masked to null and clamped + const futureDelistPayload = await callTool({ + query: 'DLST4', + includeDelisted: false, + }); + expect(futureDelistPayload.rowCount).toBe(1); + expect(futureDelistPayload.rows[0]!.listingId).toBe(111); + expect(futureDelistPayload.rows[0]!.lastBarDate).toBe(VAULT_CUTOFF_DATE); + expect(futureDelistPayload.rows[0]!.delistedAt).toBeNull(); + }); +}); From c6fcc341b992ff47914d53e3b0548a4dca37dd2f Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 08:56:23 -0500 Subject: [PATCH 02/21] =?UTF-8?q?T-158:=20M2.1k=20=E2=80=94=20PostgreSQL?= =?UTF-8?q?=20security-master=20adapter=20for=20the=20MCP=20copilot=20`sea?= =?UTF-8?q?rch=5Fsymbols`=20tool:=20`SymbolSearchPort`=20over=20an=20injec?= =?UTF-8?q?ted=20executor=20in=20`libs/research/src/mcp/adapters/postgres-?= =?UTF-8?q?symbol-search.ts`=20(as-of-cutoff=20ticker=20resolution,=20para?= =?UTF-8?q?meterized=20SQL,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mcp-symbol-search-adapter.test.ts | 101 ++++++++++++++---- 1 file changed, 81 insertions(+), 20 deletions(-) diff --git a/test/postgres/mcp-symbol-search-adapter.test.ts b/test/postgres/mcp-symbol-search-adapter.test.ts index a66a0b8c..6f5e253f 100644 --- a/test/postgres/mcp-symbol-search-adapter.test.ts +++ b/test/postgres/mcp-symbol-search-adapter.test.ts @@ -1,6 +1,6 @@ import { randomUUID } from 'node:crypto'; import { afterEach, describe, expect, test } from 'bun:test'; -import { Pool } from 'pg'; +import { Client, Pool, type PoolConfig } from 'pg'; import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; import { @@ -46,21 +46,45 @@ function createPgExecutor(pool: Pool): SymbolSearchExecutor { }; } -async function createIsolatedFixture() { - const safeUrl = assertSafetyDatabaseUrl(url); +function buildIsolatedPoolConfig(connectionString: string | undefined, schema: string): PoolConfig { + const safeUrl = assertSafetyDatabaseUrl(connectionString); + const parsed = new URL(safeUrl); + const existingOptions = parsed.searchParams + .getAll('options') + .map(value => value.trim()) + .filter(value => value.length > 0); + parsed.searchParams.delete('options'); + + const schemaOptions = `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`; + const options = [...existingOptions, schemaOptions].join(' '); + + return { + connectionString: parsed.toString(), + options, + }; +} + +async function createIsolatedFixture(connectionString: string | undefined = url) { + const safeUrl = assertSafetyDatabaseUrl(connectionString); const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; const admin = new Pool({ connectionString: safeUrl }); await admin.query(`CREATE SCHEMA ${schema}`); - const pool = new Pool({ - connectionString: safeUrl, - options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`, - }); + const pool = new Pool(buildIsolatedPoolConfig(safeUrl, schema)); cleanup.push(async () => { await pool.end(); await admin.query(`DROP SCHEMA ${schema} CASCADE`); await admin.end(); }); + const { rows: schemaRows } = await pool.query<{ current_schema: string | null }>( + 'SELECT current_schema() AS current_schema' + ); + if (schemaRows[0]?.current_schema !== schema) { + throw new Error( + `Isolated fixture pool expected current_schema()=${schema}, got ${String(schemaRows[0]?.current_schema)}` + ); + } + const postgres = new PostgreSQLClient( { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, logger @@ -95,7 +119,7 @@ async function seedFixture(pool: Pool): Promise { INSERT INTO instrument (instrument_id, primary_isin, canonical_name, security_type, issuer_country) OVERRIDING SYSTEM VALUE VALUES - (101, 'US1010000001', 'Renamed Holdings Inc', 'common', 'US'), + (101, 'CA1010000001', 'Alpha Oldco Canada', 'common', 'CA'), (102, 'US1020000002', 'Gap Rename Corp', 'common', 'US'), (103, 'US1030000003', 'Stealth Future Ventures', 'common', 'US'), (104, 'CA1040000004', 'No History Metals', 'common', 'CA'), @@ -108,7 +132,7 @@ async function seedFixture(pool: Pool): Promise { (111, 'US1110000011', 'Delist Boundary Future', 'common', 'US'), (112, 'US1120000012', '100% Pure_Wild\\Co', 'common', 'US'), (113, 'US1130000013', 'Second Oldco Group', 'common', 'US'), - (114, 'CA1140000014', 'Alpha Oldco Canada', 'common', 'CA') + (114, 'US1140000014', 'Renamed Holdings Inc', 'common', 'US') `); await client.query(` @@ -118,7 +142,7 @@ async function seedFixture(pool: Pool): Promise { ) OVERRIDING SYSTEM VALUE VALUES - (101, 101, 'XNAS', 'NEWCO', '', 'USD', '2018-01-02', '2024-12-31', 'active'), + (101, 101, 'XTSE', 'ZOLD', '', 'CAD', '2020-01-01', '2024-06-28', 'active'), (102, 102, 'XNYS', 'GAPNEW', '', 'USD', '2019-01-01', '2024-12-31', 'active'), (103, 103, 'XNAS', 'FUTROOT', '', 'USD', '2020-01-01', NULL, NULL), (104, 104, 'XTSE', 'NOHIST', 'A', 'CAD', '2021-03-15', '2024-06-28', 'active'), @@ -131,14 +155,14 @@ async function seedFixture(pool: Pool): Promise { (111, 111, 'XNAS', 'DLST4', '', 'USD', '2015-01-01', '2024-09-15', 'bankruptcy_cancelled'), (112, 112, 'XNYS', 'WILD', '', 'USD', '2020-01-01', '2024-06-28', 'active'), (113, 113, 'XNAS', 'OLDCO2', '', 'USD', '2020-01-01', '2024-06-28', 'active'), - (114, 114, 'XTSE', 'ZOLD', '', 'CAD', '2020-01-01', '2024-06-28', 'active') + (114, 114, 'XNAS', 'NEWCO', '', 'USD', '2018-01-02', '2024-12-31', 'active') `); await client.query(` INSERT INTO listing_symbol_history (listing_id, ticker, valid_from, valid_to, source) VALUES - (101, 'OLDCO', '2018-01-02', '2024-06-30', 'eod'), - (101, 'NEWCO', '2024-07-01', NULL, 'eod'), + (114, 'OLDCO', '2018-01-02', '2024-06-30', 'eod'), + (114, 'NEWCO', '2024-07-01', NULL, 'eod'), (102, 'GAPOLD', '2019-01-01', '2024-05-31', 'eod'), (102, 'GAPNEW', '2024-07-01', NULL, 'eod'), (103, 'FUTROOT', '2024-07-15', NULL, 'eod'), @@ -169,6 +193,22 @@ describe('PostgreSQL symbol search safety guard', () => { assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test') ).toBe('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test'); }); + + test('preserves isolated schema search_path precedence over URL startup options', () => { + const schema = 'stock_bot_safety_fixture_options'; + const urlWithOptions = + 'postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test?options=-c%20statement_timeout%3D30000%20-c%20search_path%3Dpublic'; + const poolConfig = buildIsolatedPoolConfig(urlWithOptions, schema); + + expect(new URL(poolConfig.connectionString!).searchParams.has('options')).toBe(false); + + const client = new Client(poolConfig); + const resolvedOptions = (client as unknown as { connectionParameters: { options?: string } }) + .connectionParameters.options; + expect(resolvedOptions).toBe( + `-c statement_timeout=30000 -c search_path=public -c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000` + ); + }); }); describe.skipIf(!url)('PostgreSQL MCP symbol search adapter', () => { @@ -184,15 +224,15 @@ describe.skipIf(!url)('PostgreSQL MCP symbol search adapter', () => { vaultCutoffTs: VAULT_CUTOFF_TS, }); expect(oldcoRows.map(r => r.listingId)).toEqual([101, 113, 114]); - expect(oldcoRows[0]).toEqual({ - listingId: 101, - instrumentId: 101, + expect(oldcoRows[2]).toEqual({ + listingId: 114, + instrumentId: 114, ticker: 'OLDCO', classSuffix: null, name: 'Renamed Holdings Inc', mic: 'XNAS', currency: 'USD', - isin: 'US1010000001', + isin: 'US1140000014', firstBarDate: '2018-01-02', lastBarDate: '2024-12-31', delistedAt: null, @@ -325,7 +365,7 @@ describe.skipIf(!url)('PostgreSQL MCP symbol search adapter', () => { vaultCutoffTs: VAULT_CUTOFF_TS, }); expect(caRows.map(r => ({ id: r.listingId, mic: r.mic }))).toEqual([ - { id: 114, mic: 'XTSE' }, + { id: 101, mic: 'XTSE' }, ]); // (e) Case-insensitive exact ISIN match with partial-ISIN negative @@ -421,14 +461,15 @@ describe.skipIf(!url)('PostgreSQL MCP symbol search adapter', () => { return JSON.parse(parsed.result.content[0]!.text) as SearchSymbolsResultPayload; }; - // Ranking & truncation: exact ticker OLDCO (101) > prefix OLDCO2 (113) > name Alpha Oldco Canada (114) + // Ranking & truncation: adapter returns ascending listing_id [101 (name), 113 (prefix), 114 (exact)]; + // MCP tool must re-rank to exact ticker OLDCO (114) > prefix OLDCO2 (113) and drop name match ZOLD (101) const oldcoPayload = await callTool({ query: 'OLDCO', limit: 2 }); expect(oldcoPayload.scope).toBe('vault_fenced'); expect(oldcoPayload.vaultCutoffTs).toBe(VAULT_CUTOFF_TS); expect(oldcoPayload.truncated).toBe(true); expect(oldcoPayload.rowCount).toBe(2); expect(oldcoPayload.rows.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([ - { id: 101, ticker: 'OLDCO' }, + { id: 114, ticker: 'OLDCO' }, { id: 113, ticker: 'OLDCO2' }, ]); // Post-cutoff lastBarDate (2024-12-31) is clamped to vaultCutoffDate (2024-06-30) @@ -444,4 +485,24 @@ describe.skipIf(!url)('PostgreSQL MCP symbol search adapter', () => { expect(futureDelistPayload.rows[0]!.lastBarDate).toBe(VAULT_CUTOFF_DATE); expect(futureDelistPayload.rows[0]!.delistedAt).toBeNull(); }); + + test('isolates fixture schema even when the safety database URL includes startup options', async () => { + const parsed = new URL(assertSafetyDatabaseUrl(url)); + parsed.searchParams.set('options', '-c statement_timeout=30000 -c search_path=public'); + + const f = await createIsolatedFixture(parsed.toString()); + const { rows } = await f.pool.query<{ current_schema: string | null }>( + 'SELECT current_schema() AS current_schema' + ); + expect(rows[0]?.current_schema).toBe(f.schema); + + const port = createPostgresSymbolSearchPort({ executor: createPgExecutor(f.pool) }); + const matches = await port.searchSymbols({ + query: 'OLDCO', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(matches.map(r => r.listingId)).toEqual([101, 113, 114]); + }); }); From 15f53dba9e67af69f9e338c124efacff71e31324 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 09:02:09 -0500 Subject: [PATCH 03/21] T-158: tests --- .../test/mcp-postgres-symbol-search.test.ts | 114 +++++++++++++++--- .../mcp-symbol-search-adapter.test.ts | 91 +++++++++++++- 2 files changed, 180 insertions(+), 25 deletions(-) diff --git a/libs/research/test/mcp-postgres-symbol-search.test.ts b/libs/research/test/mcp-postgres-symbol-search.test.ts index ea9a3edd..d4fb71c5 100644 --- a/libs/research/test/mcp-postgres-symbol-search.test.ts +++ b/libs/research/test/mcp-postgres-symbol-search.test.ts @@ -1,10 +1,10 @@ import { describe, expect, test } from 'bun:test'; import { MarketDataStoreValidationError } from '../src/market-data-store'; import { + createPostgresSymbolSearchPort, PostgresSymbolSearchError, type SymbolSearchExecutor, type SymbolSearchQuery, - createPostgresSymbolSearchPort, } from '../src/mcp/index'; interface RecordedCall { @@ -70,13 +70,7 @@ describe('createPostgresSymbolSearchPort (fake executor)', () => { expect(call.text).not.toContain(';'); expect(call.text).not.toContain(injection); expect(call.text).not.toContain('DROP TABLE'); - expect(call.params).toEqual([ - '2024-06-30', - `%${injection}%`, - injection, - null, - true, - ]); + expect(call.params).toEqual(['2024-06-30', `%${injection}%`, injection, null, true]); }); test('escapes %, _, and backslash literals in the ILIKE pattern while preserving raw query for ISIN', async () => { @@ -91,13 +85,7 @@ describe('createPostgresSymbolSearchPort (fake executor)', () => { expect(fake.calls).toHaveLength(1); const call = fake.calls[0]!; expect(call.text).toContain("ESCAPE '\\'"); - expect(call.params).toEqual([ - '2024-06-30', - '%A\\%B\\_C\\\\D%', - 'A%B_C\\D', - null, - true, - ]); + expect(call.params).toEqual(['2024-06-30', '%A\\%B\\_C\\\\D%', 'A%B_C\\D', null, true]); }); test('converts vaultCutoffTs epoch-ms to UTC calendar date across midnight boundaries', async () => { @@ -173,10 +161,16 @@ describe('createPostgresSymbolSearchPort (fake executor)', () => { expect(sql).toContain('h_past.valid_from <= $1::date'); // Both fallback resolution and root ILIKE predicate are gated by NOT root_state.is_future expect(sql).toContain('WHEN NOT root_state.is_future THEN l.ticker_root'); - expect(sql).toContain("OR (NOT root_state.is_future AND l.ticker_root ILIKE $2::text ESCAPE '\\')"); + expect(sql).toContain( + "OR (NOT root_state.is_future AND l.ticker_root ILIKE $2::text ESCAPE '\\')" + ); // delisted_at derivation and $5 filter - expect(sql).toContain("WHEN l.delist_reason IS NOT NULL AND l.delist_reason <> 'active' THEN l.listed_to"); - expect(sql).toContain('($5::boolean OR delisted.delisted_at IS NULL OR delisted.delisted_at > $1::date)'); + expect(sql).toContain( + "WHEN l.delist_reason IS NOT NULL AND l.delist_reason <> 'active' THEN l.listed_to" + ); + expect(sql).toContain( + '($5::boolean OR delisted.delisted_at IS NULL OR delisted.delisted_at > $1::date)' + ); }); test('quotes optional validated schema on all security-master tables and omits prefix when unset', async () => { @@ -302,7 +296,9 @@ describe('createPostgresSymbolSearchPort (fake executor)', () => { for (const opts of invalidOptions) { let caught: unknown; try { - createPostgresSymbolSearchPort(opts as Parameters[0]); + createPostgresSymbolSearchPort( + opts as Parameters[0] + ); } catch (err) { caught = err; } @@ -411,3 +407,83 @@ describe('createPostgresSymbolSearchPort (fake executor)', () => { ); }); }); + +describe('createPostgresSymbolSearchPort (QA edge cases)', () => { + test('accepts a pg.Pool-shaped executor whose query method lives on the prototype', async () => { + class PrototypeExecutor { + readonly calls: RecordedCall[] = []; + async query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + this.calls.push({ text, params }); + return { rows: [makeRawRow()] as unknown as readonly Row[] }; + } + } + const executor = new PrototypeExecutor(); + const port = createPostgresSymbolSearchPort({ executor }); + + const rows = await port.searchSymbols(BASE_QUERY); + + expect(rows.map(r => r.listingId)).toEqual([101]); + expect(executor.calls).toHaveLength(1); + }); + + test('accepts minimal valid schema identifiers and quotes them', async () => { + for (const schema of ['_', 'a', 'stock_bot_safety_0abc']) { + const fake = createFakeExecutor([]); + const port = createPostgresSymbolSearchPort({ executor: fake.executor, schema }); + await port.searchSymbols(BASE_QUERY); + expect(fake.calls[0]!.text).toContain(`FROM "${schema}".listing l`); + } + }); + + test('propagates executor failures unchanged without retrying', async () => { + const failure = new Error('connection terminated'); + let attempts = 0; + const executor: SymbolSearchExecutor = { + async query() { + attempts += 1; + throw failure; + }, + }; + const port = createPostgresSymbolSearchPort({ executor }); + + await expect(port.searchSymbols(BASE_QUERY)).rejects.toBe(failure); + expect(attempts).toBe(1); + }); + + test('binds the UTC calendar date for an instant that is already the next day east of UTC', async () => { + const fake = createFakeExecutor([]); + const port = createPostgresSymbolSearchPort({ executor: fake.executor }); + + // 2024-02-29T23:30Z is 2024-03-01 in UTC+1 zones; the adapter must still bind the UTC date. + await port.searchSymbols({ ...BASE_QUERY, vaultCutoffTs: Date.UTC(2024, 1, 29, 23, 30) }); + + expect(fake.calls[0]!.params?.[0]).toBe('2024-02-29'); + }); + + test('returns an empty array (not null) when the executor returns no rows', async () => { + const fake = createFakeExecutor([]); + const port = createPostgresSymbolSearchPort({ executor: fake.executor }); + + expect(await port.searchSymbols(BASE_QUERY)).toEqual([]); + }); + + test('rejects the whole result when any row in a batch is malformed', async () => { + const fake = createFakeExecutor([ + makeRawRow(), + makeRawRow({ listing_id: 102, last_bar_date: '2024-04-31' }), + ]); + const port = createPostgresSymbolSearchPort({ executor: fake.executor }); + + let caught: unknown; + try { + await port.searchSymbols(BASE_QUERY); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresSymbolSearchError); + expect((caught as PostgresSymbolSearchError).code).toBe('INVALID_ROW'); + }); +}); diff --git a/test/postgres/mcp-symbol-search-adapter.test.ts b/test/postgres/mcp-symbol-search-adapter.test.ts index 6f5e253f..d0270313 100644 --- a/test/postgres/mcp-symbol-search-adapter.test.ts +++ b/test/postgres/mcp-symbol-search-adapter.test.ts @@ -4,11 +4,11 @@ import { Client, Pool, type PoolConfig } from 'pg'; import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; import { - type SearchSymbolsResultPayload, - type SymbolSearchExecutor, createMcpServer, createPostgresSymbolSearchPort, createSearchSymbolsTool, + type SearchSymbolsResultPayload, + type SymbolSearchExecutor, } from '../../libs/research/src/mcp/index'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); @@ -182,7 +182,9 @@ async function seedFixture(pool: Pool): Promise { describe('PostgreSQL symbol search safety guard', () => { test('rejects unsafe database targets before connecting', () => { - expect(() => assertSafetyDatabaseUrl(undefined)).toThrow('Dedicated stock_bot_safety database required'); + expect(() => assertSafetyDatabaseUrl(undefined)).toThrow( + 'Dedicated stock_bot_safety database required' + ); expect(() => assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/trading_bot') ).toThrow('Dedicated stock_bot_safety database required'); @@ -364,9 +366,7 @@ describe.skipIf(!url)('PostgreSQL MCP symbol search adapter', () => { includeDelisted: true, vaultCutoffTs: VAULT_CUTOFF_TS, }); - expect(caRows.map(r => ({ id: r.listingId, mic: r.mic }))).toEqual([ - { id: 101, mic: 'XTSE' }, - ]); + expect(caRows.map(r => ({ id: r.listingId, mic: r.mic }))).toEqual([{ id: 101, mic: 'XTSE' }]); // (e) Case-insensitive exact ISIN match with partial-ISIN negative const isinRows = await port.searchSymbols({ @@ -486,6 +486,85 @@ describe.skipIf(!url)('PostgreSQL MCP symbol search adapter', () => { expect(futureDelistPayload.rows[0]!.delistedAt).toBeNull(); }); + test('moves as-of resolution with the cutoff date, including a near-midnight UTC instant', async () => { + const f = await createIsolatedFixture(); + const port = createPostgresSymbolSearchPort({ executor: createPgExecutor(f.pool) }); + const search = (query: string, vaultCutoffTs: number, includeDelisted = true) => + port.searchSymbols({ query, limit: 20, includeDelisted, vaultCutoffTs }); + const lastMsOfCutoffDay = Date.UTC(2024, 5, 30, 23, 59, 59, 999); + const dayAfterCutoff = Date.UTC(2024, 6, 1, 0, 0, 0, 0); + + // Last millisecond of 2024-06-30 UTC still resolves the pre-rename ticker. + const lateOld = await search('OLDCO', lastMsOfCutoffDay); + expect(lateOld.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([ + { id: 101, ticker: 'ZOLD' }, + { id: 113, ticker: 'OLDCO2' }, + { id: 114, ticker: 'OLDCO' }, + ]); + expect(await search('NEWCO', lastMsOfCutoffDay)).toEqual([]); + + // One day later the rename, the GAPNEW start and the IPO become visible, and OLDCO no longer resolves to 114. + const nextOld = await search('OLDCO', dayAfterCutoff); + expect(nextOld.map(r => r.listingId)).toEqual([101, 113]); + const nextNew = await search('NEWCO', dayAfterCutoff); + expect(nextNew.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([ + { id: 114, ticker: 'NEWCO' }, + ]); + const nextGap = await search('GAPNEW', dayAfterCutoff); + expect(nextGap.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([ + { id: 102, ticker: 'GAPNEW' }, + ]); + expect(await search('GAPOLD', dayAfterCutoff)).toEqual([]); + expect((await search('IPO25', dayAfterCutoff)).map(r => r.listingId)).toEqual([106]); + + // A cutoff on the future delisting date makes that delisting confirmed and filterable. + const onFutureDelist = await search('Delist Boundary', Date.UTC(2024, 8, 15), false); + expect(onFutureDelist.map(r => r.listingId)).toEqual([109, 110]); + }); + + test('projects identical calendar dates regardless of the session TimeZone', async () => { + const f = await createIsolatedFixture(); + const client = await f.pool.connect(); + try { + await client.query("SET TimeZone = 'Pacific/Kiritimati'"); + const executor: SymbolSearchExecutor = { + query>(text: string, params?: readonly unknown[]) { + return client.query( + text, + params === undefined ? undefined : [...params] + ) as unknown as Promise<{ + readonly rows: readonly Row[]; + }>; + }, + }; + const port = createPostgresSymbolSearchPort({ executor }); + + const rows = await port.searchSymbols({ + query: 'Delist Boundary', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + expect( + rows.map(r => ({ + id: r.listingId, + first: r.firstBarDate, + last: r.lastBarDate, + delistedAt: r.delistedAt, + })) + ).toEqual([ + { id: 108, first: '2015-01-01', last: '2024-06-30', delistedAt: '2024-06-30' }, + { id: 109, first: '2015-01-01', last: '2024-06-28', delistedAt: null }, + { id: 110, first: '2015-01-01', last: '2024-06-28', delistedAt: null }, + { id: 111, first: '2015-01-01', last: '2024-09-15', delistedAt: '2024-09-15' }, + ]); + } finally { + await client.query('RESET TimeZone'); + client.release(); + } + }); + test('isolates fixture schema even when the safety database URL includes startup options', async () => { const parsed = new URL(assertSafetyDatabaseUrl(url)); parsed.searchParams.set('options', '-c statement_timeout=30000 -c search_path=public'); From 4f4ff8b4fb659251bc68de940a62bdc002e59b57 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 09:00:38 -0500 Subject: [PATCH 04/21] T-157: edits made in the worktree --- tools/curate-etl/src/events.rs | 4 +- tools/curate-etl/src/lib.rs | 7 + tools/curate-etl/src/parquet_posts.rs | 109 ++++ tools/curate-etl/src/parquet_posts_tests.rs | 609 ++++++++++++++++++++ tools/curate-etl/src/posts.rs | 2 + 5 files changed, 729 insertions(+), 2 deletions(-) create mode 100644 tools/curate-etl/src/parquet_posts.rs create mode 100644 tools/curate-etl/src/parquet_posts_tests.rs diff --git a/tools/curate-etl/src/events.rs b/tools/curate-etl/src/events.rs index e1f6b52b..a66653d5 100644 --- a/tools/curate-etl/src/events.rs +++ b/tools/curate-etl/src/events.rs @@ -494,7 +494,7 @@ fn sanitize_opt_f64(value: Option) -> Option { const HEX_LOWER: &[u8; 16] = b"0123456789abcdef"; -fn push_json_str(out: &mut String, s: &str) { +pub(crate) fn push_json_str(out: &mut String, s: &str) { out.push('"'); let bytes = s.as_bytes(); let mut start = 0usize; @@ -534,7 +534,7 @@ fn push_json_str(out: &mut String, s: &str) { } #[inline] -fn push_json_opt_str(out: &mut String, s: Option<&str>) { +pub(crate) fn push_json_opt_str(out: &mut String, s: Option<&str>) { match s { Some(v) => push_json_str(out, v), None => out.push_str("null"), diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 1a8ff478..3e6ac6f0 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -27,6 +27,7 @@ pub mod parquet_corporate_actions; pub mod parquet_events; pub mod parquet_fundamentals; pub mod parquet_fx; +pub mod parquet_posts; mod parquet_publish; pub mod parquet_shorts; pub mod posts; @@ -172,6 +173,10 @@ pub use parquet_fx::{ fx_1d_parquet_schema, write_fx_1d_dataset, Fx1dParquetRow, Fx1dWriteOptions, Fx1dWriteStats, ParquetFxError, }; +pub use parquet_posts::{ + posts_to_event_rows, EVENT_KIND_POST, KNOWN_AT_SOURCE_POST_EDITED, + KNOWN_AT_SOURCE_POST_TIMESTAMP, POST_SUBTYPE_NEWSWIRE, POST_SUBTYPE_RETAIL, +}; pub use parquet_shorts::{ shorts_parquet_schema, write_shorts_dataset, ParquetShortsError, ShortsParquetRow, ShortsWriteOptions, ShortsWriteStats, @@ -312,6 +317,8 @@ pub use run_mongo::{ CurateEventsMongoArgs, CurateFx1dMongoArgs, CurateShortsMongoArgs, RunMongoCurateError, }; +#[cfg(test)] +mod parquet_posts_tests; #[cfg(test)] mod posts_tests; #[cfg(test)] diff --git a/tools/curate-etl/src/parquet_posts.rs b/tools/curate-etl/src/parquet_posts.rs new file mode 100644 index 00000000..07500644 --- /dev/null +++ b/tools/curate-etl/src/parquet_posts.rs @@ -0,0 +1,109 @@ +//! Adapter mapping curated `ceoPosts` rows ([`PostRow`] / [`PostsBuild`]) into the +//! 7-column `events` Parquet contract ([`EventsParquetRow`], `events/year=YYYY/part.parquet`). +//! +//! Aligned with `design/DATA-CONTRACTS.md` §1 & §3A and `design/PLATFORM-PLAN.md`: +//! - `kind` is always [`EVENT_KIND_POST`] (`"post"`). +//! - `subtype` is [`POST_SUBTYPE_NEWSWIRE`] (`"newswire"`) when `is_bot` is `true`, and +//! [`POST_SUBTYPE_RETAIL`] (`"retail"`) otherwise, so wire releases are never pooled with crowd +//! chat. +//! - `ts` is the posting timestamp (`posted_at`) and `known_at` is the point-in-time text +//! availability timestamp (`known_at >= posted_at`). +//! - `known_at_source` is [`KNOWN_AT_SOURCE_POST_EDITED`] (`"post_edited"`) iff +//! `known_at > posted_at`, and [`KNOWN_AT_SOURCE_POST_TIMESTAMP`] (`"post_timestamp"`) otherwise +//! (including when an edit timestamp before `posted_at` was clamped back to `posted_at`). + +use std::borrow::Cow; + +use crate::events::{push_json_opt_str, push_json_str}; +use crate::parquet_events::EventsParquetRow; +use crate::posts::{PostRow, PostsBuild}; + +/// Canonical `events.kind` label for curated `ceoPosts` rows. +pub const EVENT_KIND_POST: &str = "post"; + +/// Canonical `events.subtype` label for `bot == "1"` newswire posts. +pub const POST_SUBTYPE_NEWSWIRE: &str = "newswire"; + +/// Canonical `events.subtype` label for non-bot retail posts. +pub const POST_SUBTYPE_RETAIL: &str = "retail"; + +/// Provenance label when `known_at` equals the post's creation timestamp (`posted_at`). +pub const KNOWN_AT_SOURCE_POST_TIMESTAMP: &str = "post_timestamp"; + +/// Provenance label when `known_at` reflects a post-creation edit timestamp (`known_at > posted_at`). +pub const KNOWN_AT_SOURCE_POST_EDITED: &str = "post_edited"; + +/// Encodes a curated post's `payload_json` as a compact RFC 8259 JSON object with fixed key order: +/// `{"spiel_id":...,"user_id":...,"is_edited":...,"source":...,"text":...}`. +fn encode_post_payload_json(row: &PostRow) -> String { + let cap = 72 + + row.spiel_id.len() + + row.user_id.as_deref().map_or(4, str::len) + + row.source.len() + + row.text.len(); + let mut out = String::with_capacity(cap); + out.push_str("{\"spiel_id\":"); + push_json_str(&mut out, &row.spiel_id); + out.push_str(",\"user_id\":"); + push_json_opt_str(&mut out, row.user_id.as_deref()); + out.push_str(",\"is_edited\":"); + out.push_str(if row.is_edited { "true" } else { "false" }); + out.push_str(",\"source\":"); + push_json_str(&mut out, row.source); + out.push_str(",\"text\":"); + push_json_str(&mut out, &row.text); + out.push('}'); + out +} + +impl From<&PostRow> for EventsParquetRow { + fn from(row: &PostRow) -> Self { + let known_at_source = if row.known_at > row.posted_at { + KNOWN_AT_SOURCE_POST_EDITED + } else { + KNOWN_AT_SOURCE_POST_TIMESTAMP + }; + let subtype = if row.is_bot { + POST_SUBTYPE_NEWSWIRE + } else { + POST_SUBTYPE_RETAIL + }; + + Self { + listing_id: row.key, + ts_micros: row.posted_at, + known_at_micros: row.known_at, + known_at_source: Cow::Borrowed(known_at_source), + kind: Cow::Borrowed(EVENT_KIND_POST), + subtype: subtype.to_string(), + payload_json: encode_post_payload_json(row), + } + } +} + +impl From> for EventsParquetRow { + fn from(row: PostRow) -> Self { + Self::from(&row) + } +} + +/// Converts both `newswire` and `retail` streams of a [`PostsBuild`] into +/// [`EventsParquetRow`] records sorted in the exact order required by +/// [`crate::parquet_events::write_events_dataset`]: +/// `(listing_id, ts_micros, kind, subtype, payload_json, known_at_micros, known_at_source)`. +pub fn posts_to_event_rows(build: &PostsBuild) -> Vec { + let mut rows = Vec::with_capacity(build.newswire.len() + build.retail.len()); + rows.extend(build.newswire.iter().map(EventsParquetRow::from)); + rows.extend(build.retail.iter().map(EventsParquetRow::from)); + rows.sort_unstable_by(|a, b| { + a.listing_id + .cmp(&b.listing_id) + .then_with(|| a.ts_micros.cmp(&b.ts_micros)) + .then_with(|| a.kind.as_ref().cmp(b.kind.as_ref())) + .then_with(|| a.subtype.cmp(&b.subtype)) + .then_with(|| a.payload_json.cmp(&b.payload_json)) + .then_with(|| a.known_at_micros.cmp(&b.known_at_micros)) + .then_with(|| a.known_at_source.as_ref().cmp(b.known_at_source.as_ref())) + }); + rows +} diff --git a/tools/curate-etl/src/parquet_posts_tests.rs b/tools/curate-etl/src/parquet_posts_tests.rs new file mode 100644 index 00000000..959cd89a --- /dev/null +++ b/tools/curate-etl/src/parquet_posts_tests.rs @@ -0,0 +1,609 @@ +use std::borrow::Cow; +use std::collections::HashSet; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + +use parquet::basic::Compression; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use crate::parquet_events::{write_events_dataset, EventsParquetRow, EventsWriteOptions}; +use crate::parquet_posts::{ + posts_to_event_rows, EVENT_KIND_POST, KNOWN_AT_SOURCE_POST_EDITED, + KNOWN_AT_SOURCE_POST_TIMESTAMP, POST_SUBTYPE_NEWSWIRE, POST_SUBTYPE_RETAIL, +}; +use crate::posts::{build_posts, CeoPost, POSTS_SOURCE_CEO}; +use crate::split::ymd_to_epoch_days; + +static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDirGuard { + path: PathBuf, +} + +impl TempDirGuard { + fn new(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = + std::env::temp_dir().join(format!("curate-etl-pq-posts-test-{label}-{pid}-{seq}")); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn utc_ms(year: i32, month: u32, day: u32, hour: u8, minute: u8, second: u8) -> i64 { + let epoch_day = ymd_to_epoch_days(year, month, day).expect("valid test date"); + let secs = i64::from(epoch_day) * 86_400 + + i64::from(hour) * 3_600 + + i64::from(minute) * 60 + + i64::from(second); + secs * 1_000 +} + +fn post( + listing_id: i32, + spiel_id: &str, + timestamp_ms: i64, + edited_ms: Option, + bot: Option<&str>, + user_id: Option<&str>, + text: &str, +) -> CeoPost { + CeoPost { + key: listing_id, + spiel_id: spiel_id.to_string(), + timestamp_ms, + edited_ms, + bot: bot.map(str::to_string), + user_id: user_id.map(str::to_string), + text: text.to_string(), + } +} + +/// Generates all permutations of `items` via Heap's algorithm. +fn all_permutations(items: &[T]) -> Vec> { + let mut out = Vec::new(); + let mut arr = items.to_vec(); + let n = arr.len(); + let mut c = vec![0usize; n]; + out.push(arr.clone()); + + let mut i = 0; + while i < n { + if c[i] < i { + if i % 2 == 0 { + arr.swap(0, i); + } else { + arr.swap(c[i], i); + } + out.push(arr.clone()); + c[i] += 1; + i = 0; + } else { + c[i] = 0; + i += 1; + } + } + out +} + +fn read_events_parquet_and_verify_zstd(path: &Path) -> Vec { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let meta = reader.metadata(); + let mut out = Vec::new(); + + for rg_idx in 0..meta.num_row_groups() { + let rg_meta = meta.row_group(rg_idx); + assert_eq!(rg_meta.num_columns(), 7, "expected 7 columns in events schema"); + for col_idx in 0..rg_meta.num_columns() { + let compression = rg_meta.column(col_idx).compression(); + assert!( + matches!(compression, Compression::ZSTD(_)), + "expected ZSTD compression for row_group={rg_idx} col={col_idx}, got {compression:?}" + ); + } + + let rg_rows = rg_meta.num_rows() as usize; + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + + let read_i32_col = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read i32 records"); + assert!(n > 0, "unexpected short read in INT32 column {col_idx}"); + read += n; + } + } + _ => panic!("expected INT32 column at index {col_idx}"), + } + vals + }; + + let read_i64_col = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int64ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read i64 records"); + assert!(n > 0, "unexpected short read in INT64 column {col_idx}"); + read += n; + } + } + _ => panic!("expected INT64 column at index {col_idx}"), + } + vals + }; + + let read_str_col = |col_idx: usize| -> Vec { + let mut raw = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut raw) + .expect("read byte_array records"); + assert!(n > 0, "unexpected short read in BYTE_ARRAY column {col_idx}"); + read += n; + } + } + _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), + } + raw.iter() + .map(|b| std::str::from_utf8(b.data()).expect("valid utf8").to_string()) + .collect() + }; + + let listing_ids = read_i32_col(0); + let ts = read_i64_col(1); + let known_at = read_i64_col(2); + let known_at_source = read_str_col(3); + let kind = read_str_col(4); + let subtype = read_str_col(5); + let payload_json = read_str_col(6); + + for i in 0..rg_rows { + out.push(EventsParquetRow { + listing_id: listing_ids[i], + ts_micros: ts[i], + known_at_micros: known_at[i], + known_at_source: Cow::Owned(known_at_source[i].clone()), + kind: Cow::Owned(kind[i].clone()), + subtype: subtype[i].clone(), + payload_json: payload_json[i].clone(), + }); + } + } + + out +} + +#[test] +fn maps_retail_unedited_edited_newswire_and_clamped_edit_for_borrowed_and_owned() { + let t_post = utc_ms(2024, 6, 15, 14, 30, 0); + let t_edit_later = t_post + 600_000; // +10 minutes + let t_edit_earlier = t_post - 5_000; // -5 seconds (clamped to posted_at) + + let build = build_posts(vec![ + post( + 101, + "sp_retail_unedited", + t_post, + None, + None, + Some("u_retail"), + "Retail baseline", + ), + post( + 102, + "sp_retail_edited", + t_post, + Some(t_edit_later), + Some("0"), + Some("u_editor"), + "Edited retail text", + ), + post( + 103, + "sp_newswire", + t_post, + None, + Some("1"), + Some("thenewswire"), + "Company announces drill results", + ), + post( + 104, + "sp_edit_clamped", + t_post, + Some(t_edit_earlier), + None, + None, + "Clock-skewed edit", + ), + ]) + .expect("build_posts should succeed"); + + // Verify borrowed and owned From impls agree on every row. + for row in build.newswire.iter().chain(build.retail.iter()) { + let from_ref = EventsParquetRow::from(row); + let from_owned = EventsParquetRow::from(row.clone()); + assert_eq!(from_ref, from_owned); + } + + let mapped = posts_to_event_rows(&build); + assert_eq!(mapped.len(), 4); + + // 101: retail unedited + assert_eq!( + mapped[0], + EventsParquetRow { + listing_id: 101, + ts_micros: t_post * 1_000, + known_at_micros: t_post * 1_000, + known_at_source: Cow::Borrowed(KNOWN_AT_SOURCE_POST_TIMESTAMP), + kind: Cow::Borrowed(EVENT_KIND_POST), + subtype: POST_SUBTYPE_RETAIL.to_string(), + payload_json: format!( + "{{\"spiel_id\":\"sp_retail_unedited\",\"user_id\":\"u_retail\",\"is_edited\":false,\"source\":\"{POSTS_SOURCE_CEO}\",\"text\":\"Retail baseline\"}}" + ), + } + ); + + // 102: retail edited (known_at > posted_at) + assert_eq!( + mapped[1], + EventsParquetRow { + listing_id: 102, + ts_micros: t_post * 1_000, + known_at_micros: t_edit_later * 1_000, + known_at_source: Cow::Borrowed(KNOWN_AT_SOURCE_POST_EDITED), + kind: Cow::Borrowed(EVENT_KIND_POST), + subtype: POST_SUBTYPE_RETAIL.to_string(), + payload_json: format!( + "{{\"spiel_id\":\"sp_retail_edited\",\"user_id\":\"u_editor\",\"is_edited\":true,\"source\":\"{POSTS_SOURCE_CEO}\",\"text\":\"Edited retail text\"}}" + ), + } + ); + + // 103: newswire (bot == "1") + assert_eq!( + mapped[2], + EventsParquetRow { + listing_id: 103, + ts_micros: t_post * 1_000, + known_at_micros: t_post * 1_000, + known_at_source: Cow::Borrowed(KNOWN_AT_SOURCE_POST_TIMESTAMP), + kind: Cow::Borrowed(EVENT_KIND_POST), + subtype: POST_SUBTYPE_NEWSWIRE.to_string(), + payload_json: format!( + "{{\"spiel_id\":\"sp_newswire\",\"user_id\":\"thenewswire\",\"is_edited\":false,\"source\":\"{POSTS_SOURCE_CEO}\",\"text\":\"Company announces drill results\"}}" + ), + } + ); + + // 104: edit-before-post clamped -> known_at == ts, known_at_source == "post_timestamp", + // payload preserves is_edited: true and user_id: null. + assert_eq!( + mapped[3], + EventsParquetRow { + listing_id: 104, + ts_micros: t_post * 1_000, + known_at_micros: t_post * 1_000, + known_at_source: Cow::Borrowed(KNOWN_AT_SOURCE_POST_TIMESTAMP), + kind: Cow::Borrowed(EVENT_KIND_POST), + subtype: POST_SUBTYPE_RETAIL.to_string(), + payload_json: format!( + "{{\"spiel_id\":\"sp_edit_clamped\",\"user_id\":null,\"is_edited\":true,\"source\":\"{POSTS_SOURCE_CEO}\",\"text\":\"Clock-skewed edit\"}}" + ), + } + ); +} + +#[test] +fn payload_json_escapes_special_chars_control_chars_non_ascii_and_preserves_key_order() { + let t_post = utc_ms(2024, 7, 1, 12, 0, 0); + let build = build_posts(vec![ + post( + 10, + "sp\"with\\slash", + t_post, + None, + None, + Some("user\"1"), + "Quote \"here\", backslash \\, newline\nctrl\x01, non-ASCII café €", + ), + post( + 11, + "sp_null_user", + t_post, + Some(t_post + 1_000), + Some("1"), + None, + "Simple wire text", + ), + ]) + .expect("build_posts should succeed"); + + let rows = posts_to_event_rows(&build); + assert_eq!(rows.len(), 2); + + assert_eq!( + rows[0].payload_json, + "{\"spiel_id\":\"sp\\\"with\\\\slash\",\"user_id\":\"user\\\"1\",\"is_edited\":false,\"source\":\"ceo_posts\",\"text\":\"Quote \\\"here\\\", backslash \\\\, newline\\nctrl\\u0001, non-ASCII café €\"}" + ); + + assert_eq!( + rows[1].payload_json, + "{\"spiel_id\":\"sp_null_user\",\"user_id\":null,\"is_edited\":true,\"source\":\"ceo_posts\",\"text\":\"Simple wire text\"}" + ); +} + +#[test] +fn round_trip_writes_two_years_via_events_writer_with_zstd_and_exact_readback() { + let dir = TempDirGuard::new("round-trip"); + let t_2024_a = utc_ms(2024, 5, 10, 15, 0, 0); + let t_2024_dec = utc_ms(2024, 12, 31, 23, 55, 0); + let t_2025_jan_edit = utc_ms(2025, 1, 1, 0, 15, 0); // edited across UTC year boundary + let t_2025_feb = utc_ms(2025, 2, 20, 13, 30, 0); + + let build = build_posts(vec![ + // Two distinct posts sharing the exact same (listing_id=200, ts=t_2024_a), one newswire and one retail. + post( + 200, + "sp_2024_wire", + t_2024_a, + None, + Some("1"), + Some("thenewswire"), + "Newswire release at identical ts", + ), + post( + 200, + "sp_2024_retail_1", + t_2024_a, + None, + None, + Some("u1"), + "Retail reply 1 at identical ts", + ), + post( + 200, + "sp_2024_retail_2", + t_2024_a, + None, + None, + Some("u2"), + "Retail reply 2 at identical ts", + ), + // December 2024 post edited in January 2025: partitions by ts -> year=2024, known_at in 2025. + post( + 201, + "sp_2024_dec_edited_2025", + t_2024_dec, + Some(t_2025_jan_edit), + None, + Some("u3"), + "Edited after New Year", + ), + // 2025 newswire and retail posts. + post( + 200, + "sp_2025_wire", + t_2025_feb, + None, + Some("1"), + Some("thenewswire"), + "2025 quarterly update", + ), + post( + 202, + "sp_2025_retail", + t_2025_feb, + None, + Some("0"), + None, + "2025 retail commentary", + ), + ]) + .expect("build_posts should succeed"); + + let event_rows = posts_to_event_rows(&build); + assert_eq!(event_rows.len(), 6); + + let stats = write_events_dataset(dir.path(), &event_rows, EventsWriteOptions::default()) + .expect("write_events_dataset should accept posts_to_event_rows output"); + assert_eq!(stats.rows_written, 6); + assert_eq!(stats.files_written, 2); + assert_eq!(stats.rows_by_year.get(&2024), Some(&4)); + assert_eq!(stats.rows_by_year.get(&2025), Some(&2)); + + let path_2024 = dir.path().join("events/year=2024/part.parquet"); + let path_2025 = dir.path().join("events/year=2025/part.parquet"); + assert!(path_2024.exists(), "expected {}", path_2024.display()); + assert!(path_2025.exists(), "expected {}", path_2025.display()); + + let read_2024 = read_events_parquet_and_verify_zstd(&path_2024); + let read_2025 = read_events_parquet_and_verify_zstd(&path_2025); + + let expected_2024: Vec = event_rows + .iter() + .filter(|r| crate::events::partition_year_utc(r.ts_micros) == 2024) + .cloned() + .collect(); + let expected_2025: Vec = event_rows + .iter() + .filter(|r| crate::events::partition_year_utc(r.ts_micros) == 2025) + .cloned() + .collect(); + + assert_eq!(read_2024, expected_2024); + assert_eq!(read_2025, expected_2025); + + // Verify all read-back rows have kind == "post", both subtypes are present, and newswire vs + // retail spiel_ids are strictly disjoint (never sharing a subtype). + let mut newswire_payloads = HashSet::new(); + let mut retail_payloads = HashSet::new(); + for row in read_2024.iter().chain(read_2025.iter()) { + assert_eq!(row.kind.as_ref(), EVENT_KIND_POST); + match row.subtype.as_str() { + POST_SUBTYPE_NEWSWIRE => { + assert!(newswire_payloads.insert(row.payload_json.clone())); + } + POST_SUBTYPE_RETAIL => { + assert!(retail_payloads.insert(row.payload_json.clone())); + } + other => panic!("unexpected post subtype: {other}"), + } + } + assert_eq!(newswire_payloads.len(), 2); + assert_eq!(retail_payloads.len(), 4); + assert!(newswire_payloads.is_disjoint(&retail_payloads)); + + // Confirm the Dec 2024 post edited in Jan 2025 landed in year=2024 with 2025 known_at. + let dec_row = read_2024 + .iter() + .find(|r| r.listing_id == 201) + .expect("December post must be in year=2024 partition"); + assert_eq!(dec_row.ts_micros, t_2024_dec * 1_000); + assert_eq!(dec_row.known_at_micros, t_2025_jan_edit * 1_000); + assert_eq!(dec_row.known_at_source.as_ref(), KNOWN_AT_SOURCE_POST_EDITED); +} + +#[test] +fn posts_to_event_rows_is_permutation_invariant_and_handles_empty_input() { + let empty_build = build_posts(Vec::>::new()).expect("empty build"); + assert!(posts_to_event_rows(&empty_build).is_empty()); + + let t0 = utc_ms(2024, 9, 1, 14, 0, 0); + let t1 = t0 + 30_000; + let fixture = vec![ + // Conflicting duplicate spiel_id: later edit wins regardless of input order. + post(50, "sp_dup", t0, None, None, Some("u1"), "Original text"), + post( + 50, + "sp_dup", + t0, + Some(t1), + None, + Some("u1"), + "Edited duplicate survivor", + ), + // Two distinct posts sharing (listing_id=50, ts=t0), one newswire and one retail. + post( + 50, + "sp_same_ts_wire", + t0, + None, + Some("1"), + Some("thenewswire"), + "Wire at t0", + ), + post( + 50, + "sp_same_ts_retail", + t0, + None, + None, + Some("u2"), + "Retail at t0", + ), + // Separate listing. + post(40, "sp_other_listing", t1, None, None, None, "Earlier listing"), + ]; + + let reference = + posts_to_event_rows(&build_posts(fixture.clone()).expect("reference build")); + assert_eq!(reference.len(), 4); + let reference_payload_bytes: Vec<&[u8]> = reference + .iter() + .map(|r| r.payload_json.as_bytes()) + .collect(); + + let perms = all_permutations(&fixture); + assert_eq!(perms.len(), 120); + for perm in perms { + let got = posts_to_event_rows(&build_posts(perm).expect("permuted build")); + assert_eq!(got, reference); + let got_payload_bytes: Vec<&[u8]> = + got.iter().map(|r| r.payload_json.as_bytes()).collect(); + assert_eq!(got_payload_bytes, reference_payload_bytes); + } +} + +#[test] +fn point_in_time_guard_excludes_edited_post_until_edit_timestamp() { + let t_post = utc_ms(2024, 8, 12, 13, 30, 0); + let t_edit = t_post + 900_000; // +15 minutes + + let build = build_posts(vec![ + post( + 300, + "sp_unedited", + t_post, + None, + None, + Some("u1"), + "Posted at open", + ), + post( + 300, + "sp_edited", + t_post, + Some(t_edit), + None, + Some("u2"), + "Edited 15m later with hindsight", + ), + ]) + .expect("build_posts should succeed"); + + let rows = posts_to_event_rows(&build); + let edited = rows + .iter() + .find(|r| r.payload_json.contains("\"sp_edited\"")) + .expect("edited row present"); + + assert_eq!(edited.ts_micros, t_post * 1_000); + assert_eq!(edited.known_at_micros, t_edit * 1_000); + assert_ne!(edited.known_at_micros, edited.ts_micros); + assert_eq!(edited.known_at_source.as_ref(), KNOWN_AT_SOURCE_POST_EDITED); + + // As-of cutoff between posting and editing must exclude the edited post. + let cutoff_between = (t_post + 300_000) * 1_000; + let visible_between: Vec<&EventsParquetRow> = rows + .iter() + .filter(|r| r.known_at_micros <= cutoff_between) + .collect(); + assert_eq!(visible_between.len(), 1); + assert!(visible_between[0].payload_json.contains("\"sp_unedited\"")); + + // As-of cutoff at the exact edit timestamp includes both. + let visible_at_edit: Vec<&EventsParquetRow> = rows + .iter() + .filter(|r| r.known_at_micros <= t_edit * 1_000) + .collect(); + assert_eq!(visible_at_edit.len(), 2); +} diff --git a/tools/curate-etl/src/posts.rs b/tools/curate-etl/src/posts.rs index 3769fcf8..a4af96cb 100644 --- a/tools/curate-etl/src/posts.rs +++ b/tools/curate-etl/src/posts.rs @@ -10,6 +10,8 @@ //! never `posted_at`. In `ceoPosts`, an edit overwrites `spiel` in place without version //! history, so the builder retains one supplied version per `spiel_id` and cannot recover //! earlier pre-edit text. +//! - See [`crate::parquet_posts`] for mapping [`PostRow`] / [`PostsBuild`] into the +//! `events` Parquet contract (`kind = "post"`, `subtype = "newswire" | "retail"`). use std::error::Error; use std::fmt; From 75a7c16e324351174cf66d0b21eeb3943401988f Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 09:14:56 -0500 Subject: [PATCH 05/21] T-157: tests --- tools/curate-etl/src/parquet_posts_tests.rs | 225 +++++++++++++++++++- 1 file changed, 216 insertions(+), 9 deletions(-) diff --git a/tools/curate-etl/src/parquet_posts_tests.rs b/tools/curate-etl/src/parquet_posts_tests.rs index 959cd89a..69812e00 100644 --- a/tools/curate-etl/src/parquet_posts_tests.rs +++ b/tools/curate-etl/src/parquet_posts_tests.rs @@ -108,7 +108,11 @@ fn read_events_parquet_and_verify_zstd(path: &Path) -> Vec { for rg_idx in 0..meta.num_row_groups() { let rg_meta = meta.row_group(rg_idx); - assert_eq!(rg_meta.num_columns(), 7, "expected 7 columns in events schema"); + assert_eq!( + rg_meta.num_columns(), + 7, + "expected 7 columns in events schema" + ); for col_idx in 0..rg_meta.num_columns() { let compression = rg_meta.column(col_idx).compression(); assert!( @@ -165,14 +169,21 @@ fn read_events_parquet_and_verify_zstd(path: &Path) -> Vec { let (n, _, _) = typed .read_records(rg_rows - read, None, None, &mut raw) .expect("read byte_array records"); - assert!(n > 0, "unexpected short read in BYTE_ARRAY column {col_idx}"); + assert!( + n > 0, + "unexpected short read in BYTE_ARRAY column {col_idx}" + ); read += n; } } _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), } raw.iter() - .map(|b| std::str::from_utf8(b.data()).expect("valid utf8").to_string()) + .map(|b| { + std::str::from_utf8(b.data()) + .expect("valid utf8") + .to_string() + }) .collect() }; @@ -489,7 +500,10 @@ fn round_trip_writes_two_years_via_events_writer_with_zstd_and_exact_readback() .expect("December post must be in year=2024 partition"); assert_eq!(dec_row.ts_micros, t_2024_dec * 1_000); assert_eq!(dec_row.known_at_micros, t_2025_jan_edit * 1_000); - assert_eq!(dec_row.known_at_source.as_ref(), KNOWN_AT_SOURCE_POST_EDITED); + assert_eq!( + dec_row.known_at_source.as_ref(), + KNOWN_AT_SOURCE_POST_EDITED + ); } #[test] @@ -531,11 +545,18 @@ fn posts_to_event_rows_is_permutation_invariant_and_handles_empty_input() { "Retail at t0", ), // Separate listing. - post(40, "sp_other_listing", t1, None, None, None, "Earlier listing"), + post( + 40, + "sp_other_listing", + t1, + None, + None, + None, + "Earlier listing", + ), ]; - let reference = - posts_to_event_rows(&build_posts(fixture.clone()).expect("reference build")); + let reference = posts_to_event_rows(&build_posts(fixture.clone()).expect("reference build")); assert_eq!(reference.len(), 4); let reference_payload_bytes: Vec<&[u8]> = reference .iter() @@ -547,8 +568,7 @@ fn posts_to_event_rows_is_permutation_invariant_and_handles_empty_input() { for perm in perms { let got = posts_to_event_rows(&build_posts(perm).expect("permuted build")); assert_eq!(got, reference); - let got_payload_bytes: Vec<&[u8]> = - got.iter().map(|r| r.payload_json.as_bytes()).collect(); + let got_payload_bytes: Vec<&[u8]> = got.iter().map(|r| r.payload_json.as_bytes()).collect(); assert_eq!(got_payload_bytes, reference_payload_bytes); } } @@ -607,3 +627,190 @@ fn point_in_time_guard_excludes_edited_post_until_edit_timestamp() { .collect(); assert_eq!(visible_at_edit.len(), 2); } + +// --------------------------------------------------------------------------------------------- +// QA edge cases (T-157) +// --------------------------------------------------------------------------------------------- + +#[test] +fn same_listing_and_ts_rows_are_ordered_by_payload_not_builder_known_at_order() { + // `build_posts` orders by (key, known_at, spiel_id), so the later-edited `retail_1` comes + // after `retail_2`. The writer orders by payload before known_at, so the adapter must flip it. + let dir = TempDirGuard::new("payload-tiebreak"); + let t_post = utc_ms(2024, 3, 4, 15, 0, 0); + let build = build_posts(vec![ + post( + 7, + "sp_retail_1", + t_post, + Some(t_post + 120_000), + None, + Some("u1"), + "first by payload, edited later", + ), + post( + 7, + "sp_retail_2", + t_post, + None, + None, + Some("u2"), + "second by payload", + ), + ]) + .expect("build_posts"); + assert_eq!( + build.retail[0].spiel_id, "sp_retail_2", + "builder sorts by known_at first" + ); + + let rows = posts_to_event_rows(&build); + assert!(rows[0].payload_json.contains("\"sp_retail_1\"")); + assert!(rows[1].payload_json.contains("\"sp_retail_2\"")); + assert_eq!(rows[0].known_at_micros, (t_post + 120_000) * 1_000); + assert_eq!( + rows[0].known_at_source.as_ref(), + KNOWN_AT_SOURCE_POST_EDITED + ); + + write_events_dataset(dir.path(), &rows, EventsWriteOptions::default()) + .expect("writer accepts payload-ordered rows"); + let back = + read_events_parquet_and_verify_zstd(&dir.path().join("events/year=2024/part.parquet")); + assert_eq!(back, rows); +} + +#[test] +fn rows_are_reordered_by_ts_when_an_earlier_post_was_edited_after_a_later_post() { + // Builder order is by known_at; the writer needs ts order within a listing. + let dir = TempDirGuard::new("ts-reorder"); + let t1 = utc_ms(2023, 11, 1, 10, 0, 0); + let t2 = utc_ms(2023, 11, 1, 11, 0, 0); + let t1_edit = utc_ms(2023, 11, 2, 9, 0, 0); + let build = build_posts(vec![ + post(5, "sp_late", t2, None, Some("1"), None, "later wire"), + post( + 5, + "sp_early_edited", + t1, + Some(t1_edit), + None, + Some("u"), + "early, edited next day", + ), + post(4, "sp_other", t2, None, None, None, "lower listing"), + ]) + .expect("build_posts"); + + let rows = posts_to_event_rows(&build); + let order: Vec<(i32, i64)> = rows.iter().map(|r| (r.listing_id, r.ts_micros)).collect(); + assert_eq!( + order, + vec![(4, t2 * 1_000), (5, t1 * 1_000), (5, t2 * 1_000)] + ); + + let stats = write_events_dataset(dir.path(), &rows, EventsWriteOptions::default()) + .expect("writer accepts ts-ordered rows"); + assert_eq!(stats.rows_written, 3); +} + +#[test] +fn newswire_requires_trimmed_bot_one_and_everything_else_is_retail() { + let t = utc_ms(2024, 1, 2, 12, 0, 0); + let build = build_posts(vec![ + post(1, "sp_ws", t, None, Some(" 1 "), None, "wire padded"), + post(1, "sp_true", t, None, Some("true"), None, "not wire"), + post(1, "sp_empty", t, None, Some(""), None, "not wire"), + post(1, "sp_two", t, None, Some("2"), None, "not wire"), + ]) + .expect("build_posts"); + + let rows = posts_to_event_rows(&build); + assert_eq!(rows.len(), 4); + for row in &rows { + assert_eq!(row.kind.as_ref(), EVENT_KIND_POST); + let expected = if row.payload_json.contains("\"sp_ws\"") { + POST_SUBTYPE_NEWSWIRE + } else { + POST_SUBTYPE_RETAIL + }; + assert_eq!(row.subtype, expected, "payload={}", row.payload_json); + } +} + +#[test] +fn edit_exactly_at_posting_time_is_post_timestamp_and_keeps_is_edited() { + let t = utc_ms(2024, 2, 29, 23, 59, 59); + let build = build_posts(vec![post(9, "sp_same", t, Some(t), None, None, "x")]).expect("build"); + let row = EventsParquetRow::from(&build.retail[0]); + assert_eq!(row.known_at_micros, row.ts_micros); + assert_eq!(row.known_at_source.as_ref(), KNOWN_AT_SOURCE_POST_TIMESTAMP); + assert!(row.payload_json.contains("\"is_edited\":true")); +} + +#[test] +fn multiple_row_groups_round_trip_and_rewrite_is_byte_identical() { + let t0 = utc_ms(2022, 6, 1, 0, 0, 0); + let fixture: Vec> = (0..11) + .map(|i| { + post( + i % 3, + &format!("sp_{i:02}"), + t0 + i64::from(i) * 60_000, + if i % 4 == 0 { + Some(t0 + 86_400_000) + } else { + None + }, + if i % 2 == 0 { Some("1") } else { None }, + Some("u"), + "row-group text", + ) + }) + .collect(); + let rows = posts_to_event_rows(&build_posts(fixture).expect("build")); + let options = EventsWriteOptions { + row_group_rows: 3, + ..EventsWriteOptions::default() + }; + + let dir_a = TempDirGuard::new("rg-a"); + let dir_b = TempDirGuard::new("rg-b"); + write_events_dataset(dir_a.path(), &rows, options).expect("write a"); + write_events_dataset(dir_b.path(), &rows, options).expect("write b"); + + let path_a = dir_a.path().join("events/year=2022/part.parquet"); + let path_b = dir_b.path().join("events/year=2022/part.parquet"); + let reader = SerializedFileReader::new(File::open(&path_a).expect("open")).expect("reader"); + assert_eq!(reader.metadata().num_row_groups(), 4); + drop(reader); + + assert_eq!(read_events_parquet_and_verify_zstd(&path_a), rows); + assert_eq!( + fs::read(&path_a).expect("read a"), + fs::read(&path_b).expect("read b"), + "same posts must produce byte-identical Parquet" + ); +} + +#[test] +fn post_2200_timestamp_is_preserved_by_adapter_and_rejected_by_writer() { + let dir = TempDirGuard::new("year-range"); + // `build_posts` rejects `timestamp_ms <= 0`, so the reachable out-of-range side is > 2200. + let t = utc_ms(2201, 1, 1, 12, 0, 0); + let rows = posts_to_event_rows( + &build_posts(vec![post(1, "sp_old", t, None, None, None, "old")]).expect("build"), + ); + assert_eq!(rows[0].ts_micros, t * 1_000); + + let err = write_events_dataset(dir.path(), &rows, EventsWriteOptions::default()) + .expect_err("writer must reject year 2201"); + assert!( + matches!( + err, + crate::parquet_events::ParquetEventsError::PartitionYearOutOfRange { year: 2201, .. } + ), + "got {err:?}" + ); + assert!(!dir.path().join("events/year=2201").exists()); +} From 061d593085567cfdf73799ac8bb7730bdeada9eb Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 09:28:42 -0500 Subject: [PATCH 06/21] =?UTF-8?q?T-160:=20M2.2g=20=E2=80=94=20`tools/curat?= =?UTF-8?q?e-etl`:=20zero-copy=20raw=20BSON=20decoder=20for=20MongoDB=20`c?= =?UTF-8?q?eoPosts`=20(`bson=5Fceo=5Fposts.rs`=20=E2=86=92=20`CeoPost<&str?= =?UTF-8?q?>`,=20explicit=20timestamp=20unit,=20fail-closed=20`edited`=20h?= =?UTF-8?q?andling)=20with=20tests=20(no=20new=20crates,=20no=20CLI/bench?= =?UTF-8?q?=20changes,=20no=20live=20Mongo)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/src/bson_ceo_posts.rs | 860 ++++++++++++++ tools/curate-etl/src/bson_ceo_posts_tests.rs | 1070 ++++++++++++++++++ tools/curate-etl/src/lib.rs | 5 + 3 files changed, 1935 insertions(+) create mode 100644 tools/curate-etl/src/bson_ceo_posts.rs create mode 100644 tools/curate-etl/src/bson_ceo_posts_tests.rs diff --git a/tools/curate-etl/src/bson_ceo_posts.rs b/tools/curate-etl/src/bson_ceo_posts.rs new file mode 100644 index 00000000..046ec0f9 --- /dev/null +++ b/tools/curate-etl/src/bson_ceo_posts.rs @@ -0,0 +1,860 @@ +//! Zero-copy raw BSON decoder for MongoDB `ceoPosts` documents (`M2.2g`). +//! +//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` without +//! allocating a `bson::Document`, emitting [`CeoPost<&str>`] rows (borrowing `key` directly from +//! the input buffer and allocating owned `String`s only for rows that will be emitted) via a +//! caller-supplied callback. +//! +//! # Unverified Live Schema & Explicit Timestamp Unit +//! +//! `apps/stock/data-ingestion/src/handlers/ceo/actions/get-posts.action.ts` establishes the +//! default stored field names (`ceoId`, `spielId`, `timestamp`, `edited`, `bot`, `userId`, +//! `spiel`), but the live MongoDB BSON types and whether `timestamp` / `edited` are stored in +//! epoch seconds or epoch milliseconds are **not verified** in the repository. Callers must +//! therefore supply [`CeoPostsTimestampUnit`] explicitly (there is intentionally no default). +//! +//! # Decoding & Validation Rules +//! - Every element and nested subdocument/array/JS-with-scope (up to depth `128`) of each +//! [`RawDocument`] is scanned and structurally validated to completion before applying semantic +//! skip rules, so structural BSON corruption always returns +//! `Err(BsonCeoPostsError::CorruptBson)` rather than being masked by an earlier semantic skip. +//! - `key` (`ceoId`): required non-blank UTF-8 BSON `String`, passed through verbatim (no +//! trimming). Missing, wrong type, or empty/whitespace-only strings skip the row under +//! `skipped_missing_key`, `skipped_wrong_key_type`, or `skipped_empty_key`. +//! - `spiel_id` (`spielId`): required UTF-8 BSON `String` (verbatim, non-blank) or `Int32` / +//! `Int64` rendered as decimal. Missing, wrong type, or empty/whitespace-only strings skip the +//! row under `skipped_missing_spiel_id`, `skipped_wrong_spiel_id_type`, or +//! `skipped_empty_spiel_id`. +//! - `timestamp` (`timestamp`): required `Int32`, `Int64`, finite integral `Double` in the +//! half-open `[-2^63, 2^63)` range, or BSON `DateTime` (already epoch milliseconds; unit +//! ignored). Under [`CeoPostsTimestampUnit::Seconds`], numeric values are multiplied by `1_000` +//! using `checked_mul`; overflow or out-of-range doubles skip under +//! `skipped_timestamp_out_of_range`. Non-finite or fractional doubles skip under +//! `skipped_invalid_timestamp`. Missing or other BSON types skip under +//! `skipped_missing_timestamp` or `skipped_wrong_timestamp_type`. Values `<= 0` are passed +//! through so [`crate::posts::build_posts`] remains the single place rejecting non-positive +//! creation timestamps. +//! - `edited` (`edited`, **point-in-time guard, fail closed**): +//! - Absent or BSON `Null` yields `edited_ms = None`. +//! - Numeric `0` (`Int32(0)`, `Int64(0)`, `Double(0.0)`, `Double(-0.0)`) or `Boolean(false)` +//! yields `edited_ms = None` and increments `edited_zero_or_false` (on emitted rows). +//! - Positive integral numeric values (`Int32`, `Int64`, finite integral `Double` in +//! `[-2^63, 2^63)`) converted with `unit` (checked multiply for seconds), or non-negative BSON +//! `DateTime` (including epoch-zero `DateTime(0)` -> `Some(0)` because the zero sentinel is +//! numeric), yield `edited_ms = Some(ms)`. +//! - Anything else — negative values, fractional or non-finite doubles, `Boolean(true)`, +//! `String`, other BSON types, seconds overflow, or repeated `edited` fields in the same +//! document — skips the row under `skipped_invalid_edited`. A row with a present but +//! unreadable `edited` field is never emitted as unedited. +//! - `text` (`spiel`): UTF-8 BSON `String` (verbatim); absent or BSON `Null` emits `String::new()` +//! and increments `empty_text` (on emitted rows); any other BSON type skips under +//! `skipped_wrong_text_type`. +//! - `bot` (`bot`): normalized only for emitted rows. UTF-8 `String` (verbatim), `Int32`/`Int64` +//! rendered as decimal, `Boolean` mapped to `"1"` / `"0"`, absent or `Null` -> `None`; any +//! other BSON type -> `None` and increments `nulled_wrong_type_bot`. +//! - `user_id` (`userId`): normalized only for emitted rows. UTF-8 `String` (verbatim), +//! `Int32`/`Int64` rendered as decimal, absent or `Null` -> `None`; any other BSON type -> +//! `None` and increments `nulled_wrong_type_user_id`. +//! - Deterministic semantic skip priority: `key` → `spiel_id` → `timestamp` → `edited` → `text`. +//! - Emitted-row counters (`edited_zero_or_false`, `nulled_wrong_type_bot`, +//! `nulled_wrong_type_user_id`, `empty_text`) are incremented only on rows that pass all skip +//! checks and are emitted to `on_row`. +//! - Conservation invariant: `docs_in == rows_out + skipped_total()`. + +use std::error::Error; +use std::fmt; + +use bson::raw::{RawBsonRef, RawDocument}; + +use crate::bson_eod_prices::{iter_raw_bson_docs, parse_single_raw_doc, BsonEodPriceError}; +use crate::posts::CeoPost; + +/// Default BSON field name for the `ceoPosts` channel / security key (`get-posts.action.ts`). +pub const DEFAULT_KEY_FIELD: &str = "ceoId"; +/// Default BSON field name for the `ceoPosts` post identifier (`get-posts.action.ts`). +pub const DEFAULT_SPIEL_ID_FIELD: &str = "spielId"; +/// Default BSON field name for the `ceoPosts` creation timestamp (`get-posts.action.ts`). +pub const DEFAULT_TIMESTAMP_FIELD: &str = "timestamp"; +/// Default BSON field name for the `ceoPosts` last-edit timestamp (`get-posts.action.ts`). +pub const DEFAULT_EDITED_FIELD: &str = "edited"; +/// Default BSON field name for the `ceoPosts` bot/newswire flag (`get-posts.action.ts`). +pub const DEFAULT_BOT_FIELD: &str = "bot"; +/// Default BSON field name for the `ceoPosts` author identifier (`get-posts.action.ts`). +pub const DEFAULT_USER_ID_FIELD: &str = "userId"; +/// Default BSON field name for the `ceoPosts` post body (`get-posts.action.ts`). +pub const DEFAULT_TEXT_FIELD: &str = "spiel"; + +/// Explicit numeric timestamp unit for `ceoPosts` `timestamp` and `edited` fields. +/// +/// Intentionally has no `Default`: the live MongoDB unit is unverified in the repository, so +/// callers must choose explicitly. BSON `DateTime` values are always epoch milliseconds and ignore +/// this setting. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CeoPostsTimestampUnit { + /// Numeric `timestamp` / `edited` values are Unix epoch seconds (multiplied by `1_000`). + Seconds, + /// Numeric `timestamp` / `edited` values are Unix epoch milliseconds. + Millis, +} + +/// Borrowed BSON field-name configuration for decoding `ceoPosts` documents. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CeoPostsFieldNames<'a> { + pub key: &'a str, + pub spiel_id: &'a str, + pub timestamp: &'a str, + pub edited: &'a str, + pub bot: &'a str, + pub user_id: &'a str, + pub text: &'a str, +} + +impl Default for CeoPostsFieldNames<'static> { + fn default() -> Self { + Self { + key: DEFAULT_KEY_FIELD, + spiel_id: DEFAULT_SPIEL_ID_FIELD, + timestamp: DEFAULT_TIMESTAMP_FIELD, + edited: DEFAULT_EDITED_FIELD, + bot: DEFAULT_BOT_FIELD, + user_id: DEFAULT_USER_ID_FIELD, + text: DEFAULT_TEXT_FIELD, + } + } +} + +impl<'a> CeoPostsFieldNames<'a> { + /// Validates that every configured field name is non-empty/non-blank and that no two + /// configured roles point to the same BSON field name. + pub fn validate(&self) -> Result<(), BsonCeoPostsError> { + let roles: [(&'static str, &str); 7] = [ + ("key", self.key), + ("spiel_id", self.spiel_id), + ("timestamp", self.timestamp), + ("edited", self.edited), + ("bot", self.bot), + ("user_id", self.user_id), + ("text", self.text), + ]; + + for &(role, name) in &roles { + if name.trim().is_empty() { + return Err(BsonCeoPostsError::InvalidFieldNames { + detail: format!("field name for '{role}' must not be empty or blank"), + }); + } + } + + for i in 0..roles.len() { + let (role_a, name_a) = roles[i]; + for &(role_b, name_b) in &roles[i + 1..] { + if name_a == name_b { + return Err(BsonCeoPostsError::InvalidFieldNames { + detail: format!( + "roles '{role_a}' and '{role_b}' cannot share BSON field '{name_a}'" + ), + }); + } + } + } + + Ok(()) + } +} + +/// Typed errors returned while validating field configuration or decoding raw `ceoPosts` BSON. +/// +/// Structural BSON framing or element errors fail closed and carry a `u64` byte offset; +/// every variant's `Display` output is a single line. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum BsonCeoPostsError { + /// Invalid [`CeoPostsFieldNames`] configuration (empty/blank name or duplicate role mapping). + InvalidFieldNames { detail: String }, + /// Buffer ended before a complete 4-byte length prefix or declared document body. + TruncatedDocument { + offset: u64, + remaining: usize, + declared_len: Option, + }, + /// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single + /// document slice). + CorruptDocumentLength { offset: u64, declared_len: i32 }, + /// Underlying BSON framing or element bytes were malformed. + CorruptBson { offset: u64, detail: String }, +} + +impl fmt::Display for BsonCeoPostsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidFieldNames { detail } => { + write!(f, "invalid ceoPosts field configuration: {detail}") + } + Self::TruncatedDocument { + offset, + remaining, + declared_len, + } => match declared_len { + Some(len) => write!( + f, + "truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes" + ), + None => write!( + f, + "truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining" + ), + }, + Self::CorruptDocumentLength { + offset, + declared_len, + } => write!( + f, + "corrupt BSON document length {declared_len} at byte offset {offset}" + ), + Self::CorruptBson { offset, detail } => { + write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}") + } + } + } +} + +impl Error for BsonCeoPostsError {} + +#[inline] +fn map_framing_error(err: BsonEodPriceError) -> BsonCeoPostsError { + match err { + BsonEodPriceError::TruncatedDocument { + offset, + remaining, + declared_len, + } => BsonCeoPostsError::TruncatedDocument { + offset: offset as u64, + remaining, + declared_len, + }, + BsonEodPriceError::CorruptDocumentLength { + offset, + declared_len, + } => BsonCeoPostsError::CorruptDocumentLength { + offset: offset as u64, + declared_len, + }, + BsonEodPriceError::CorruptBson { offset, detail } => BsonCeoPostsError::CorruptBson { + offset: offset as u64, + detail, + }, + other => BsonCeoPostsError::CorruptBson { + offset: 0, + detail: other.to_string(), + }, + } +} + +/// Per-batch decode accounting for `ceoPosts`. +/// +/// Conservation invariant: +/// `docs_in == rows_out + skipped_total()` +/// +/// Emitted-row counters (`edited_zero_or_false`, `nulled_wrong_type_bot`, +/// `nulled_wrong_type_user_id`, `empty_text`) are incremented only for emitted rows and are +/// excluded from [`Self::skipped_total`]. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BsonCeoPostsDecodeStats { + pub docs_in: usize, + pub rows_out: usize, + pub skipped_missing_key: usize, + pub skipped_wrong_key_type: usize, + pub skipped_empty_key: usize, + pub skipped_missing_spiel_id: usize, + pub skipped_wrong_spiel_id_type: usize, + pub skipped_empty_spiel_id: usize, + pub skipped_missing_timestamp: usize, + pub skipped_wrong_timestamp_type: usize, + pub skipped_invalid_timestamp: usize, + pub skipped_timestamp_out_of_range: usize, + pub skipped_invalid_edited: usize, + pub skipped_wrong_text_type: usize, + pub edited_zero_or_false: usize, + pub nulled_wrong_type_bot: usize, + pub nulled_wrong_type_user_id: usize, + pub empty_text: usize, +} + +impl BsonCeoPostsDecodeStats { + /// Total number of semantically skipped documents across all skip categories. + #[inline] + pub fn skipped_total(&self) -> usize { + self.skipped_missing_key + + self.skipped_wrong_key_type + + self.skipped_empty_key + + self.skipped_missing_spiel_id + + self.skipped_wrong_spiel_id_type + + self.skipped_empty_spiel_id + + self.skipped_missing_timestamp + + self.skipped_wrong_timestamp_type + + self.skipped_invalid_timestamp + + self.skipped_timestamp_out_of_range + + self.skipped_invalid_edited + + self.skipped_wrong_text_type + } + + /// Accumulates counters from another batch into `self`. + #[inline] + pub fn merge(&mut self, other: &Self) { + self.docs_in += other.docs_in; + self.rows_out += other.rows_out; + self.skipped_missing_key += other.skipped_missing_key; + self.skipped_wrong_key_type += other.skipped_wrong_key_type; + self.skipped_empty_key += other.skipped_empty_key; + self.skipped_missing_spiel_id += other.skipped_missing_spiel_id; + self.skipped_wrong_spiel_id_type += other.skipped_wrong_spiel_id_type; + self.skipped_empty_spiel_id += other.skipped_empty_spiel_id; + self.skipped_missing_timestamp += other.skipped_missing_timestamp; + self.skipped_wrong_timestamp_type += other.skipped_wrong_timestamp_type; + self.skipped_invalid_timestamp += other.skipped_invalid_timestamp; + self.skipped_timestamp_out_of_range += other.skipped_timestamp_out_of_range; + self.skipped_invalid_edited += other.skipped_invalid_edited; + self.skipped_wrong_text_type += other.skipped_wrong_text_type; + self.edited_zero_or_false += other.edited_zero_or_false; + self.nulled_wrong_type_bot += other.nulled_wrong_type_bot; + self.nulled_wrong_type_user_id += other.nulled_wrong_type_user_id; + self.empty_text += other.empty_text; + } +} + +impl std::ops::AddAssign for BsonCeoPostsDecodeStats { + #[inline] + fn add_assign(&mut self, rhs: Self) { + self.merge(&rhs); + } +} + +enum KeyState<'a> { + Missing, + WrongType, + Empty, + Valid(&'a str), +} + +enum SpielIdState<'a> { + Missing, + WrongType, + Empty, + Str(&'a str), + Int32(i32), + Int64(i64), +} + +enum TimestampState { + Missing, + WrongType, + Invalid, + OutOfRange, + Valid(i64), +} + +enum EditedState { + Absent, + Null, + ZeroOrFalse, + Valid(i64), + Invalid, +} + +enum TextState<'a> { + MissingOrNull, + WrongType, + Str(&'a str), +} + +enum BotState<'a> { + None, + WrongType, + Str(&'a str), + Int32(i32), + Int64(i64), + Bool(bool), +} + +enum UserIdState<'a> { + None, + WrongType, + Str(&'a str), + Int32(i32), + Int64(i64), +} + +#[inline] +fn scale_numeric_timestamp(raw: i64, unit: CeoPostsTimestampUnit) -> TimestampState { + match unit { + CeoPostsTimestampUnit::Millis => TimestampState::Valid(raw), + CeoPostsTimestampUnit::Seconds => match raw.checked_mul(1_000) { + Some(ms) => TimestampState::Valid(ms), + None => TimestampState::OutOfRange, + }, + } +} + +#[inline] +fn decode_timestamp_val(val: RawBsonRef<'_>, unit: CeoPostsTimestampUnit) -> TimestampState { + match val { + RawBsonRef::DateTime(dt) => TimestampState::Valid(dt.timestamp_millis()), + RawBsonRef::Int32(v) => scale_numeric_timestamp(i64::from(v), unit), + RawBsonRef::Int64(v) => scale_numeric_timestamp(v, unit), + RawBsonRef::Double(v) => { + if !v.is_finite() || v.fract() != 0.0 { + return TimestampState::Invalid; + } + // Exact half-open range of `f64` values representable as `i64` (`[-2^63, 2^63)`). + if !(-9_223_372_036_854_775_808.0..9_223_372_036_854_775_808.0).contains(&v) { + return TimestampState::OutOfRange; + } + scale_numeric_timestamp(v as i64, unit) + } + _ => TimestampState::WrongType, + } +} + +#[inline] +fn decode_edited_val(val: RawBsonRef<'_>, unit: CeoPostsTimestampUnit) -> EditedState { + match val { + RawBsonRef::Null => EditedState::Null, + RawBsonRef::Boolean(false) => EditedState::ZeroOrFalse, + RawBsonRef::Boolean(true) => EditedState::Invalid, + RawBsonRef::DateTime(dt) => { + let ms = dt.timestamp_millis(); + if ms < 0 { + EditedState::Invalid + } else { + // Epoch-zero BSON DateTime is a timestamp, not the numeric `0` sentinel. + EditedState::Valid(ms) + } + } + RawBsonRef::Int32(_) | RawBsonRef::Int64(_) | RawBsonRef::Double(_) => { + match decode_timestamp_val(val, unit) { + TimestampState::Valid(0) => EditedState::ZeroOrFalse, + TimestampState::Valid(ms) if ms > 0 => EditedState::Valid(ms), + TimestampState::Valid(_) + | TimestampState::Invalid + | TimestampState::OutOfRange + | TimestampState::WrongType + | TimestampState::Missing => EditedState::Invalid, + } + } + _ => EditedState::Invalid, + } +} + +#[inline] +fn decode_spiel_id_val(val: RawBsonRef<'_>) -> SpielIdState<'_> { + match val { + RawBsonRef::String(s) => { + if s.trim().is_empty() { + SpielIdState::Empty + } else { + SpielIdState::Str(s) + } + } + RawBsonRef::Int32(v) => SpielIdState::Int32(v), + RawBsonRef::Int64(v) => SpielIdState::Int64(v), + _ => SpielIdState::WrongType, + } +} + +#[inline] +fn decode_bot_val(val: RawBsonRef<'_>) -> BotState<'_> { + match val { + RawBsonRef::Null => BotState::None, + RawBsonRef::String(s) => BotState::Str(s), + RawBsonRef::Int32(v) => BotState::Int32(v), + RawBsonRef::Int64(v) => BotState::Int64(v), + RawBsonRef::Boolean(b) => BotState::Bool(b), + _ => BotState::WrongType, + } +} + +#[inline] +fn decode_user_id_val(val: RawBsonRef<'_>) -> UserIdState<'_> { + match val { + RawBsonRef::Null => UserIdState::None, + RawBsonRef::String(s) => UserIdState::Str(s), + RawBsonRef::Int32(v) => UserIdState::Int32(v), + RawBsonRef::Int64(v) => UserIdState::Int64(v), + _ => UserIdState::WrongType, + } +} + +#[inline] +fn decode_text_val(val: RawBsonRef<'_>) -> TextState<'_> { + match val { + RawBsonRef::Null => TextState::MissingOrNull, + RawBsonRef::String(s) => TextState::Str(s), + _ => TextState::WrongType, + } +} + +/// Maximum recursive nesting depth accepted while validating raw BSON documents and arrays. +const MAX_BSON_VALIDATION_DEPTH: usize = 128; + +#[inline] +fn is_exact_array_index(key: &str, expected: usize) -> bool { + let bytes = key.as_bytes(); + if bytes.is_empty() || (bytes.len() > 1 && bytes[0] == b'0') { + return false; + } + let mut parsed: usize = 0; + for &b in bytes { + if !b.is_ascii_digit() { + return false; + } + let digit = usize::from(b - b'0'); + match parsed.checked_mul(10).and_then(|n| n.checked_add(digit)) { + Some(next) => parsed = next, + None => return false, + } + } + parsed == expected +} + +fn validate_raw_bson_value( + val: RawBsonRef<'_>, + doc_offset: u64, + field_name: &str, + depth: usize, +) -> Result<(), BsonCeoPostsError> { + match val { + RawBsonRef::Document(subdoc) => { + validate_raw_document(subdoc, doc_offset, field_name, depth + 1) + } + RawBsonRef::Array(arr) => { + if depth >= MAX_BSON_VALIDATION_DEPTH { + return Err(BsonCeoPostsError::CorruptBson { + offset: doc_offset, + detail: format!( + "field '{field_name}': nested BSON depth exceeds limit {MAX_BSON_VALIDATION_DEPTH}" + ), + }); + } + for (expected_idx, elem_res) in arr.iter_elements().enumerate() { + let elem = elem_res.map_err(|err| BsonCeoPostsError::CorruptBson { + offset: doc_offset, + detail: format!("field '{field_name}': {err}"), + })?; + let key = elem.key().as_str(); + if !is_exact_array_index(key, expected_idx) { + return Err(BsonCeoPostsError::CorruptBson { + offset: doc_offset, + detail: format!( + "field '{field_name}': invalid BSON array index '{key}' at position {expected_idx}" + ), + }); + } + let item = elem.value().map_err(|err| BsonCeoPostsError::CorruptBson { + offset: doc_offset, + detail: format!("field '{field_name}': {err}"), + })?; + validate_raw_bson_value(item, doc_offset, field_name, depth + 1)?; + } + Ok(()) + } + RawBsonRef::JavaScriptCodeWithScope(code_with_scope) => { + validate_raw_document(code_with_scope.scope, doc_offset, field_name, depth + 1) + } + _ => Ok(()), + } +} + +fn validate_raw_document( + doc: &RawDocument, + doc_offset: u64, + field_name: &str, + depth: usize, +) -> Result<(), BsonCeoPostsError> { + if depth > MAX_BSON_VALIDATION_DEPTH { + return Err(BsonCeoPostsError::CorruptBson { + offset: doc_offset, + detail: format!( + "field '{field_name}': nested BSON depth exceeds limit {MAX_BSON_VALIDATION_DEPTH}" + ), + }); + } + for elem_res in doc.iter_elements() { + let elem = elem_res.map_err(|err| BsonCeoPostsError::CorruptBson { + offset: doc_offset, + detail: format!("field '{field_name}': {err}"), + })?; + let val = elem.value().map_err(|err| BsonCeoPostsError::CorruptBson { + offset: doc_offset, + detail: format!("field '{field_name}': {err}"), + })?; + validate_raw_bson_value(val, doc_offset, field_name, depth)?; + } + Ok(()) +} + +fn decode_ceo_posts_doc_at<'a, F>( + doc: &'a RawDocument, + doc_offset: u64, + fields: &CeoPostsFieldNames<'_>, + unit: CeoPostsTimestampUnit, + mut on_row: F, +) -> Result +where + F: FnMut(CeoPost<&'a str>), +{ + let mut stats = BsonCeoPostsDecodeStats { + docs_in: 1, + ..BsonCeoPostsDecodeStats::default() + }; + + let mut key_state = KeyState::Missing; + let mut spiel_id_state = SpielIdState::Missing; + let mut timestamp_state = TimestampState::Missing; + let mut edited_state = EditedState::Absent; + let mut bot_state = BotState::None; + let mut user_id_state = UserIdState::None; + let mut text_state = TextState::MissingOrNull; + + // Scan and validate every element and nested raw value to completion so structural BSON + // corruption (including invalid UTF-8 in unused fields or malformed nested documents/arrays) + // always fails closed and is never masked by an earlier semantic skip. + for elem_res in doc.iter_elements() { + let elem = elem_res.map_err(|err| BsonCeoPostsError::CorruptBson { + offset: doc_offset, + detail: err.to_string(), + })?; + let name = elem.key().as_str(); + let val = elem.value().map_err(|err| BsonCeoPostsError::CorruptBson { + offset: doc_offset, + detail: format!("field '{name}': {err}"), + })?; + validate_raw_bson_value(val, doc_offset, name, 0)?; + + if name == fields.key { + key_state = match val { + RawBsonRef::String(s) => { + if s.trim().is_empty() { + KeyState::Empty + } else { + KeyState::Valid(s) + } + } + _ => KeyState::WrongType, + }; + } else if name == fields.spiel_id { + spiel_id_state = decode_spiel_id_val(val); + } else if name == fields.timestamp { + timestamp_state = decode_timestamp_val(val, unit); + } else if name == fields.edited { + // Fail closed on repeated `edited` fields so a later value (e.g. Null) can never + // mask an earlier unreadable or later edit timestamp. + edited_state = if matches!(edited_state, EditedState::Absent) { + decode_edited_val(val, unit) + } else { + EditedState::Invalid + }; + } else if name == fields.bot { + bot_state = decode_bot_val(val); + } else if name == fields.user_id { + user_id_state = decode_user_id_val(val); + } else if name == fields.text { + text_state = decode_text_val(val); + } + } + + // Apply deterministic semantic skip priority: key -> spiel_id -> timestamp -> edited -> text. + let key = match key_state { + KeyState::Valid(s) => s, + KeyState::Missing => { + stats.skipped_missing_key += 1; + return Ok(stats); + } + KeyState::WrongType => { + stats.skipped_wrong_key_type += 1; + return Ok(stats); + } + KeyState::Empty => { + stats.skipped_empty_key += 1; + return Ok(stats); + } + }; + + match spiel_id_state { + SpielIdState::Str(_) | SpielIdState::Int32(_) | SpielIdState::Int64(_) => {} + SpielIdState::Missing => { + stats.skipped_missing_spiel_id += 1; + return Ok(stats); + } + SpielIdState::WrongType => { + stats.skipped_wrong_spiel_id_type += 1; + return Ok(stats); + } + SpielIdState::Empty => { + stats.skipped_empty_spiel_id += 1; + return Ok(stats); + } + } + + let timestamp_ms = match timestamp_state { + TimestampState::Valid(ms) => ms, + TimestampState::Missing => { + stats.skipped_missing_timestamp += 1; + return Ok(stats); + } + TimestampState::WrongType => { + stats.skipped_wrong_timestamp_type += 1; + return Ok(stats); + } + TimestampState::Invalid => { + stats.skipped_invalid_timestamp += 1; + return Ok(stats); + } + TimestampState::OutOfRange => { + stats.skipped_timestamp_out_of_range += 1; + return Ok(stats); + } + }; + + let (edited_ms, edited_is_zero_or_false) = match edited_state { + EditedState::Absent | EditedState::Null => (None, false), + EditedState::ZeroOrFalse => (None, true), + EditedState::Valid(ms) => (Some(ms), false), + EditedState::Invalid => { + stats.skipped_invalid_edited += 1; + return Ok(stats); + } + }; + + let (text, text_is_empty) = match text_state { + TextState::Str(s) => (s.to_owned(), false), + TextState::MissingOrNull => (String::new(), true), + TextState::WrongType => { + stats.skipped_wrong_text_type += 1; + return Ok(stats); + } + }; + + // Row passed all skip checks: record emitted-row counters and allocate owned fields. + if edited_is_zero_or_false { + stats.edited_zero_or_false += 1; + } + if text_is_empty { + stats.empty_text += 1; + } + + let spiel_id = match spiel_id_state { + SpielIdState::Str(s) => s.to_owned(), + SpielIdState::Int32(v) => v.to_string(), + SpielIdState::Int64(v) => v.to_string(), + SpielIdState::Missing | SpielIdState::WrongType | SpielIdState::Empty => { + unreachable!("validated above") + } + }; + + let bot = match bot_state { + BotState::None => None, + BotState::Str(s) => Some(s.to_owned()), + BotState::Int32(v) => Some(v.to_string()), + BotState::Int64(v) => Some(v.to_string()), + BotState::Bool(true) => Some("1".to_owned()), + BotState::Bool(false) => Some("0".to_owned()), + BotState::WrongType => { + stats.nulled_wrong_type_bot += 1; + None + } + }; + + let user_id = match user_id_state { + UserIdState::None => None, + UserIdState::Str(s) => Some(s.to_owned()), + UserIdState::Int32(v) => Some(v.to_string()), + UserIdState::Int64(v) => Some(v.to_string()), + UserIdState::WrongType => { + stats.nulled_wrong_type_user_id += 1; + None + } + }; + + stats.rows_out += 1; + on_row(CeoPost { + key, + spiel_id, + timestamp_ms, + edited_ms, + bot, + user_id, + text, + }); + Ok(stats) +} + +/// Decodes a single `&RawDocument` representing a `ceoPosts` MongoDB document in one forward pass +/// without allocating a `bson::Document`. +/// +/// Validates `fields` before inspecting the document. +pub fn decode_ceo_posts_doc<'a, F>( + doc: &'a RawDocument, + fields: &CeoPostsFieldNames<'_>, + unit: CeoPostsTimestampUnit, + on_row: F, +) -> Result +where + F: FnMut(CeoPost<&'a str>), +{ + fields.validate()?; + decode_ceo_posts_doc_at(doc, 0, fields, unit, on_row) +} + +/// Decodes a single length-prefixed raw BSON document byte slice representing a `ceoPosts` +/// document. +/// +/// Validates `fields` before inspecting the bytes. +pub fn decode_ceo_posts_bytes<'a, F>( + bytes: &'a [u8], + fields: &CeoPostsFieldNames<'_>, + unit: CeoPostsTimestampUnit, + on_row: F, +) -> Result +where + F: FnMut(CeoPost<&'a str>), +{ + fields.validate()?; + let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?; + decode_ceo_posts_doc_at(doc, 0, fields, unit, on_row) +} + +/// Streams a concatenated length-prefixed BSON buffer through [`decode_ceo_posts_doc`], +/// emitting every valid [`CeoPost<&str>`] to `on_row` and failing closed on the first structural +/// BSON framing or element corruption. +/// +/// Validates `fields` once before reading the buffer. If an error occurs after one or more valid +/// documents, `on_row` has already been invoked for those earlier documents. +/// +/// Always maintains `stats.docs_in == stats.rows_out + stats.skipped_total()`. +pub fn decode_ceo_posts_buffer<'a, F>( + buf: &'a [u8], + fields: &CeoPostsFieldNames<'_>, + unit: CeoPostsTimestampUnit, + mut on_row: F, +) -> Result +where + F: FnMut(CeoPost<&'a str>), +{ + fields.validate()?; + let mut total = BsonCeoPostsDecodeStats::default(); + let mut iter = iter_raw_bson_docs(buf); + while let Some(item) = iter.next_with_offset() { + match item { + Ok((offset, doc)) => { + let doc_stats = + decode_ceo_posts_doc_at(doc, offset as u64, fields, unit, &mut on_row)?; + total += doc_stats; + } + Err((_, err)) => return Err(map_framing_error(err)), + } + } + Ok(total) +} + +#[cfg(test)] +#[path = "bson_ceo_posts_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/bson_ceo_posts_tests.rs b/tools/curate-etl/src/bson_ceo_posts_tests.rs new file mode 100644 index 00000000..b80fd2b0 --- /dev/null +++ b/tools/curate-etl/src/bson_ceo_posts_tests.rs @@ -0,0 +1,1070 @@ +use bson::raw::{cstr, RawArrayBuf, RawBson, RawDocument, RawDocumentBuf}; +use bson::DateTime as BsonDateTime; + +use super::*; +use crate::posts::build_posts; + +fn assert_conservation(stats: &BsonCeoPostsDecodeStats) { + assert_eq!( + stats.docs_in, + stats.rows_out + stats.skipped_total(), + "conservation invariant failed: {stats:?}" + ); +} + +fn make_base_doc(key: &str, spiel_id: &str, ts_secs: i64) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("ceoId"), key); + doc.append(cstr!("spielId"), spiel_id); + doc.append(cstr!("timestamp"), ts_secs); + doc.append(cstr!("spiel"), "hello world"); + doc +} + +#[test] +fn validates_field_names_rejecting_empty_blank_and_duplicates() { + let defaults = CeoPostsFieldNames::default(); + assert_eq!(defaults.key, DEFAULT_KEY_FIELD); + assert_eq!(defaults.spiel_id, DEFAULT_SPIEL_ID_FIELD); + assert_eq!(defaults.timestamp, DEFAULT_TIMESTAMP_FIELD); + assert_eq!(defaults.edited, DEFAULT_EDITED_FIELD); + assert_eq!(defaults.bot, DEFAULT_BOT_FIELD); + assert_eq!(defaults.user_id, DEFAULT_USER_ID_FIELD); + assert_eq!(defaults.text, DEFAULT_TEXT_FIELD); + assert!(defaults.validate().is_ok()); + + let custom = CeoPostsFieldNames { + key: "channel", + spiel_id: "postId", + timestamp: "createdAt", + edited: "updatedAt", + bot: "isBot", + user_id: "authorId", + text: "body", + }; + assert!(custom.validate().is_ok()); + + let bad_configs = [ + CeoPostsFieldNames { + key: "", + ..defaults + }, + CeoPostsFieldNames { + key: " \t ", + ..defaults + }, + CeoPostsFieldNames { + spiel_id: "", + ..defaults + }, + CeoPostsFieldNames { + timestamp: " ", + ..defaults + }, + CeoPostsFieldNames { + edited: "", + ..defaults + }, + CeoPostsFieldNames { + bot: " ", + ..defaults + }, + CeoPostsFieldNames { + user_id: "", + ..defaults + }, + CeoPostsFieldNames { + text: "\t", + ..defaults + }, + // Duplicate role mappings + CeoPostsFieldNames { + key: "dup", + spiel_id: "dup", + ..defaults + }, + CeoPostsFieldNames { + timestamp: "edited", + ..defaults + }, + CeoPostsFieldNames { + bot: "userId", + ..defaults + }, + CeoPostsFieldNames { + text: "ceoId", + ..defaults + }, + ]; + + let empty_doc = RawDocumentBuf::new(); + + for cfg in bad_configs { + let err = cfg.validate().unwrap_err(); + assert!( + matches!(err, BsonCeoPostsError::InvalidFieldNames { .. }), + "expected InvalidFieldNames for {cfg:?}, got {err:?}" + ); + let msg = err.to_string(); + assert!(!msg.contains('\n'), "single-line display expected: {msg}"); + + // All three entry points validate config before touching bytes/docs. + assert!(matches!( + decode_ceo_posts_buffer(&[], &cfg, CeoPostsTimestampUnit::Seconds, |_| {}), + Err(BsonCeoPostsError::InvalidFieldNames { .. }) + )); + assert!(matches!( + decode_ceo_posts_bytes(&[], &cfg, CeoPostsTimestampUnit::Millis, |_| {}), + Err(BsonCeoPostsError::InvalidFieldNames { .. }) + )); + assert!(matches!( + decode_ceo_posts_doc( + empty_doc.as_ref(), + &cfg, + CeoPostsTimestampUnit::Seconds, + |_| {} + ), + Err(BsonCeoPostsError::InvalidFieldNames { .. }) + )); + } +} + +#[test] +fn decodes_timestamp_and_edited_across_types_under_seconds_and_millis() { + let fields = CeoPostsFieldNames::default(); + let ts_sec_i32: i32 = 1_710_460_800; // 2024-03-15T00:00:00Z + let ed_sec_i32: i32 = 1_710_461_400; // +600s + let ts_sec_i64: i64 = 1_710_460_900; + let ed_sec_i64: i64 = 1_710_461_900; + let ts_dt_ms: i64 = 1_710_460_800_123; + let ed_dt_ms: i64 = 1_710_461_400_456; + + // --- Seconds unit --- + let mut sec_buf = Vec::new(); + + // 1. Int32 timestamp + Int32 edited + let mut d1 = RawDocumentBuf::new(); + d1.append(cstr!("ceoId"), " CH-1 "); // verbatim + d1.append(cstr!("spielId"), "s1"); + d1.append(cstr!("timestamp"), ts_sec_i32); + d1.append(cstr!("edited"), ed_sec_i32); + d1.append(cstr!("spiel"), "int32"); + sec_buf.extend_from_slice(d1.as_bytes()); + + // 2. Int64 timestamp + Int64 edited + let mut d2 = RawDocumentBuf::new(); + d2.append(cstr!("ceoId"), "CH-2"); + d2.append(cstr!("spielId"), 200_i32); + d2.append(cstr!("timestamp"), ts_sec_i64); + d2.append(cstr!("edited"), ed_sec_i64); + d2.append(cstr!("spiel"), "int64"); + sec_buf.extend_from_slice(d2.as_bytes()); + + // 3. Integral Double timestamp + integral Double edited + let mut d3 = RawDocumentBuf::new(); + d3.append(cstr!("ceoId"), "CH-3"); + d3.append(cstr!("spielId"), 300_i64); + d3.append(cstr!("timestamp"), ts_sec_i64 as f64); + d3.append(cstr!("edited"), ed_sec_i64 as f64); + d3.append(cstr!("spiel"), "double"); + sec_buf.extend_from_slice(d3.as_bytes()); + + // 4. BSON DateTime (already ms; unit ignored) + let mut d4 = RawDocumentBuf::new(); + d4.append(cstr!("ceoId"), "CH-4"); + d4.append(cstr!("spielId"), "s4"); + d4.append(cstr!("timestamp"), BsonDateTime::from_millis(ts_dt_ms)); + d4.append(cstr!("edited"), BsonDateTime::from_millis(ed_dt_ms)); + d4.append(cstr!("spiel"), "datetime"); + sec_buf.extend_from_slice(d4.as_bytes()); + + // 5. Non-positive creation times (<= 0) passed through verbatim (build_posts rejects them) + let mut d5 = RawDocumentBuf::new(); + d5.append(cstr!("ceoId"), "CH-5"); + d5.append(cstr!("spielId"), "s5"); + d5.append(cstr!("timestamp"), 0_i32); + d5.append(cstr!("spiel"), "zero"); + sec_buf.extend_from_slice(d5.as_bytes()); + + let mut d6 = RawDocumentBuf::new(); + d6.append(cstr!("ceoId"), "CH-6"); + d6.append(cstr!("spielId"), "s6"); + d6.append(cstr!("timestamp"), -10_i64); + d6.append(cstr!("spiel"), "neg"); + sec_buf.extend_from_slice(d6.as_bytes()); + + let mut d7 = RawDocumentBuf::new(); + d7.append(cstr!("ceoId"), "CH-7"); + d7.append(cstr!("spielId"), "s7"); + d7.append(cstr!("timestamp"), -0.0_f64); + d7.append(cstr!("spiel"), "negzero"); + sec_buf.extend_from_slice(d7.as_bytes()); + + let buf_start = sec_buf.as_ptr() as usize; + let buf_end = buf_start + sec_buf.len(); + + let mut sec_rows = Vec::new(); + let stats = decode_ceo_posts_buffer(&sec_buf, &fields, CeoPostsTimestampUnit::Seconds, |r| { + // Verify zero-copy borrow: `key` points directly into `sec_buf`. + let key_ptr = r.key.as_ptr() as usize; + assert!( + key_ptr >= buf_start && key_ptr + r.key.len() <= buf_end, + "decoded key must borrow directly from input buffer" + ); + sec_rows.push(( + r.key.to_owned(), + r.spiel_id, + r.timestamp_ms, + r.edited_ms, + r.text, + )); + }) + .expect("decode seconds buffer"); + + assert_conservation(&stats); + assert_eq!(stats.docs_in, 7); + assert_eq!(stats.rows_out, 7); + assert_eq!( + sec_rows, + vec![ + ( + " CH-1 ".to_string(), + "s1".to_string(), + i64::from(ts_sec_i32) * 1_000, + Some(i64::from(ed_sec_i32) * 1_000), + "int32".to_string() + ), + ( + "CH-2".to_string(), + "200".to_string(), + ts_sec_i64 * 1_000, + Some(ed_sec_i64 * 1_000), + "int64".to_string() + ), + ( + "CH-3".to_string(), + "300".to_string(), + ts_sec_i64 * 1_000, + Some(ed_sec_i64 * 1_000), + "double".to_string() + ), + ( + "CH-4".to_string(), + "s4".to_string(), + ts_dt_ms, + Some(ed_dt_ms), + "datetime".to_string() + ), + ( + "CH-5".to_string(), + "s5".to_string(), + 0, + None, + "zero".to_string() + ), + ( + "CH-6".to_string(), + "s6".to_string(), + -10_000, + None, + "neg".to_string() + ), + ( + "CH-7".to_string(), + "s7".to_string(), + 0, + None, + "negzero".to_string() + ), + ] + ); + + // --- Millis unit --- + let mut ms_buf = Vec::new(); + + // Int32 millis + let mut m1 = RawDocumentBuf::new(); + m1.append(cstr!("ceoId"), "M1"); + m1.append(cstr!("spielId"), "m1"); + m1.append(cstr!("timestamp"), 1_000_000_i32); + m1.append(cstr!("edited"), 1_000_500_i32); + m1.append(cstr!("spiel"), "m1"); + ms_buf.extend_from_slice(m1.as_bytes()); + + // Int64 millis + let mut m2 = RawDocumentBuf::new(); + m2.append(cstr!("ceoId"), "M2"); + m2.append(cstr!("spielId"), "m2"); + m2.append(cstr!("timestamp"), ts_dt_ms); + m2.append(cstr!("edited"), ed_dt_ms); + m2.append(cstr!("spiel"), "m2"); + ms_buf.extend_from_slice(m2.as_bytes()); + + // Integral Double millis (including exact -2^63 and 2^63 - 1024 boundaries) + let mut m3 = RawDocumentBuf::new(); + m3.append(cstr!("ceoId"), "M3"); + m3.append(cstr!("spielId"), "m3"); + m3.append(cstr!("timestamp"), -9_223_372_036_854_775_808.0_f64); + m3.append(cstr!("edited"), 9_223_372_036_854_774_784.0_f64); + m3.append(cstr!("spiel"), "m3"); + ms_buf.extend_from_slice(m3.as_bytes()); + + // BSON DateTime under Millis (unchanged) + let mut m4 = RawDocumentBuf::new(); + m4.append(cstr!("ceoId"), "M4"); + m4.append(cstr!("spielId"), "m4"); + m4.append(cstr!("timestamp"), BsonDateTime::from_millis(ts_dt_ms)); + m4.append(cstr!("edited"), BsonDateTime::from_millis(ed_dt_ms)); + m4.append(cstr!("spiel"), "m4"); + ms_buf.extend_from_slice(m4.as_bytes()); + + let mut ms_rows = Vec::new(); + let ms_stats = decode_ceo_posts_buffer(&ms_buf, &fields, CeoPostsTimestampUnit::Millis, |r| { + ms_rows.push((r.spiel_id, r.timestamp_ms, r.edited_ms)); + }) + .expect("decode millis buffer"); + + assert_conservation(&ms_stats); + assert_eq!(ms_stats.docs_in, 4); + assert_eq!(ms_stats.rows_out, 4); + assert_eq!( + ms_rows, + vec![ + ("m1".to_string(), 1_000_000, Some(1_000_500)), + ("m2".to_string(), ts_dt_ms, Some(ed_dt_ms)), + ( + "m3".to_string(), + i64::MIN, + Some(9_223_372_036_854_774_784_i64) + ), + ("m4".to_string(), ts_dt_ms, Some(ed_dt_ms)), + ] + ); +} + +#[test] +fn skips_timestamp_seconds_overflow_and_double_range_boundaries() { + let fields = CeoPostsFieldNames::default(); + let mut buf = Vec::new(); + + // 1. Positive Int64 seconds overflow (i64::MAX / 1_000 + 1) + let mut d1 = RawDocumentBuf::new(); + d1.append(cstr!("ceoId"), "CH"); + d1.append(cstr!("spielId"), "ovf_pos"); + d1.append(cstr!("timestamp"), (i64::MAX / 1_000) + 1); + buf.extend_from_slice(d1.as_bytes()); + + // 2. Negative Int64 seconds overflow (i64::MIN / 1_000 - 1) + let mut d2 = RawDocumentBuf::new(); + d2.append(cstr!("ceoId"), "CH"); + d2.append(cstr!("spielId"), "ovf_neg"); + d2.append(cstr!("timestamp"), (i64::MIN / 1_000) - 1); + buf.extend_from_slice(d2.as_bytes()); + + // 3. Double exactly at 2^63 (outside half-open [-2^63, 2^63)) + let mut d3 = RawDocumentBuf::new(); + d3.append(cstr!("ceoId"), "CH"); + d3.append(cstr!("spielId"), "dbl_2p63"); + d3.append(cstr!("timestamp"), 9_223_372_036_854_775_808.0_f64); + buf.extend_from_slice(d3.as_bytes()); + + // 4. Double below -2^63 + let mut d4 = RawDocumentBuf::new(); + d4.append(cstr!("ceoId"), "CH"); + d4.append(cstr!("spielId"), "dbl_neg_oob"); + d4.append(cstr!("timestamp"), -1e20_f64); + buf.extend_from_slice(d4.as_bytes()); + + // 5. Double in i64 range but overflows when multiplied by 1_000 + let mut d5 = RawDocumentBuf::new(); + d5.append(cstr!("ceoId"), "CH"); + d5.append(cstr!("spielId"), "dbl_sec_ovf"); + d5.append(cstr!("timestamp"), 9_223_372_036_854_774_784.0_f64); + buf.extend_from_slice(d5.as_bytes()); + + let mut emitted = 0usize; + let stats = decode_ceo_posts_buffer(&buf, &fields, CeoPostsTimestampUnit::Seconds, |_| { + emitted += 1; + }) + .expect("decode overflow buffer"); + + assert_conservation(&stats); + assert_eq!(emitted, 0); + assert_eq!(stats.docs_in, 5); + assert_eq!(stats.skipped_timestamp_out_of_range, 5); + + // Under Millis, 2^63 is still out of range. + let stats_2p63 = + decode_ceo_posts_bytes(d3.as_bytes(), &fields, CeoPostsTimestampUnit::Millis, |_| { + panic!("2^63 double must not emit") + }) + .expect("decode 2^63 under millis"); + assert_eq!(stats_2p63.skipped_timestamp_out_of_range, 1); +} + +#[test] +fn edited_fail_closed_rule_and_sentinel_accounting() { + let fields = CeoPostsFieldNames::default(); + let ts_sec: i64 = 1_710_460_800; + + // --- Unedited & valid cases --- + let mut valid_buf = Vec::new(); + + // 1. Absent edited -> None (not counted in edited_zero_or_false) + valid_buf.extend_from_slice(make_base_doc("CH", "e_absent", ts_sec).as_bytes()); + + // 2. Null edited -> None (not counted in edited_zero_or_false) + let mut d = make_base_doc("CH", "e_null", ts_sec); + d.append(cstr!("edited"), RawBson::Null); + valid_buf.extend_from_slice(d.as_bytes()); + + // 3. Int32(0) -> None + edited_zero_or_false + let mut d = make_base_doc("CH", "e_i32_zero", ts_sec); + d.append(cstr!("edited"), 0_i32); + valid_buf.extend_from_slice(d.as_bytes()); + + // 4. Int64(0) -> None + edited_zero_or_false + let mut d = make_base_doc("CH", "e_i64_zero", ts_sec); + d.append(cstr!("edited"), 0_i64); + valid_buf.extend_from_slice(d.as_bytes()); + + // 5. Double(0.0) -> None + edited_zero_or_false + let mut d = make_base_doc("CH", "e_f64_zero", ts_sec); + d.append(cstr!("edited"), 0.0_f64); + valid_buf.extend_from_slice(d.as_bytes()); + + // 6. Double(-0.0) -> None + edited_zero_or_false + let mut d = make_base_doc("CH", "e_f64_neg_zero", ts_sec); + d.append(cstr!("edited"), -0.0_f64); + valid_buf.extend_from_slice(d.as_bytes()); + + // 7. Boolean(false) -> None + edited_zero_or_false + let mut d = make_base_doc("CH", "e_bool_false", ts_sec); + d.append(cstr!("edited"), false); + valid_buf.extend_from_slice(d.as_bytes()); + + // 8. Epoch-zero BSON DateTime -> Some(0) (not numeric zero sentinel) + let mut d = make_base_doc("CH", "e_dt_zero", ts_sec); + d.append(cstr!("edited"), BsonDateTime::from_millis(0)); + valid_buf.extend_from_slice(d.as_bytes()); + + let mut valid_out = Vec::new(); + let valid_stats = + decode_ceo_posts_buffer(&valid_buf, &fields, CeoPostsTimestampUnit::Seconds, |r| { + valid_out.push((r.spiel_id, r.edited_ms)); + }) + .expect("decode valid edited buffer"); + + assert_conservation(&valid_stats); + assert_eq!(valid_stats.docs_in, 8); + assert_eq!(valid_stats.rows_out, 8); + assert_eq!(valid_stats.skipped_invalid_edited, 0); + assert_eq!(valid_stats.edited_zero_or_false, 5); + assert_eq!( + valid_out, + vec![ + ("e_absent".to_string(), None), + ("e_null".to_string(), None), + ("e_i32_zero".to_string(), None), + ("e_i64_zero".to_string(), None), + ("e_f64_zero".to_string(), None), + ("e_f64_neg_zero".to_string(), None), + ("e_bool_false".to_string(), None), + ("e_dt_zero".to_string(), Some(0)), + ] + ); + + // --- Fail-closed rejected cases (must NEVER invoke on_row) --- + let mut bad_buf = Vec::new(); + + // 1. Negative Int32 + let mut d = make_base_doc("CH", "bad_neg_i32", ts_sec); + d.append(cstr!("edited"), -1_i32); + bad_buf.extend_from_slice(d.as_bytes()); + + // 2. Negative Int64 + let mut d = make_base_doc("CH", "bad_neg_i64", ts_sec); + d.append(cstr!("edited"), -5_000_i64); + bad_buf.extend_from_slice(d.as_bytes()); + + // 3. Negative Double + let mut d = make_base_doc("CH", "bad_neg_f64", ts_sec); + d.append(cstr!("edited"), -1.0_f64); + bad_buf.extend_from_slice(d.as_bytes()); + + // 4. Negative DateTime + let mut d = make_base_doc("CH", "bad_neg_dt", ts_sec); + d.append(cstr!("edited"), BsonDateTime::from_millis(-1)); + bad_buf.extend_from_slice(d.as_bytes()); + + // 5. Fractional Double + let mut d = make_base_doc("CH", "bad_frac", ts_sec); + d.append(cstr!("edited"), 1_710_461_400.5_f64); + bad_buf.extend_from_slice(d.as_bytes()); + + // 6. NaN Double + let mut d = make_base_doc("CH", "bad_nan", ts_sec); + d.append(cstr!("edited"), f64::NAN); + bad_buf.extend_from_slice(d.as_bytes()); + + // 7. +Inf Double + let mut d = make_base_doc("CH", "bad_inf", ts_sec); + d.append(cstr!("edited"), f64::INFINITY); + bad_buf.extend_from_slice(d.as_bytes()); + + // 8. Boolean(true) + let mut d = make_base_doc("CH", "bad_true", ts_sec); + d.append(cstr!("edited"), true); + bad_buf.extend_from_slice(d.as_bytes()); + + // 9. String + let mut d = make_base_doc("CH", "bad_str", ts_sec); + d.append(cstr!("edited"), "1710461400"); + bad_buf.extend_from_slice(d.as_bytes()); + + // 10. Unsupported type (embedded document) + let mut d = make_base_doc("CH", "bad_doc", ts_sec); + d.append(cstr!("edited"), RawDocumentBuf::new()); + bad_buf.extend_from_slice(d.as_bytes()); + + // 11. Seconds overflow + let mut d = make_base_doc("CH", "bad_ovf", ts_sec); + d.append(cstr!("edited"), (i64::MAX / 1_000) + 1); + bad_buf.extend_from_slice(d.as_bytes()); + + // 12. Repeated `edited` with unreadable value followed by Null (must fail closed!) + let mut d = make_base_doc("CH", "bad_dup_unreadable_then_null", ts_sec); + d.append(cstr!("edited"), "unreadable"); + d.append(cstr!("edited"), RawBson::Null); + bad_buf.extend_from_slice(d.as_bytes()); + + // 13. Repeated `edited` with valid timestamp followed by Null + let mut d = make_base_doc("CH", "bad_dup_valid_then_null", ts_sec); + d.append(cstr!("edited"), ts_sec + 60); + d.append(cstr!("edited"), RawBson::Null); + bad_buf.extend_from_slice(d.as_bytes()); + + // 14. Repeated `edited` with Null followed by valid timestamp + let mut d = make_base_doc("CH", "bad_dup_null_then_valid", ts_sec); + d.append(cstr!("edited"), RawBson::Null); + d.append(cstr!("edited"), ts_sec + 60); + bad_buf.extend_from_slice(d.as_bytes()); + + let mut bad_emitted = 0usize; + let bad_stats = + decode_ceo_posts_buffer(&bad_buf, &fields, CeoPostsTimestampUnit::Seconds, |_| { + bad_emitted += 1; + }) + .expect("decode bad edited buffer"); + + assert_conservation(&bad_stats); + assert_eq!(bad_emitted, 0); + assert_eq!(bad_stats.docs_in, 14); + assert_eq!(bad_stats.rows_out, 0); + assert_eq!(bad_stats.skipped_invalid_edited, 14); + assert_eq!(bad_stats.edited_zero_or_false, 0); +} + +#[test] +fn skips_every_counter_respects_priority_and_matches_single_doc_sum() { + let fields = CeoPostsFieldNames::default(); + let ts_sec: i64 = 1_710_460_800; + + let mut docs: Vec = Vec::new(); + + // 1. skipped_missing_key (also missing spiel_id, timestamp, bad edited, bad text -> key wins) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("spiel"), 123_i32); + d.append(cstr!("edited"), true); + docs.push(d); + + // 2. skipped_wrong_key_type (fields in reverse priority order -> key still wins) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("spiel"), 123_i32); + d.append(cstr!("edited"), "bad"); + d.append(cstr!("timestamp"), "bad"); + d.append(cstr!("spielId"), true); + d.append(cstr!("ceoId"), 42_i32); + docs.push(d); + + // 3. skipped_empty_key (with wrong-type optionals & zero edited -> emitted-row counters stay 0) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), " "); + d.append(cstr!("spielId"), "s3"); + d.append(cstr!("timestamp"), ts_sec); + d.append(cstr!("edited"), 0_i32); + d.append(cstr!("bot"), 1.5_f64); + d.append(cstr!("userId"), true); + docs.push(d); + + // 4. skipped_missing_spiel_id (also bad timestamp, edited, text -> spiel_id wins) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("spiel"), false); + d.append(cstr!("edited"), true); + d.append(cstr!("timestamp"), f64::NAN); + d.append(cstr!("ceoId"), "CH"); + docs.push(d); + + // 5. skipped_wrong_spiel_id_type + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), true); + d.append(cstr!("timestamp"), ts_sec); + docs.push(d); + + // 6. skipped_empty_spiel_id + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), " "); + d.append(cstr!("timestamp"), ts_sec); + docs.push(d); + + // 7. skipped_missing_timestamp (also bad edited & bad text -> timestamp wins) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("spiel"), 99_i32); + d.append(cstr!("edited"), "bad"); + d.append(cstr!("spielId"), "s7"); + d.append(cstr!("ceoId"), "CH"); + docs.push(d); + + // 8. skipped_wrong_timestamp_type + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), "s8"); + d.append(cstr!("timestamp"), "2024-03-15"); + docs.push(d); + + // 9. skipped_invalid_timestamp (fractional Double) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), "s9"); + d.append(cstr!("timestamp"), 1_710_460_800.25_f64); + docs.push(d); + + // 10. skipped_timestamp_out_of_range (Seconds overflow) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), "s10"); + d.append(cstr!("timestamp"), i64::MAX); + docs.push(d); + + // 11. skipped_invalid_edited (also bad text -> edited wins over text) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("spiel"), 99_i32); + d.append(cstr!("edited"), true); + d.append(cstr!("timestamp"), ts_sec); + d.append(cstr!("spielId"), "s11"); + d.append(cstr!("ceoId"), "CH"); + docs.push(d); + + // 12. skipped_wrong_text_type (with valid edited=0 and wrong-type bot/userId -> emitted counters stay 0) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), "s12"); + d.append(cstr!("timestamp"), ts_sec); + d.append(cstr!("edited"), false); + d.append(cstr!("bot"), 2.5_f64); + d.append(cstr!("userId"), true); + d.append(cstr!("spiel"), 123_i32); + docs.push(d); + + // 13. Valid emitted row with missing text, wrong-type bot & userId, edited=false + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), "ok1"); + d.append(cstr!("timestamp"), ts_sec); + d.append(cstr!("edited"), false); + d.append(cstr!("bot"), 2.5_f64); + d.append(cstr!("userId"), false); + docs.push(d); + + // 14. Valid emitted row with Null text, Int32 userId, String bot + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), "ok2"); + d.append(cstr!("timestamp"), ts_sec); + d.append(cstr!("bot"), "1"); + d.append(cstr!("userId"), 777_i32); + d.append(cstr!("spiel"), RawBson::Null); + docs.push(d); + + // 15. Valid emitted row with explicit empty string text (not counted in empty_text) and Int64 userId + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), "ok3"); + d.append(cstr!("timestamp"), ts_sec); + d.append(cstr!("bot"), 0_i64); + d.append(cstr!("userId"), 9_000_000_000_i64); + d.append(cstr!("spiel"), ""); + docs.push(d); + + let mut combined = Vec::new(); + let mut summed = BsonCeoPostsDecodeStats::default(); + for doc in &docs { + combined.extend_from_slice(doc.as_bytes()); + let single = + decode_ceo_posts_doc(doc.as_ref(), &fields, CeoPostsTimestampUnit::Seconds, |_| {}) + .expect("decode single doc"); + assert_conservation(&single); + summed += single; + } + + let mut emitted = Vec::new(); + let buf_stats = decode_ceo_posts_buffer( + &combined, + &fields, + CeoPostsTimestampUnit::Seconds, + |r| emitted.push((r.spiel_id, r.bot, r.user_id, r.text)), + ) + .expect("decode combined buffer"); + + assert_conservation(&buf_stats); + assert_eq!(buf_stats, summed); + assert_eq!(buf_stats.docs_in, 15); + assert_eq!(buf_stats.rows_out, 3); + assert_eq!(buf_stats.skipped_total(), 12); + assert_eq!(buf_stats.skipped_missing_key, 1); + assert_eq!(buf_stats.skipped_wrong_key_type, 1); + assert_eq!(buf_stats.skipped_empty_key, 1); + assert_eq!(buf_stats.skipped_missing_spiel_id, 1); + assert_eq!(buf_stats.skipped_wrong_spiel_id_type, 1); + assert_eq!(buf_stats.skipped_empty_spiel_id, 1); + assert_eq!(buf_stats.skipped_missing_timestamp, 1); + assert_eq!(buf_stats.skipped_wrong_timestamp_type, 1); + assert_eq!(buf_stats.skipped_invalid_timestamp, 1); + assert_eq!(buf_stats.skipped_timestamp_out_of_range, 1); + assert_eq!(buf_stats.skipped_invalid_edited, 1); + assert_eq!(buf_stats.skipped_wrong_text_type, 1); + assert_eq!(buf_stats.edited_zero_or_false, 1); + assert_eq!(buf_stats.nulled_wrong_type_bot, 1); + assert_eq!(buf_stats.nulled_wrong_type_user_id, 1); + assert_eq!(buf_stats.empty_text, 2); + + assert_eq!( + emitted, + vec![ + ("ok1".to_string(), None, None, String::new()), + ( + "ok2".to_string(), + Some("1".to_string()), + Some("777".to_string()), + String::new() + ), + ( + "ok3".to_string(), + Some("0".to_string()), + Some("9000000000".to_string()), + String::new() + ), + ] + ); +} + +#[test] +fn decodes_custom_field_names_and_feeds_build_posts_deterministically() { + let fields = CeoPostsFieldNames { + key: "channelId", + spiel_id: "postId", + timestamp: "postedSec", + edited: "editedSec", + bot: "botFlag", + user_id: "author", + text: "body", + }; + + let t0_sec: i64 = 1_710_460_800; // 2024-03-15T00:00:00Z + let t_edit_sec: i64 = t0_sec + 900; // +15m + + let mut raw_docs: Vec = Vec::new(); + + // 1. bot = "1" (newswire, unedited baseline) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("channelId"), "CH-A"); + d.append(cstr!("postId"), "nw_str_1"); + d.append(cstr!("postedSec"), t0_sec); + d.append(cstr!("botFlag"), "1"); + d.append(cstr!("author"), "wire"); + d.append(cstr!("body"), "Press release"); + raw_docs.push(d); + + // 2. bot = Int32(1) (newswire, edited later -> known_at == edited_ms * 1_000) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("channelId"), "CH-A"); + d.append(cstr!("postId"), "nw_i32_1"); + d.append(cstr!("postedSec"), t0_sec + 10); + d.append(cstr!("editedSec"), t_edit_sec); + d.append(cstr!("botFlag"), 1_i32); + d.append(cstr!("author"), 42_i32); + d.append(cstr!("body"), "Corrected release"); + raw_docs.push(d); + + // 3. bot = Boolean(true) (newswire) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("channelId"), "CH-A"); + d.append(cstr!("postId"), "nw_bool_true"); + d.append(cstr!("postedSec"), t0_sec + 20); + d.append(cstr!("botFlag"), true); + d.append(cstr!("body"), "Auto alert"); + raw_docs.push(d); + + // 4. bot = "0" (retail) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("channelId"), "CH-A"); + d.append(cstr!("postId"), "ret_str_0"); + d.append(cstr!("postedSec"), t0_sec + 30); + d.append(cstr!("botFlag"), "0"); + d.append(cstr!("body"), "Retail chatter"); + raw_docs.push(d); + + // 5. bot absent (retail) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("channelId"), "CH-A"); + d.append(cstr!("postId"), "ret_absent"); + d.append(cstr!("postedSec"), t0_sec + 40); + d.append(cstr!("body"), "No bot field"); + raw_docs.push(d); + + // 6. bot wrong type (Double -> nulled -> retail) + let mut d = RawDocumentBuf::new(); + d.append(cstr!("channelId"), "CH-A"); + d.append(cstr!("postId"), "ret_wrong_type"); + d.append(cstr!("postedSec"), t0_sec + 50); + d.append(cstr!("botFlag"), 1.0_f64); + d.append(cstr!("body"), "Wrong type bot"); + raw_docs.push(d); + + // 7. Non-positive creation time passed through by decoder, rejected by build_posts + let mut d = RawDocumentBuf::new(); + d.append(cstr!("channelId"), "CH-A"); + d.append(cstr!("postId"), "zero_ts"); + d.append(cstr!("postedSec"), 0_i64); + d.append(cstr!("body"), "Zero ts"); + raw_docs.push(d); + + let mut buf = Vec::new(); + for d in &raw_docs { + buf.extend_from_slice(d.as_bytes()); + } + + // Run through all three entry points and confirm identical decoded rows. + let mut rows_from_buffer = Vec::new(); + let stats_buf = decode_ceo_posts_buffer(&buf, &fields, CeoPostsTimestampUnit::Seconds, |r| { + rows_from_buffer.push(r); + }) + .expect("decode buffer"); + + let mut rows_from_bytes = Vec::new(); + let mut stats_bytes = BsonCeoPostsDecodeStats::default(); + for d in &raw_docs { + stats_bytes += decode_ceo_posts_bytes( + d.as_bytes(), + &fields, + CeoPostsTimestampUnit::Seconds, + |r| rows_from_bytes.push(r), + ) + .expect("decode bytes"); + } + + let mut rows_from_doc = Vec::new(); + let mut stats_doc = BsonCeoPostsDecodeStats::default(); + for d in &raw_docs { + let raw_doc = RawDocument::from_bytes(d.as_bytes()).expect("valid raw doc"); + stats_doc += decode_ceo_posts_doc(raw_doc, &fields, CeoPostsTimestampUnit::Seconds, |r| { + rows_from_doc.push(r) + }) + .expect("decode doc"); + } + + assert_eq!(stats_buf, stats_bytes); + assert_eq!(stats_buf, stats_doc); + assert_eq!(stats_buf.nulled_wrong_type_bot, 1); + assert_eq!(rows_from_buffer, rows_from_bytes); + assert_eq!(rows_from_buffer, rows_from_doc); + + // Feed into `build_posts` twice and verify exact classification, known_at, and determinism. + let build1 = build_posts(rows_from_buffer.clone()).expect("build_posts run 1"); + let build2 = build_posts(rows_from_buffer).expect("build_posts run 2"); + assert_eq!(build1, build2); + + let newswire_ids: Vec<&str> = build1 + .newswire + .iter() + .map(|r| r.spiel_id.as_str()) + .collect(); + let retail_ids: Vec<&str> = build1.retail.iter().map(|r| r.spiel_id.as_str()).collect(); + assert_eq!(newswire_ids, vec!["nw_str_1", "nw_bool_true", "nw_i32_1"]); + assert_eq!(retail_ids, vec!["ret_str_0", "ret_absent", "ret_wrong_type"]); + assert_eq!(build1.stats.rejected_invalid, 1); + + // Baseline unedited post: known_at == posted_at. + let baseline = build1 + .newswire + .iter() + .find(|r| r.spiel_id == "nw_str_1") + .expect("baseline row"); + assert_eq!(baseline.posted_at, t0_sec * 1_000_000); + assert_eq!(baseline.known_at, baseline.posted_at); + assert!(!baseline.is_edited); + + // Edited post: known_at == edited_ms * 1_000 (UTC microseconds). + let edited = build1 + .newswire + .iter() + .find(|r| r.spiel_id == "nw_i32_1") + .expect("edited row"); + assert_eq!(edited.posted_at, (t0_sec + 10) * 1_000_000); + assert_eq!(edited.known_at, (t_edit_sec * 1_000) * 1_000); + assert!(edited.is_edited); + assert_eq!(edited.user_id.as_deref(), Some("42")); +} + +#[test] +fn framing_and_structural_corruption_fail_closed_with_exact_offsets() { + let fields = CeoPostsFieldNames::default(); + let ts_sec: i64 = 1_710_460_800; + + let good = make_base_doc("CH-OK", "ok_first", ts_sec); + let good_len = good.as_bytes().len() as u64; + + // 1. Truncated header (< 4 bytes) after one valid doc + let mut combined = good.as_bytes().to_vec(); + combined.extend_from_slice(&[0x10, 0x00]); + let mut emitted = Vec::new(); + let err = decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { + emitted.push(r.spiel_id); + }) + .unwrap_err(); + assert_eq!(emitted, vec!["ok_first".to_string()]); + assert_eq!( + err, + BsonCeoPostsError::TruncatedDocument { + offset: good_len, + remaining: 2, + declared_len: None, + } + ); + assert!(!err.to_string().contains('\n')); + + // 2. Truncated body after one valid doc + let mut combined = good.as_bytes().to_vec(); + combined.extend_from_slice(&[20, 0, 0, 0, 0, 0]); + let mut emitted = Vec::new(); + let err = decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { + emitted.push(r.spiel_id); + }) + .unwrap_err(); + assert_eq!(emitted, vec!["ok_first".to_string()]); + assert_eq!( + err, + BsonCeoPostsError::TruncatedDocument { + offset: good_len, + remaining: 6, + declared_len: Some(20), + } + ); + assert!(!err.to_string().contains('\n')); + + // 3. Declared length < 5 after one valid doc + let mut combined = good.as_bytes().to_vec(); + combined.extend_from_slice(&[3, 0, 0, 0, 0]); + let mut emitted = Vec::new(); + let err = decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { + emitted.push(r.spiel_id); + }) + .unwrap_err(); + assert_eq!(emitted, vec!["ok_first".to_string()]); + assert_eq!( + err, + BsonCeoPostsError::CorruptDocumentLength { + offset: good_len, + declared_len: 3, + } + ); + assert!(!err.to_string().contains('\n')); + + // 4. Malformed element AFTER a semantically invalid field (must not be masked by skip) + let mut bad_after_skip = RawDocumentBuf::new(); + bad_after_skip.append(cstr!("ceoId"), ""); // would be skipped_empty_key + bad_after_skip.append(cstr!("z"), 1_i32); + let mut bad_bytes = bad_after_skip.into_bytes(); + let z_pos = bad_bytes + .windows(3) + .position(|w| w == [0x10, b'z', 0x00]) + .expect("locate z element"); + bad_bytes[z_pos] = 0x7e; + + let mut combined = good.as_bytes().to_vec(); + combined.extend_from_slice(&bad_bytes); + let mut emitted = Vec::new(); + let err = decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { + emitted.push(r.spiel_id); + }) + .unwrap_err(); + assert_eq!(emitted, vec!["ok_first".to_string()]); + assert!( + matches!(err, BsonCeoPostsError::CorruptBson { offset, .. } if offset == good_len), + "expected CorruptBson at offset {good_len}, got {err:?}" + ); + assert!(!err.to_string().contains('\n')); + + // 5. Corruption inside an unused nested embedded document after one valid doc + let mut inner = RawDocumentBuf::new(); + inner.append(cstr!("nestedText"), "INNER!"); + let mut nested_bad = make_base_doc("CH-2", "nested_bad", ts_sec); + nested_bad.append(cstr!("poll"), inner); + let mut nested_bytes = nested_bad.into_bytes(); + let pos = nested_bytes + .windows(6) + .position(|w| w == b"INNER!") + .expect("locate INNER!"); + nested_bytes[pos] = 0xff; + + let mut combined = good.as_bytes().to_vec(); + combined.extend_from_slice(&nested_bytes); + let mut emitted = Vec::new(); + let err = decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { + emitted.push(r.spiel_id); + }) + .unwrap_err(); + assert_eq!(emitted, vec!["ok_first".to_string()]); + assert!( + matches!(err, BsonCeoPostsError::CorruptBson { offset, .. } if offset == good_len), + "expected CorruptBson for nested embedded doc at offset {good_len}, got {err:?}" + ); + + // 6. Corrupt array index inside an unused array after one valid doc + let mut arr = RawArrayBuf::new(); + arr.push(10_i32); + arr.push(20_i32); + let mut arr_bad = make_base_doc("CH-3", "arr_bad", ts_sec); + arr_bad.append(cstr!("votes"), arr); + let mut arr_bytes = arr_bad.into_bytes(); + let idx1 = arr_bytes + .windows(3) + .position(|w| w == [0x10, b'1', 0x00]) + .expect("locate index 1"); + arr_bytes[idx1 + 1] = b'2'; + + let mut combined = good.as_bytes().to_vec(); + combined.extend_from_slice(&arr_bytes); + let mut emitted = Vec::new(); + let err = decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { + emitted.push(r.spiel_id); + }) + .unwrap_err(); + assert_eq!(emitted, vec!["ok_first".to_string()]); + assert!( + matches!(err, BsonCeoPostsError::CorruptBson { offset, .. } if offset == good_len), + "expected CorruptBson for corrupt array index at offset {good_len}, got {err:?}" + ); + + // 7. Trailing bytes on decode_ceo_posts_bytes -> CorruptDocumentLength + let mut extra = good.as_bytes().to_vec(); + extra.push(0x00); + let err = decode_ceo_posts_bytes(&extra, &fields, CeoPostsTimestampUnit::Seconds, |_| {}) + .unwrap_err(); + assert!(matches!( + err, + BsonCeoPostsError::CorruptDocumentLength { .. } + )); +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 3e6ac6f0..ad00e80b 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -4,6 +4,7 @@ pub mod adj; pub mod bars; pub mod bars_1m; pub mod bench; +pub mod bson_ceo_posts; pub mod bson_ceo_shorts; pub mod bson_eod_intraday; pub mod bson_eod_prices; @@ -50,6 +51,10 @@ pub use bars_1m::{ SessionCloseCheck, SessionCloseCutoffPolicy, SessionCloseMismatchSample, SessionCloseStats, BARS_1M_SOURCE_EOD, BARS_1M_SOURCE_QM, RTH_END_MINUTE_ET, RTH_START_MINUTE_ET, }; +pub use bson_ceo_posts::{ + decode_ceo_posts_buffer, decode_ceo_posts_bytes, decode_ceo_posts_doc, + BsonCeoPostsDecodeStats, BsonCeoPostsError, CeoPostsFieldNames, CeoPostsTimestampUnit, +}; pub use bson_ceo_shorts::{ decode_ceo_shorts_buffer, decode_ceo_shorts_bytes, decode_ceo_shorts_doc, BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames, DEFAULT_KEY_FIELD, From ac12439fe28c29ac860546ce9aaa9072645238a6 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 09:36:18 -0500 Subject: [PATCH 07/21] T-160: tests --- tools/curate-etl/src/bson_ceo_posts_tests.rs | 429 ++++++++++++++++++- 1 file changed, 406 insertions(+), 23 deletions(-) diff --git a/tools/curate-etl/src/bson_ceo_posts_tests.rs b/tools/curate-etl/src/bson_ceo_posts_tests.rs index b80fd2b0..abd8a6cd 100644 --- a/tools/curate-etl/src/bson_ceo_posts_tests.rs +++ b/tools/curate-etl/src/bson_ceo_posts_tests.rs @@ -394,11 +394,13 @@ fn skips_timestamp_seconds_overflow_and_double_range_boundaries() { assert_eq!(stats.skipped_timestamp_out_of_range, 5); // Under Millis, 2^63 is still out of range. - let stats_2p63 = - decode_ceo_posts_bytes(d3.as_bytes(), &fields, CeoPostsTimestampUnit::Millis, |_| { - panic!("2^63 double must not emit") - }) - .expect("decode 2^63 under millis"); + let stats_2p63 = decode_ceo_posts_bytes( + d3.as_bytes(), + &fields, + CeoPostsTimestampUnit::Millis, + |_| panic!("2^63 double must not emit"), + ) + .expect("decode 2^63 under millis"); assert_eq!(stats_2p63.skipped_timestamp_out_of_range, 1); } @@ -702,21 +704,23 @@ fn skips_every_counter_respects_priority_and_matches_single_doc_sum() { let mut summed = BsonCeoPostsDecodeStats::default(); for doc in &docs { combined.extend_from_slice(doc.as_bytes()); - let single = - decode_ceo_posts_doc(doc.as_ref(), &fields, CeoPostsTimestampUnit::Seconds, |_| {}) - .expect("decode single doc"); + let single = decode_ceo_posts_doc( + doc.as_ref(), + &fields, + CeoPostsTimestampUnit::Seconds, + |_| {}, + ) + .expect("decode single doc"); assert_conservation(&single); summed += single; } let mut emitted = Vec::new(); - let buf_stats = decode_ceo_posts_buffer( - &combined, - &fields, - CeoPostsTimestampUnit::Seconds, - |r| emitted.push((r.spiel_id, r.bot, r.user_id, r.text)), - ) - .expect("decode combined buffer"); + let buf_stats = + decode_ceo_posts_buffer(&combined, &fields, CeoPostsTimestampUnit::Seconds, |r| { + emitted.push((r.spiel_id, r.bot, r.user_id, r.text)) + }) + .expect("decode combined buffer"); assert_conservation(&buf_stats); assert_eq!(buf_stats, summed); @@ -856,13 +860,11 @@ fn decodes_custom_field_names_and_feeds_build_posts_deterministically() { let mut rows_from_bytes = Vec::new(); let mut stats_bytes = BsonCeoPostsDecodeStats::default(); for d in &raw_docs { - stats_bytes += decode_ceo_posts_bytes( - d.as_bytes(), - &fields, - CeoPostsTimestampUnit::Seconds, - |r| rows_from_bytes.push(r), - ) - .expect("decode bytes"); + stats_bytes += + decode_ceo_posts_bytes(d.as_bytes(), &fields, CeoPostsTimestampUnit::Seconds, |r| { + rows_from_bytes.push(r) + }) + .expect("decode bytes"); } let mut rows_from_doc = Vec::new(); @@ -893,7 +895,10 @@ fn decodes_custom_field_names_and_feeds_build_posts_deterministically() { .collect(); let retail_ids: Vec<&str> = build1.retail.iter().map(|r| r.spiel_id.as_str()).collect(); assert_eq!(newswire_ids, vec!["nw_str_1", "nw_bool_true", "nw_i32_1"]); - assert_eq!(retail_ids, vec!["ret_str_0", "ret_absent", "ret_wrong_type"]); + assert_eq!( + retail_ids, + vec!["ret_str_0", "ret_absent", "ret_wrong_type"] + ); assert_eq!(build1.stats.rejected_invalid, 1); // Baseline unedited post: known_at == posted_at. @@ -1068,3 +1073,381 @@ fn framing_and_structural_corruption_fail_closed_with_exact_offsets() { BsonCeoPostsError::CorruptDocumentLength { .. } )); } + +// --------------------------------------------------------------------------- +// QA edge cases (T-160) +// --------------------------------------------------------------------------- + +fn decode_one_seconds_and_millis( + doc: &RawDocumentBuf, +) -> [(BsonCeoPostsDecodeStats, Vec>); 2] { + let fields = CeoPostsFieldNames::default(); + [ + CeoPostsTimestampUnit::Seconds, + CeoPostsTimestampUnit::Millis, + ] + .map(|unit| { + let mut rows = Vec::new(); + let stats = decode_ceo_posts_bytes(doc.as_bytes(), &fields, unit, |r| { + rows.push(CeoPost { + key: r.key.to_owned(), + spiel_id: r.spiel_id, + timestamp_ms: r.timestamp_ms, + edited_ms: r.edited_ms, + bot: r.bot, + user_id: r.user_id, + text: r.text, + }) + }) + .expect("decode single doc"); + assert_conservation(&stats); + (stats, rows) + }) +} + +#[test] +fn same_numeric_bytes_scale_by_unit_but_datetime_ignores_unit() { + // Arrange: numeric Int64 timestamp/edited and a DateTime doc. + let mut numeric = make_base_doc("CH", "n", 1_710_460_800); + numeric.append(cstr!("edited"), 1_710_461_400_i64); + let mut dt_doc = RawDocumentBuf::new(); + dt_doc.append(cstr!("ceoId"), "CH"); + dt_doc.append(cstr!("spielId"), "d"); + dt_doc.append( + cstr!("timestamp"), + BsonDateTime::from_millis(1_710_460_800_000), + ); + dt_doc.append( + cstr!("edited"), + BsonDateTime::from_millis(1_710_461_400_000), + ); + + // Act + let [(_, n_sec), (_, n_ms)] = decode_one_seconds_and_millis(&numeric); + let [(_, d_sec), (_, d_ms)] = decode_one_seconds_and_millis(&dt_doc); + + // Assert: numeric values differ by exactly 1000x; DateTime is identical under both units. + assert_eq!(n_sec[0].timestamp_ms, 1_710_460_800_000); + assert_eq!(n_sec[0].edited_ms, Some(1_710_461_400_000)); + assert_eq!(n_ms[0].timestamp_ms, 1_710_460_800); + assert_eq!(n_ms[0].edited_ms, Some(1_710_461_400)); + assert_eq!(d_sec, d_ms); + assert_eq!(d_sec[0].timestamp_ms, 1_710_460_800_000); + assert_eq!(d_sec[0].edited_ms, Some(1_710_461_400_000)); +} + +#[test] +fn edited_rejections_hold_under_millis_and_large_millis_values_do_not_overflow() { + // Negative/fractional/true/string edits must also fail closed under Millis. + let bad: Vec = vec![ + RawBson::Int32(-1), + RawBson::Int64(i64::MIN), + RawBson::Double(-0.5), + RawBson::Double(0.5), + RawBson::Double(f64::NEG_INFINITY), + RawBson::Boolean(true), + RawBson::String(String::new()), + RawBson::Double(9_223_372_036_854_775_808.0), + ]; + for value in bad { + let mut d = make_base_doc("CH", "x", 1_710_460_800_000); + d.append(cstr!("edited"), value.clone()); + let [_, (stats, rows)] = decode_one_seconds_and_millis(&d); + assert!( + rows.is_empty(), + "edited {value:?} must not emit under Millis" + ); + assert_eq!(stats.skipped_invalid_edited, 1, "edited {value:?}"); + } + + // A value that overflows under Seconds is valid under Millis. + let mut d = make_base_doc("CH", "big", 1); + d.append(cstr!("edited"), i64::MAX); + let [(sec_stats, sec_rows), (ms_stats, ms_rows)] = decode_one_seconds_and_millis(&d); + assert!(sec_rows.is_empty()); + assert_eq!(sec_stats.skipped_invalid_edited, 1); + assert_eq!(ms_stats.rows_out, 1); + assert_eq!(ms_rows[0].edited_ms, Some(i64::MAX)); +} + +#[test] +fn bot_and_user_id_normalization_covers_int64_false_null_and_verbatim_strings() { + let cases: Vec<(RawBson, Option<&str>, usize)> = vec![ + (RawBson::Int64(1), Some("1"), 0), + (RawBson::Int32(-7), Some("-7"), 0), + (RawBson::Boolean(false), Some("0"), 0), + (RawBson::Null, None, 0), + (RawBson::String(" 1 ".into()), Some(" 1 "), 0), + (RawBson::Document(RawDocumentBuf::new()), None, 1), + ]; + for (value, expected, nulled) in cases { + let mut d = make_base_doc("CH", "b", 1_710_460_800); + d.append(cstr!("bot"), value.clone()); + d.append(cstr!("userId"), value.clone()); + let [(stats, rows), _] = decode_one_seconds_and_millis(&d); + assert_eq!(stats.rows_out, 1, "bot {value:?}"); + assert_eq!(rows[0].bot.as_deref(), expected, "bot {value:?}"); + assert_eq!(stats.nulled_wrong_type_bot, nulled, "bot {value:?}"); + let expected_user = match value { + // Boolean is not an accepted user_id type. + RawBson::Boolean(_) => None, + _ => expected, + }; + let expected_user_nulled = usize::from(matches!(value, RawBson::Boolean(_))) + nulled; + assert_eq!( + rows[0].user_id.as_deref(), + expected_user, + "userId {value:?}" + ); + assert_eq!( + stats.nulled_wrong_type_user_id, expected_user_nulled, + "userId {value:?}" + ); + } +} + +#[test] +fn preserves_unicode_text_and_key_verbatim_and_key_borrows_from_single_doc_bytes() { + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "Ünïcødé-CH 📈"); + d.append(cstr!("spielId"), " s 1 "); + d.append(cstr!("timestamp"), 1_710_460_800_i64); + d.append(cstr!("spiel"), " $XYZ to the 🌕\nline2\t "); + let bytes = d.as_bytes(); + let (start, end) = ( + bytes.as_ptr() as usize, + bytes.as_ptr() as usize + bytes.len(), + ); + + let mut seen = Vec::new(); + decode_ceo_posts_bytes( + bytes, + &CeoPostsFieldNames::default(), + CeoPostsTimestampUnit::Seconds, + |r| { + let p = r.key.as_ptr() as usize; + assert!( + p >= start && p + r.key.len() <= end, + "key must borrow from input bytes" + ); + seen.push((r.key, r.spiel_id, r.text)); + }, + ) + .expect("decode"); + + assert_eq!( + seen, + vec![( + "Ünïcødé-CH 📈", + " s 1 ".to_string(), + " $XYZ to the 🌕\nline2\t ".to_string() + )] + ); +} + +#[test] +fn spiel_id_int64_extremes_render_as_decimal() { + for (value, expected) in [ + (RawBson::Int64(i64::MIN), i64::MIN.to_string()), + (RawBson::Int64(i64::MAX), i64::MAX.to_string()), + (RawBson::Int32(0), "0".to_string()), + ] { + let mut d = RawDocumentBuf::new(); + d.append(cstr!("ceoId"), "CH"); + d.append(cstr!("spielId"), value); + d.append(cstr!("timestamp"), 1_i64); + let [(_, rows), _] = decode_one_seconds_and_millis(&d); + assert_eq!(rows[0].spiel_id, expected); + } +} + +#[test] +fn invalid_utf8_in_unused_or_key_field_is_corrupt_bson_not_a_skip() { + let fields = CeoPostsFieldNames::default(); + for marker in ["ceoId", "extra"] { + let mut d = make_base_doc("KEYVAL", "s", 1_710_460_800); + d.append(cstr!("extra"), "EXTRAV"); + let mut bytes = d.into_bytes(); + let needle: &[u8] = if marker == "ceoId" { + b"KEYVAL" + } else { + b"EXTRAV" + }; + let pos = bytes.windows(6).position(|w| w == needle).expect("needle"); + bytes[pos] = 0xff; + + let mut emitted = 0; + let err = decode_ceo_posts_buffer(&bytes, &fields, CeoPostsTimestampUnit::Seconds, |_| { + emitted += 1 + }) + .unwrap_err(); + assert_eq!(emitted, 0, "{marker}"); + assert!( + matches!(err, BsonCeoPostsError::CorruptBson { offset: 0, .. }), + "{marker}: {err:?}" + ); + } +} + +#[test] +fn corruption_in_first_document_reports_offset_zero_and_emits_nothing() { + let fields = CeoPostsFieldNames::default(); + let good = make_base_doc("CH", "after", 1_710_460_800); + let mut buf = vec![3, 0, 0, 0, 0]; + buf.extend_from_slice(good.as_bytes()); + let mut emitted = 0; + let err = decode_ceo_posts_buffer(&buf, &fields, CeoPostsTimestampUnit::Seconds, |_| { + emitted += 1 + }) + .unwrap_err(); + assert_eq!(emitted, 0); + assert_eq!( + err, + BsonCeoPostsError::CorruptDocumentLength { + offset: 0, + declared_len: 3 + } + ); +} + +#[test] +fn excessive_nesting_fails_closed_without_stack_overflow_and_moderate_nesting_decodes() { + fn nested(depth: usize) -> RawDocumentBuf { + let mut inner = RawDocumentBuf::new(); + inner.append(cstr!("leaf"), 1_i32); + for _ in 0..depth { + let mut outer = RawDocumentBuf::new(); + outer.append(cstr!("n"), inner); + inner = outer; + } + inner + } + let fields = CeoPostsFieldNames::default(); + + let mut ok = make_base_doc("CH", "shallow", 1_710_460_800); + ok.append(cstr!("meta"), nested(10)); + let stats = decode_ceo_posts_bytes( + ok.as_bytes(), + &fields, + CeoPostsTimestampUnit::Seconds, + |_| {}, + ) + .expect("moderate nesting decodes"); + assert_eq!(stats.rows_out, 1); + + let mut deep = make_base_doc("CH", "deep", 1_710_460_800); + deep.append(cstr!("meta"), nested(400)); + let err = decode_ceo_posts_bytes( + deep.as_bytes(), + &fields, + CeoPostsTimestampUnit::Seconds, + |_| panic!("deep nesting must not emit"), + ) + .unwrap_err(); + assert!( + matches!(err, BsonCeoPostsError::CorruptBson { offset: 0, .. }), + "{err:?}" + ); +} + +#[test] +fn empty_buffer_yields_zero_stats() { + let stats = decode_ceo_posts_buffer( + &[], + &CeoPostsFieldNames::default(), + CeoPostsTimestampUnit::Millis, + |_| panic!("no rows"), + ) + .expect("empty buffer ok"); + assert_eq!(stats, BsonCeoPostsDecodeStats::default()); +} + +#[test] +fn add_assign_sums_every_counter() { + let a = BsonCeoPostsDecodeStats { + docs_in: 1, + rows_out: 2, + skipped_missing_key: 3, + skipped_wrong_key_type: 4, + skipped_empty_key: 5, + skipped_missing_spiel_id: 6, + skipped_wrong_spiel_id_type: 7, + skipped_empty_spiel_id: 8, + skipped_missing_timestamp: 9, + skipped_wrong_timestamp_type: 10, + skipped_invalid_timestamp: 11, + skipped_timestamp_out_of_range: 12, + skipped_invalid_edited: 13, + skipped_wrong_text_type: 14, + edited_zero_or_false: 15, + nulled_wrong_type_bot: 16, + nulled_wrong_type_user_id: 17, + empty_text: 18, + }; + let mut sum = a; + sum += a; + let doubled = BsonCeoPostsDecodeStats { + docs_in: 2, + rows_out: 4, + skipped_missing_key: 6, + skipped_wrong_key_type: 8, + skipped_empty_key: 10, + skipped_missing_spiel_id: 12, + skipped_wrong_spiel_id_type: 14, + skipped_empty_spiel_id: 16, + skipped_missing_timestamp: 18, + skipped_wrong_timestamp_type: 20, + skipped_invalid_timestamp: 22, + skipped_timestamp_out_of_range: 24, + skipped_invalid_edited: 26, + skipped_wrong_text_type: 28, + edited_zero_or_false: 30, + nulled_wrong_type_bot: 32, + nulled_wrong_type_user_id: 34, + empty_text: 36, + }; + assert_eq!(sum, doubled); + // skipped_total excludes docs_in, rows_out and emitted-row counters: 3+..+14 = 102. + assert_eq!(a.skipped_total(), 102); +} + +#[test] +fn edited_text_is_excluded_at_a_cutoff_between_post_and_edit() { + // Point-in-time check: a consumer filtering `known_at < cutoff` must not see edited text + // whose edit happened after the cutoff, while an unedited post at the same time is visible. + let posted = 1_710_460_800_i64; // seconds + let edit = posted + 600; + let cutoff_us = (posted + 300) * 1_000_000; + + let mut unedited = make_base_doc("CH", "plain", posted); + unedited.append(cstr!("edited"), 0_i32); + let mut edited = make_base_doc("CH", "edited", posted); + edited.append(cstr!("edited"), edit); + let mut buf = unedited.into_bytes(); + buf.extend_from_slice(edited.as_bytes()); + + let mut rows = Vec::new(); + decode_ceo_posts_buffer( + &buf, + &CeoPostsFieldNames::default(), + CeoPostsTimestampUnit::Seconds, + |r| rows.push(r), + ) + .expect("decode"); + let built = build_posts(rows).expect("build"); + + let visible: Vec<&str> = built + .retail + .iter() + .filter(|r| r.known_at < cutoff_us) + .map(|r| r.spiel_id.as_str()) + .collect(); + assert_eq!(visible, vec!["plain"]); + let late = built + .retail + .iter() + .find(|r| r.spiel_id == "edited") + .expect("edited row"); + assert_eq!(late.known_at, edit * 1_000_000); + assert_eq!(late.posted_at, posted * 1_000_000); +} From 5654b9cc0519ee6b53b88dc0c45acfde55dd9226 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 09:35:55 -0500 Subject: [PATCH 08/21] =?UTF-8?q?T-161:=20M2.1j=20(re-queue)=20=E2=80=94?= =?UTF-8?q?=20PostgreSQL=20findings=20adapter=20for=20the=20MCP=20copilot:?= =?UTF-8?q?=20`FindingWritePort`=20(atomic=20idempotent=20append)=20+=20`l?= =?UTF-8?q?istFindings`=20/=20`listProviderCaveats`=20readers=20over=20an?= =?UTF-8?q?=20injected=20executor=20in=20`libs/research/src/mcp/adapters/p?= =?UTF-8?q?ostgres-findings.ts`=20(no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/README.md | 7 + .../src/mcp/adapters/postgres-findings.ts | 653 +++++++++++++++++ libs/research/src/mcp/index.ts | 1 + .../test/mcp-postgres-findings.test.ts | 674 ++++++++++++++++++ test/postgres/mcp-findings-adapter.test.ts | 537 ++++++++++++++ 5 files changed, 1872 insertions(+) create mode 100644 libs/research/src/mcp/adapters/postgres-findings.ts create mode 100644 libs/research/test/mcp-postgres-findings.test.ts create mode 100644 test/postgres/mcp-findings-adapter.test.ts diff --git a/libs/research/README.md b/libs/research/README.md index cf49f406..2de5f04b 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -264,6 +264,13 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported - **`delistedAt` derivation:** Projects `delistedAt` as `listing.listed_to` (`YYYY-MM-DD`) when `delist_reason IS NOT NULL AND delist_reason <> 'active'`, else `null`. When `q.includeDelisted === false`, rows with non-null `delistedAt <= cutoff` are filtered out while future delistings (`delistedAt > cutoff`) remain eligible as of the cutoff. - **Port matching vs. MCP ranking:** The adapter matches on resolved as-of ticker (`ILIKE`), `listing.ticker_root` (`ILIKE`, gated by `NOT root_is_future`), `instrument.canonical_name` (`ILIKE`), or case-insensitive exact `instrument.primary_isin`, ignores `q.limit`, and returns all candidates ordered by `listing_id ASC`. When composed with `createSearchSymbolsTool`, the MCP tool applies Vault clamping/masking, ranks by exact ticker > ticker prefix > company name substring (tie-breaking by `listingId ASC`), and truncates to `limit` — so callers needing ticker-substring, root-only, or exact-ISIN lookups should call the port directly, while MCP tool callers should query by ticker or company name. +### PostgreSQL Findings & Provider Caveats Adapter + +- **`createPostgresFindingWritePort({ executor, schema? })`** and **`createPostgresKnowledgeReaders({ executor, schema? })`** (exported from `@stock-bot/research/mcp` alongside `PostgresFindingsExecutor`, `PostgresFindingsOptions`, `PostgresKnowledgeReaders`, `PostgresFindingsError`, and `PostgresFindingsErrorCode`) back `file_finding` (`FindingWritePort`) and the `findings` / `provider_caveats` halves of `read_knowledge` (`Pick`) over `37-research-findings.sql` with zero runtime `pg` dependency. +- **Inputs, schema & row validation:** Validates `executor.query` (`INVALID_EXECUTOR`) and optional `schema` against `^[a-z_][a-z0-9_]*$` (`INVALID_SCHEMA`; defaults to the executor's `search_path`), binds every caller value via `$n` parameters, issues zero `UPDATE`/`DELETE` statements, and fails closed (`INVALID_ROW`) on malformed result envelopes, non-1D/non-string ref arrays, unknown `kind`, or invalid timestamps (converting PostgreSQL `Date` values or strictly parsed timezone-qualified ISO-8601 strings to UTC ISO-8601 output). +- **Atomic idempotency & fresh-snapshot requirement:** Unkeyed appends execute a plain `INSERT ... RETURNING id, created_at`. Keyed appends use `INSERT ... ON CONFLICT (idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING RETURNING id, created_at` followed by a separate keyed `SELECT` on zero rows (and on same-ID `23505` primary-key retries), comparing normalized `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs` via `areFiledFindingPayloadsEqual`. Pass a fresh-snapshot `READ COMMITTED` executor (such as a `pg.Pool`, not a `REPEATABLE READ`/`SERIALIZABLE` transaction) so concurrent callers can observe the committed winner. +- **Reader filtering & research-visible corpus boundary:** `listFindings` and `listProviderCaveats` push down case-sensitive exact `id` (taking precedence over `query`), escaped `ILIKE` substring matching (`%`, `_`, `\`), and `lower(provider) = lower($n::text)` (matching `idx_provider_caveats_lower_provider`), returning all eligible rows ordered by `id ASC` with no `LIMIT` so `createReadKnowledgeTool` owns ranking and global limits. Because `findings` and `provider_caveats` carry no Vault visibility column, callers must bind the adapter to a research-visible corpus and keep `createFileFindingTool` responsible for verifying `trialRefs` via `trialLookup` before writing. + ### 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/postgres-findings.ts b/libs/research/src/mcp/adapters/postgres-findings.ts new file mode 100644 index 00000000..38bfdfb9 --- /dev/null +++ b/libs/research/src/mcp/adapters/postgres-findings.ts @@ -0,0 +1,653 @@ +/** + * PostgreSQL adapter for the MCP copilot findings and provider caveats tables + * (`37-research-findings.sql`), implementing {@link FindingWritePort} for + * `file_finding` and the `listFindings` / `listProviderCaveats` readers of + * {@link KnowledgePort} for `read_knowledge`. + * + * Dependency-free (no `pg`, no `node:*`, no bare `process`): SQL execution is + * injected via {@link PostgresFindingsExecutor}. + */ + +import { + type AppendFindingResult, + FILE_FINDING_KINDS, + type FileFindingKind, + type FiledFindingComparablePayload, + type FiledFindingRecord, + type FindingWritePort, + areFiledFindingPayloadsEqual, +} from '../tools/file-finding'; +import type { + FindingQuery, + FindingRecord, + KnowledgePort, + ProviderCaveatQuery, + ProviderCaveatRecord, +} from '../tools/read-knowledge'; +import { MAX_ECMASCRIPT_EPOCH_MS } from '../tools/vault-fenced-input'; + +const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/; +const ISO_INSTANT_RE = + /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|([+-])(\d{2}):(\d{2}))$/; +const DAYS_IN_MONTH: readonly number[] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +const FILE_FINDING_KIND_SET: ReadonlySet = new Set(FILE_FINDING_KINDS); + +/** Error codes thrown by {@link PostgresFindingsError}. */ +export type PostgresFindingsErrorCode = 'INVALID_EXECUTOR' | 'INVALID_SCHEMA' | 'INVALID_ROW'; + +/** Typed validation error thrown by the PostgreSQL findings adapter. */ +export class PostgresFindingsError extends RangeError { + readonly code: PostgresFindingsErrorCode; + + constructor(code: PostgresFindingsErrorCode, message: string) { + super(message); + this.name = 'PostgresFindingsError'; + this.code = code; + Object.setPrototypeOf(this, new.target.prototype); + } +} + +/** + * Structural `pg.Pool` / `pg.PoolClient`-compatible query interface so this module + * has no runtime dependency on `pg` and is unit-testable with a fake executor. + * + * For {@link createPostgresFindingWritePort}, the executor should run each call on + * a fresh `READ COMMITTED` snapshot (such as a `pg.Pool`) rather than inside a + * `REPEATABLE READ` / `SERIALIZABLE` transaction so concurrent idempotent callers + * can observe the committed winner after `ON CONFLICT ... DO NOTHING`. + */ +export interface PostgresFindingsExecutor { + query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }>; +} + +/** Factory options for {@link createPostgresFindingWritePort} and {@link createPostgresKnowledgeReaders}. */ +export interface PostgresFindingsOptions { + readonly executor: PostgresFindingsExecutor; + /** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */ + readonly schema?: string; +} + +/** PostgreSQL-backed subset of {@link KnowledgePort} (`findings` and `provider_caveats`). */ +export type PostgresKnowledgeReaders = Pick; + +interface RawFindingReceiptRow { + readonly id: unknown; + readonly created_at: unknown; +} + +interface RawStoredFindingForReplayRow { + readonly id: unknown; + readonly kind: unknown; + readonly title: unknown; + readonly summary: unknown; + readonly created_at: unknown; + readonly trial_refs: unknown; + readonly evidence_refs: unknown; +} + +interface RawFindingRow { + readonly id: unknown; + readonly title: unknown; + readonly status: unknown; + readonly created_at: unknown; + readonly summary: unknown; + readonly trial_refs: unknown; + readonly evidence_refs: unknown; +} + +interface RawProviderCaveatRow { + readonly id: unknown; + readonly provider: unknown; + readonly dataset: unknown; + readonly caveat: unknown; + readonly created_at: unknown; +} + +function isLeapYear(year: number): boolean { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +function daysInUtcMonth(year: number, monthIndex: number): number { + if (monthIndex === 1 && isLeapYear(year)) { + return 29; + } + return DAYS_IN_MONTH[monthIndex] ?? 0; +} + +function utcDateMs( + year: number, + monthIndex: number, + day: number, + hours: number, + minutes: number, + seconds: number, + ms: number +): number { + const date = new Date(0); + date.setUTCFullYear(year, monthIndex, day); + date.setUTCHours(hours, minutes, seconds, ms); + return date.getTime(); +} + +function escapeLikePattern(value: string): string { + return value.replace(/[\\%_]/g, '\\$&'); +} + +function quoteTable(schemaPrefix: string, table: string): string { + return `${schemaPrefix}${table}`; +} + +function validateFactoryOptions(options: PostgresFindingsOptions): { + readonly executor: PostgresFindingsExecutor; + readonly schemaPrefix: string; +} { + if (typeof options !== 'object' || options === null) { + throw new PostgresFindingsError( + 'INVALID_EXECUTOR', + 'Invalid options: expected an object with a PostgresFindingsExecutor.' + ); + } + + const { executor, schema } = options; + if (typeof executor !== 'object' || executor === null || typeof executor.query !== 'function') { + throw new PostgresFindingsError( + 'INVALID_EXECUTOR', + 'Invalid executor: expected an object with a callable query(text, params?) method.' + ); + } + + if (schema === undefined) { + return { executor, schemaPrefix: '' }; + } + + if (typeof schema !== 'string' || !SCHEMA_IDENT_RE.test(schema)) { + throw new PostgresFindingsError( + 'INVALID_SCHEMA', + 'Invalid schema: expected an identifier matching ^[a-z_][a-z0-9_]*$.' + ); + } + + return { executor, schemaPrefix: `"${schema}".` }; +} + +function extractRows(result: unknown): readonly Row[] { + if ( + typeof result !== 'object' || + result === null || + !Array.isArray((result as { readonly rows?: unknown }).rows) + ) { + throw new PostgresFindingsError( + 'INVALID_ROW', + 'Invalid executor response: expected an object with a rows array.' + ); + } + return (result as { readonly rows: readonly Row[] }).rows; +} + +function parseNonEmptyString(value: unknown, field: string): string { + if (typeof value !== 'string' || value.trim().length === 0) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" must be a non-empty string.` + ); + } + return value; +} + +function parseFindingKind(value: unknown): FileFindingKind { + if (typeof value !== 'string' || !FILE_FINDING_KIND_SET.has(value)) { + throw new PostgresFindingsError( + 'INVALID_ROW', + 'Invalid findings row: "kind" must be "finding" or "dead_end".' + ); + } + return value as FileFindingKind; +} + +function parseStringArray(value: unknown, field: string): readonly string[] { + if (!Array.isArray(value)) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" must be a one-dimensional string array.` + ); + } + const result: string[] = []; + for (let i = 0; i < value.length; i += 1) { + const entry: unknown = value[i]; + if (typeof entry !== 'string') { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}[${i}]" must be a string.` + ); + } + result.push(entry); + } + return result; +} + +function parseTimestampIso(value: unknown, field: string): string { + if (value instanceof Date) { + const ms = value.getTime(); + if (!Number.isFinite(ms) || Math.abs(ms) >= MAX_ECMASCRIPT_EPOCH_MS) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" must be a finite Date.` + ); + } + return new Date(ms).toISOString(); + } + + if (typeof value !== 'string') { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" must be a Date or timezone-qualified ISO-8601 timestamp string.` + ); + } + + const match = ISO_INSTANT_RE.exec(value); + if (match === null) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" must be a timezone-qualified ISO-8601 timestamp string.` + ); + } + + const year = Number(match[1]); + const month = Number(match[2]); + const day = Number(match[3]); + const hours = Number(match[4]); + const minutes = Number(match[5]); + const seconds = Number(match[6]); + const fractional = match[7]; + const tzToken = match[8]; + const tzSign = match[9]; + const tzHoursRaw = match[10]; + const tzMinutesRaw = match[11]; + + if (month < 1 || month > 12) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" has an out-of-range calendar month.` + ); + } + const maxDay = daysInUtcMonth(year, month - 1); + if (day < 1 || day > maxDay) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" has an out-of-range calendar day.` + ); + } + if (hours > 23 || minutes > 59 || seconds > 59) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" has an out-of-range time of day.` + ); + } + + let ms = 0; + if (fractional !== undefined) { + ms = Number(fractional.slice(0, 3).padEnd(3, '0')); + } + + let offsetMs = 0; + if (tzToken !== 'Z') { + const offsetHours = Number(tzHoursRaw); + const offsetMinutes = Number(tzMinutesRaw); + if (offsetHours > 23 || offsetMinutes > 59) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" has an out-of-range timezone offset.` + ); + } + const sign = tzSign === '+' ? 1 : -1; + offsetMs = sign * (offsetHours * 60 + offsetMinutes) * 60_000; + } + + const epochMs = utcDateMs(year, month - 1, day, hours, minutes, seconds, ms) - offsetMs; + if (!Number.isFinite(epochMs) || Math.abs(epochMs) >= MAX_ECMASCRIPT_EPOCH_MS) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Invalid findings row: "${field}" is outside the valid ECMAScript timestamp range.` + ); + } + + return new Date(epochMs).toISOString(); +} + +function parseReceiptRow(raw: unknown): { readonly id: string; readonly createdAt: string } { + if (typeof raw !== 'object' || raw === null) { + throw new PostgresFindingsError( + 'INVALID_ROW', + 'Invalid findings receipt row: expected a non-null object.' + ); + } + const row = raw as RawFindingReceiptRow; + return { + id: parseNonEmptyString(row.id, 'id'), + createdAt: parseTimestampIso(row.created_at, 'created_at'), + }; +} + +function parseStoredFindingForReplayRow(raw: unknown): { + readonly id: string; + readonly createdAt: string; + readonly payload: FiledFindingComparablePayload; +} { + if (typeof raw !== 'object' || raw === null) { + throw new PostgresFindingsError( + 'INVALID_ROW', + 'Invalid findings replay row: expected a non-null object.' + ); + } + const row = raw as RawStoredFindingForReplayRow; + const id = parseNonEmptyString(row.id, 'id'); + const kind = parseFindingKind(row.kind); + const title = parseNonEmptyString(row.title, 'title'); + const summary = parseNonEmptyString(row.summary, 'summary'); + const createdAt = parseTimestampIso(row.created_at, 'created_at'); + const trialRefs = parseStringArray(row.trial_refs, 'trial_refs'); + const evidenceRefs = parseStringArray(row.evidence_refs, 'evidence_refs'); + + return { + id, + createdAt, + payload: { + kind, + title, + summary, + trialRefs, + evidenceRefs, + }, + }; +} + +function parseFindingRow(raw: unknown): FindingRecord { + if (typeof raw !== 'object' || raw === null) { + throw new PostgresFindingsError( + 'INVALID_ROW', + 'Invalid findings row: expected a non-null object.' + ); + } + const row = raw as RawFindingRow; + return { + id: parseNonEmptyString(row.id, 'id'), + title: parseNonEmptyString(row.title, 'title'), + status: parseNonEmptyString(row.status, 'status'), + createdAt: parseTimestampIso(row.created_at, 'created_at'), + summary: parseNonEmptyString(row.summary, 'summary'), + trialRefs: parseStringArray(row.trial_refs, 'trial_refs'), + evidenceRefs: parseStringArray(row.evidence_refs, 'evidence_refs'), + }; +} + +function parseProviderCaveatRow(raw: unknown): ProviderCaveatRecord { + if (typeof raw !== 'object' || raw === null) { + throw new PostgresFindingsError( + 'INVALID_ROW', + 'Invalid provider_caveats row: expected a non-null object.' + ); + } + const row = raw as RawProviderCaveatRow; + return { + id: parseNonEmptyString(row.id, 'id'), + provider: parseNonEmptyString(row.provider, 'provider'), + dataset: parseNonEmptyString(row.dataset, 'dataset'), + caveat: parseNonEmptyString(row.caveat, 'caveat'), + createdAt: parseTimestampIso(row.created_at, 'created_at'), + }; +} + +function isPostgresUniqueViolation(err: unknown): boolean { + return ( + typeof err === 'object' && + err !== null && + (err as { readonly code?: unknown }).code === '23505' + ); +} + +function buildInsertFindingSql(schemaPrefix: string, keyed: boolean): string { + const findingsTable = quoteTable(schemaPrefix, 'findings'); + const lines = [ + `INSERT INTO ${findingsTable} (`, + ' id,', + ' kind,', + ' title,', + ' summary,', + ' status,', + ' created_at,', + ' trial_refs,', + ' evidence_refs,', + ' idempotency_key', + ')', + 'VALUES ($1, $2, $3, $4, $5, $6::timestamptz, $7::text[], $8::text[], $9)', + ]; + if (keyed) { + lines.push('ON CONFLICT (idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING'); + } + lines.push('RETURNING id, created_at'); + return lines.join('\n'); +} + +function buildSelectByIdempotencyKeySql(schemaPrefix: string): string { + const findingsTable = quoteTable(schemaPrefix, 'findings'); + return [ + 'SELECT', + ' id,', + ' kind,', + ' title,', + ' summary,', + ' created_at,', + ' trial_refs,', + ' evidence_refs', + `FROM ${findingsTable}`, + 'WHERE idempotency_key = $1::text', + ].join('\n'); +} + +/** + * Creates an append-only PostgreSQL {@link FindingWritePort} backed by the + * `findings` table (`37-research-findings.sql`). + */ +export function createPostgresFindingWritePort(options: PostgresFindingsOptions): FindingWritePort { + const { executor, schemaPrefix } = validateFactoryOptions(options); + const unkeyedInsertSql = buildInsertFindingSql(schemaPrefix, false); + const keyedInsertSql = buildInsertFindingSql(schemaPrefix, true); + const selectByKeySql = buildSelectByIdempotencyKeySql(schemaPrefix); + + return { + async appendFinding( + record: FiledFindingRecord, + idempotencyKey?: string + ): Promise { + const insertParams: readonly unknown[] = [ + record.id, + record.kind, + record.title, + record.summary, + record.status, + record.createdAt, + [...record.trialRefs], + [...record.evidenceRefs], + idempotencyKey ?? null, + ]; + + if (idempotencyKey === undefined) { + const result = await executor.query(unkeyedInsertSql, insertParams); + const rows = extractRows(result); + if (rows.length !== 1) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Expected 1 inserted findings row, received ${rows.length}.` + ); + } + const receipt = parseReceiptRow(rows[0]); + return { + status: 'created', + id: receipt.id, + createdAt: receipt.createdAt, + }; + } + + let insertRows: readonly RawFindingReceiptRow[]; + try { + const result = await executor.query(keyedInsertSql, insertParams); + insertRows = extractRows(result); + } catch (err) { + if (!isPostgresUniqueViolation(err)) { + throw err; + } + // A concurrent same-ID retry can collide on the primary key before the + // partial idempotency_key index; resolve only if the stored row for this + // key has the exact same ID, otherwise propagate the primary-key error. + const lookupResult = await executor.query(selectByKeySql, [ + idempotencyKey, + ]); + const lookupRows = extractRows(lookupResult); + if (lookupRows.length === 0) { + throw err; + } + if (lookupRows.length > 1) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Expected at most 1 stored finding for idempotency_key, received ${lookupRows.length}.` + ); + } + const stored = parseStoredFindingForReplayRow(lookupRows[0]); + if (stored.id !== record.id) { + throw err; + } + return areFiledFindingPayloadsEqual(stored.payload, record) + ? { status: 'replayed', id: stored.id, createdAt: stored.createdAt } + : { status: 'conflict' }; + } + + if (insertRows.length === 1) { + const receipt = parseReceiptRow(insertRows[0]); + return { + status: 'created', + id: receipt.id, + createdAt: receipt.createdAt, + }; + } + + if (insertRows.length > 1) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Expected 0 or 1 inserted findings rows, received ${insertRows.length}.` + ); + } + + // Separate SELECT on a fresh READ COMMITTED snapshot so a concurrent winner + // committed during ON CONFLICT DO NOTHING is visible. + const winnerResult = await executor.query(selectByKeySql, [ + idempotencyKey, + ]); + const winnerRows = extractRows(winnerResult); + if (winnerRows.length !== 1) { + throw new PostgresFindingsError( + 'INVALID_ROW', + `Expected 1 stored finding for idempotency_key after conflict, received ${winnerRows.length}.` + ); + } + + const stored = parseStoredFindingForReplayRow(winnerRows[0]); + return areFiledFindingPayloadsEqual(stored.payload, record) + ? { status: 'replayed', id: stored.id, createdAt: stored.createdAt } + : { status: 'conflict' }; + }, + }; +} + +/** + * Creates read-only PostgreSQL readers (`listFindings` and `listProviderCaveats`) + * for composing {@link KnowledgePort} in `read_knowledge`. + */ +export function createPostgresKnowledgeReaders( + options: PostgresFindingsOptions +): PostgresKnowledgeReaders { + const { executor, schemaPrefix } = validateFactoryOptions(options); + const findingsTable = quoteTable(schemaPrefix, 'findings'); + const caveatsTable = quoteTable(schemaPrefix, 'provider_caveats'); + + return { + async listFindings(q: FindingQuery): Promise { + const lines = [ + 'SELECT', + ' id,', + ' title,', + ' status,', + ' created_at,', + ' summary,', + ' trial_refs,', + ' evidence_refs', + `FROM ${findingsTable}`, + ]; + const params: unknown[] = []; + + if (q.id !== undefined) { + params.push(q.id); + lines.push('WHERE id = $1::text'); + } else if (q.query !== undefined) { + params.push(`%${escapeLikePattern(q.query)}%`); + lines.push("WHERE title ILIKE $1::text ESCAPE '\\' OR summary ILIKE $1::text ESCAPE '\\'"); + } + + lines.push('ORDER BY id ASC'); + + const result = await executor.query(lines.join('\n'), params); + const rows = extractRows(result); + const mapped: FindingRecord[] = []; + for (let i = 0; i < rows.length; i += 1) { + mapped.push(parseFindingRow(rows[i])); + } + return mapped; + }, + + async listProviderCaveats(q: ProviderCaveatQuery): Promise { + const lines = [ + 'SELECT', + ' id,', + ' provider,', + ' dataset,', + ' caveat,', + ' created_at', + `FROM ${caveatsTable}`, + ]; + const conditions: string[] = []; + const params: unknown[] = []; + + if (q.provider !== undefined) { + params.push(q.provider); + conditions.push(`lower(provider) = lower($${params.length}::text)`); + } + + if (q.id !== undefined) { + params.push(q.id); + conditions.push(`id = $${params.length}::text`); + } else if (q.query !== undefined) { + params.push(`%${escapeLikePattern(q.query)}%`); + const idx = params.length; + conditions.push( + `(provider ILIKE $${idx}::text ESCAPE '\\' OR dataset ILIKE $${idx}::text ESCAPE '\\' OR caveat ILIKE $${idx}::text ESCAPE '\\')` + ); + } + + if (conditions.length > 0) { + lines.push(`WHERE ${conditions.join(' AND ')}`); + } + + lines.push('ORDER BY id ASC'); + + const result = await executor.query(lines.join('\n'), params); + const rows = extractRows(result); + const mapped: ProviderCaveatRecord[] = []; + for (let i = 0; i < rows.length; i += 1) { + mapped.push(parseProviderCaveatRow(rows[i])); + } + return mapped; + }, + }; +} diff --git a/libs/research/src/mcp/index.ts b/libs/research/src/mcp/index.ts index f8f50f75..2af06a5e 100644 --- a/libs/research/src/mcp/index.ts +++ b/libs/research/src/mcp/index.ts @@ -1,3 +1,4 @@ +export * from './adapters/postgres-findings'; export * from './adapters/postgres-symbol-search'; export * from './copilot-server'; export * from './protocol'; diff --git a/libs/research/test/mcp-postgres-findings.test.ts b/libs/research/test/mcp-postgres-findings.test.ts new file mode 100644 index 00000000..ebdf3464 --- /dev/null +++ b/libs/research/test/mcp-postgres-findings.test.ts @@ -0,0 +1,674 @@ +import { describe, expect, test } from 'bun:test'; +import { + type FiledFindingRecord, + type PostgresFindingsExecutor, + PostgresFindingsError, + createPostgresFindingWritePort, + createPostgresKnowledgeReaders, +} from '../src/mcp/index'; + +interface RecordedCall { + readonly text: string; + readonly params: readonly unknown[] | undefined; +} + +type QueryHandler = ( + text: string, + params: readonly unknown[] | undefined, + callIndex: number +) => Promise<{ readonly rows: readonly Record[] }> | { readonly rows: readonly Record[] }; + +function createSequenceExecutor(handler: QueryHandler): { + readonly calls: RecordedCall[]; + readonly executor: PostgresFindingsExecutor; +} { + const calls: RecordedCall[] = []; + const executor: PostgresFindingsExecutor = { + async query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + const idx = calls.length; + calls.push({ text, params }); + const res = await handler(text, params, idx); + return res as unknown as { readonly rows: readonly Row[] }; + }, + }; + return { calls, executor }; +} + +function createFakeExecutor(rows: readonly Record[] = []): { + readonly calls: RecordedCall[]; + readonly executor: PostgresFindingsExecutor; +} { + return createSequenceExecutor(() => ({ rows })); +} + +const FIXED_TS = '2026-01-15T12:34:56.789Z'; + +function makeFiledRecord(overrides: Partial = {}): FiledFindingRecord { + return { + id: 'finding-001', + kind: 'finding', + title: 'Momentum decays after 5 sessions', + status: 'pending_review', + createdAt: FIXED_TS, + summary: 'Cross-sectional rank IC turns negative past day 5.', + trialRefs: ['101', '102'], + evidenceRefs: ['snap:2026-01-15:ic'], + ...overrides, + }; +} + +function makeRawFindingRow(overrides: Record = {}): Record { + return { + id: 'finding-001', + title: 'Momentum decays after 5 sessions', + status: 'pending_review', + created_at: new Date(FIXED_TS), + summary: 'Cross-sectional rank IC turns negative past day 5.', + trial_refs: ['101', '102'], + evidence_refs: ['snap:2026-01-15:ic'], + ...overrides, + }; +} + +function makeRawReplayRow(overrides: Record = {}): Record { + return { + id: 'finding-001', + kind: 'finding', + title: 'Momentum decays after 5 sessions', + summary: 'Cross-sectional rank IC turns negative past day 5.', + created_at: new Date(FIXED_TS), + trial_refs: ['101', '102'], + evidence_refs: ['snap:2026-01-15:ic'], + ...overrides, + }; +} + +function makeRawCaveatRow(overrides: Record = {}): Record { + return { + id: 'caveat-001', + provider: 'EODHD', + dataset: 'eodIntraday1M', + caveat: 'Intraday 1m OHLCV is retroactively split-adjusted.', + created_at: new Date(FIXED_TS), + ...overrides, + }; +} + +function assertNoMutationOrReaderLimitSql(calls: readonly RecordedCall[], checkNoLimit = false): void { + for (const call of calls) { + expect(call.text).not.toMatch(/\bUPDATE\b/i); + expect(call.text).not.toMatch(/\bDELETE\b/i); + expect(call.text).not.toMatch(/\bTRUNCATE\b/i); + if (checkNoLimit) { + expect(call.text).not.toMatch(/\bLIMIT\b/i); + } + } +} + +describe('createPostgresFindingWritePort (fake executor)', () => { + test('unkeyed append issues plain parameterized INSERT with NULL key and never interpolates values', async () => { + const injection = "'; DROP TABLE findings; --"; + const fake = createFakeExecutor([{ id: 'finding-inj', created_at: new Date(FIXED_TS) }]); + const port = createPostgresFindingWritePort({ executor: fake.executor }); + + const record = makeFiledRecord({ + id: 'finding-inj', + title: injection, + summary: `summary ${injection}`, + trialRefs: [injection], + evidenceRefs: [`ev:${injection}`], + }); + + const outcome = await port.appendFinding(record); + + expect(outcome).toEqual({ + status: 'created', + id: 'finding-inj', + createdAt: FIXED_TS, + }); + expect(fake.calls).toHaveLength(1); + const call = fake.calls[0]!; + expect(call.text).toContain('INSERT INTO findings'); + expect(call.text).not.toContain('ON CONFLICT'); + expect(call.text).toContain('RETURNING id, created_at'); + expect(call.text).not.toContain(injection); + expect(call.text).not.toContain(';'); + expect(call.params).toEqual([ + 'finding-inj', + 'finding', + injection, + `summary ${injection}`, + 'pending_review', + FIXED_TS, + [injection], + [`ev:${injection}`], + null, + ]); + assertNoMutationOrReaderLimitSql(fake.calls); + }); + + test('keyed append uses partial-index ON CONFLICT DO NOTHING and returns created on 1 returned row', async () => { + const fake = createFakeExecutor([ + { id: 'finding-001', created_at: '2026-01-15T14:34:56.789+02:00' }, + ]); + const port = createPostgresFindingWritePort({ executor: fake.executor }); + + const outcome = await port.appendFinding(makeFiledRecord(), 'idem-key-1'); + + expect(outcome).toEqual({ + status: 'created', + id: 'finding-001', + createdAt: FIXED_TS, + }); + expect(fake.calls).toHaveLength(1); + const call = fake.calls[0]!; + expect(call.text).toContain( + 'ON CONFLICT (idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING' + ); + expect(call.text).not.toContain('idem-key-1'); + expect(call.params).toEqual([ + 'finding-001', + 'finding', + 'Momentum decays after 5 sessions', + 'Cross-sectional rank IC turns negative past day 5.', + 'pending_review', + FIXED_TS, + ['101', '102'], + ['snap:2026-01-15:ic'], + 'idem-key-1', + ]); + assertNoMutationOrReaderLimitSql(fake.calls); + }); + + test('keyed append reads winner in separate SELECT on 0 rows and returns replayed with stored metadata', async () => { + const fake = createSequenceExecutor((_text, _params, idx) => { + if (idx === 0) { + return { rows: [] }; + } + return { + rows: [ + makeRawReplayRow({ + id: 'finding-original', + created_at: '2026-01-15T07:34:56.789999-05:00', + }), + ], + }; + }); + const port = createPostgresFindingWritePort({ executor: fake.executor }); + + // Incoming call has a new id and createdAt, but identical comparable payload + const outcome = await port.appendFinding( + makeFiledRecord({ + id: 'finding-retry-new-id', + createdAt: '2026-01-16T00:00:00.000Z', + }), + 'idem-replay' + ); + + expect(outcome).toEqual({ + status: 'replayed', + id: 'finding-original', + createdAt: FIXED_TS, + }); + expect(fake.calls).toHaveLength(2); + expect(fake.calls[1]!.text).toContain('SELECT'); + expect(fake.calls[1]!.text).toContain('WHERE idempotency_key = $1::text'); + expect(fake.calls[1]!.params).toEqual(['idem-replay']); + assertNoMutationOrReaderLimitSql(fake.calls); + }); + + test('keyed append returns conflict when stored payload differs on any comparable field', async () => { + const diffs: readonly Partial[] = [ + { kind: 'dead_end' }, + { title: 'Different title' }, + { summary: 'Different summary' }, + { trialRefs: ['101'] }, + { trialRefs: ['102', '101'] }, + { evidenceRefs: [] }, + ]; + + for (const diff of diffs) { + const fake = createSequenceExecutor((_text, _params, idx) => + idx === 0 ? { rows: [] } : { rows: [makeRawReplayRow()] } + ); + const port = createPostgresFindingWritePort({ executor: fake.executor }); + + const outcome = await port.appendFinding(makeFiledRecord(diff), 'idem-conflict'); + expect(outcome).toEqual({ status: 'conflict' }); + expect(fake.calls).toHaveLength(2); + assertNoMutationOrReaderLimitSql(fake.calls); + } + }); + + test('keyed append resolves same-ID 23505 retry as replayed or conflict, and propagates unrelated 23505 or other errors', async () => { + const pkErr = Object.assign(new Error('duplicate key value violates unique constraint'), { + code: '23505', + }); + + // Same ID + identical payload -> replayed + const fakeReplay = createSequenceExecutor((_text, _params, idx) => { + if (idx === 0) { + throw pkErr; + } + return { rows: [makeRawReplayRow({ id: 'finding-001' })] }; + }); + const replayPort = createPostgresFindingWritePort({ executor: fakeReplay.executor }); + expect(await replayPort.appendFinding(makeFiledRecord(), 'idem-same-id')).toEqual({ + status: 'replayed', + id: 'finding-001', + createdAt: FIXED_TS, + }); + expect(fakeReplay.calls).toHaveLength(2); + + // Same ID + different payload -> conflict + const fakeConflict = createSequenceExecutor((_text, _params, idx) => { + if (idx === 0) { + throw pkErr; + } + return { rows: [makeRawReplayRow({ id: 'finding-001', title: 'Other title' })] }; + }); + const conflictPort = createPostgresFindingWritePort({ executor: fakeConflict.executor }); + expect(await conflictPort.appendFinding(makeFiledRecord(), 'idem-same-id')).toEqual({ + status: 'conflict', + }); + + // Unrelated PK collision: no stored row for idempotency_key -> propagate pkErr + const fakeMissing = createSequenceExecutor((_text, _params, idx) => { + if (idx === 0) { + throw pkErr; + } + return { rows: [] }; + }); + const missingPort = createPostgresFindingWritePort({ executor: fakeMissing.executor }); + await expect(missingPort.appendFinding(makeFiledRecord(), 'idem-unrelated')).rejects.toBe( + pkErr + ); + + // Unrelated PK collision: stored row for idempotency_key has different ID -> propagate pkErr + const fakeDifferentId = createSequenceExecutor((_text, _params, idx) => { + if (idx === 0) { + throw pkErr; + } + return { rows: [makeRawReplayRow({ id: 'finding-other' })] }; + }); + const diffIdPort = createPostgresFindingWritePort({ executor: fakeDifferentId.executor }); + await expect(diffIdPort.appendFinding(makeFiledRecord(), 'idem-other-id')).rejects.toBe(pkErr); + + // Non-23505 error -> propagates immediately without SELECT + const checkErr = Object.assign(new Error('check violation'), { code: '23514' }); + const fakeOther = createSequenceExecutor(() => { + throw checkErr; + }); + const otherPort = createPostgresFindingWritePort({ executor: fakeOther.executor }); + await expect(otherPort.appendFinding(makeFiledRecord(), 'idem-check')).rejects.toBe(checkErr); + expect(fakeOther.calls).toHaveLength(1); + + // Unkeyed 23505 -> propagates immediately without SELECT + const fakeUnkeyed = createSequenceExecutor(() => { + throw pkErr; + }); + const unkeyedPort = createPostgresFindingWritePort({ executor: fakeUnkeyed.executor }); + await expect(unkeyedPort.appendFinding(makeFiledRecord())).rejects.toBe(pkErr); + expect(fakeUnkeyed.calls).toHaveLength(1); + }); + + test('quotes explicit schema on INSERT and replay SELECT, and omits prefix when unset', async () => { + const fakeScoped = createSequenceExecutor((_text, _params, idx) => + idx === 0 ? { rows: [] } : { rows: [makeRawReplayRow()] } + ); + const scopedPort = createPostgresFindingWritePort({ + executor: fakeScoped.executor, + schema: 'custom_research_1', + }); + await scopedPort.appendFinding(makeFiledRecord(), 'idem-schema'); + + expect(fakeScoped.calls[0]!.text).toContain('INSERT INTO "custom_research_1".findings'); + expect(fakeScoped.calls[1]!.text).toContain('FROM "custom_research_1".findings'); + assertNoMutationOrReaderLimitSql(fakeScoped.calls); + }); +}); + +describe('createPostgresKnowledgeReaders (fake executor)', () => { + test('listFindings binds exact id (taking precedence over query), escaped ILIKE query, and unfiltered queries with ORDER BY id ASC and no LIMIT', async () => { + const injection = "'; DELETE FROM findings; --"; + const fake = createFakeExecutor([makeRawFindingRow()]); + const readers = createPostgresKnowledgeReaders({ executor: fake.executor }); + + // Unfiltered + const allRows = await readers.listFindings({}); + expect(allRows).toEqual([ + { + id: 'finding-001', + title: 'Momentum decays after 5 sessions', + status: 'pending_review', + createdAt: FIXED_TS, + summary: 'Cross-sectional rank IC turns negative past day 5.', + trialRefs: ['101', '102'], + evidenceRefs: ['snap:2026-01-15:ic'], + }, + ]); + expect(fake.calls[0]!.text).not.toContain('WHERE'); + expect(fake.calls[0]!.text.trimEnd().endsWith('ORDER BY id ASC')).toBe(true); + expect(fake.calls[0]!.params).toEqual([]); + + // Exact id takes precedence over query + await readers.listFindings({ id: injection, query: 'ignored' }); + expect(fake.calls[1]!.text).toContain('WHERE id = $1::text'); + expect(fake.calls[1]!.text).not.toContain('ILIKE'); + expect(fake.calls[1]!.text).not.toContain(injection); + expect(fake.calls[1]!.params).toEqual([injection]); + + // Escaped ILIKE query on title and summary + await readers.listFindings({ query: '100% pure_wild\\path' }); + expect(fake.calls[2]!.text).toContain( + "WHERE title ILIKE $1::text ESCAPE '\\' OR summary ILIKE $1::text ESCAPE '\\'" + ); + expect(fake.calls[2]!.params).toEqual(['%100\\% pure\\_wild\\\\path%']); + + assertNoMutationOrReaderLimitSql(fake.calls, true); + }); + + test('listProviderCaveats combines case-insensitive provider with id or escaped ILIKE query and no LIMIT', async () => { + const fake = createFakeExecutor([ + makeRawCaveatRow({ created_at: '2026-01-15T12:34:56.789Z' }), + ]); + const readers = createPostgresKnowledgeReaders({ + executor: fake.executor, + schema: 'custom_research_2', + }); + + // Unfiltered + const rows = await readers.listProviderCaveats({}); + expect(rows).toEqual([ + { + id: 'caveat-001', + provider: 'EODHD', + dataset: 'eodIntraday1M', + caveat: 'Intraday 1m OHLCV is retroactively split-adjusted.', + createdAt: FIXED_TS, + }, + ]); + expect(fake.calls[0]!.text).toContain('FROM "custom_research_2".provider_caveats'); + expect(fake.calls[0]!.text).not.toContain('WHERE'); + expect(fake.calls[0]!.params).toEqual([]); + + // Provider + exact id (id takes precedence over query) + await readers.listProviderCaveats({ + provider: 'eodhd', + id: 'caveat-001', + query: 'ignored', + }); + expect(fake.calls[1]!.text).toContain( + 'WHERE lower(provider) = lower($1::text) AND id = $2::text' + ); + expect(fake.calls[1]!.text).not.toContain('ILIKE'); + expect(fake.calls[1]!.params).toEqual(['eodhd', 'caveat-001']); + + // Provider + query with wildcards + await readers.listProviderCaveats({ + provider: 'QuoteMedia', + query: '50%_ratio\\inv', + }); + expect(fake.calls[2]!.text).toContain( + "WHERE lower(provider) = lower($1::text) AND (provider ILIKE $2::text ESCAPE '\\' OR dataset ILIKE $2::text ESCAPE '\\' OR caveat ILIKE $2::text ESCAPE '\\')" + ); + expect(fake.calls[2]!.params).toEqual(['QuoteMedia', '%50\\%\\_ratio\\\\inv%']); + + // Query only + await readers.listProviderCaveats({ query: 'split' }); + expect(fake.calls[3]!.text).toContain( + "WHERE (provider ILIKE $1::text ESCAPE '\\' OR dataset ILIKE $1::text ESCAPE '\\' OR caveat ILIKE $1::text ESCAPE '\\')" + ); + expect(fake.calls[3]!.params).toEqual(['%split%']); + + assertNoMutationOrReaderLimitSql(fake.calls, true); + }); +}); + +describe('PostgreSQL findings adapter validation (fake executor)', () => { + test('rejects invalid executors and options with INVALID_EXECUTOR before any query', () => { + const invalidOptions: unknown[] = [ + null, + undefined, + {}, + { executor: null }, + { executor: {} }, + { executor: { query: 'not-a-fn' } }, + ]; + + for (const opts of invalidOptions) { + for (const factory of [createPostgresFindingWritePort, createPostgresKnowledgeReaders]) { + let caught: unknown; + try { + factory(opts as Parameters[0]); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresFindingsError); + expect((caught as PostgresFindingsError).code).toBe('INVALID_EXECUTOR'); + } + } + }); + + test('rejects invalid schema names with INVALID_SCHEMA before any query', () => { + const fake = createFakeExecutor([]); + const badSchemas: unknown[] = [ + '', + 'Public', + '1schema', + 'bad-name', + 'bad.name', + 'public"; DROP TABLE findings; --', + 'space name', + 123, + null, + ]; + + for (const schema of badSchemas) { + for (const factory of [createPostgresFindingWritePort, createPostgresKnowledgeReaders]) { + let caught: unknown; + try { + factory({ executor: fake.executor, schema: schema as string }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresFindingsError); + expect((caught as PostgresFindingsError).code).toBe('INVALID_SCHEMA'); + } + } + + expect(fake.calls).toHaveLength(0); + }); + + test('accepts prototype-method executors', async () => { + class ProtoExecutor { + async query>(): Promise<{ readonly rows: readonly Row[] }> { + return { rows: [makeRawFindingRow()] as unknown as readonly Row[] }; + } + } + const readers = createPostgresKnowledgeReaders({ executor: new ProtoExecutor() }); + const rows = await readers.listFindings({}); + expect(rows).toHaveLength(1); + expect(rows[0]!.id).toBe('finding-001'); + }); + + test('rejects invalid result envelopes and missing/duplicate receipt or winner rows with INVALID_ROW', async () => { + const badEnvelopeExecutor: PostgresFindingsExecutor = { + async query() { + return { rows: 'not-an-array' as unknown as readonly never[] }; + }, + }; + const badWritePort = createPostgresFindingWritePort({ executor: badEnvelopeExecutor }); + const badReaders = createPostgresKnowledgeReaders({ executor: badEnvelopeExecutor }); + + for (const op of [ + () => badWritePort.appendFinding(makeFiledRecord()), + () => badWritePort.appendFinding(makeFiledRecord(), 'k1'), + () => badReaders.listFindings({}), + () => badReaders.listProviderCaveats({}), + ]) { + let caught: unknown; + try { + await op(); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresFindingsError); + expect((caught as PostgresFindingsError).code).toBe('INVALID_ROW'); + } + + // Unkeyed insert returning 0 rows or 2 rows + for (const rows of [[], [{ id: 'a', created_at: FIXED_TS }, { id: 'b', created_at: FIXED_TS }]]) { + const port = createPostgresFindingWritePort({ executor: createFakeExecutor(rows).executor }); + await expect(port.appendFinding(makeFiledRecord())).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + } + + // Keyed insert returning 2 rows + const dupInsertPort = createPostgresFindingWritePort({ + executor: createFakeExecutor([ + { id: 'a', created_at: FIXED_TS }, + { id: 'b', created_at: FIXED_TS }, + ]).executor, + }); + await expect(dupInsertPort.appendFinding(makeFiledRecord(), 'k-dup')).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + + // Keyed conflict lookup returning 0 rows or 2 rows + for (const lookupRows of [[], [makeRawReplayRow(), makeRawReplayRow({ id: 'finding-002' })]]) { + const fake = createSequenceExecutor((_t, _p, idx) => + idx === 0 ? { rows: [] } : { rows: lookupRows } + ); + const port = createPostgresFindingWritePort({ executor: fake.executor }); + await expect(port.appendFinding(makeFiledRecord(), 'k-missing-or-dup')).rejects.toMatchObject( + { + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + } + ); + } + + // 23505 lookup returning 2 rows + const pkErr = Object.assign(new Error('dup'), { code: '23505' }); + const fakeDup23505 = createSequenceExecutor((_t, _p, idx) => { + if (idx === 0) { + throw pkErr; + } + return { rows: [makeRawReplayRow(), makeRawReplayRow({ id: 'finding-002' })] }; + }); + const dup23505Port = createPostgresFindingWritePort({ executor: fakeDup23505.executor }); + await expect(dup23505Port.appendFinding(makeFiledRecord(), 'k-dup-23505')).rejects.toMatchObject( + { + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + } + ); + }); + + test('rejects malformed timestamps, invalid kinds on replay, and non-string or nested arrays with INVALID_ROW', async () => { + const badTimestamps: readonly unknown[] = [ + null, + 1700000000000, + new Date(Number.NaN), + '', + '2026-01-15', + '2026-01-15T12:34:56', + '2026-02-30T00:00:00Z', + '2026-01-15T24:00:00Z', + '2026-01-15T12:00:00+25:00', + 'not-a-timestamp', + ]; + + for (const badTs of badTimestamps) { + const findingReaders = createPostgresKnowledgeReaders({ + executor: createFakeExecutor([makeRawFindingRow({ created_at: badTs })]).executor, + }); + await expect(findingReaders.listFindings({})).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + + const caveatReaders = createPostgresKnowledgeReaders({ + executor: createFakeExecutor([makeRawCaveatRow({ created_at: badTs })]).executor, + }); + await expect(caveatReaders.listProviderCaveats({})).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + } + + // Invalid kind on replay + for (const badKind of ['hypothesis', 'FINDING', '', null, 42]) { + const fake = createSequenceExecutor((_t, _p, idx) => + idx === 0 ? { rows: [] } : { rows: [makeRawReplayRow({ kind: badKind })] } + ); + const port = createPostgresFindingWritePort({ executor: fake.executor }); + await expect(port.appendFinding(makeFiledRecord(), 'k-bad-kind')).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + } + + // Invalid ref arrays (nested arrays, null elements, non-arrays) + const badArrays: readonly unknown[] = [null, '101', [101], ['101', null], [['101']]]; + for (const badArr of badArrays) { + const readers = createPostgresKnowledgeReaders({ + executor: createFakeExecutor([makeRawFindingRow({ trial_refs: badArr })]).executor, + }); + await expect(readers.listFindings({})).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + + const readersEv = createPostgresKnowledgeReaders({ + executor: createFakeExecutor([makeRawFindingRow({ evidence_refs: badArr })]).executor, + }); + await expect(readersEv.listFindings({})).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + } + + // Non-object rows & blank strings + const badFindingRows: readonly unknown[] = [ + null, + makeRawFindingRow({ id: ' ' }), + makeRawFindingRow({ title: '' }), + makeRawFindingRow({ status: null }), + makeRawFindingRow({ summary: '' }), + ]; + for (const badRow of badFindingRows) { + const readers = createPostgresKnowledgeReaders({ + executor: createFakeExecutor([badRow as Record]).executor, + }); + await expect(readers.listFindings({})).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + } + + const badCaveatRows: readonly unknown[] = [ + null, + makeRawCaveatRow({ id: '' }), + makeRawCaveatRow({ provider: ' ' }), + makeRawCaveatRow({ dataset: '' }), + makeRawCaveatRow({ caveat: null }), + ]; + for (const badRow of badCaveatRows) { + const readers = createPostgresKnowledgeReaders({ + executor: createFakeExecutor([badRow as Record]).executor, + }); + await expect(readers.listProviderCaveats({})).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + } + }); +}); diff --git a/test/postgres/mcp-findings-adapter.test.ts b/test/postgres/mcp-findings-adapter.test.ts new file mode 100644 index 00000000..51636f7d --- /dev/null +++ b/test/postgres/mcp-findings-adapter.test.ts @@ -0,0 +1,537 @@ +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Client, Pool, type PoolConfig } from 'pg'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; +import { + FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, + type FileFindingResultPayload, + type FiledFindingRecord, + type PostgresFindingsExecutor, + type ReadKnowledgeResultPayload, + createFileFindingTool, + createMcpServer, + createPostgresFindingWritePort, + createPostgresKnowledgeReaders, + createReadKnowledgeTool, +} from '../../libs/research/src/mcp/index'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('mcp-findings-adapter-pg-test'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; +const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); + +const FIXED_TS = '2026-01-15T12:34:56.789Z'; + +const cleanup: (() => Promise | void)[] = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); + +function assertSafetyDatabaseUrl(connectionString: string | undefined): string { + if (!connectionString || !new URL(connectionString).pathname.startsWith('/stock_bot_safety')) { + throw new Error('Dedicated stock_bot_safety database required'); + } + return connectionString; +} + +function createPgExecutor(pool: Pool): PostgresFindingsExecutor { + return { + query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + return pool.query( + text, + params === undefined ? undefined : [...params] + ) as unknown as Promise<{ readonly rows: readonly Row[] }>; + }, + }; +} + +function buildIsolatedPoolConfig(connectionString: string | undefined, schema: string): PoolConfig { + const safeUrl = assertSafetyDatabaseUrl(connectionString); + const parsed = new URL(safeUrl); + const existingOptions = parsed.searchParams + .getAll('options') + .map(value => value.trim()) + .filter(value => value.length > 0); + parsed.searchParams.delete('options'); + + const schemaOptions = `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`; + const options = [...existingOptions, schemaOptions].join(' '); + + return { + connectionString: parsed.toString(), + options, + }; +} + +async function createIsolatedFixture(connectionString: string | undefined = url) { + const safeUrl = assertSafetyDatabaseUrl(connectionString); + const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; + const admin = new Pool({ connectionString: safeUrl }); + await admin.query(`CREATE SCHEMA ${schema}`); + const pool = new Pool(buildIsolatedPoolConfig(safeUrl, schema)); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + + const { rows: schemaRows } = await pool.query<{ current_schema: string | null }>( + 'SELECT current_schema() AS current_schema' + ); + if (schemaRows[0]?.current_schema !== schema) { + throw new Error( + `Isolated fixture pool expected current_schema()=${schema}, got ${String(schemaRows[0]?.current_schema)}` + ); + } + + // Bootstrap pre-additive tables needed by the research migration track. + for (const filename of [ + '06-create-backtest-tables.sql', + '07-fix-execution-time-type.sql', + '08-create-runs-table.sql', + ]) { + await pool.query(readFileSync(`${initDir}${filename}`, 'utf8')); + } + + const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, + logger + ); + Object.defineProperty(postgres, 'connectionPool', { + get: () => ({ + connect: () => pool.connect(), + }), + }); + + await runPostgresMigrations(postgres, { track: 'research' }); + + return { admin, pool, schema }; +} + +function makeFinding(overrides: Partial = {}): FiledFindingRecord { + return { + id: `finding-${randomUUID()}`, + kind: 'finding', + title: 'Momentum factor decays after 5 sessions', + status: 'pending_review', + createdAt: FIXED_TS, + summary: 'Cross-sectional rank IC turns negative past day 5.', + trialRefs: ['101', '102'], + evidenceRefs: ['snap:2026-01-15:ic'], + ...overrides, + }; +} + +describe('PostgreSQL findings adapter safety guard', () => { + test('rejects unsafe database targets before connecting', () => { + expect(() => assertSafetyDatabaseUrl(undefined)).toThrow( + 'Dedicated stock_bot_safety database required' + ); + expect(() => + assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/trading_bot') + ).toThrow('Dedicated stock_bot_safety database required'); + expect(() => + assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5433/trading_bot_dev') + ).toThrow('Dedicated stock_bot_safety database required'); + expect( + assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test') + ).toBe('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test'); + }); + + test('preserves isolated schema search_path precedence over URL startup options', () => { + const schema = 'stock_bot_safety_findings_options'; + const urlWithOptions = + 'postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test?options=-c%20statement_timeout%3D30000%20-c%20search_path%3Dpublic'; + const poolConfig = buildIsolatedPoolConfig(urlWithOptions, schema); + + expect(new URL(poolConfig.connectionString!).searchParams.has('options')).toBe(false); + + const client = new Client(poolConfig); + const resolvedOptions = (client as unknown as { connectionParameters: { options?: string } }) + .connectionParameters.options; + expect(resolvedOptions).toBe( + `-c statement_timeout=30000 -c search_path=public -c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000` + ); + }); +}); + +describe.skipIf(!url)('PostgreSQL MCP findings & provider caveats adapter', () => { + test('supports unkeyed inserts, keyed created -> replayed -> conflict, same-ID retries, and unrelated duplicate PK errors', async () => { + const f = await createIsolatedFixture(); + const writePort = createPostgresFindingWritePort({ executor: createPgExecutor(f.pool) }); + + // Two independent unkeyed inserts produce two distinct rows. + const u1 = await writePort.appendFinding(makeFinding({ id: 'f-unkeyed-1' })); + const u2 = await writePort.appendFinding(makeFinding({ id: 'f-unkeyed-2' })); + expect(u1).toEqual({ status: 'created', id: 'f-unkeyed-1', createdAt: FIXED_TS }); + expect(u2).toEqual({ status: 'created', id: 'f-unkeyed-2', createdAt: FIXED_TS }); + + // Keyed create -> replay -> conflict + const original = makeFinding({ + id: 'f-keyed-1', + createdAt: '2026-01-15T12:34:56.789Z', + }); + const created = await writePort.appendFinding(original, 'idem-roundtrip'); + expect(created).toEqual({ + status: 'created', + id: 'f-keyed-1', + createdAt: '2026-01-15T12:34:56.789Z', + }); + + // Replay with new generated ID and timestamp returns original stored ID and timestamp. + const replayed = await writePort.appendFinding( + { + ...original, + id: 'f-keyed-retry-new-id', + createdAt: '2026-01-16T00:00:00.000Z', + }, + 'idem-roundtrip' + ); + expect(replayed).toEqual({ + status: 'replayed', + id: 'f-keyed-1', + createdAt: '2026-01-15T12:34:56.789Z', + }); + + // Same-ID retry (triggers PK 23505) resolves cleanly as replayed / conflict. + const sameIdReplay = await writePort.appendFinding(original, 'idem-roundtrip'); + expect(sameIdReplay).toEqual({ + status: 'replayed', + id: 'f-keyed-1', + createdAt: '2026-01-15T12:34:56.789Z', + }); + const sameIdConflict = await writePort.appendFinding( + { ...original, title: 'Mutated title on same-ID retry' }, + 'idem-roundtrip' + ); + expect(sameIdConflict).toEqual({ status: 'conflict' }); + + // Different payload with new ID returns conflict and leaves row count unchanged. + const conflict = await writePort.appendFinding( + { ...original, id: 'f-keyed-conflict', summary: 'Different summary' }, + 'idem-roundtrip' + ); + expect(conflict).toEqual({ status: 'conflict' }); + + // Unrelated duplicate primary key (collides with unkeyed row f-unkeyed-1) propagates 23505. + let pkError: unknown; + try { + await writePort.appendFinding(makeFinding({ id: 'f-unkeyed-1' }), 'idem-fresh-unrelated'); + } catch (err) { + pkError = err; + } + expect((pkError as { code?: string } | null)?.code).toBe('23505'); + + const countRow = (await f.pool.query<{ c: number }>('SELECT count(*)::int AS c FROM findings')) + .rows[0]; + expect(countRow?.c).toBe(3); + }); + + test('concurrent same-key appends on separate connections leave exactly one stored row for identical and differing payloads', async () => { + const f = await createIsolatedFixture(); + const writePort = createPostgresFindingWritePort({ executor: createPgExecutor(f.pool) }); + + // Concurrent identical payloads + const recA = makeFinding({ id: 'f-race-same-a', createdAt: '2026-01-15T10:00:00.000Z' }); + const recB = { ...recA, id: 'f-race-same-b', createdAt: '2026-01-15T10:00:01.000Z' }; + + const sameOutcomes = await Promise.all([ + writePort.appendFinding(recA, 'idem-race-same'), + writePort.appendFinding(recB, 'idem-race-same'), + ]); + const sameStatuses = sameOutcomes.map(o => o.status).sort(); + expect(sameStatuses).toEqual(['created', 'replayed']); + + const winnerSame = sameOutcomes.find(o => o.status === 'created')!; + const loserSame = sameOutcomes.find(o => o.status === 'replayed')!; + expect(loserSame.id).toBe(winnerSame.id); + expect(loserSame.createdAt).toBe(winnerSame.createdAt); + + const storedSame = ( + await f.pool.query<{ id: string }>( + 'SELECT id FROM findings WHERE idempotency_key = $1', + ['idem-race-same'] + ) + ).rows; + expect(storedSame).toEqual([{ id: winnerSame.id }]); + + // Concurrent differing payloads + const diffA = makeFinding({ + id: 'f-race-diff-a', + title: 'Race title A', + createdAt: '2026-01-15T11:00:00.000Z', + }); + const diffB = makeFinding({ + id: 'f-race-diff-b', + title: 'Race title B', + createdAt: '2026-01-15T11:00:01.000Z', + }); + + const diffOutcomes = await Promise.all([ + writePort.appendFinding(diffA, 'idem-race-diff'), + writePort.appendFinding(diffB, 'idem-race-diff'), + ]); + const diffStatuses = diffOutcomes.map(o => o.status).sort(); + expect(diffStatuses).toEqual(['conflict', 'created']); + + const winnerDiff = diffOutcomes.find(o => o.status === 'created')!; + const storedDiff = ( + await f.pool.query<{ id: string }>( + 'SELECT id FROM findings WHERE idempotency_key = $1', + ['idem-race-diff'] + ) + ).rows; + expect(storedDiff).toEqual([{ id: winnerDiff.id }]); + }); + + test('readers return all eligible candidates in deterministic id order with mixed-case, provider, exact-id precedence, wildcard escaping, and explicit schema', async () => { + const f = await createIsolatedFixture(); + // Use admin pool (default search_path) with explicit schema option to verify quoting. + const writePort = createPostgresFindingWritePort({ + executor: createPgExecutor(f.admin), + schema: f.schema, + }); + const readers = createPostgresKnowledgeReaders({ + executor: createPgExecutor(f.admin), + schema: f.schema, + }); + + await writePort.appendFinding( + makeFinding({ + id: 'f-003', + title: '100% Pure_Wild\\Match', + summary: 'Literal wildcard finding.', + createdAt: '2026-01-15T03:00:00.000Z', + }) + ); + await writePort.appendFinding( + makeFinding({ + id: 'f-001', + title: '100X PureAWildXMatch', + summary: 'Near-match without literal wildcards.', + createdAt: '2026-01-15T01:00:00.000Z', + }) + ); + await writePort.appendFinding( + makeFinding({ + id: 'f-002', + title: 'Alpha Drift Signal', + summary: 'Observed on TSX equities.', + createdAt: '2026-01-15T02:00:00.000Z', + }) + ); + + await f.pool.query( + `INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at) + VALUES + ('c-003', 'EODHD', 'eodIntraday1M', '100% split_adjusted\\bars', '2026-01-15T03:00:00.000Z'), + ('c-001', 'QuoteMedia', 'qmSplits', '100X splitXadjustedYbars', '2026-01-15T01:00:00.000Z'), + ('c-002', 'EODHD', 'eodPrices', 'Daily raw OHLCV needs un-adjustment.', '2026-01-15T02:00:00.000Z')` + ); + + // Deterministic id ASC order for unfiltered reads + expect((await readers.listFindings({})).map(r => r.id)).toEqual(['f-001', 'f-002', 'f-003']); + expect((await readers.listProviderCaveats({})).map(r => r.id)).toEqual([ + 'c-001', + 'c-002', + 'c-003', + ]); + + // Mixed-case query matching + expect((await readers.listFindings({ query: 'tsx EQUITIES' })).map(r => r.id)).toEqual([ + 'f-002', + ]); + expect((await readers.listProviderCaveats({ query: 'DAILY RAW' })).map(r => r.id)).toEqual([ + 'c-002', + ]); + + // Case-insensitive provider filter + expect((await readers.listProviderCaveats({ provider: 'eodhd' })).map(r => r.id)).toEqual([ + 'c-002', + 'c-003', + ]); + + // Exact id is case-sensitive and takes precedence over query + expect( + (await readers.listFindings({ id: 'f-002', query: 'does-not-match' })).map(r => r.id) + ).toEqual(['f-002']); + expect(await readers.listFindings({ id: 'F-002' })).toEqual([]); + + // Provider condition still applies with exact id + expect( + (await readers.listProviderCaveats({ id: 'c-002', provider: 'eodhd', query: 'nope' })).map( + r => r.id + ) + ).toEqual(['c-002']); + expect( + await readers.listProviderCaveats({ id: 'c-002', provider: 'quotemedia' }) + ).toEqual([]); + + // Literal wildcard escaping: matches f-003 / c-003 and excludes near-matches f-001 / c-001 + expect((await readers.listFindings({ query: '100% Pure_Wild\\' })).map(r => r.id)).toEqual([ + 'f-003', + ]); + expect( + (await readers.listProviderCaveats({ query: '100% split_adjusted\\' })).map(r => r.id) + ).toEqual(['c-003']); + }); + + test('round-trips createFileFindingTool -> createReadKnowledgeTool through MCP server', async () => { + const f = await createIsolatedFixture(); + const executor = createPgExecutor(f.pool); + const writePort = createPostgresFindingWritePort({ executor }); + const readers = createPostgresKnowledgeReaders({ executor }); + + await f.pool.query( + `INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at) + VALUES ('caveat-eod-1', 'EODHD', 'eodIntraday1M', 'Retroactively split-adjusted.', $1::timestamptz)`, + [FIXED_TS] + ); + + let idSeq = 0; + const allowedTrials = new Set(['101', '102']); + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: writePort, + trialLookup: { + hasResearchVisibleTrial(ref) { + return allowedTrials.has(ref); + }, + }, + newId: () => { + idSeq += 1; + return `finding-mcp-${idSeq}`; + }, + now: () => new Date(FIXED_TS), + }), + createReadKnowledgeTool({ + port: { + listLibraryCards: async () => [], + ...readers, + }, + }), + ], + }); + + const callTool = async (name: string, args: Record) => { + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: `req-${name}`, + method: 'tools/call', + params: { name, arguments: args }, + }) + ); + expect(raw).not.toBeNull(); + const parsed = JSON.parse(raw!) as { + result: { isError?: boolean; content: Array<{ text: string }> }; + }; + return parsed.result; + }; + + // File a new finding through MCP + const fileRes = await callTool('file_finding', { + kind: 'finding', + title: 'Post-earnings drift persists 3 sessions', + summary: 'Positive rank IC across research-visible trials 101 and 102.', + trialRefs: ['102', '101'], + evidenceRefs: ['snap:b', 'snap:a'], + idempotencyKey: 'mcp-idem-1', + }); + expect(fileRes.isError).toBeUndefined(); + const receipt = JSON.parse(fileRes.content[0]!.text) as FileFindingResultPayload; + expect(receipt).toEqual({ + id: 'finding-mcp-1', + createdAt: FIXED_TS, + created: true, + }); + + // Retry with reordered & duplicate refs -> normalized replay with original receipt + const retryRes = await callTool('file_finding', { + kind: 'finding', + title: 'Post-earnings drift persists 3 sessions', + summary: 'Positive rank IC across research-visible trials 101 and 102.', + trialRefs: ['101', '102', '101'], + evidenceRefs: ['snap:a', 'snap:b', 'snap:a'], + idempotencyKey: 'mcp-idem-1', + }); + expect(retryRes.isError).toBeUndefined(); + const retryReceipt = JSON.parse(retryRes.content[0]!.text) as FileFindingResultPayload; + expect(retryReceipt).toEqual({ + id: 'finding-mcp-1', + createdAt: FIXED_TS, + created: false, + }); + + // Unavailable / Vault-only trial ref returns error and writes zero rows + const deniedRes = await callTool('file_finding', { + kind: 'dead_end', + title: 'Should not persist', + summary: 'References unavailable trial.', + trialRefs: ['999-vault'], + }); + expect(deniedRes.isError).toBe(true); + expect(deniedRes.content[0]!.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); + + // Read back the filed finding by receipt ID via read_knowledge + const readRes = await callTool('read_knowledge', { + source: 'findings', + id: receipt.id, + }); + expect(readRes.isError).toBeUndefined(); + const knowledge = JSON.parse(readRes.content[0]!.text) as ReadKnowledgeResultPayload; + expect(knowledge).toEqual({ + rowCount: 1, + sources: { library: 0, findings: 1, provider_caveats: 0 }, + rows: [ + { + source: 'findings', + id: 'finding-mcp-1', + title: 'Post-earnings drift persists 3 sessions', + status: 'pending_review', + createdAt: FIXED_TS, + summary: 'Positive rank IC across research-visible trials 101 and 102.', + trialRefs: ['101', '102'], + evidenceRefs: ['snap:a', 'snap:b'], + truncated: false, + }, + ], + }); + + // Verify provider_caveats case-insensitive filter through read_knowledge + const caveatRes = await callTool('read_knowledge', { + source: 'provider_caveats', + provider: 'eodhd', + }); + expect(caveatRes.isError).toBeUndefined(); + const caveatsPayload = JSON.parse(caveatRes.content[0]!.text) as ReadKnowledgeResultPayload; + expect(caveatsPayload.rowCount).toBe(1); + expect(caveatsPayload.sources).toEqual({ library: 0, findings: 0, provider_caveats: 1 }); + expect(caveatsPayload.rows[0]).toEqual({ + source: 'provider_caveats', + id: 'caveat-eod-1', + provider: 'EODHD', + dataset: 'eodIntraday1M', + caveat: 'Retroactively split-adjusted.', + createdAt: FIXED_TS, + truncated: false, + }); + + // Confirm only 1 finding row was persisted in total + const totalFindings = ( + await f.pool.query<{ c: number }>('SELECT count(*)::int AS c FROM findings') + ).rows[0]?.c; + expect(totalFindings).toBe(1); + }); +}); From a535ebefb55587f80121a22ab9e172d532d577b3 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 09:46:21 -0500 Subject: [PATCH 09/21] =?UTF-8?q?T-161:=20M2.1j=20(re-queue)=20=E2=80=94?= =?UTF-8?q?=20PostgreSQL=20findings=20adapter=20for=20the=20MCP=20copilot:?= =?UTF-8?q?=20`FindingWritePort`=20(atomic=20idempotent=20append)=20+=20`l?= =?UTF-8?q?istFindings`=20/=20`listProviderCaveats`=20readers=20over=20an?= =?UTF-8?q?=20injected=20executor=20in=20`libs/research/src/mcp/adapters/p?= =?UTF-8?q?ostgres-findings.ts`=20(no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/README.md | 4 +- .../src/mcp/adapters/postgres-findings.ts | 89 +++++++-- .../test/mcp-postgres-findings.test.ts | 48 +++++ test/postgres/mcp-findings-adapter.test.ts | 186 +++++++++++++++--- 4 files changed, 280 insertions(+), 47 deletions(-) diff --git a/libs/research/README.md b/libs/research/README.md index 2de5f04b..33fb2a88 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -268,8 +268,8 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported - **`createPostgresFindingWritePort({ executor, schema? })`** and **`createPostgresKnowledgeReaders({ executor, schema? })`** (exported from `@stock-bot/research/mcp` alongside `PostgresFindingsExecutor`, `PostgresFindingsOptions`, `PostgresKnowledgeReaders`, `PostgresFindingsError`, and `PostgresFindingsErrorCode`) back `file_finding` (`FindingWritePort`) and the `findings` / `provider_caveats` halves of `read_knowledge` (`Pick`) over `37-research-findings.sql` with zero runtime `pg` dependency. - **Inputs, schema & row validation:** Validates `executor.query` (`INVALID_EXECUTOR`) and optional `schema` against `^[a-z_][a-z0-9_]*$` (`INVALID_SCHEMA`; defaults to the executor's `search_path`), binds every caller value via `$n` parameters, issues zero `UPDATE`/`DELETE` statements, and fails closed (`INVALID_ROW`) on malformed result envelopes, non-1D/non-string ref arrays, unknown `kind`, or invalid timestamps (converting PostgreSQL `Date` values or strictly parsed timezone-qualified ISO-8601 strings to UTC ISO-8601 output). -- **Atomic idempotency & fresh-snapshot requirement:** Unkeyed appends execute a plain `INSERT ... RETURNING id, created_at`. Keyed appends use `INSERT ... ON CONFLICT (idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING RETURNING id, created_at` followed by a separate keyed `SELECT` on zero rows (and on same-ID `23505` primary-key retries), comparing normalized `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs` via `areFiledFindingPayloadsEqual`. Pass a fresh-snapshot `READ COMMITTED` executor (such as a `pg.Pool`, not a `REPEATABLE READ`/`SERIALIZABLE` transaction) so concurrent callers can observe the committed winner. -- **Reader filtering & research-visible corpus boundary:** `listFindings` and `listProviderCaveats` push down case-sensitive exact `id` (taking precedence over `query`), escaped `ILIKE` substring matching (`%`, `_`, `\`), and `lower(provider) = lower($n::text)` (matching `idx_provider_caveats_lower_provider`), returning all eligible rows ordered by `id ASC` with no `LIMIT` so `createReadKnowledgeTool` owns ranking and global limits. Because `findings` and `provider_caveats` carry no Vault visibility column, callers must bind the adapter to a research-visible corpus and keep `createFileFindingTool` responsible for verifying `trialRefs` via `trialLookup` before writing. +- **Atomic idempotency & autocommit requirement:** Unkeyed appends execute a plain `INSERT ... RETURNING id, created_at`. Keyed appends use `INSERT ... ON CONFLICT (idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING RETURNING id, created_at` followed by a separate keyed `SELECT` on zero rows (and on same-ID `23505` primary-key retries), comparing normalized `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs` via `areFiledFindingPayloadsEqual`. Pass an autocommit, fresh-snapshot `READ COMMITTED` executor (such as a `pg.Pool`, not a `REPEATABLE READ`/`SERIALIZABLE` or explicit `BEGIN` transaction unless the executor rolls back a `SAVEPOINT` before rethrowing errors) so concurrent callers observe the committed winner and `23505` retry lookups do not hit `25P02`. +- **Reader filtering & research-visible corpus boundary:** `listFindings` and `listProviderCaveats` push down case-sensitive exact `id` (taking precedence over `query`), escaped `ILIKE` substring matching (`%`, `_`, `\`) for ASCII queries, and `lower(provider) = lower($n::text)` (matching `idx_provider_caveats_lower_provider`) for ASCII provider filters, falling back to JavaScript `.toLowerCase()` matching on validated candidates for non-ASCII text (e.g., Greek final sigma) so PostgreSQL libc casing never drops `read_knowledge` matches. All eligible rows are returned ordered by `id ASC` with no `LIMIT` so `createReadKnowledgeTool` owns ranking and global limits. Because `findings` and `provider_caveats` carry no Vault visibility column, callers must bind the adapter to a research-visible corpus and keep `createFileFindingTool` responsible for verifying `trialRefs` via `trialLookup` before writing. ### Copilot Server diff --git a/libs/research/src/mcp/adapters/postgres-findings.ts b/libs/research/src/mcp/adapters/postgres-findings.ts index 38bfdfb9..54d12af6 100644 --- a/libs/research/src/mcp/adapters/postgres-findings.ts +++ b/libs/research/src/mcp/adapters/postgres-findings.ts @@ -51,10 +51,13 @@ export class PostgresFindingsError extends RangeError { * Structural `pg.Pool` / `pg.PoolClient`-compatible query interface so this module * has no runtime dependency on `pg` and is unit-testable with a fake executor. * - * For {@link createPostgresFindingWritePort}, the executor should run each call on - * a fresh `READ COMMITTED` snapshot (such as a `pg.Pool`) rather than inside a - * `REPEATABLE READ` / `SERIALIZABLE` transaction so concurrent idempotent callers - * can observe the committed winner after `ON CONFLICT ... DO NOTHING`. + * For {@link createPostgresFindingWritePort}, the executor must run each `query()` + * call in autocommit mode on a fresh `READ COMMITTED` snapshot (such as a `pg.Pool`) + * rather than inside a `REPEATABLE READ` / `SERIALIZABLE` or explicit `BEGIN` + * transaction (unless the executor wraps each statement in a `SAVEPOINT` and rolls + * it back before rethrowing errors). Autocommit ensures that `ON CONFLICT ... DO + * NOTHING` winner lookups observe the committed winner and that same-ID `23505` + * primary-key retry lookups do not fail with `25P02` (aborted transaction). */ export interface PostgresFindingsExecutor { query>( @@ -136,6 +139,24 @@ function escapeLikePattern(value: string): string { return value.replace(/[\\%_]/g, '\\$&'); } +/** + * Returns `true` when every UTF-16 code unit in `value` is ASCII (`<= 0x7F`). + * + * PostgreSQL libc `ILIKE` / `lower()` lowercases characters individually, which + * diverges from JavaScript's context-sensitive Unicode `.toLowerCase()` (e.g. + * Greek final sigma `ΚΟΣΜΟΣ` -> `κοσμος`). SQL pushdown is used only for ASCII + * text where casing agrees with `read_knowledge`; non-ASCII queries fall back + * to filtering validated candidates with JavaScript's `.toLowerCase()` rules. + */ +function isAsciiOnly(value: string): boolean { + for (let i = 0; i < value.length; i += 1) { + if (value.charCodeAt(i) > 0x7f) { + return false; + } + } + return true; +} + function quoteTable(schemaPrefix: string, table: string): string { return `${schemaPrefix}${table}`; } @@ -586,13 +607,18 @@ export function createPostgresKnowledgeReaders( `FROM ${findingsTable}`, ]; const params: unknown[] = []; + let fallbackNormalizedQuery: string | null = null; if (q.id !== undefined) { params.push(q.id); lines.push('WHERE id = $1::text'); } else if (q.query !== undefined) { - params.push(`%${escapeLikePattern(q.query)}%`); - lines.push("WHERE title ILIKE $1::text ESCAPE '\\' OR summary ILIKE $1::text ESCAPE '\\'"); + if (isAsciiOnly(q.query)) { + params.push(`%${escapeLikePattern(q.query)}%`); + lines.push("WHERE title ILIKE $1::text ESCAPE '\\' OR summary ILIKE $1::text ESCAPE '\\'"); + } else { + fallbackNormalizedQuery = q.query.toLowerCase(); + } } lines.push('ORDER BY id ASC'); @@ -601,7 +627,15 @@ export function createPostgresKnowledgeReaders( const rows = extractRows(result); const mapped: FindingRecord[] = []; for (let i = 0; i < rows.length; i += 1) { - mapped.push(parseFindingRow(rows[i])); + const finding = parseFindingRow(rows[i]); + if ( + fallbackNormalizedQuery !== null && + !finding.title.toLowerCase().includes(fallbackNormalizedQuery) && + !finding.summary.toLowerCase().includes(fallbackNormalizedQuery) + ) { + continue; + } + mapped.push(finding); } return mapped; }, @@ -618,21 +652,31 @@ export function createPostgresKnowledgeReaders( ]; const conditions: string[] = []; const params: unknown[] = []; + let fallbackNormalizedProvider: string | null = null; + let fallbackNormalizedQuery: string | null = null; if (q.provider !== undefined) { - params.push(q.provider); - conditions.push(`lower(provider) = lower($${params.length}::text)`); + if (isAsciiOnly(q.provider)) { + params.push(q.provider); + conditions.push(`lower(provider) = lower($${params.length}::text)`); + } else { + fallbackNormalizedProvider = q.provider.toLowerCase(); + } } if (q.id !== undefined) { params.push(q.id); conditions.push(`id = $${params.length}::text`); } else if (q.query !== undefined) { - params.push(`%${escapeLikePattern(q.query)}%`); - const idx = params.length; - conditions.push( - `(provider ILIKE $${idx}::text ESCAPE '\\' OR dataset ILIKE $${idx}::text ESCAPE '\\' OR caveat ILIKE $${idx}::text ESCAPE '\\')` - ); + if (isAsciiOnly(q.query)) { + params.push(`%${escapeLikePattern(q.query)}%`); + const idx = params.length; + conditions.push( + `(provider ILIKE $${idx}::text ESCAPE '\\' OR dataset ILIKE $${idx}::text ESCAPE '\\' OR caveat ILIKE $${idx}::text ESCAPE '\\')` + ); + } else { + fallbackNormalizedQuery = q.query.toLowerCase(); + } } if (conditions.length > 0) { @@ -645,7 +689,22 @@ export function createPostgresKnowledgeReaders( const rows = extractRows(result); const mapped: ProviderCaveatRecord[] = []; for (let i = 0; i < rows.length; i += 1) { - mapped.push(parseProviderCaveatRow(rows[i])); + const caveat = parseProviderCaveatRow(rows[i]); + if ( + fallbackNormalizedProvider !== null && + caveat.provider.toLowerCase() !== fallbackNormalizedProvider + ) { + continue; + } + if ( + fallbackNormalizedQuery !== null && + !caveat.provider.toLowerCase().includes(fallbackNormalizedQuery) && + !caveat.dataset.toLowerCase().includes(fallbackNormalizedQuery) && + !caveat.caveat.toLowerCase().includes(fallbackNormalizedQuery) + ) { + continue; + } + mapped.push(caveat); } return mapped; }, diff --git a/libs/research/test/mcp-postgres-findings.test.ts b/libs/research/test/mcp-postgres-findings.test.ts index ebdf3464..2f3f1f03 100644 --- a/libs/research/test/mcp-postgres-findings.test.ts +++ b/libs/research/test/mcp-postgres-findings.test.ts @@ -426,6 +426,54 @@ describe('createPostgresKnowledgeReaders (fake executor)', () => { assertNoMutationOrReaderLimitSql(fake.calls, true); }); + + test('falls back to JS Unicode lowercasing for non-ASCII query/provider while preserving ASCII SQL pushdown and row validation', async () => { + // Findings: non-ASCII query (Greek final sigma) omits SQL ILIKE and filters with JS .toLowerCase() + const findingFake = createFakeExecutor([ + makeRawFindingRow({ id: 'f-1', title: 'Αλφα κοσμος', summary: 'Greek cosmos finding.' }), + makeRawFindingRow({ id: 'f-2', title: 'Unrelated', summary: 'Does not match.' }), + makeRawFindingRow({ id: 'f-3', title: 'Other', summary: 'Summary has κοσμος too.' }), + ]); + const findingReaders = createPostgresKnowledgeReaders({ executor: findingFake.executor }); + const findingMatches = await findingReaders.listFindings({ query: 'ΚΟΣΜΟΣ' }); + expect(findingMatches.map(r => r.id)).toEqual(['f-1', 'f-3']); + expect(findingFake.calls[0]!.text).not.toContain('ILIKE'); + expect(findingFake.calls[0]!.text).not.toContain('WHERE'); + expect(findingFake.calls[0]!.params).toEqual([]); + + // Provider caveats: ASCII provider still pushes down SQL lower(provider), non-ASCII query filters in JS + const caveatFake = createFakeExecutor([ + makeRawCaveatRow({ id: 'c-1', provider: 'EODHD', caveat: 'Note on κοσμος regime.' }), + makeRawCaveatRow({ id: 'c-2', provider: 'EODHD', caveat: 'Unrelated note.' }), + ]); + const caveatReaders = createPostgresKnowledgeReaders({ executor: caveatFake.executor }); + const caveatMatches = await caveatReaders.listProviderCaveats({ + provider: 'eodhd', + query: 'ΚΟΣΜΟΣ', + }); + expect(caveatMatches.map(r => r.id)).toEqual(['c-1']); + expect(caveatFake.calls[0]!.text).toContain('WHERE lower(provider) = lower($1::text)'); + expect(caveatFake.calls[0]!.text).not.toContain('ILIKE'); + expect(caveatFake.calls[0]!.params).toEqual(['eodhd']); + + // Provider caveats: non-ASCII provider falls back to JS exact case-insensitive match + const nonAsciiProvFake = createFakeExecutor([ + makeRawCaveatRow({ id: 'c-1', provider: 'κοσμος', dataset: 'ds', caveat: 'c' }), + makeRawCaveatRow({ id: 'c-2', provider: 'EODHD', dataset: 'ds', caveat: 'c' }), + ]); + const nonAsciiProvReaders = createPostgresKnowledgeReaders({ + executor: nonAsciiProvFake.executor, + }); + const provMatches = await nonAsciiProvReaders.listProviderCaveats({ provider: 'ΚΟΣΜΟΣ' }); + expect(provMatches.map(r => r.id)).toEqual(['c-1']); + expect(nonAsciiProvFake.calls[0]!.text).not.toContain('WHERE'); + expect(nonAsciiProvFake.calls[0]!.params).toEqual([]); + + assertNoMutationOrReaderLimitSql( + [...findingFake.calls, ...caveatFake.calls, ...nonAsciiProvFake.calls], + true + ); + }); }); describe('PostgreSQL findings adapter validation (fake executor)', () => { diff --git a/test/postgres/mcp-findings-adapter.test.ts b/test/postgres/mcp-findings-adapter.test.ts index 51636f7d..a6c9c285 100644 --- a/test/postgres/mcp-findings-adapter.test.ts +++ b/test/postgres/mcp-findings-adapter.test.ts @@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto'; import { readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { afterEach, describe, expect, test } from 'bun:test'; -import { Client, Pool, type PoolConfig } from 'pg'; +import { Client, Pool, type PoolClient, type PoolConfig } from 'pg'; import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; import { @@ -33,19 +33,39 @@ afterEach(async () => { }); function assertSafetyDatabaseUrl(connectionString: string | undefined): string { - if (!connectionString || !new URL(connectionString).pathname.startsWith('/stock_bot_safety')) { + if (!connectionString) { + throw new Error('Dedicated stock_bot_safety database required'); + } + let parsed: URL; + try { + parsed = new URL(connectionString); + } catch { + throw new Error('Dedicated stock_bot_safety database required'); + } + if (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') { + throw new Error('Dedicated stock_bot_safety database required'); + } + const client = new Client({ connectionString }); + const effectiveDb = ( + client as unknown as { connectionParameters?: { database?: unknown } } + ).connectionParameters?.database; + if ( + typeof effectiveDb !== 'string' || + !effectiveDb.startsWith('stock_bot_safety') || + !parsed.pathname.startsWith('/stock_bot_safety') + ) { throw new Error('Dedicated stock_bot_safety database required'); } return connectionString; } -function createPgExecutor(pool: Pool): PostgresFindingsExecutor { +function createPgExecutor(queryable: Pick | Pick): PostgresFindingsExecutor { return { query>( text: string, params?: readonly unknown[] ): Promise<{ readonly rows: readonly Row[] }> { - return pool.query( + return queryable.query( text, params === undefined ? undefined : [...params] ) as unknown as Promise<{ readonly rows: readonly Row[] }>; @@ -53,6 +73,21 @@ function createPgExecutor(pool: Pool): PostgresFindingsExecutor { }; } +async function waitForBackendLockWait(pool: Pool, pid: number, timeoutMs = 2000): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const { rows } = await pool.query<{ wait_event_type: string | null }>( + 'SELECT wait_event_type FROM pg_stat_activity WHERE pid = $1', + [pid] + ); + if (rows[0]?.wait_event_type === 'Lock') { + return; + } + await new Promise(resolve => setTimeout(resolve, 10)); + } + throw new Error(`Timed out waiting for backend pid ${pid} to enter Lock wait`); +} + function buildIsolatedPoolConfig(connectionString: string | undefined, schema: string): PoolConfig { const safeUrl = assertSafetyDatabaseUrl(connectionString); const parsed = new URL(safeUrl); @@ -141,9 +176,26 @@ describe('PostgreSQL findings adapter safety guard', () => { expect(() => assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5433/trading_bot_dev') ).toThrow('Dedicated stock_bot_safety database required'); + expect(() => + assertSafetyDatabaseUrl('socket:/stock_bot_safety?db=trading_bot') + ).toThrow('Dedicated stock_bot_safety database required'); + expect(() => + assertSafetyDatabaseUrl('socket:///stock_bot_safety?db=trading_bot') + ).toThrow('Dedicated stock_bot_safety database required'); + expect(() => + assertSafetyDatabaseUrl('http://127.0.0.1:5432/stock_bot_safety_test') + ).toThrow('Dedicated stock_bot_safety database required'); + expect(() => assertSafetyDatabaseUrl('not-a-valid-url')).toThrow( + 'Dedicated stock_bot_safety database required' + ); expect( assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test') ).toBe('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test'); + expect( + assertSafetyDatabaseUrl( + 'postgresql://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test' + ) + ).toBe('postgresql://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test'); }); test('preserves isolated schema search_path precedence over URL startup options', () => { @@ -235,25 +287,66 @@ describe.skipIf(!url)('PostgreSQL MCP findings & provider caveats adapter', () = expect(countRow?.c).toBe(3); }); - test('concurrent same-key appends on separate connections leave exactly one stored row for identical and differing payloads', async () => { + test('concurrent same-key appends on pinned connections observe committed winner via fresh snapshot for identical and differing payloads', async () => { const f = await createIsolatedFixture(); - const writePort = createPostgresFindingWritePort({ executor: createPgExecutor(f.pool) }); - // Concurrent identical payloads + const runPinnedRace = async ( + key: string, + winnerRecord: FiledFindingRecord, + loserRecord: FiledFindingRecord + ) => { + const winnerClient = await f.pool.connect(); + const loserClient = await f.pool.connect(); + let winnerOpen = false; + cleanup.push(async () => { + if (winnerOpen) { + await winnerClient.query('ROLLBACK').catch(() => {}); + } + winnerClient.release(); + loserClient.release(); + }); + + const loserPid = ( + await loserClient.query<{ pid: number }>('SELECT pg_backend_pid() AS pid') + ).rows[0]!.pid; + + const winnerPort = createPostgresFindingWritePort({ + executor: createPgExecutor(winnerClient), + }); + const loserPort = createPostgresFindingWritePort({ + executor: createPgExecutor(loserClient), + }); + + await winnerClient.query('BEGIN'); + winnerOpen = true; + const winnerOutcome = await winnerPort.appendFinding(winnerRecord, key); + expect(winnerOutcome).toEqual({ + status: 'created', + id: winnerRecord.id, + createdAt: winnerRecord.createdAt, + }); + + // Start the competing append on the second connection and wait until PostgreSQL + // blocks its INSERT ... ON CONFLICT DO NOTHING on the winner's uncommitted tuple. + const loserPromise = loserPort.appendFinding(loserRecord, key); + await waitForBackendLockWait(f.pool, loserPid); + + await winnerClient.query('COMMIT'); + winnerOpen = false; + + const loserOutcome = await loserPromise; + return { winnerOutcome, loserOutcome }; + }; + + // Concurrent identical payloads: loser's separate READ COMMITTED lookup sees winner -> replayed const recA = makeFinding({ id: 'f-race-same-a', createdAt: '2026-01-15T10:00:00.000Z' }); const recB = { ...recA, id: 'f-race-same-b', createdAt: '2026-01-15T10:00:01.000Z' }; - - const sameOutcomes = await Promise.all([ - writePort.appendFinding(recA, 'idem-race-same'), - writePort.appendFinding(recB, 'idem-race-same'), - ]); - const sameStatuses = sameOutcomes.map(o => o.status).sort(); - expect(sameStatuses).toEqual(['created', 'replayed']); - - const winnerSame = sameOutcomes.find(o => o.status === 'created')!; - const loserSame = sameOutcomes.find(o => o.status === 'replayed')!; - expect(loserSame.id).toBe(winnerSame.id); - expect(loserSame.createdAt).toBe(winnerSame.createdAt); + const sameRace = await runPinnedRace('idem-race-same', recA, recB); + expect(sameRace.loserOutcome).toEqual({ + status: 'replayed', + id: recA.id, + createdAt: recA.createdAt, + }); const storedSame = ( await f.pool.query<{ id: string }>( @@ -261,9 +354,9 @@ describe.skipIf(!url)('PostgreSQL MCP findings & provider caveats adapter', () = ['idem-race-same'] ) ).rows; - expect(storedSame).toEqual([{ id: winnerSame.id }]); + expect(storedSame).toEqual([{ id: recA.id }]); - // Concurrent differing payloads + // Concurrent differing payloads: loser's separate READ COMMITTED lookup sees winner -> conflict const diffA = makeFinding({ id: 'f-race-diff-a', title: 'Race title A', @@ -274,22 +367,16 @@ describe.skipIf(!url)('PostgreSQL MCP findings & provider caveats adapter', () = title: 'Race title B', createdAt: '2026-01-15T11:00:01.000Z', }); + const diffRace = await runPinnedRace('idem-race-diff', diffA, diffB); + expect(diffRace.loserOutcome).toEqual({ status: 'conflict' }); - const diffOutcomes = await Promise.all([ - writePort.appendFinding(diffA, 'idem-race-diff'), - writePort.appendFinding(diffB, 'idem-race-diff'), - ]); - const diffStatuses = diffOutcomes.map(o => o.status).sort(); - expect(diffStatuses).toEqual(['conflict', 'created']); - - const winnerDiff = diffOutcomes.find(o => o.status === 'created')!; const storedDiff = ( await f.pool.query<{ id: string }>( 'SELECT id FROM findings WHERE idempotency_key = $1', ['idem-race-diff'] ) ).rows; - expect(storedDiff).toEqual([{ id: winnerDiff.id }]); + expect(storedDiff).toEqual([{ id: diffA.id }]); }); test('readers return all eligible candidates in deterministic id order with mixed-case, provider, exact-id precedence, wildcard escaping, and explicit schema', async () => { @@ -533,5 +620,44 @@ describe.skipIf(!url)('PostgreSQL MCP findings & provider caveats adapter', () = await f.pool.query<{ c: number }>('SELECT count(*)::int AS c FROM findings') ).rows[0]?.c; expect(totalFindings).toBe(1); + + // Regression: Unicode final sigma (κοσμος vs ΚΟΣΜΟΣ) must not be dropped by libc ILIKE + const sigmaFileRes = await callTool('file_finding', { + kind: 'finding', + title: 'κοσμος', + summary: 'Greek final sigma regression finding.', + trialRefs: ['101'], + evidenceRefs: [], + }); + expect(sigmaFileRes.isError).toBeUndefined(); + const sigmaReceipt = JSON.parse(sigmaFileRes.content[0]!.text) as FileFindingResultPayload; + + const sigmaReadRes = await callTool('read_knowledge', { + source: 'findings', + query: 'ΚΟΣΜΟΣ', + }); + expect(sigmaReadRes.isError).toBeUndefined(); + const sigmaKnowledge = JSON.parse( + sigmaReadRes.content[0]!.text + ) as ReadKnowledgeResultPayload; + expect(sigmaKnowledge.rowCount).toBe(1); + expect(sigmaKnowledge.rows[0]?.id).toBe(sigmaReceipt.id); + + await f.pool.query( + `INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at) + VALUES ('caveat-sigma-1', 'EODHD', 'eodPrices', 'Caveat for κοσμος tickers.', $1::timestamptz)`, + [FIXED_TS] + ); + const sigmaCaveatRes = await callTool('read_knowledge', { + source: 'provider_caveats', + provider: 'eodhd', + query: 'ΚΟΣΜΟΣ', + }); + expect(sigmaCaveatRes.isError).toBeUndefined(); + const sigmaCaveats = JSON.parse( + sigmaCaveatRes.content[0]!.text + ) as ReadKnowledgeResultPayload; + expect(sigmaCaveats.rowCount).toBe(1); + expect(sigmaCaveats.rows[0]?.id).toBe('caveat-sigma-1'); }); }); From 3064e15c0fc640c92b7c12415c00ee8333b5040d Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 09:58:38 -0500 Subject: [PATCH 10/21] =?UTF-8?q?T-161:=20M2.1j=20(re-queue)=20=E2=80=94?= =?UTF-8?q?=20PostgreSQL=20findings=20adapter=20for=20the=20MCP=20copilot:?= =?UTF-8?q?=20`FindingWritePort`=20(atomic=20idempotent=20append)=20+=20`l?= =?UTF-8?q?istFindings`=20/=20`listProviderCaveats`=20readers=20over=20an?= =?UTF-8?q?=20injected=20executor=20in=20`libs/research/src/mcp/adapters/p?= =?UTF-8?q?ostgres-findings.ts`=20(no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/README.md | 2 +- .../src/mcp/adapters/postgres-findings.ts | 62 ++++---- .../test/mcp-postgres-findings.test.ts | 64 +++++++- test/postgres/mcp-findings-adapter.test.ts | 143 +++++++++++++++++- 4 files changed, 236 insertions(+), 35 deletions(-) diff --git a/libs/research/README.md b/libs/research/README.md index 33fb2a88..e5fd65e5 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -269,7 +269,7 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported - **`createPostgresFindingWritePort({ executor, schema? })`** and **`createPostgresKnowledgeReaders({ executor, schema? })`** (exported from `@stock-bot/research/mcp` alongside `PostgresFindingsExecutor`, `PostgresFindingsOptions`, `PostgresKnowledgeReaders`, `PostgresFindingsError`, and `PostgresFindingsErrorCode`) back `file_finding` (`FindingWritePort`) and the `findings` / `provider_caveats` halves of `read_knowledge` (`Pick`) over `37-research-findings.sql` with zero runtime `pg` dependency. - **Inputs, schema & row validation:** Validates `executor.query` (`INVALID_EXECUTOR`) and optional `schema` against `^[a-z_][a-z0-9_]*$` (`INVALID_SCHEMA`; defaults to the executor's `search_path`), binds every caller value via `$n` parameters, issues zero `UPDATE`/`DELETE` statements, and fails closed (`INVALID_ROW`) on malformed result envelopes, non-1D/non-string ref arrays, unknown `kind`, or invalid timestamps (converting PostgreSQL `Date` values or strictly parsed timezone-qualified ISO-8601 strings to UTC ISO-8601 output). - **Atomic idempotency & autocommit requirement:** Unkeyed appends execute a plain `INSERT ... RETURNING id, created_at`. Keyed appends use `INSERT ... ON CONFLICT (idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING RETURNING id, created_at` followed by a separate keyed `SELECT` on zero rows (and on same-ID `23505` primary-key retries), comparing normalized `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs` via `areFiledFindingPayloadsEqual`. Pass an autocommit, fresh-snapshot `READ COMMITTED` executor (such as a `pg.Pool`, not a `REPEATABLE READ`/`SERIALIZABLE` or explicit `BEGIN` transaction unless the executor rolls back a `SAVEPOINT` before rethrowing errors) so concurrent callers observe the committed winner and `23505` retry lookups do not hit `25P02`. -- **Reader filtering & research-visible corpus boundary:** `listFindings` and `listProviderCaveats` push down case-sensitive exact `id` (taking precedence over `query`), escaped `ILIKE` substring matching (`%`, `_`, `\`) for ASCII queries, and `lower(provider) = lower($n::text)` (matching `idx_provider_caveats_lower_provider`) for ASCII provider filters, falling back to JavaScript `.toLowerCase()` matching on validated candidates for non-ASCII text (e.g., Greek final sigma) so PostgreSQL libc casing never drops `read_knowledge` matches. All eligible rows are returned ordered by `id ASC` with no `LIMIT` so `createReadKnowledgeTool` owns ranking and global limits. Because `findings` and `provider_caveats` carry no Vault visibility column, callers must bind the adapter to a research-visible corpus and keep `createFileFindingTool` responsible for verifying `trialRefs` via `trialLookup` before writing. +- **Reader filtering & research-visible corpus boundary:** `listFindings` and `listProviderCaveats` push down case-sensitive exact `id` (taking precedence over `query`), escaped `ILIKE` substring matching (`%`, `_`, `\`) for ASCII queries, and `lower(provider) = lower($n::text)` (matching `idx_provider_caveats_lower_provider`) for ASCII provider filters while retaining non-ASCII stored rows as candidates (and omitting SQL casing filters for non-ASCII selectors), then applying JavaScript `.toLowerCase()` matching after row validation so PostgreSQL libc/C collation casing (e.g., Greek final sigma or `BİST` / `K`) never drops `read_knowledge` matches. All eligible rows are returned ordered by `id ASC` with no `LIMIT` so `createReadKnowledgeTool` owns ranking and global limits. Because `findings` and `provider_caveats` carry no Vault visibility column, callers must bind the adapter to a research-visible corpus and keep `createFileFindingTool` responsible for verifying `trialRefs` via `trialLookup` before writing. ### Copilot Server diff --git a/libs/research/src/mcp/adapters/postgres-findings.ts b/libs/research/src/mcp/adapters/postgres-findings.ts index 54d12af6..388aa8f3 100644 --- a/libs/research/src/mcp/adapters/postgres-findings.ts +++ b/libs/research/src/mcp/adapters/postgres-findings.ts @@ -139,14 +139,23 @@ function escapeLikePattern(value: string): string { return value.replace(/[\\%_]/g, '\\$&'); } +/** + * PostgreSQL POSIX regex matching any non-ASCII character (`> 0x7F`). + * + * Used alongside ASCII SQL pushdown (`ILIKE` / `lower()`) so rows containing + * non-ASCII stored text (e.g. `BİST` under `C` collation or `K` U+212A) are + * kept as candidates and evaluated with JavaScript's `.toLowerCase()` rules. + */ +const PG_NON_ASCII_REGEX = "'[^\\x01-\\x7f]'"; + /** * Returns `true` when every UTF-16 code unit in `value` is ASCII (`<= 0x7F`). * - * PostgreSQL libc `ILIKE` / `lower()` lowercases characters individually, which - * diverges from JavaScript's context-sensitive Unicode `.toLowerCase()` (e.g. - * Greek final sigma `ΚΟΣΜΟΣ` -> `κοσμος`). SQL pushdown is used only for ASCII - * text where casing agrees with `read_knowledge`; non-ASCII queries fall back - * to filtering validated candidates with JavaScript's `.toLowerCase()` rules. + * PostgreSQL `ILIKE` / `lower()` agrees with JavaScript `.toLowerCase()` only + * when both the selector and the stored text are pure ASCII. Non-ASCII + * selectors omit SQL casing filters, and ASCII selectors retain non-ASCII + * stored rows as candidates; all returned rows are then filtered with + * JavaScript's `.toLowerCase()` rules after validation. */ function isAsciiOnly(value: string): boolean { for (let i = 0; i < value.length; i += 1) { @@ -607,17 +616,18 @@ export function createPostgresKnowledgeReaders( `FROM ${findingsTable}`, ]; const params: unknown[] = []; - let fallbackNormalizedQuery: string | null = null; + let normalizedQuery: string | null = null; if (q.id !== undefined) { params.push(q.id); lines.push('WHERE id = $1::text'); } else if (q.query !== undefined) { + normalizedQuery = q.query.toLowerCase(); if (isAsciiOnly(q.query)) { params.push(`%${escapeLikePattern(q.query)}%`); - lines.push("WHERE title ILIKE $1::text ESCAPE '\\' OR summary ILIKE $1::text ESCAPE '\\'"); - } else { - fallbackNormalizedQuery = q.query.toLowerCase(); + lines.push( + `WHERE title ILIKE $1::text ESCAPE '\\' OR summary ILIKE $1::text ESCAPE '\\' OR title ~ ${PG_NON_ASCII_REGEX} OR summary ~ ${PG_NON_ASCII_REGEX}` + ); } } @@ -629,9 +639,9 @@ export function createPostgresKnowledgeReaders( for (let i = 0; i < rows.length; i += 1) { const finding = parseFindingRow(rows[i]); if ( - fallbackNormalizedQuery !== null && - !finding.title.toLowerCase().includes(fallbackNormalizedQuery) && - !finding.summary.toLowerCase().includes(fallbackNormalizedQuery) + normalizedQuery !== null && + !finding.title.toLowerCase().includes(normalizedQuery) && + !finding.summary.toLowerCase().includes(normalizedQuery) ) { continue; } @@ -652,15 +662,16 @@ export function createPostgresKnowledgeReaders( ]; const conditions: string[] = []; const params: unknown[] = []; - let fallbackNormalizedProvider: string | null = null; - let fallbackNormalizedQuery: string | null = null; + let normalizedProvider: string | null = null; + let normalizedQuery: string | null = null; if (q.provider !== undefined) { + normalizedProvider = q.provider.toLowerCase(); if (isAsciiOnly(q.provider)) { params.push(q.provider); - conditions.push(`lower(provider) = lower($${params.length}::text)`); - } else { - fallbackNormalizedProvider = q.provider.toLowerCase(); + conditions.push( + `(lower(provider) = lower($${params.length}::text) OR provider ~ ${PG_NON_ASCII_REGEX})` + ); } } @@ -668,14 +679,13 @@ export function createPostgresKnowledgeReaders( params.push(q.id); conditions.push(`id = $${params.length}::text`); } else if (q.query !== undefined) { + normalizedQuery = q.query.toLowerCase(); if (isAsciiOnly(q.query)) { params.push(`%${escapeLikePattern(q.query)}%`); const idx = params.length; conditions.push( - `(provider ILIKE $${idx}::text ESCAPE '\\' OR dataset ILIKE $${idx}::text ESCAPE '\\' OR caveat ILIKE $${idx}::text ESCAPE '\\')` + `(provider ILIKE $${idx}::text ESCAPE '\\' OR dataset ILIKE $${idx}::text ESCAPE '\\' OR caveat ILIKE $${idx}::text ESCAPE '\\' OR provider ~ ${PG_NON_ASCII_REGEX} OR dataset ~ ${PG_NON_ASCII_REGEX} OR caveat ~ ${PG_NON_ASCII_REGEX})` ); - } else { - fallbackNormalizedQuery = q.query.toLowerCase(); } } @@ -691,16 +701,16 @@ export function createPostgresKnowledgeReaders( for (let i = 0; i < rows.length; i += 1) { const caveat = parseProviderCaveatRow(rows[i]); if ( - fallbackNormalizedProvider !== null && - caveat.provider.toLowerCase() !== fallbackNormalizedProvider + normalizedProvider !== null && + caveat.provider.toLowerCase() !== normalizedProvider ) { continue; } if ( - fallbackNormalizedQuery !== null && - !caveat.provider.toLowerCase().includes(fallbackNormalizedQuery) && - !caveat.dataset.toLowerCase().includes(fallbackNormalizedQuery) && - !caveat.caveat.toLowerCase().includes(fallbackNormalizedQuery) + normalizedQuery !== null && + !caveat.provider.toLowerCase().includes(normalizedQuery) && + !caveat.dataset.toLowerCase().includes(normalizedQuery) && + !caveat.caveat.toLowerCase().includes(normalizedQuery) ) { continue; } diff --git a/libs/research/test/mcp-postgres-findings.test.ts b/libs/research/test/mcp-postgres-findings.test.ts index 2f3f1f03..6b5ddaf3 100644 --- a/libs/research/test/mcp-postgres-findings.test.ts +++ b/libs/research/test/mcp-postgres-findings.test.ts @@ -361,10 +361,10 @@ describe('createPostgresKnowledgeReaders (fake executor)', () => { expect(fake.calls[1]!.text).not.toContain(injection); expect(fake.calls[1]!.params).toEqual([injection]); - // Escaped ILIKE query on title and summary + // Escaped ILIKE query on title and summary (retaining non-ASCII stored rows as candidates) await readers.listFindings({ query: '100% pure_wild\\path' }); expect(fake.calls[2]!.text).toContain( - "WHERE title ILIKE $1::text ESCAPE '\\' OR summary ILIKE $1::text ESCAPE '\\'" + "WHERE title ILIKE $1::text ESCAPE '\\' OR summary ILIKE $1::text ESCAPE '\\' OR title ~ '[^\\x01-\\x7f]' OR summary ~ '[^\\x01-\\x7f]'" ); expect(fake.calls[2]!.params).toEqual(['%100\\% pure\\_wild\\\\path%']); @@ -402,7 +402,7 @@ describe('createPostgresKnowledgeReaders (fake executor)', () => { query: 'ignored', }); expect(fake.calls[1]!.text).toContain( - 'WHERE lower(provider) = lower($1::text) AND id = $2::text' + "WHERE (lower(provider) = lower($1::text) OR provider ~ '[^\\x01-\\x7f]') AND id = $2::text" ); expect(fake.calls[1]!.text).not.toContain('ILIKE'); expect(fake.calls[1]!.params).toEqual(['eodhd', 'caveat-001']); @@ -413,14 +413,14 @@ describe('createPostgresKnowledgeReaders (fake executor)', () => { query: '50%_ratio\\inv', }); expect(fake.calls[2]!.text).toContain( - "WHERE lower(provider) = lower($1::text) AND (provider ILIKE $2::text ESCAPE '\\' OR dataset ILIKE $2::text ESCAPE '\\' OR caveat ILIKE $2::text ESCAPE '\\')" + "WHERE (lower(provider) = lower($1::text) OR provider ~ '[^\\x01-\\x7f]') AND (provider ILIKE $2::text ESCAPE '\\' OR dataset ILIKE $2::text ESCAPE '\\' OR caveat ILIKE $2::text ESCAPE '\\' OR provider ~ '[^\\x01-\\x7f]' OR dataset ~ '[^\\x01-\\x7f]' OR caveat ~ '[^\\x01-\\x7f]')" ); expect(fake.calls[2]!.params).toEqual(['QuoteMedia', '%50\\%\\_ratio\\\\inv%']); // Query only await readers.listProviderCaveats({ query: 'split' }); expect(fake.calls[3]!.text).toContain( - "WHERE (provider ILIKE $1::text ESCAPE '\\' OR dataset ILIKE $1::text ESCAPE '\\' OR caveat ILIKE $1::text ESCAPE '\\')" + "WHERE (provider ILIKE $1::text ESCAPE '\\' OR dataset ILIKE $1::text ESCAPE '\\' OR caveat ILIKE $1::text ESCAPE '\\' OR provider ~ '[^\\x01-\\x7f]' OR dataset ~ '[^\\x01-\\x7f]' OR caveat ~ '[^\\x01-\\x7f]')" ); expect(fake.calls[3]!.params).toEqual(['%split%']); @@ -452,7 +452,9 @@ describe('createPostgresKnowledgeReaders (fake executor)', () => { query: 'ΚΟΣΜΟΣ', }); expect(caveatMatches.map(r => r.id)).toEqual(['c-1']); - expect(caveatFake.calls[0]!.text).toContain('WHERE lower(provider) = lower($1::text)'); + expect(caveatFake.calls[0]!.text).toContain( + "WHERE (lower(provider) = lower($1::text) OR provider ~ '[^\\x01-\\x7f]')" + ); expect(caveatFake.calls[0]!.text).not.toContain('ILIKE'); expect(caveatFake.calls[0]!.params).toEqual(['eodhd']); @@ -469,8 +471,56 @@ describe('createPostgresKnowledgeReaders (fake executor)', () => { expect(nonAsciiProvFake.calls[0]!.text).not.toContain('WHERE'); expect(nonAsciiProvFake.calls[0]!.params).toEqual([]); + // ASCII query / ASCII provider against Unicode stored rows (e.g. BİST and K under C collation): + // SQL retains non-ASCII stored rows as candidates and JS .toLowerCase() filters out non-matches. + const asciiAgainstUnicodeFindingFake = createFakeExecutor([ + makeRawFindingRow({ + id: 'f-bist', + title: 'BİST exchange coverage', + summary: 'Turkish equities.', + }), + makeRawFindingRow({ + id: 'f-other-unicode', + title: 'κόσμος', + summary: 'Unrelated Greek finding.', + }), + ]); + const asciiFindingReaders = createPostgresKnowledgeReaders({ + executor: asciiAgainstUnicodeFindingFake.executor, + }); + expect((await asciiFindingReaders.listFindings({ query: 'bi' })).map(r => r.id)).toEqual([ + 'f-bist', + ]); + + const asciiAgainstUnicodeCaveatFake = createFakeExecutor([ + makeRawCaveatRow({ + id: 'c-kelvin', + provider: 'K', + dataset: 'ds', + caveat: 'BİST feed note.', + }), + makeRawCaveatRow({ + id: 'c-other-unicode', + provider: 'κόσμος', + dataset: 'ds', + caveat: 'Unrelated.', + }), + ]); + const asciiCaveatReaders = createPostgresKnowledgeReaders({ + executor: asciiAgainstUnicodeCaveatFake.executor, + }); + expect( + (await asciiCaveatReaders.listProviderCaveats({ provider: 'k', query: 'bi' })).map(r => r.id) + ).toEqual(['c-kelvin']); + assertNoMutationOrReaderLimitSql( - [...findingFake.calls, ...caveatFake.calls, ...nonAsciiProvFake.calls], + [ + ...findingFake.calls, + ...caveatFake.calls, + ...nonAsciiProvFake.calls, + ...asciiAgainstUnicodeFindingFake.calls, + ...asciiAgainstUnicodeCaveatFake.calls, + ], true ); }); diff --git a/test/postgres/mcp-findings-adapter.test.ts b/test/postgres/mcp-findings-adapter.test.ts index a6c9c285..98c7e2c4 100644 --- a/test/postgres/mcp-findings-adapter.test.ts +++ b/test/postgres/mcp-findings-adapter.test.ts @@ -296,13 +296,15 @@ describe.skipIf(!url)('PostgreSQL MCP findings & provider caveats adapter', () = loserRecord: FiledFindingRecord ) => { const winnerClient = await f.pool.connect(); - const loserClient = await f.pool.connect(); let winnerOpen = false; cleanup.push(async () => { if (winnerOpen) { await winnerClient.query('ROLLBACK').catch(() => {}); } winnerClient.release(); + }); + const loserClient = await f.pool.connect(); + cleanup.push(() => { loserClient.release(); }); @@ -660,4 +662,143 @@ describe.skipIf(!url)('PostgreSQL MCP findings & provider caveats adapter', () = expect(sigmaCaveats.rowCount).toBe(1); expect(sigmaCaveats.rows[0]?.id).toBe('caveat-sigma-1'); }); + + test('matches ASCII queries and providers against Unicode stored text under PostgreSQL C collation through MCP', async () => { + const f = await createIsolatedFixture(); + + // Force C collation on text columns to reproduce the C-collation casing mismatch + // regardless of the host test database's default collation. + await f.pool.query(` + ALTER TABLE findings + ALTER COLUMN title TYPE TEXT COLLATE "C", + ALTER COLUMN summary TYPE TEXT COLLATE "C"; + ALTER TABLE provider_caveats + ALTER COLUMN provider TYPE TEXT COLLATE "C", + ALTER COLUMN dataset TYPE TEXT COLLATE "C", + ALTER COLUMN caveat TYPE TEXT COLLATE "C"; + `); + + // Prove PostgreSQL C collation itself fails both direct SQL casing comparisons. + const pgCheck = ( + await f.pool.query<{ ilike_match: boolean; lower_match: boolean }>( + `SELECT + ('BİST exchange coverage' COLLATE "C" ILIKE '%bi%') AS ilike_match, + (lower('K' COLLATE "C") = lower('k' COLLATE "C")) AS lower_match` + ) + ).rows[0]!; + expect(pgCheck.ilike_match).toBe(false); + expect(pgCheck.lower_match).toBe(false); + + const executor = createPgExecutor(f.pool); + const writePort = createPostgresFindingWritePort({ executor }); + const readers = createPostgresKnowledgeReaders({ executor }); + + let idSeq = 0; + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: writePort, + trialLookup: { + hasResearchVisibleTrial(ref) { + return ref === '101'; + }, + }, + newId: () => { + idSeq += 1; + return `finding-c-coll-${idSeq}`; + }, + now: () => new Date(FIXED_TS), + }), + createReadKnowledgeTool({ + port: { + listLibraryCards: async () => [], + ...readers, + }, + }), + ], + }); + + const callTool = async (name: string, args: Record) => { + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: `req-c-coll-${name}`, + method: 'tools/call', + params: { name, arguments: args }, + }) + ); + expect(raw).not.toBeNull(); + const parsed = JSON.parse(raw!) as { + result: { isError?: boolean; content: Array<{ text: string }> }; + }; + return parsed.result; + }; + + // File Unicode finding 'BİST exchange coverage' and an unrelated Unicode finding 'κόσμος' + const bistFileRes = await callTool('file_finding', { + kind: 'finding', + title: 'BİST exchange coverage', + summary: 'Turkish equities universe check.', + trialRefs: ['101'], + evidenceRefs: [], + }); + expect(bistFileRes.isError).toBeUndefined(); + const bistReceipt = JSON.parse(bistFileRes.content[0]!.text) as FileFindingResultPayload; + + const unrelatedFileRes = await callTool('file_finding', { + kind: 'finding', + title: 'κόσμος', + summary: 'Unrelated Greek finding.', + trialRefs: ['101'], + evidenceRefs: [], + }); + expect(unrelatedFileRes.isError).toBeUndefined(); + + // ASCII query 'bi' must match 'BİST exchange coverage' and exclude 'κόσμος' + const bistReadRes = await callTool('read_knowledge', { + source: 'findings', + query: 'bi', + }); + expect(bistReadRes.isError).toBeUndefined(); + const bistKnowledge = JSON.parse( + bistReadRes.content[0]!.text + ) as ReadKnowledgeResultPayload; + expect(bistKnowledge.rowCount).toBe(1); + expect(bistKnowledge.rows[0]?.id).toBe(bistReceipt.id); + + // Provider caveats: ASCII query against 'BİST' text, and ASCII provider 'k' against 'K' (U+212A) + await f.pool.query( + `INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at) + VALUES + ('caveat-c-bist', 'EODHD', 'eodPrices', 'BİST intraday feed caveat.', $1::timestamptz), + ('caveat-c-kelvin', 'K', 'kelvinBars', 'Kelvin sign provider caveat.', $1::timestamptz), + ('caveat-c-greek', 'EODHD', 'eodPrices', 'Unrelated κόσμος caveat.', $1::timestamptz)`, + [FIXED_TS] + ); + + const bistCaveatRes = await callTool('read_knowledge', { + source: 'provider_caveats', + provider: 'eodhd', + query: 'bi', + }); + expect(bistCaveatRes.isError).toBeUndefined(); + const bistCaveats = JSON.parse( + bistCaveatRes.content[0]!.text + ) as ReadKnowledgeResultPayload; + expect(bistCaveats.rowCount).toBe(1); + expect(bistCaveats.rows[0]?.id).toBe('caveat-c-bist'); + + const kelvinCaveatRes = await callTool('read_knowledge', { + source: 'provider_caveats', + provider: 'k', + }); + expect(kelvinCaveatRes.isError).toBeUndefined(); + const kelvinCaveats = JSON.parse( + kelvinCaveatRes.content[0]!.text + ) as ReadKnowledgeResultPayload; + expect(kelvinCaveats.rowCount).toBe(1); + expect(kelvinCaveats.rows[0]?.id).toBe('caveat-c-kelvin'); + }); }); From 52306675dfd284a3dd3178459b08f2b05884214e Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 10:05:17 -0500 Subject: [PATCH 11/21] T-161: tests --- .../test/mcp-postgres-findings-qa.test.ts | 268 ++++++++++++++++++ test/postgres/mcp-findings-adapter.test.ts | 130 +++++++++ 2 files changed, 398 insertions(+) create mode 100644 libs/research/test/mcp-postgres-findings-qa.test.ts diff --git a/libs/research/test/mcp-postgres-findings-qa.test.ts b/libs/research/test/mcp-postgres-findings-qa.test.ts new file mode 100644 index 00000000..249816fd --- /dev/null +++ b/libs/research/test/mcp-postgres-findings-qa.test.ts @@ -0,0 +1,268 @@ +import { describe, expect, test } from 'bun:test'; +import { + type FiledFindingRecord, + type PostgresFindingsExecutor, + createPostgresFindingWritePort, + createPostgresKnowledgeReaders, +} from '../src/mcp/index'; + +// QA edge cases for the PostgreSQL findings adapter (T-161), complementing +// mcp-postgres-findings.test.ts. All randomness is seeded; no wall clock. + +interface RecordedCall { + readonly text: string; + readonly params: readonly unknown[] | undefined; +} + +function createRowsExecutor(rows: readonly Record[]): { + readonly calls: RecordedCall[]; + readonly executor: PostgresFindingsExecutor; +} { + const calls: RecordedCall[] = []; + return { + calls, + executor: { + async query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + calls.push({ text, params }); + return { rows: rows as unknown as readonly Row[] }; + }, + }, + }; +} + +function mulberry32(seed: number): () => number { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +// Mix of ASCII (incl. LIKE wildcards / escape) and casing-hostile Unicode. +const ALPHABET = ['a', 'B', 'i', 'I', 's', 'S', 'k', '%', '_', '\\', ' ', 'İ', 'ı', 'Σ', 'ς', 'K', 'é', 'ß']; + +function randomText(rand: () => number, min: number, max: number): string { + const len = min + Math.floor(rand() * (max - min + 1)); + let out = ''; + for (let i = 0; i < len; i += 1) { + out += ALPHABET[Math.floor(rand() * ALPHABET.length)]; + } + return out; +} + +function randomQuery(rand: () => number, corpus: readonly string[]): string { + if (rand() < 0.5) { + const source = corpus[Math.floor(rand() * corpus.length)]!; + const start = Math.floor(rand() * source.length); + const end = Math.min(source.length, start + 1 + Math.floor(rand() * 3)); + let q = ''; + for (const ch of source.slice(start, end)) { + q += rand() < 0.5 ? ch.toUpperCase() : ch.toLowerCase(); + } + return q.length > 0 ? q : 'a'; + } + return randomText(rand, 1, 2); +} + +const TS = '2026-01-15T12:34:56.789Z'; + +describe('PostgreSQL findings readers QA: JS post-filter agrees with read_knowledge matching', () => { + test('seeded fuzz: listFindings returns exactly the read_knowledge-matching rows in SQL order', async () => { + const rand = mulberry32(161); + const rows = Array.from({ length: 40 }, (_, i) => ({ + id: `f-${String(i).padStart(3, '0')}`, + title: `T${randomText(rand, 2, 6)}`, + summary: `S${randomText(rand, 2, 6)}`, + status: 'pending_review', + created_at: new Date(TS), + trial_refs: [], + evidence_refs: [], + })); + const corpus = rows.flatMap(r => [r.title, r.summary]); + const { executor } = createRowsExecutor(rows); + const readers = createPostgresKnowledgeReaders({ executor }); + + for (let n = 0; n < 200; n += 1) { + const query = randomQuery(rand, corpus); + const lower = query.toLowerCase(); + const expected = rows + .filter(r => r.title.toLowerCase().includes(lower) || r.summary.toLowerCase().includes(lower)) + .map(r => r.id); + const actual = (await readers.listFindings({ query })).map(r => r.id); + expect({ query, ids: actual }).toEqual({ query, ids: expected }); + } + }); + + test('seeded fuzz: listProviderCaveats applies provider equality and query substring like read_knowledge', async () => { + const rand = mulberry32(2026); + const providers = ['EODHD', 'eodhd', 'K', 'kelvin', 'İBK', 'ibk', 'ΣΙΣ', 'σις']; + const rows = Array.from({ length: 40 }, (_, i) => ({ + id: `c-${String(i).padStart(3, '0')}`, + provider: providers[Math.floor(rand() * providers.length)]!, + dataset: `D${randomText(rand, 2, 5)}`, + caveat: `C${randomText(rand, 2, 6)}`, + created_at: new Date(TS), + })); + const corpus = rows.flatMap(r => [r.provider, r.dataset, r.caveat]); + const { executor } = createRowsExecutor(rows); + const readers = createPostgresKnowledgeReaders({ executor }); + + for (let n = 0; n < 200; n += 1) { + const provider = + rand() < 0.6 ? providers[Math.floor(rand() * providers.length)]!.toUpperCase() : undefined; + const query = rand() < 0.7 ? randomQuery(rand, corpus) : undefined; + const lowerProvider = provider?.toLowerCase(); + const lowerQuery = query?.toLowerCase(); + const expected = rows + .filter(r => lowerProvider === undefined || r.provider.toLowerCase() === lowerProvider) + .filter( + r => + lowerQuery === undefined || + r.provider.toLowerCase().includes(lowerQuery) || + r.dataset.toLowerCase().includes(lowerQuery) || + r.caveat.toLowerCase().includes(lowerQuery) + ) + .map(r => r.id); + const actual = ( + await readers.listProviderCaveats({ + ...(provider !== undefined ? { provider } : {}), + ...(query !== undefined ? { query } : {}), + }) + ).map(r => r.id); + expect({ provider, query, ids: actual }).toEqual({ provider, query, ids: expected }); + } + }); + + test('non-ASCII Kelvin-sign query omits SQL casing and still matches ASCII stored text via JS lowering', async () => { + const { calls, executor } = createRowsExecutor([ + { id: 'f-1', title: 'kelvin bars', summary: 'x', status: 's', created_at: new Date(TS), trial_refs: [], evidence_refs: [] }, + { id: 'f-2', title: 'other', summary: 'y', status: 's', created_at: new Date(TS), trial_refs: [], evidence_refs: [] }, + ]); + const readers = createPostgresKnowledgeReaders({ executor }); + + const result = await readers.listFindings({ query: 'Kelvin' }); + + expect(result.map(r => r.id)).toEqual(['f-1']); + expect(calls[0]!.text).not.toContain('WHERE'); + expect(calls[0]!.params).toEqual([]); + }); + + test('exact id ignores a non-ASCII query in the JS post-filter too', async () => { + const { calls, executor } = createRowsExecutor([ + { id: 'f-1', title: 'plain', summary: 'plain', status: 's', created_at: new Date(TS), trial_refs: [], evidence_refs: [] }, + ]); + const readers = createPostgresKnowledgeReaders({ executor }); + + const result = await readers.listFindings({ id: 'f-1', query: 'ΚΟΣΜΟΣ' }); + + expect(result.map(r => r.id)).toEqual(['f-1']); + expect(calls[0]!.params).toEqual(['f-1']); + }); + + test('ASCII provider selector excludes ASCII-different and Unicode-different providers after JS check', async () => { + const { executor } = createRowsExecutor([ + { id: 'c-1', provider: 'EODHD', dataset: 'd', caveat: 'c', created_at: new Date(TS) }, + { id: 'c-2', provider: 'EODHD2', dataset: 'd', caveat: 'c', created_at: new Date(TS) }, + { id: 'c-3', provider: 'ЕODHD', dataset: 'd', caveat: 'c', created_at: new Date(TS) }, // Cyrillic Е + ]); + const readers = createPostgresKnowledgeReaders({ executor }); + + expect((await readers.listProviderCaveats({ provider: 'eodhd' })).map(r => r.id)).toEqual(['c-1']); + }); +}); + +describe('PostgreSQL findings adapter QA: timestamps and write params', () => { + function readerForCreatedAt(createdAt: unknown) { + return createPostgresKnowledgeReaders({ + executor: createRowsExecutor([ + { id: 'c-1', provider: 'p', dataset: 'd', caveat: 'c', created_at: createdAt }, + ]).executor, + }); + } + + test.each([ + ['2024-02-29T00:00:00Z', '2024-02-29T00:00:00.000Z'], + ['2000-02-29T23:59:59.5+00:00', '2000-02-29T23:59:59.500Z'], + ['2026-01-01T01:30:00+02:00', '2025-12-31T23:30:00.000Z'], + ['2025-12-31T23:00:00-05:30', '2026-01-01T04:30:00.000Z'], + ['2026-01-15T12:34:56.123999+00:00', '2026-01-15T12:34:56.123Z'], + ['0099-06-01T00:00:00Z', '0099-06-01T00:00:00.000Z'], + ])('accepts valid timezone-qualified instant %s as UTC %s', async (raw, expectedIso) => { + const rows = await readerForCreatedAt(raw).listProviderCaveats({}); + expect(rows[0]!.createdAt).toBe(expectedIso); + }); + + test.each(['2025-02-29T00:00:00Z', '1900-02-29T00:00:00Z', '2026-04-31T00:00:00Z', '2026-00-10T00:00:00Z', '2026-01-15T12:60:00Z', '2026-01-15T12:00:00+05:60', '2026-01-15 12:00:00Z'])( + 'rejects invalid instant %s with INVALID_ROW', + async raw => { + await expect(readerForCreatedAt(raw).listProviderCaveats({})).rejects.toMatchObject({ + name: 'PostgresFindingsError', + code: 'INVALID_ROW', + }); + } + ); + + test('appendFinding binds copies of ref arrays and does not mutate the caller record', async () => { + const { calls, executor } = createRowsExecutor([{ id: 'f-1', created_at: new Date(TS) }]); + const port = createPostgresFindingWritePort({ executor }); + const trialRefs = Object.freeze(['1', '2']); + const evidenceRefs = Object.freeze(['e']); + const record: FiledFindingRecord = Object.freeze({ + id: 'f-1', + kind: 'dead_end', + title: 't', + status: 'pending_review', + createdAt: TS, + summary: 's', + trialRefs, + evidenceRefs, + }); + + const outcome = await port.appendFinding(record, 'k-1'); + + expect(outcome).toEqual({ status: 'created', id: 'f-1', createdAt: TS }); + const params = calls[0]!.params!; + expect(params[6]).toEqual(['1', '2']); + expect(params[6]).not.toBe(trialRefs); + expect(params[7]).not.toBe(evidenceRefs); + expect(params[8]).toBe('k-1'); + }); + + test('replay with identical payload but different status/createdAt still replays the stored receipt', async () => { + let call = 0; + const executor: PostgresFindingsExecutor = { + async query>(): Promise<{ readonly rows: readonly Row[] }> { + call += 1; + const rows = + call === 1 + ? [] + : [ + { + id: 'f-orig', + kind: 'finding', + title: 't', + summary: 's', + created_at: '2026-01-01T00:00:00+01:00', + trial_refs: ['1'], + evidence_refs: [], + }, + ]; + return { rows: rows as unknown as readonly Row[] }; + }, + }; + const port = createPostgresFindingWritePort({ executor }); + + const outcome = await port.appendFinding( + { id: 'f-new', kind: 'finding', title: 't', summary: 's', status: 'other', createdAt: TS, trialRefs: ['1'], evidenceRefs: [] }, + 'k' + ); + + expect(outcome).toEqual({ status: 'replayed', id: 'f-orig', createdAt: '2025-12-31T23:00:00.000Z' }); + }); +}); diff --git a/test/postgres/mcp-findings-adapter.test.ts b/test/postgres/mcp-findings-adapter.test.ts index 98c7e2c4..30857d7d 100644 --- a/test/postgres/mcp-findings-adapter.test.ts +++ b/test/postgres/mcp-findings-adapter.test.ts @@ -802,3 +802,133 @@ describe.skipIf(!url)('PostgreSQL MCP findings & provider caveats adapter', () = expect(kelvinCaveats.rows[0]?.id).toBe('caveat-c-kelvin'); }); }); + +// QA (T-161): seeded differential check that the adapter's SQL pushdown plus JS +// post-filter never drops or adds a row relative to read_knowledge's JS matching +// rules, against real PostgreSQL under both the database default and "C" collation. +function qaMulberry32(seed: number): () => number { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +const QA_ALPHABET = ['a', 'B', 'i', 'I', 's', 'S', 'k', '%', '_', '\\', ' ', 'İ', 'ı', 'Σ', 'ς', 'K', 'é', 'ß']; + +function qaText(rand: () => number, min: number, max: number): string { + const len = min + Math.floor(rand() * (max - min + 1)); + let out = ''; + for (let i = 0; i < len; i += 1) { + out += QA_ALPHABET[Math.floor(rand() * QA_ALPHABET.length)]; + } + return out; +} + +function qaQuery(rand: () => number, corpus: readonly string[]): string { + if (rand() < 0.5) { + const source = corpus[Math.floor(rand() * corpus.length)]!; + const start = Math.floor(rand() * source.length); + const end = Math.min(source.length, start + 1 + Math.floor(rand() * 3)); + let q = ''; + for (const ch of source.slice(start, end)) { + q += rand() < 0.5 ? ch.toUpperCase() : ch.toLowerCase(); + } + return q.length > 0 ? q : 'a'; + } + return qaText(rand, 1, 2); +} + +describe.skipIf(!url)('PostgreSQL findings readers QA differential vs read_knowledge matching', () => { + for (const forceCCollation of [false, true]) { + test(`seeded corpus/query fuzz agrees with JS matching (${forceCCollation ? 'C' : 'default'} collation)`, async () => { + const f = await createIsolatedFixture(); + if (forceCCollation) { + await f.pool.query(` + ALTER TABLE findings + ALTER COLUMN title TYPE TEXT COLLATE "C", + ALTER COLUMN summary TYPE TEXT COLLATE "C"; + ALTER TABLE provider_caveats + ALTER COLUMN provider TYPE TEXT COLLATE "C", + ALTER COLUMN dataset TYPE TEXT COLLATE "C", + ALTER COLUMN caveat TYPE TEXT COLLATE "C"; + `); + } + const executor = createPgExecutor(f.pool); + const writePort = createPostgresFindingWritePort({ executor }); + const readers = createPostgresKnowledgeReaders({ executor }); + const rand = qaMulberry32(forceCCollation ? 4242 : 161); + + const findings = Array.from({ length: 30 }, (_, i) => ({ + id: `qa-f-${String(i).padStart(3, '0')}`, + title: `T${qaText(rand, 2, 6)}`, + summary: `S${qaText(rand, 2, 6)}`, + })); + for (const row of findings) { + const outcome = await writePort.appendFinding( + makeFinding({ id: row.id, title: row.title, summary: row.summary }) + ); + expect(outcome.status).toBe('created'); + } + + const providers = ['EODHD', 'eodhd', 'K', 'kelvin', 'İBK', 'ibk', 'ΣΙΣ', 'σις']; + const caveats = Array.from({ length: 30 }, (_, i) => ({ + id: `qa-c-${String(i).padStart(3, '0')}`, + provider: providers[Math.floor(rand() * providers.length)]!, + dataset: `D${qaText(rand, 2, 5)}`, + caveat: `C${qaText(rand, 2, 6)}`, + })); + for (const row of caveats) { + await f.pool.query( + `INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at) + VALUES ($1, $2, $3, $4, $5::timestamptz)`, + [row.id, row.provider, row.dataset, row.caveat, FIXED_TS] + ); + } + + const findingCorpus = findings.flatMap(r => [r.title, r.summary]); + for (let n = 0; n < 60; n += 1) { + const query = qaQuery(rand, findingCorpus); + const lower = query.toLowerCase(); + const expected = findings + .filter( + r => r.title.toLowerCase().includes(lower) || r.summary.toLowerCase().includes(lower) + ) + .map(r => r.id); + const actual = (await readers.listFindings({ query })).map(r => r.id); + expect({ query, ids: actual }).toEqual({ query, ids: expected }); + } + + const caveatCorpus = caveats.flatMap(r => [r.provider, r.dataset, r.caveat]); + for (let n = 0; n < 60; n += 1) { + const provider = + rand() < 0.6 + ? providers[Math.floor(rand() * providers.length)]!.toUpperCase() + : undefined; + const query = rand() < 0.7 ? qaQuery(rand, caveatCorpus) : undefined; + const lowerProvider = provider?.toLowerCase(); + const lowerQuery = query?.toLowerCase(); + const expected = caveats + .filter(r => lowerProvider === undefined || r.provider.toLowerCase() === lowerProvider) + .filter( + r => + lowerQuery === undefined || + r.provider.toLowerCase().includes(lowerQuery) || + r.dataset.toLowerCase().includes(lowerQuery) || + r.caveat.toLowerCase().includes(lowerQuery) + ) + .map(r => r.id); + const actual = ( + await readers.listProviderCaveats({ + ...(provider !== undefined ? { provider } : {}), + ...(query !== undefined ? { query } : {}), + }) + ).map(r => r.id); + expect({ provider, query, ids: actual }).toEqual({ provider, query, ids: expected }); + } + }, 30_000); + } +}); From ffd41b209fdccc8ab72ae5e4193e1c01f2e0ab8d Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 10:07:02 -0500 Subject: [PATCH 12/21] =?UTF-8?q?T-162:=20M2.2h=20=E2=80=94=20`tools/curat?= =?UTF-8?q?e-etl`:=20pure=20`posts`=20curation=20stage=20(`CeoPost`=20?= =?UTF-8?q?=E2=86=92=20`build=5Fposts`=20=E2=86=92=20`provider=5Fmapping`?= =?UTF-8?q?=20on=20Eastern=20post=20date=20=E2=86=92=20`EventsParquetRow`s?= =?UTF-8?q?=20=E2=86=92=20`events`=20Zstd=20Parquet)=20in=20`curate=5Fpost?= =?UTF-8?q?s.rs`=20with=20tests=20(no=20new=20crates,=20no=20CLI/bench=20c?= =?UTF-8?q?hanges,=20no=20live=20Mongo)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/README.md | 26 +- tools/curate-etl/src/curate_posts.rs | 300 +++++++ tools/curate-etl/src/curate_posts_tests.rs | 953 +++++++++++++++++++++ tools/curate-etl/src/lib.rs | 6 + 4 files changed, 1284 insertions(+), 1 deletion(-) create mode 100644 tools/curate-etl/src/curate_posts.rs create mode 100644 tools/curate-etl/src/curate_posts_tests.rs diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index d47f9e02..26f6a65f 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`: `ceoPosts` raw-BSON decoding (pending live `edited` BSON type verification), `provider_mapping` resolution, Parquet writing, CLI subcommand, and benchmarks. +Deferred out of `src/posts.rs`: `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`, `events` Parquet row mapping in `src/parquet_posts.rs`, and `provider_mapping` listing resolution + Parquet writing in `src/curate_posts.rs`). ## `events` Builder (`M1.2g`) @@ -890,6 +890,30 @@ Command (`2026-11-28`, two back-to-back runs with identical checksum `0x0a1b7ace - Parquet write: `elapsed=682.82 ms`, `throughput=709419 rows/s` - Combined (stage → Parquet): `elapsed=1272.06 ms`, `throughput=393065 rows/s` +## `posts` Curation Stage (`M2.2h`) + +`curate_posts` and `curate_and_write_posts` (`src/curate_posts.rs`) join `build_posts`, `ProviderMappingTable`, `parquet_posts`, and `write_events_dataset` into contract `EventsParquetRow` records strictly ascending in the 7-field writer sort key `(listing_id, ts_micros, kind, subtype, payload_json, known_at_micros, known_at_source)`. + +1. **Contract & Eastern-posting-date mapping rules:** + - Validates that `mapping_source` is non-blank before consuming the input iterator (`CuratePostsError::EmptyMappingSource`), then runs `build_posts` unchanged on source keys so global `spiel_id` deduplication, `bot == "1"` newswire vs. retail splitting, and the `edited` text `known_at` guard execute before listing resolution. + - **Mapping date (`posted_at` in `America/Toronto`):** resolves `(mapping_source, key, et_date) -> listing_id` where `et_date` is the Eastern local calendar date of `posted_at` computed via `session_close::utc_micros_to_et_local` (supported Eastern calendar range `1976-01-01..=2030-12-31`, i.e. `1976-01-01T05:00:00Z..=2031-01-01T04:59:59.999999Z`). Never uses the UTC date and never uses the `known_at` date, so a post edited days later stays on the listing active when it was posted while its text remains guarded by `known_at`. + - Uses one `ProviderMappingTable::cursor_for` per contiguous `key` run in each builder stream (`newswire`, then `retail`); because `build_posts` sorts by `(key, known_at, spiel_id)` rather than `posted_at`, backward `et_date` steps use `ProviderMappingCursor::resolve`'s binary-search fallback automatically. + - Converts each mapped `PostRow` via `EventsParquetRow::from` (reusing `parquet_posts` labels `kind = "post"`, `subtype = "newswire" | "retail"`, `known_at_source = "post_timestamp" | "post_edited"`, and its RFC 8259 `payload_json` encoder), then sorts in place by the 7-field writer key and collapses exact 7-field duplicates into `listing_duplicate_collapsed`. + - `curate_and_write_posts` publishes Zstd Parquet partitions to `/events/year=YYYY/part.parquet` (partitioned by UTC calendar year of `ts_micros`). Any `CuratePostsError` returns before `write_events_dataset` is called, leaving `out_dir` untouched. +2. **Drop policy & stats conservation invariants (`CuratePostsStats`):** + - Posts whose `posted_at` falls outside `utc_micros_to_et_local`'s supported range are dropped and counted in `dropped_unsupported_date` (checked before mapping coverage) without aborting or panicking. + - Posts whose `(mapping_source, key, et_date)` has no covering `provider_mapping` range are dropped into `dropped_unmapped`. + - Exact conservation invariants: + - `rows_in == builder.newswire + builder.retail` + - `rows_in == rows_out + dropped_unmapped + dropped_unsupported_date + listing_duplicate_collapsed` + - `rows_out == newswire_out + retail_out` + - Typed errors: `CuratePostsError` (`Posts(PostsError)`, `EmptyMappingSource`) and `CuratePostsWriteError` (`Curate(CuratePostsError)`, `Parquet(ParquetEventsError)`). +3. **Known limits & deferred work:** + - **Global `spiel_id` deduplication & `listing_duplicate_collapsed`:** because `build_posts` deduplicates globally on `spiel_id` (keeping the greatest `known_at` and breaking ties by the maximum `(posted_at, is_edited, is_bot, key, user_id, text)` tuple) and `payload_json` carries `spiel_id`, `listing_duplicate_collapsed` is expected to be `0` for real input and exists only as a defensive writer-key uniqueness guard; when the same `spiel_id` appears under two source keys, the surviving key is chosen by `build_posts`'s existing tie-break. + - **In-memory buffering:** both `build_posts` and the final 7-field sort buffer all rows in RAM; full-corpus memory and throughput over the 14.8M-row `ceoPosts` dataset remain unverified. + - **Separate output root (no co-publishing with `curate-events`):** `write_events_dataset` writes and replaces `/events/year=YYYY/part.parquet` partitions, so publishing curated posts alongside `curate-events` filings/earnings in the same `events/` directory is not handled here; pass a dedicated `out_dir` until a unified publisher exists. + - **Not done / deferred:** the `curate-posts` CLI subcommand, benchmark, live `ceoPosts` run/verification, and co-publishing posts with `curate-events` output remain deferred to follow-up tasks. + ## `fx_1d` Curation Stage (`M1.2t`) `curate_fx_1d` and `curate_and_write_fx_1d` (`src/curate_fx.rs`) join `build_fx_1d` and `write_fx_1d_dataset` into contract `Fx1dParquetRow` records sorted and unique by `session_date` (no `provider_mapping` lookup is needed because FX rows are keyed by `pair = "USDCAD"`, not `listing_id`). diff --git a/tools/curate-etl/src/curate_posts.rs b/tools/curate-etl/src/curate_posts.rs new file mode 100644 index 00000000..752ae9c9 --- /dev/null +++ b/tools/curate-etl/src/curate_posts.rs @@ -0,0 +1,300 @@ +//! Pure, in-memory `posts` curation stage joining [`crate::posts::build_posts`], +//! [`crate::provider_mapping::ProviderMappingTable`], [`crate::parquet_posts`], and +//! [`crate::parquet_events::write_events_dataset`] into contract [`EventsParquetRow`]s. +//! +//! # Contract & Point-in-Time Rules +//! - Calls [`build_posts`] unchanged on source keys so global `spiel_id` deduplication, +//! `bot == "1"` newswire vs. retail splitting, and the `edited` text `known_at` guard run +//! before `provider_mapping` resolution. +//! - **Eastern local posting date (`posted_at`, not UTC date or `known_at`):** resolves each +//! post's `(mapping_source, key, et_date)` to a permanent `listing_id: i32` where `et_date` is +//! the `America/Toronto` (Eastern) local calendar date of `posted_at` via +//! [`crate::session_close::utc_micros_to_et_local`]. Late edits never shift a post onto a +//! different listing, while text availability remains guarded by `known_at`. +//! - Timestamps outside the range supported by `utc_micros_to_et_local` (`1976-01-01..=2030-12-31` +//! Eastern) are dropped and counted in [`CuratePostsStats::dropped_unsupported_date`] before +//! checking mapping coverage, without aborting or panicking. +//! - Rows with no covering `provider_mapping` range are dropped into +//! [`CuratePostsStats::dropped_unmapped`]. Because `build_posts` sorts by +//! `(key, known_at, spiel_id)` rather than `posted_at`, per-key lookups rely on +//! [`ProviderMappingCursor::resolve`]'s binary-search fallback whenever `et_date` steps +//! backward. +//! - Converts each mapped [`PostRow`] via [`EventsParquetRow::from`] (reusing +//! [`crate::parquet_posts`] labels and payload encoding verbatim), frees builder vectors before +//! re-sorting in place by the exact 7-field writer key +//! `(listing_id, ts_micros, kind, subtype, payload_json, known_at_micros, known_at_source)`, +//! and collapses exact 7-field duplicates into [`CuratePostsStats::listing_duplicate_collapsed`] +//! as a defensive writer-key uniqueness guard. + +use std::cmp::Ordering; +use std::error::Error; +use std::fmt; +use std::path::Path; + +use crate::parquet_events::{ + write_events_dataset, EventsParquetRow, EventsWriteOptions, EventsWriteStats, + ParquetEventsError, +}; +use crate::parquet_posts::{POST_SUBTYPE_NEWSWIRE, POST_SUBTYPE_RETAIL}; +use crate::posts::{build_posts, CeoPost, PostRow, PostsBuild, PostsError, PostsStats}; +use crate::provider_mapping::{ProviderMappingCursor, ProviderMappingTable}; +use crate::session_close::utc_micros_to_et_local; + +/// Accounting summary produced alongside [`CuratePostsOutput::rows`]. +/// +/// Conservation invariants: +/// - `rows_in == builder.newswire + builder.retail` +/// - `rows_in == rows_out + dropped_unmapped + dropped_unsupported_date + listing_duplicate_collapsed` +/// - `rows_out == newswire_out + retail_out` +/// - `builder` independently satisfies all [`PostsStats`] conservation invariants. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CuratePostsStats { + pub builder: PostsStats, + pub rows_in: usize, + pub rows_out: usize, + pub newswire_out: usize, + pub retail_out: usize, + pub listings_out: usize, + pub dropped_unmapped: usize, + pub dropped_unsupported_date: usize, + pub listing_duplicate_collapsed: usize, +} + +/// Output of [`curate_posts`]: contract Parquet rows strictly ascending in the 7-field writer +/// sort key and full stage + builder stats. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CuratePostsOutput { + pub rows: Vec, + pub stats: CuratePostsStats, +} + +/// Typed caller errors returned by [`curate_posts`]. +/// +/// Unmapped rows and posts outside the supported Eastern calendar range are dropped and counted +/// in [`CuratePostsStats`] rather than aborting the stage. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CuratePostsError { + /// Error propagated from [`build_posts`] (e.g., [`PostsError::TimestampOverflow`]). + Posts(PostsError), + /// Caller-supplied `mapping_source` was empty or contained only whitespace. + EmptyMappingSource, +} + +impl fmt::Display for CuratePostsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Posts(err) => write!(f, "{err}"), + Self::EmptyMappingSource => { + write!(f, "mapping_source must not be empty or blank") + } + } + } +} + +impl Error for CuratePostsError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Posts(err) => Some(err), + Self::EmptyMappingSource => None, + } + } +} + +impl From for CuratePostsError { + fn from(err: PostsError) -> Self { + Self::Posts(err) + } +} + +/// Combined stats returned by [`curate_and_write_posts`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CuratePostsWriteReport { + pub curate_stats: CuratePostsStats, + pub write_stats: EventsWriteStats, +} + +/// Typed error returned by [`curate_and_write_posts`]. +#[derive(Debug)] +pub enum CuratePostsWriteError { + Curate(CuratePostsError), + Parquet(ParquetEventsError), +} + +impl fmt::Display for CuratePostsWriteError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Curate(err) => write!(f, "posts curation failed: {err}"), + Self::Parquet(err) => write!(f, "posts Parquet write failed: {err}"), + } + } +} + +impl Error for CuratePostsWriteError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Curate(err) => Some(err), + Self::Parquet(err) => Some(err), + } + } +} + +impl From for CuratePostsWriteError { + fn from(err: CuratePostsError) -> Self { + Self::Curate(err) + } +} + +impl From for CuratePostsWriteError { + fn from(err: ParquetEventsError) -> Self { + Self::Parquet(err) + } +} + +#[inline] +fn compare_event_rows(a: &EventsParquetRow, b: &EventsParquetRow) -> Ordering { + a.listing_id + .cmp(&b.listing_id) + .then_with(|| a.ts_micros.cmp(&b.ts_micros)) + .then_with(|| a.kind.as_ref().cmp(b.kind.as_ref())) + .then_with(|| a.subtype.cmp(&b.subtype)) + .then_with(|| a.payload_json.cmp(&b.payload_json)) + .then_with(|| a.known_at_micros.cmp(&b.known_at_micros)) + .then_with(|| a.known_at_source.as_ref().cmp(b.known_at_source.as_ref())) +} + +fn resolve_and_finalize( + build: PostsBuild, + mapping_source: &str, + mapping: &ProviderMappingTable, +) -> CuratePostsOutput +where + K: Ord + Clone + AsRef, +{ + let rows_in = build.newswire.len() + build.retail.len(); + let mut stats = CuratePostsStats { + builder: build.stats, + rows_in, + ..CuratePostsStats::default() + }; + + let mut rows: Vec = Vec::with_capacity(rows_in); + + for stream in [build.newswire, build.retail] { + let mut current_key: Option = None; + let mut current_cursor: Option> = None; + + for row in stream { + if current_key.as_ref() != Some(&row.key) { + current_cursor = Some(mapping.cursor_for(mapping_source, row.key.as_ref())); + current_key = Some(row.key); + } + + let Ok(et_local) = utc_micros_to_et_local(row.posted_at) else { + stats.dropped_unsupported_date += 1; + continue; + }; + + let cursor = current_cursor + .as_mut() + .expect("cursor initialized for current key run"); + if cursor.ranges().is_empty() { + stats.dropped_unmapped += 1; + continue; + } + + let Some(listing_id) = cursor.resolve(et_local.session_date) else { + stats.dropped_unmapped += 1; + continue; + }; + + let mapped_row = PostRow { + key: listing_id, + spiel_id: row.spiel_id, + posted_at: row.posted_at, + known_at: row.known_at, + is_bot: row.is_bot, + is_edited: row.is_edited, + user_id: row.user_id, + text: row.text, + source: row.source, + }; + rows.push(EventsParquetRow::from(mapped_row)); + } + } + + rows.sort_unstable_by(compare_event_rows); + + let mapped_len = rows.len(); + rows.dedup(); + stats.listing_duplicate_collapsed = mapped_len - rows.len(); + + let mut last_listing_id: Option = None; + for row in &rows { + if last_listing_id != Some(row.listing_id) { + stats.listings_out += 1; + last_listing_id = Some(row.listing_id); + } + match row.subtype.as_str() { + POST_SUBTYPE_NEWSWIRE => stats.newswire_out += 1, + POST_SUBTYPE_RETAIL => stats.retail_out += 1, + other => unreachable!("unexpected post subtype from parquet_posts: {other:?}"), + } + } + stats.rows_out = rows.len(); + + CuratePostsOutput { rows, stats } +} + +/// Pure `posts` curation stage: builds point-in-time `ceoPosts` newswire and retail streams on +/// source keys via [`build_posts`], resolves `(mapping_source, key, et_date) -> listing_id` on +/// each post's `America/Toronto` (Eastern) local posting date via `provider_mapping`, and emits +/// contract [`EventsParquetRow`]s strictly ascending in the 7-field writer key. +/// +/// Mapping lookup always uses the Eastern local calendar date of `posted_at` (never UTC date and +/// never `known_at`). Posts outside the supported Eastern calendar range are dropped into +/// `dropped_unsupported_date`; unmapped posts are dropped into `dropped_unmapped`. +pub fn curate_posts( + posts: I, + mapping_source: &str, + mapping: &ProviderMappingTable, +) -> Result +where + K: Ord + Clone + AsRef, + I: IntoIterator>, +{ + if mapping_source.trim().is_empty() { + return Err(CuratePostsError::EmptyMappingSource); + } + + let built = build_posts(posts)?; + Ok(resolve_and_finalize(built, mapping_source, mapping)) +} + +/// Thin end-to-end wrapper running [`curate_posts`] and publishing the resulting contract rows +/// via [`write_events_dataset`] to `/events/year=YYYY/part.parquet`. +/// +/// Any [`CuratePostsError`] returns before [`write_events_dataset`] is invoked, leaving +/// `out_dir` untouched. +pub fn curate_and_write_posts( + out_dir: P, + posts: I, + mapping_source: &str, + mapping: &ProviderMappingTable, + options: EventsWriteOptions, +) -> Result +where + P: AsRef, + K: Ord + Clone + AsRef, + I: IntoIterator>, +{ + let curated = curate_posts(posts, mapping_source, mapping)?; + let write_stats = write_events_dataset(out_dir, &curated.rows, options)?; + Ok(CuratePostsWriteReport { + curate_stats: curated.stats, + write_stats, + }) +} + +#[cfg(test)] +#[path = "curate_posts_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/curate_posts_tests.rs b/tools/curate-etl/src/curate_posts_tests.rs new file mode 100644 index 00000000..177b3878 --- /dev/null +++ b/tools/curate-etl/src/curate_posts_tests.rs @@ -0,0 +1,953 @@ +use std::borrow::Cow; +use std::collections::HashSet; +use std::error::Error; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + +use parquet::basic::Compression; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::*; +use crate::events::partition_year_utc; +use crate::parquet_posts::{ + EVENT_KIND_POST, KNOWN_AT_SOURCE_POST_EDITED, KNOWN_AT_SOURCE_POST_TIMESTAMP, + POST_SUBTYPE_NEWSWIRE, POST_SUBTYPE_RETAIL, +}; +use crate::posts::{PostRow, PostsBuild, PostsError, PostsStats, POSTS_SOURCE_CEO}; +use crate::provider_mapping::{ProviderMappingRow, ProviderMappingTable}; +use crate::split::ymd_to_epoch_days; + +static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDirGuard { + path: PathBuf, +} + +impl TempDirGuard { + fn new(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = + std::env::temp_dir().join(format!("curate-etl-curate-posts-test-{label}-{pid}-{seq}")); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + fn new_uncreated(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = std::env::temp_dir().join(format!( + "curate-etl-curate-posts-uncreated-{label}-{pid}-{seq}" + )); + let _ = fs::remove_dir_all(&path); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn d(year: i32, month: u32, day: u32) -> i32 { + ymd_to_epoch_days(year, month, day).expect("valid test date") +} + +fn utc_ms(year: i32, month: u32, day: u32, hour: u8, minute: u8, second: u8) -> i64 { + let epoch_day = d(year, month, day); + let secs = i64::from(epoch_day) * 86_400 + + i64::from(hour) * 3_600 + + i64::from(minute) * 60 + + i64::from(second); + secs * 1_000 +} + +fn map_row( + source: &str, + source_id: &str, + valid_from: i32, + valid_to: Option, + listing_id: i32, +) -> ProviderMappingRow { + ProviderMappingRow { + source: source.to_string(), + source_id: source_id.to_string(), + valid_from, + valid_to, + listing_id, + } +} + +fn post( + key: &str, + spiel_id: &str, + timestamp_ms: i64, + edited_ms: Option, + bot: Option<&str>, + user_id: Option<&str>, + text: &str, +) -> CeoPost { + CeoPost { + key: key.to_string(), + spiel_id: spiel_id.to_string(), + timestamp_ms, + edited_ms, + bot: bot.map(str::to_string), + user_id: user_id.map(str::to_string), + text: text.to_string(), + } +} + +fn assert_stats_invariants(output: &CuratePostsOutput) { + let s = output.stats; + assert_eq!( + s.builder.input, + s.builder.newswire + + s.builder.retail + + s.builder.duplicates_dropped + + s.builder.rejected_invalid + ); + assert_eq!(s.rows_in, s.builder.newswire + s.builder.retail); + assert_eq!( + s.rows_in, + s.rows_out + + s.dropped_unmapped + + s.dropped_unsupported_date + + s.listing_duplicate_collapsed + ); + assert_eq!(s.rows_out, s.newswire_out + s.retail_out); + assert_eq!(s.rows_out, output.rows.len()); + + let distinct_listings: HashSet = output.rows.iter().map(|r| r.listing_id).collect(); + assert_eq!(s.listings_out, distinct_listings.len()); + + for pair in output.rows.windows(2) { + assert_eq!( + compare_event_rows(&pair[0], &pair[1]), + Ordering::Less, + "rows must be strictly ascending in 7-field writer key" + ); + } +} + +fn all_permutations(items: &[T]) -> Vec> { + let mut out = Vec::new(); + let mut arr = items.to_vec(); + let n = arr.len(); + let mut c = vec![0usize; n]; + out.push(arr.clone()); + + let mut i = 0; + while i < n { + if c[i] < i { + if i % 2 == 0 { + arr.swap(0, i); + } else { + arr.swap(c[i], i); + } + out.push(arr.clone()); + c[i] += 1; + i = 0; + } else { + c[i] = 0; + i += 1; + } + } + out +} + +fn read_events_parquet_and_verify_zstd(path: &Path) -> Vec { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let meta = reader.metadata(); + let mut out = Vec::new(); + + for rg_idx in 0..meta.num_row_groups() { + let rg_meta = meta.row_group(rg_idx); + assert_eq!( + rg_meta.num_columns(), + 7, + "expected 7 columns in events schema" + ); + for col_idx in 0..rg_meta.num_columns() { + let compression = rg_meta.column(col_idx).compression(); + assert!( + matches!(compression, Compression::ZSTD(_)), + "expected ZSTD compression for row_group={rg_idx} col={col_idx}, got {compression:?}" + ); + } + + let rg_rows = rg_meta.num_rows() as usize; + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + + let read_i32_col = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read i32 records"); + assert!(n > 0, "unexpected short read in INT32 column {col_idx}"); + read += n; + } + } + _ => panic!("expected INT32 column at index {col_idx}"), + } + vals + }; + + let read_i64_col = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int64ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read i64 records"); + assert!(n > 0, "unexpected short read in INT64 column {col_idx}"); + read += n; + } + } + _ => panic!("expected INT64 column at index {col_idx}"), + } + vals + }; + + let read_str_col = |col_idx: usize| -> Vec { + let mut raw = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut raw) + .expect("read byte_array records"); + assert!( + n > 0, + "unexpected short read in BYTE_ARRAY column {col_idx}" + ); + read += n; + } + } + _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), + } + raw.iter() + .map(|b| { + std::str::from_utf8(b.data()) + .expect("valid utf8") + .to_string() + }) + .collect() + }; + + let listing_ids = read_i32_col(0); + let ts = read_i64_col(1); + let known_at = read_i64_col(2); + let known_at_source = read_str_col(3); + let kind = read_str_col(4); + let subtype = read_str_col(5); + let payload_json = read_str_col(6); + + for i in 0..rg_rows { + out.push(EventsParquetRow { + listing_id: listing_ids[i], + ts_micros: ts[i], + known_at_micros: known_at[i], + known_at_source: Cow::Owned(known_at_source[i].clone()), + kind: Cow::Owned(kind[i].clone()), + subtype: subtype[i].clone(), + payload_json: payload_json[i].clone(), + }); + } + } + + out +} + +#[test] +fn bot_and_retail_posts_map_to_listing_with_matching_subtypes_and_counts() { + let mapping = + ProviderMappingTable::from_rows(vec![map_row("ceo", "CEO_ABC", d(2024, 1, 1), None, 42)]) + .expect("valid mapping"); + + let t_wire = utc_ms(2024, 6, 15, 14, 0, 0); + let t_retail = utc_ms(2024, 6, 15, 14, 5, 0); + + let output = curate_posts( + vec![ + post( + "CEO_ABC", + "sp_wire", + t_wire, + None, + Some("1"), + Some("thenewswire"), + "Company announces drill results", + ), + post( + "CEO_ABC", + "sp_retail", + t_retail, + None, + Some("0"), + Some("retail_user"), + "Looking strong today", + ), + ], + "ceo", + &mapping, + ) + .expect("curate_posts should succeed"); + + assert_stats_invariants(&output); + assert_eq!(output.rows.len(), 2); + assert_eq!(output.stats.rows_in, 2); + assert_eq!(output.stats.rows_out, 2); + assert_eq!(output.stats.newswire_out, 1); + assert_eq!(output.stats.retail_out, 1); + assert_eq!(output.stats.listings_out, 1); + + assert_eq!(output.rows[0].listing_id, 42); + assert_eq!(output.rows[0].kind.as_ref(), EVENT_KIND_POST); + assert_eq!(output.rows[0].subtype, POST_SUBTYPE_NEWSWIRE); + assert_eq!( + output.rows[0].known_at_source.as_ref(), + KNOWN_AT_SOURCE_POST_TIMESTAMP + ); + + assert_eq!(output.rows[1].listing_id, 42); + assert_eq!(output.rows[1].kind.as_ref(), EVENT_KIND_POST); + assert_eq!(output.rows[1].subtype, POST_SUBTYPE_RETAIL); + assert_eq!( + output.rows[1].known_at_source.as_ref(), + KNOWN_AT_SOURCE_POST_TIMESTAMP + ); +} + +#[test] +fn eastern_boundary_late_edit_and_non_monotonic_cursor_resolve_to_posting_date_listing() { + // Adjacent Eastern ranges: + // 2024-06-14 -> listing 101 + // 2024-06-15.. -> listing 202 + let mapping = ProviderMappingTable::from_rows(vec![ + map_row( + "ceo", + "CEO_REUSE", + d(2024, 6, 14), + Some(d(2024, 6, 14)), + 101, + ), + map_row("ceo", "CEO_REUSE", d(2024, 6, 15), None, 202), + ]) + .expect("valid mapping"); + + // 2024-06-15T03:30:00Z is 2024-06-14 23:30 EDT (Eastern date = June 14 -> listing 101). + // Edited on 2024-06-17T15:00:00Z (well inside listing 202's range), so its builder known_at + // comes AFTER the later post, forcing backward posted_at lookup on the same key & subtype. + let t_early_utc_next_day = utc_ms(2024, 6, 15, 3, 30, 0); + let t_early_edit = utc_ms(2024, 6, 17, 15, 0, 0); + // 2024-06-15T04:30:00Z is 2024-06-15 00:30 EDT (Eastern date = June 15 -> listing 202). + let t_later_et_next_day = utc_ms(2024, 6, 15, 4, 30, 0); + + let inputs = vec![ + post( + "CEO_REUSE", + "sp_june14_et_edited_late", + t_early_utc_next_day, + Some(t_early_edit), + None, + Some("u1"), + "Posted late evening June 14 EDT, edited June 17", + ), + post( + "CEO_REUSE", + "sp_june15_et_unedited", + t_later_et_next_day, + None, + None, + Some("u2"), + "Posted early morning June 15 EDT", + ), + ]; + + // Confirm the builder really puts the June 15 post BEFORE the June 14 post in the same + // (key, subtype) stream so the cursor must step backward from June 15 to June 14. + let built = build_posts(inputs.clone()).expect("build_posts"); + assert_eq!(built.retail.len(), 2); + assert_eq!(built.retail[0].spiel_id, "sp_june15_et_unedited"); + assert_eq!(built.retail[1].spiel_id, "sp_june14_et_edited_late"); + + let output = curate_posts(inputs, "ceo", &mapping).expect("curate_posts"); + assert_stats_invariants(&output); + assert_eq!(output.rows.len(), 2); + assert_eq!(output.stats.listings_out, 2); + + // Output is sorted by listing_id ascending: listing 101 first, listing 202 second. + let early = &output.rows[0]; + assert_eq!(early.listing_id, 101); + assert_eq!(early.ts_micros, t_early_utc_next_day * 1_000); + assert_eq!(early.known_at_micros, t_early_edit * 1_000); + assert!(early.known_at_micros > early.ts_micros); + assert_eq!(early.known_at_source.as_ref(), KNOWN_AT_SOURCE_POST_EDITED); + assert!(early.payload_json.contains("\"sp_june14_et_edited_late\"")); + + let later = &output.rows[1]; + assert_eq!(later.listing_id, 202); + assert_eq!(later.ts_micros, t_later_et_next_day * 1_000); + assert_eq!(later.known_at_micros, t_later_et_next_day * 1_000); + assert_eq!( + later.known_at_source.as_ref(), + KNOWN_AT_SOURCE_POST_TIMESTAMP + ); + assert!(later.payload_json.contains("\"sp_june15_et_unedited\"")); + + // Point-in-time guard: immediately before the edit timestamp, the edited text is excluded. + let cutoff_before_edit = early.known_at_micros - 1; + let visible_before: Vec<&EventsParquetRow> = output + .rows + .iter() + .filter(|r| r.known_at_micros <= cutoff_before_edit) + .collect(); + assert_eq!(visible_before.len(), 1); + assert_eq!(visible_before[0].listing_id, 202); + + let visible_at_edit: Vec<&EventsParquetRow> = output + .rows + .iter() + .filter(|r| r.known_at_micros <= early.known_at_micros) + .collect(); + assert_eq!(visible_at_edit.len(), 2); +} + +#[test] +fn unmapped_keys_out_of_range_dates_and_unsupported_timestamps_are_dropped_cleanly() { + let mapping = ProviderMappingTable::from_rows(vec![map_row( + "ceo", + "CEO_MAPPED", + d(2024, 6, 1), + Some(d(2024, 6, 30)), + 77, + )]) + .expect("valid mapping"); + + let t_inside = utc_ms(2024, 6, 15, 15, 0, 0); + let t_before_range = utc_ms(2024, 5, 31, 15, 0, 0); + let t_after_range = utc_ms(2024, 7, 1, 15, 0, 0); + // 2032-01-01T00:00:00Z converts to micros without overflow but exceeds 2030-12-31 ET. + let t_unsupported_future = utc_ms(2032, 1, 1, 0, 0, 0); + + let output = curate_posts( + vec![ + post( + "CEO_MAPPED", + "sp_ok", + t_inside, + None, + None, + Some("u1"), + "in range", + ), + post( + "CEO_MAPPED", + "sp_before", + t_before_range, + None, + None, + None, + "before range", + ), + post( + "CEO_MAPPED", + "sp_after", + t_after_range, + None, + Some("1"), + None, + "after range", + ), + post( + "CEO_UNKNOWN", + "sp_unknown_key", + t_inside, + None, + None, + None, + "unknown key", + ), + post( + "CEO_MAPPED", + "sp_unsupported_mapped", + t_unsupported_future, + None, + None, + None, + "unsupported year on mapped key", + ), + post( + "CEO_UNKNOWN", + "sp_unsupported_unmapped", + t_unsupported_future, + None, + Some("1"), + None, + "unsupported year on unmapped key counted as unsupported date first", + ), + ], + "ceo", + &mapping, + ) + .expect("curate_posts should not error on unmapped or unsupported-date rows"); + + assert_stats_invariants(&output); + assert_eq!(output.stats.rows_in, 6); + assert_eq!(output.stats.rows_out, 1); + assert_eq!(output.stats.retail_out, 1); + assert_eq!(output.stats.newswire_out, 0); + assert_eq!(output.stats.dropped_unmapped, 3); + assert_eq!(output.stats.dropped_unsupported_date, 2); + assert_eq!(output.stats.listing_duplicate_collapsed, 0); + assert_eq!(output.rows[0].listing_id, 77); +} + +#[test] +fn resolve_and_finalize_collapses_exact_seven_field_duplicates_across_source_keys() { + let mapping = ProviderMappingTable::from_rows(vec![ + map_row("ceo", "CEO_ALIAS_A", d(2024, 1, 1), None, 500), + map_row("ceo", "CEO_ALIAS_B", d(2024, 1, 1), None, 500), + ]) + .expect("valid mapping"); + + let posted_at = utc_ms(2024, 8, 10, 14, 0, 0) * 1_000; + let known_at = utc_ms(2024, 8, 10, 14, 15, 0) * 1_000; + + let build = PostsBuild { + newswire: Vec::new(), + retail: vec![ + PostRow { + key: "CEO_ALIAS_A".to_string(), + spiel_id: "sp_shared".to_string(), + posted_at, + known_at, + is_bot: false, + is_edited: true, + user_id: Some("u_same".to_string()), + text: "Identical post body".to_string(), + source: POSTS_SOURCE_CEO, + }, + PostRow { + key: "CEO_ALIAS_B".to_string(), + spiel_id: "sp_shared".to_string(), + posted_at, + known_at, + is_bot: false, + is_edited: true, + user_id: Some("u_same".to_string()), + text: "Identical post body".to_string(), + source: POSTS_SOURCE_CEO, + }, + ], + stats: PostsStats { + input: 2, + newswire: 0, + retail: 2, + edited: 2, + edited_before_posted: 0, + duplicates_dropped: 0, + rejected_invalid: 0, + }, + }; + + let output = resolve_and_finalize(build, "ceo", &mapping); + assert_stats_invariants(&output); + assert_eq!(output.stats.rows_in, 2); + assert_eq!(output.stats.rows_out, 1); + assert_eq!(output.stats.retail_out, 1); + assert_eq!(output.stats.newswire_out, 0); + assert_eq!(output.stats.listings_out, 1); + assert_eq!(output.stats.listing_duplicate_collapsed, 1); + assert_eq!(output.rows[0].listing_id, 500); +} + +#[test] +fn public_curate_posts_dedups_repeated_spiel_id_in_builder_and_keeps_distinct_spiel_ids() { + let mapping = ProviderMappingTable::from_rows(vec![ + map_row("ceo", "CEO_ALIAS_A", d(2024, 1, 1), None, 500), + map_row("ceo", "CEO_ALIAS_B", d(2024, 1, 1), None, 500), + ]) + .expect("valid mapping"); + + let t_post = utc_ms(2024, 8, 10, 14, 0, 0); + + // Same spiel_id under two source keys mapping to the same listing -> builder dedups before + // mapping, so duplicates_dropped == 1 and listing_duplicate_collapsed == 0. + let same_spiel = curate_posts( + vec![ + post( + "CEO_ALIAS_A", + "sp_dup", + t_post, + None, + None, + Some("u1"), + "Same post", + ), + post( + "CEO_ALIAS_B", + "sp_dup", + t_post, + None, + None, + Some("u1"), + "Same post", + ), + ], + "ceo", + &mapping, + ) + .expect("curate_posts"); + + assert_stats_invariants(&same_spiel); + assert_eq!(same_spiel.stats.builder.duplicates_dropped, 1); + assert_eq!(same_spiel.stats.rows_in, 1); + assert_eq!(same_spiel.stats.rows_out, 1); + assert_eq!(same_spiel.stats.listing_duplicate_collapsed, 0); + assert_eq!(same_spiel.rows[0].listing_id, 500); + + // Distinct spiel_ids (everything else identical) under the two alias keys -> both survive. + let distinct_spiel = curate_posts( + vec![ + post( + "CEO_ALIAS_A", + "sp_one", + t_post, + None, + None, + Some("u1"), + "Same text", + ), + post( + "CEO_ALIAS_B", + "sp_two", + t_post, + None, + None, + Some("u1"), + "Same text", + ), + ], + "ceo", + &mapping, + ) + .expect("curate_posts"); + + assert_stats_invariants(&distinct_spiel); + assert_eq!(distinct_spiel.stats.builder.duplicates_dropped, 0); + assert_eq!(distinct_spiel.stats.rows_in, 2); + assert_eq!(distinct_spiel.stats.rows_out, 2); + assert_eq!(distinct_spiel.stats.listing_duplicate_collapsed, 0); + assert_eq!(distinct_spiel.stats.listings_out, 1); +} + +#[test] +fn permutation_invariance_strict_sort_order_and_empty_input_accounting() { + let mapping = ProviderMappingTable::from_rows(vec![ + map_row("ceo", "CEO_A", d(2024, 1, 1), None, 10), + map_row("ceo", "CEO_B", d(2024, 1, 1), None, 20), + ]) + .expect("valid mapping"); + + // Empty input -> empty rows and default stats. + let empty = curate_posts(Vec::>::new(), "ceo", &mapping).expect("empty"); + assert!(empty.rows.is_empty()); + assert_eq!(empty.stats, CuratePostsStats::default()); + assert_stats_invariants(&empty); + + // Mixed fixture: newswire, retail, edited, unmapped, unsupported date, invalid row. + let t0 = utc_ms(2024, 9, 10, 14, 0, 0); + let t1 = utc_ms(2024, 9, 10, 15, 0, 0); + let t_future = utc_ms(2035, 1, 1, 0, 0, 0); + + let fixture = vec![ + post( + "CEO_B", + "sp_b_wire", + t0, + None, + Some("1"), + Some("wire"), + "Newswire release", + ), + post( + "CEO_A", + "sp_a_retail", + t1, + Some(t1 + 60_000), + None, + Some("u_a"), + "Edited retail post", + ), + post( + "CEO_A", + "sp_a_wire", + t0, + None, + Some(" 1 "), + None, + "Another wire", + ), + post( + "CEO_UNKNOWN", + "sp_unmapped", + t0, + None, + None, + None, + "Unmapped", + ), + post( + "CEO_A", + "sp_unsupported", + t_future, + None, + None, + None, + "Future unsupported", + ), + post("CEO_A", "", t0, None, None, None, "Invalid empty spiel_id"), + ]; + + let baseline = curate_posts(fixture.clone(), "ceo", &mapping).expect("baseline"); + assert_stats_invariants(&baseline); + assert_eq!(baseline.stats.builder.input, 6); + assert_eq!(baseline.stats.builder.rejected_invalid, 1); + assert_eq!(baseline.stats.rows_in, 5); + assert_eq!(baseline.stats.rows_out, 3); + assert_eq!(baseline.stats.newswire_out, 2); + assert_eq!(baseline.stats.retail_out, 1); + assert_eq!(baseline.stats.listings_out, 2); + assert_eq!(baseline.stats.dropped_unmapped, 1); + assert_eq!(baseline.stats.dropped_unsupported_date, 1); + + let perms = all_permutations(&fixture); + assert_eq!(perms.len(), 720); + for perm in perms { + let got = curate_posts(perm, "ceo", &mapping).expect("permuted curate_posts"); + assert_eq!(got, baseline); + } +} + +struct PanicOnConsumeIter; + +impl Iterator for PanicOnConsumeIter { + type Item = CeoPost; + + fn next(&mut self) -> Option { + panic!("iterator must not be consumed when mapping_source is blank"); + } +} + +#[test] +fn typed_errors_for_blank_mapping_source_and_timestamp_overflow_leave_out_dir_untouched() { + let mapping = ProviderMappingTable::default(); + + for blank in ["", " ", "\t\n"] { + let err = curate_posts(PanicOnConsumeIter, blank, &mapping) + .expect_err("blank mapping_source must fail before consuming iterator"); + assert_eq!(err, CuratePostsError::EmptyMappingSource); + assert!(err.source().is_none()); + assert!(err.to_string().contains("mapping_source")); + + // Missing output path stays missing. + let missing_dir = TempDirGuard::new_uncreated("blank-missing"); + let write_err = curate_and_write_posts( + missing_dir.path(), + PanicOnConsumeIter, + blank, + &mapping, + EventsWriteOptions::default(), + ) + .expect_err("curate_and_write_posts must fail on blank mapping_source"); + assert!(matches!( + write_err, + CuratePostsWriteError::Curate(CuratePostsError::EmptyMappingSource) + )); + assert!(write_err.source().is_some()); + assert!(write_err.to_string().contains("posts curation failed")); + assert!(!missing_dir.path().exists()); + + // Existing empty output directory stays empty. + let empty_dir = TempDirGuard::new("blank-empty"); + let _ = curate_and_write_posts( + empty_dir.path(), + PanicOnConsumeIter, + blank, + &mapping, + EventsWriteOptions::default(), + ) + .expect_err("curate_and_write_posts must fail on blank mapping_source"); + assert_eq!(fs::read_dir(empty_dir.path()).expect("read dir").count(), 0); + } + + // TimestampOverflow propagates as CuratePostsError::Posts and leaves out_dir untouched. + let overflow_posts = vec![post( + "CEO_A", + "sp_overflow", + i64::MAX, + None, + None, + None, + "overflow timestamp", + )]; + + let err = curate_posts(overflow_posts.clone(), "ceo", &mapping) + .expect_err("overflow timestamp must fail"); + assert_eq!( + err, + CuratePostsError::Posts(PostsError::TimestampOverflow { + spiel_id: "sp_overflow".to_string(), + field: "timestamp_ms", + timestamp_ms: i64::MAX, + }) + ); + assert!(err.source().is_some()); + assert!(err.to_string().contains("sp_overflow")); + + let missing_dir = TempDirGuard::new_uncreated("overflow-missing"); + let write_err = curate_and_write_posts( + missing_dir.path(), + overflow_posts.clone(), + "ceo", + &mapping, + EventsWriteOptions::default(), + ) + .expect_err("curate_and_write_posts must fail on overflow"); + assert!(matches!( + write_err, + CuratePostsWriteError::Curate(CuratePostsError::Posts( + PostsError::TimestampOverflow { .. } + )) + )); + assert!(write_err.source().is_some()); + assert!(!missing_dir.path().exists()); + + let empty_dir = TempDirGuard::new("overflow-empty"); + let _ = curate_and_write_posts( + empty_dir.path(), + overflow_posts, + "ceo", + &mapping, + EventsWriteOptions::default(), + ) + .expect_err("curate_and_write_posts must fail on overflow"); + assert_eq!(fs::read_dir(empty_dir.path()).expect("read dir").count(), 0); +} + +#[test] +fn curate_and_write_posts_round_trips_zstd_parquet_field_for_field() { + let dir = TempDirGuard::new("round-trip"); + let mapping = ProviderMappingTable::from_rows(vec![ + map_row("ceo", "CEO_A", d(2024, 1, 1), None, 101), + map_row("ceo", "CEO_B", d(2024, 1, 1), None, 202), + ]) + .expect("valid mapping"); + + let t_2024 = utc_ms(2024, 12, 31, 23, 30, 0); + let t_2025_edit = utc_ms(2025, 1, 1, 0, 10, 0); + let t_2025 = utc_ms(2025, 2, 14, 15, 0, 0); + + let fixture = vec![ + post( + "CEO_A", + "sp_2024_special", + t_2024, + Some(t_2025_edit), + None, + Some("user\"1"), + "Quote \"here\", newline\nline2, non-ASCII café €", + ), + post( + "CEO_B", + "sp_2024_wire", + t_2024, + None, + Some("1"), + Some("thenewswire"), + "Year-end wire release", + ), + post( + "CEO_A", + "sp_2025_retail", + t_2025, + None, + None, + None, + "2025 commentary", + ), + post( + "CEO_UNMAPPED", + "sp_dropped", + t_2025, + None, + None, + None, + "Dropped unmapped", + ), + ]; + + let pure = curate_posts(fixture.clone(), "ceo", &mapping).expect("pure curate_posts"); + assert_stats_invariants(&pure); + assert_eq!(pure.rows.len(), 3); + + let report = curate_and_write_posts( + dir.path(), + fixture, + "ceo", + &mapping, + EventsWriteOptions::default(), + ) + .expect("curate_and_write_posts should succeed"); + + assert_eq!(report.curate_stats, pure.stats); + assert_eq!(report.write_stats.rows_written, pure.stats.rows_out); + assert_eq!(report.write_stats.files_written, 2); + assert_eq!(report.write_stats.rows_by_year.get(&2024), Some(&2)); + assert_eq!(report.write_stats.rows_by_year.get(&2025), Some(&1)); + + let path_2024 = dir.path().join("events/year=2024/part.parquet"); + let path_2025 = dir.path().join("events/year=2025/part.parquet"); + assert!(path_2024.exists()); + assert!(path_2025.exists()); + + let read_2024 = read_events_parquet_and_verify_zstd(&path_2024); + let read_2025 = read_events_parquet_and_verify_zstd(&path_2025); + + let expected_2024: Vec = pure + .rows + .iter() + .filter(|r| partition_year_utc(r.ts_micros) == 2024) + .cloned() + .collect(); + let expected_2025: Vec = pure + .rows + .iter() + .filter(|r| partition_year_utc(r.ts_micros) == 2025) + .cloned() + .collect(); + + assert_eq!(read_2024, expected_2024); + assert_eq!(read_2025, expected_2025); + assert!(read_2024[0].payload_json.contains("café €")); + assert!(read_2024[0].payload_json.contains("\\nline2")); + assert!(read_2024[0].payload_json.contains("\\\"here\\\"")); +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index ad00e80b..bbcac68c 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -230,6 +230,12 @@ pub use curate_events::{ CurateEventsStats, CurateEventsWriteError, CurateEventsWriteReport, }; +pub mod curate_posts; +pub use curate_posts::{ + curate_and_write_posts, curate_posts, CuratePostsError, CuratePostsOutput, CuratePostsStats, + CuratePostsWriteError, CuratePostsWriteReport, +}; + pub mod curate_fx; pub use curate_fx::{ curate_and_write_fx_1d, curate_fx_1d, fx_1d_utc_day_end_micros, CurateFx1dOutput, From b061299b449aaa0b0a978075f7b4338c9649095b Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 10:19:44 -0500 Subject: [PATCH 13/21] T-162: tests --- tools/curate-etl/src/curate_posts_tests.rs | 453 +++++++++++++++++++++ 1 file changed, 453 insertions(+) diff --git a/tools/curate-etl/src/curate_posts_tests.rs b/tools/curate-etl/src/curate_posts_tests.rs index 177b3878..b58de460 100644 --- a/tools/curate-etl/src/curate_posts_tests.rs +++ b/tools/curate-etl/src/curate_posts_tests.rs @@ -951,3 +951,456 @@ fn curate_and_write_posts_round_trips_zstd_parquet_field_for_field() { assert!(read_2024[0].payload_json.contains("\\nline2")); assert!(read_2024[0].payload_json.contains("\\\"here\\\"")); } + +// --------------------------------------------------------------------------- +// QA edge cases (T-162). +// --------------------------------------------------------------------------- + +/// Independent 7-field writer key built from raw fields (does not reuse `compare_event_rows`). +fn writer_key(r: &EventsParquetRow) -> (i32, i64, String, String, String, i64, String) { + ( + r.listing_id, + r.ts_micros, + r.kind.to_string(), + r.subtype.clone(), + r.payload_json.clone(), + r.known_at_micros, + r.known_at_source.to_string(), + ) +} + +fn assert_strictly_ascending_by_tuple(rows: &[EventsParquetRow]) { + for pair in rows.windows(2) { + assert!( + writer_key(&pair[0]) < writer_key(&pair[1]), + "rows not strictly ascending by 7-field tuple: {:?} !< {:?}", + writer_key(&pair[0]), + writer_key(&pair[1]) + ); + } +} + +#[test] +fn supported_eastern_range_boundaries_are_inclusive_and_drop_outside_without_error() { + use crate::session_close::{ + SESSION_MAX_SUPPORTED_UTC_MICROS, SESSION_MIN_SUPPORTED_UTC_MICROS, + }; + + // Mapping covers the whole supported range for one key. + let mapping = + ProviderMappingTable::from_rows(vec![map_row("ceo", "CEO_EDGE", d(1976, 1, 1), None, 9)]) + .expect("valid mapping"); + + // `posted_at` = ms * 1000, so millisecond-aligned edges. + let min_ms = SESSION_MIN_SUPPORTED_UTC_MICROS / 1_000; + assert_eq!(min_ms * 1_000, SESSION_MIN_SUPPORTED_UTC_MICROS); + let max_ms = SESSION_MAX_SUPPORTED_UTC_MICROS / 1_000; // 2031-01-01T04:59:59.999Z + assert_eq!(min_ms, utc_ms(1976, 1, 1, 5, 0, 0)); + assert_eq!(max_ms + 1, utc_ms(2031, 1, 1, 5, 0, 0)); + + let output = curate_posts( + vec![ + post( + "CEO_EDGE", + "sp_min", + min_ms, + None, + None, + None, + "first supported ms", + ), + post( + "CEO_EDGE", + "sp_min_minus", + min_ms - 1, + None, + None, + None, + "1975 EST", + ), + post( + "CEO_EDGE", + "sp_max", + max_ms, + None, + Some("1"), + None, + "last supported ms", + ), + post( + "CEO_EDGE", + "sp_max_plus", + max_ms + 1, + None, + None, + None, + "2031 EST", + ), + // Positive but early (1970) timestamp passes the builder and must be dropped too. + post("CEO_EDGE", "sp_1970", 1, None, None, None, "epoch + 1ms"), + ], + "ceo", + &mapping, + ) + .expect("out-of-range dates must not error"); + + assert_stats_invariants(&output); + assert_eq!(output.stats.builder.rejected_invalid, 0); + assert_eq!(output.stats.rows_in, 5); + assert_eq!(output.stats.rows_out, 2); + assert_eq!(output.stats.dropped_unsupported_date, 3); + assert_eq!(output.stats.dropped_unmapped, 0); + let ts: Vec = output.rows.iter().map(|r| r.ts_micros).collect(); + assert_eq!(ts, vec![min_ms * 1_000, max_ms * 1_000]); + assert!(output.rows.iter().all(|r| r.listing_id == 9)); +} + +#[test] +fn winter_est_midnight_boundary_uses_eastern_date_not_utc_date() { + // EST (UTC-5) in January: 04:59:59Z is still the previous Eastern day, 05:00:00Z is not. + let mapping = ProviderMappingTable::from_rows(vec![ + map_row("ceo", "CEO_W", d(2024, 1, 1), Some(d(2024, 1, 14)), 31), + map_row("ceo", "CEO_W", d(2024, 1, 15), None, 32), + ]) + .expect("valid mapping"); + + let before_et_midnight = utc_ms(2024, 1, 15, 4, 59, 59); // 2024-01-14 23:59:59 EST + let at_et_midnight = utc_ms(2024, 1, 15, 5, 0, 0); // 2024-01-15 00:00:00 EST + let utc_prev_day_evening = utc_ms(2024, 1, 14, 23, 0, 0); // 2024-01-14 18:00 EST + + let output = curate_posts( + vec![ + post("CEO_W", "sp_a", before_et_midnight, None, None, None, "a"), + post("CEO_W", "sp_b", at_et_midnight, None, None, None, "b"), + post("CEO_W", "sp_c", utc_prev_day_evening, None, None, None, "c"), + ], + "ceo", + &mapping, + ) + .expect("curate_posts"); + assert_stats_invariants(&output); + + let listing_of = |spiel: &str| { + output + .rows + .iter() + .find(|r| r.payload_json.contains(&format!("\"{spiel}\""))) + .map(|r| r.listing_id) + .expect("row present") + }; + assert_eq!( + listing_of("sp_a"), + 31, + "UTC date is Jan 15 but Eastern date is Jan 14" + ); + assert_eq!(listing_of("sp_b"), 32); + assert_eq!(listing_of("sp_c"), 31); +} + +#[test] +fn multi_range_key_with_repeated_backward_date_jumps_matches_table_resolve() { + // Three ranges plus a gap; late edits scramble known_at order relative to posted_at. + let mapping = ProviderMappingTable::from_rows(vec![ + map_row("ceo", "CEO_M", d(2023, 1, 1), Some(d(2023, 3, 31)), 1), + map_row("ceo", "CEO_M", d(2023, 4, 1), Some(d(2023, 6, 30)), 2), + // gap 2023-07-01..=2023-07-31 + map_row("ceo", "CEO_M", d(2023, 8, 1), None, 3), + ]) + .expect("valid mapping"); + + // (spiel, posted, edited, expected listing or None for unmapped gap) + let cases: Vec<(&str, i64, Option, Option)> = vec![ + ( + "sp_feb", + utc_ms(2023, 2, 10, 15, 0, 0), + Some(utc_ms(2023, 12, 1, 15, 0, 0)), + Some(1), + ), + ( + "sp_may", + utc_ms(2023, 5, 10, 15, 0, 0), + Some(utc_ms(2023, 11, 1, 15, 0, 0)), + Some(2), + ), + ("sp_sep", utc_ms(2023, 9, 10, 15, 0, 0), None, Some(3)), + ( + "sp_jul_gap", + utc_ms(2023, 7, 10, 15, 0, 0), + Some(utc_ms(2023, 10, 1, 15, 0, 0)), + None, + ), + ( + "sp_jan", + utc_ms(2023, 1, 5, 15, 0, 0), + Some(utc_ms(2024, 1, 1, 15, 0, 0)), + Some(1), + ), + ("sp_jun", utc_ms(2023, 6, 30, 15, 0, 0), None, Some(2)), + // 2023-04-01T03:00Z = 2023-03-31 23:00 EDT -> listing 1, edited later. + ( + "sp_mar_et", + utc_ms(2023, 4, 1, 3, 0, 0), + Some(utc_ms(2023, 12, 15, 15, 0, 0)), + Some(1), + ), + ]; + + let inputs: Vec> = cases + .iter() + .map(|(s, p, e, _)| post("CEO_M", s, *p, *e, None, None, s)) + .collect(); + + // Prove the builder stream really is non-monotonic in posted_at. + let built = build_posts(inputs.clone()).expect("build"); + let posted: Vec = built.retail.iter().map(|r| r.posted_at).collect(); + assert!(posted.windows(2).filter(|w| w[1] < w[0]).count() >= 2); + + let output = curate_posts(inputs, "ceo", &mapping).expect("curate"); + assert_stats_invariants(&output); + assert_eq!(output.stats.dropped_unmapped, 1); + assert_eq!(output.stats.rows_out, 6); + + for (spiel, posted_ms, _, expected) in &cases { + let got = output + .rows + .iter() + .find(|r| { + r.payload_json + .contains(&format!("\"spiel_id\":\"{spiel}\"")) + }) + .map(|r| r.listing_id); + assert_eq!(got, *expected, "spiel {spiel}"); + // Oracle: fresh table-level binary search on the Eastern posting date. + let et = utc_micros_to_et_local(posted_ms * 1_000).expect("supported"); + assert_eq!(mapping.resolve("ceo", "CEO_M", et.session_date), *expected); + } +} + +#[test] +fn mapping_rows_for_another_source_do_not_resolve() { + let mapping = ProviderMappingTable::from_rows(vec![ + map_row("eod", "CEO_X", d(2024, 1, 1), None, 7), + map_row("ceo", "CEO_Y", d(2024, 1, 1), None, 8), + ]) + .expect("valid mapping"); + let t = utc_ms(2024, 5, 1, 15, 0, 0); + + let output = curate_posts( + vec![ + post("CEO_X", "sp_x", t, None, None, None, "x"), + post("CEO_Y", "sp_y", t, None, None, None, "y"), + ], + "ceo", + &mapping, + ) + .expect("curate"); + assert_stats_invariants(&output); + assert_eq!(output.stats.dropped_unmapped, 1); + assert_eq!(output.rows.len(), 1); + assert_eq!(output.rows[0].listing_id, 8); +} + +#[test] +fn same_key_in_newswire_and_retail_streams_resolves_both() { + // The key appears in both builder streams; each stream needs its own cursor run. + let mapping = ProviderMappingTable::from_rows(vec![ + map_row("ceo", "CEO_A", d(2024, 1, 1), Some(d(2024, 3, 31)), 1), + map_row("ceo", "CEO_A", d(2024, 4, 1), None, 2), + map_row("ceo", "CEO_Z", d(2024, 1, 1), None, 3), + ]) + .expect("valid mapping"); + + let output = curate_posts( + vec![ + post( + "CEO_A", + "w1", + utc_ms(2024, 5, 1, 15, 0, 0), + None, + Some("1"), + None, + "w1", + ), + post( + "CEO_Z", + "w2", + utc_ms(2024, 5, 1, 15, 0, 0), + None, + Some("1"), + None, + "w2", + ), + post( + "CEO_A", + "r1", + utc_ms(2024, 2, 1, 15, 0, 0), + None, + None, + None, + "r1", + ), + post( + "CEO_Z", + "r2", + utc_ms(2024, 2, 1, 15, 0, 0), + None, + None, + None, + "r2", + ), + ], + "ceo", + &mapping, + ) + .expect("curate"); + assert_stats_invariants(&output); + let got: Vec<(i32, &str)> = output + .rows + .iter() + .map(|r| (r.listing_id, r.subtype.as_str())) + .collect(); + assert_eq!( + got, + // Listing 3: Feb retail precedes May newswire by ts_micros. + vec![ + (1, "retail"), + (2, "newswire"), + (3, "retail"), + (3, "newswire") + ] + ); + assert_eq!(output.stats.listings_out, 3); +} + +#[test] +fn parquet_writer_error_is_wrapped_and_curate_stats_not_returned() { + let dir = TempDirGuard::new("writer-error"); + let mapping = + ProviderMappingTable::from_rows(vec![map_row("ceo", "CEO_A", d(2024, 1, 1), None, 1)]) + .expect("valid mapping"); + + let err = curate_and_write_posts( + dir.path(), + vec![post( + "CEO_A", + "sp", + utc_ms(2024, 5, 1, 15, 0, 0), + None, + None, + None, + "t", + )], + "ceo", + &mapping, + EventsWriteOptions { + row_group_rows: 0, + ..EventsWriteOptions::default() + }, + ) + .expect_err("invalid writer options must fail"); + assert!(matches!( + err, + CuratePostsWriteError::Parquet(ParquetEventsError::InvalidRowGroupRows) + )); + assert!(err.source().is_some()); + assert!(err.to_string().contains("posts Parquet write failed")); + assert!(!dir.path().join("events/year=2024/part.parquet").exists()); +} + +#[test] +fn same_listing_same_timestamp_tie_breaks_on_subtype_then_payload_and_round_trips() { + let dir = TempDirGuard::new("tie-break"); + let mapping = + ProviderMappingTable::from_rows(vec![map_row("ceo", "CEO_T", d(2024, 1, 1), None, 55)]) + .expect("valid mapping"); + + let t = utc_ms(2024, 7, 1, 14, 0, 0); + let fixture = vec![ + // Same listing + ts: two retail (payload differs via spiel_id) and two newswire. + post( + "CEO_T", + "sp_r_b", + t, + None, + None, + Some("u"), + "retail \"b\"\nné", + ), + post( + "CEO_T", + "sp_r_a", + t, + Some(t + 5_000), + None, + Some("u"), + "retail a", + ), + post("CEO_T", "sp_w_b", t, None, Some("1"), None, "wire b"), + post("CEO_T", "sp_w_a", t, None, Some("1"), None, "wire a"), + ]; + + let pure = curate_posts(fixture.clone(), "ceo", &mapping).expect("curate"); + assert_stats_invariants(&pure); + assert_strictly_ascending_by_tuple(&pure.rows); + + let order: Vec<(String, String)> = pure + .rows + .iter() + .map(|r| { + let spiel = r.payload_json[13..].split('"').next().unwrap().to_string(); + (r.subtype.clone(), spiel) + }) + .collect(); + assert_eq!( + order, + vec![ + ("newswire".to_string(), "sp_w_a".to_string()), + ("newswire".to_string(), "sp_w_b".to_string()), + ("retail".to_string(), "sp_r_a".to_string()), + ("retail".to_string(), "sp_r_b".to_string()), + ] + ); + assert_eq!( + pure.rows[2].known_at_source.as_ref(), + KNOWN_AT_SOURCE_POST_EDITED + ); + assert_eq!(pure.rows[2].known_at_micros, (t + 5_000) * 1_000); + + let report = curate_and_write_posts( + dir.path(), + fixture, + "ceo", + &mapping, + EventsWriteOptions::default(), + ) + .expect("write"); + assert_eq!(report.curate_stats, pure.stats); + assert_eq!(report.write_stats.rows_written, 4); + let read = + read_events_parquet_and_verify_zstd(&dir.path().join("events/year=2024/part.parquet")); + assert_eq!(read, pure.rows); + assert_strictly_ascending_by_tuple(&read); +} + +#[test] +fn permutation_fixture_is_strictly_ascending_by_independent_tuple() { + let mapping = ProviderMappingTable::from_rows(vec![ + map_row("ceo", "CEO_A", d(2024, 1, 1), None, 10), + map_row("ceo", "CEO_B", d(2024, 1, 1), None, 20), + ]) + .expect("valid mapping"); + let t0 = utc_ms(2024, 9, 10, 14, 0, 0); + let fixture = vec![ + post("CEO_B", "b1", t0, None, Some("1"), None, "x"), + post("CEO_A", "a1", t0, None, None, None, "x"), + post("CEO_A", "a2", t0, None, Some("1"), None, "x"), + post("CEO_A", "a3", t0, Some(t0 + 1), None, None, "x"), + post("CEO_B", "b2", t0 - 1, None, None, None, "x"), + ]; + let baseline = curate_posts(fixture.clone(), "ceo", &mapping).expect("baseline"); + assert_strictly_ascending_by_tuple(&baseline.rows); + for perm in all_permutations(&fixture) { + let got = curate_posts(perm, "ceo", &mapping).expect("perm"); + assert_eq!(got, baseline); + } +} From d999ebe5958be2be0a82df2a471bd6ddbe80b145 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 10:34:50 -0500 Subject: [PATCH 14/21] =?UTF-8?q?T-164:=20M2.2i=20=E2=80=94=20`tools/curat?= =?UTF-8?q?e-etl`:=20file-to-file=20`ceoPosts`=20runner=20(`decode=5Fceo?= =?UTF-8?q?=5Fposts=5Fchunks`=20in=20`bson=5Fstream.rs`=20+=20`run=5Fcurat?= =?UTF-8?q?e=5Fposts.rs`:=20raw=20BSON=20dump=20+=20`provider=5Fmapping.ts?= =?UTF-8?q?v`=20=E2=86=92=20`curate=5Fand=5Fwrite=5Fposts`=20=E2=86=92=20`?= =?UTF-8?q?events`=20Zstd=20Parquet)=20with=20tests=20(no=20new=20crates,?= =?UTF-8?q?=20no=20CLI/bench=20changes,=20no=20live=20Mongo)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/README.md | 11 +- tools/curate-etl/src/bson_stream.rs | 111 ++ tools/curate-etl/src/bson_stream_tests.rs | 262 +++++ tools/curate-etl/src/lib.rs | 21 +- tools/curate-etl/src/run_curate_posts.rs | 615 ++++++++++ .../curate-etl/src/run_curate_posts_tests.rs | 1011 +++++++++++++++++ 6 files changed, 2023 insertions(+), 8 deletions(-) create mode 100644 tools/curate-etl/src/run_curate_posts.rs create mode 100644 tools/curate-etl/src/run_curate_posts_tests.rs diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 26f6a65f..599110d5 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -142,7 +142,16 @@ Rules: 4. **Global `spiel_id` deduplication & deterministic tie-break:** Deduplicates globally on `spiel_id` before splitting into `newswire` and `retail`. Within each `spiel_id` group, the survivor is the row with the greatest `known_at`, breaking ties by the maximum lexicographic tuple `(posted_at, is_edited, is_bot, key, user_id, text)` (`None < Some` for `user_id`), with zero dependence on input order. The remaining `group_len - 1` rows are counted in `stats.duplicates_dropped`. 5. **Sort order & invariants:** Both `newswire` and `retail` are sorted strictly ascending by `(key, known_at, spiel_id)`. Any input permutation yields identical `newswire`, `retail`, and `stats`, and `input == newswire + retail + duplicates_dropped + rejected_invalid`. -Deferred out of `src/posts.rs`: `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`, `events` Parquet row mapping in `src/parquet_posts.rs`, and `provider_mapping` listing resolution + Parquet writing in `src/curate_posts.rs`). +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`). + +### `run_curate_posts` File-to-File Runner (`M2.2i`) + +`run_curate_posts` / `run_curate_posts_with_reader` (`src/run_curate_posts.rs`) connects a concatenated raw BSON `ceoPosts` dump file and a headerless 5-column `provider_mapping.tsv` (`load_provider_mapping_tsv`) through `decode_ceo_posts_chunks` (`src/bson_stream.rs`) and `curate_and_write_posts` into `/events/year=YYYY/part.parquet` (Zstd Parquet): + +- **Explicit timestamp unit (no default):** `CuratePostsArgs::timestamp_unit` requires callers to pass `CeoPostsTimestampUnit::Seconds` or `CeoPostsTimestampUnit::Millis` explicitly (the live MongoDB numeric unit is unverified in the repo; BSON `DateTime` values are always epoch milliseconds). +- **Dedicated output directory & clobber guard:** Because `write_events_dataset` replaces whole `events/year=YYYY/part.parquet` files and `run_curate_events` (filings + earnings) writes to the same `/events` path, `run_curate_posts` requires a dedicated `--out` directory and fails closed with `RunCuratePostsError::EventsDatasetExists` before any write whenever `/events` already contains any `year=*` entry. Combining filings, earnings, and posts into a single `events` dataset is a separate follow-up. +- **Zero-row & fail-closed behavior:** Empty or all-unmapped inputs return `Ok` with `rows_written == 0` without creating `/events`. Validation, clobber checks, TSV loading, full BSON decoding, and curation complete before `out_dir` is touched. +- **In-memory accumulation:** `RawBsonChunkReader` bounds only the raw BSON chunk buffer (`peak_chunk_bytes`); decoded posts and their text accumulate in memory before `curate_and_write_posts` runs (as `curate_posts` requires). ## `events` Builder (`M1.2g`) diff --git a/tools/curate-etl/src/bson_stream.rs b/tools/curate-etl/src/bson_stream.rs index be7c201a..270dd83d 100644 --- a/tools/curate-etl/src/bson_stream.rs +++ b/tools/curate-etl/src/bson_stream.rs @@ -21,6 +21,10 @@ use std::error::Error; use std::fmt; use std::io; +use crate::bson_ceo_posts::{ + decode_ceo_posts_buffer, BsonCeoPostsDecodeStats, BsonCeoPostsError, CeoPostsFieldNames, + CeoPostsTimestampUnit, +}; use crate::bson_ceo_shorts::{ decode_ceo_shorts_buffer, BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames, }; @@ -50,6 +54,7 @@ use crate::bson_te_market_data::{ decode_te_market_data_buffer, BsonTeMarketDataDecodeStats, BsonTeMarketDataError, }; use crate::fx::FxDailyBar; +use crate::posts::CeoPost; use crate::shorts::CeoShortReport; /// Default chunk buffer capacity: 8 MiB. @@ -973,6 +978,112 @@ where decode_te_market_data_chunks(&mut chunk_reader, target_symbol, on_bar, on_error) } +/// Terminal error returned by [`decode_ceo_posts_chunks`] and [`decode_ceo_posts_stream`]. +#[derive(Debug)] +pub enum BsonCeoPostsStreamError { + Stream(BsonStreamError), + Decode(BsonCeoPostsError), +} + +impl fmt::Display for BsonCeoPostsStreamError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Stream(err) => write!(f, "{err}"), + Self::Decode(err) => write!(f, "{err}"), + } + } +} + +impl Error for BsonCeoPostsStreamError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Stream(err) => Some(err), + Self::Decode(err) => Some(err), + } + } +} + +impl From for BsonCeoPostsStreamError { + fn from(err: BsonStreamError) -> Self { + Self::Stream(err) + } +} + +impl From for BsonCeoPostsStreamError { + fn from(err: BsonCeoPostsError) -> Self { + Self::Decode(err) + } +} + +#[inline] +fn rebase_ceo_posts_error(base: u64, err: BsonCeoPostsError) -> BsonCeoPostsError { + match err { + BsonCeoPostsError::TruncatedDocument { + offset, + remaining, + declared_len, + } => BsonCeoPostsError::TruncatedDocument { + offset: base.saturating_add(offset), + remaining, + declared_len, + }, + BsonCeoPostsError::CorruptDocumentLength { + offset, + declared_len, + } => BsonCeoPostsError::CorruptDocumentLength { + offset: base.saturating_add(offset), + declared_len, + }, + BsonCeoPostsError::CorruptBson { offset, detail } => BsonCeoPostsError::CorruptBson { + offset: base.saturating_add(offset), + detail, + }, + other => other, + } +} + +/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_ceo_posts_buffer`], +/// accumulating [`BsonCeoPostsDecodeStats`] and rebasing structural BSON error offsets to +/// absolute stream byte offsets. +pub fn decode_ceo_posts_chunks( + reader: &mut RawBsonChunkReader, + fields: &CeoPostsFieldNames<'_>, + unit: CeoPostsTimestampUnit, + mut on_row: F, +) -> Result +where + R: io::Read, + F: for<'a> FnMut(CeoPost<&'a str>), +{ + fields.validate()?; + let mut total = BsonCeoPostsDecodeStats::default(); + while let Some(chunk) = reader.next_chunk()? { + let base = chunk.start_offset; + let chunk_stats = decode_ceo_posts_buffer(chunk.bytes, fields, unit, &mut on_row) + .map_err(|err| BsonCeoPostsStreamError::Decode(rebase_ceo_posts_error(base, err)))?; + total += chunk_stats; + } + Ok(total) +} + +/// Streams a concatenated raw BSON `ceoPosts` [`std::io::Read`] source through +/// [`decode_ceo_posts_buffer`] with bounded memory. +pub fn decode_ceo_posts_stream( + reader: R, + options: BsonStreamOptions, + fields: &CeoPostsFieldNames<'_>, + unit: CeoPostsTimestampUnit, + on_row: F, +) -> Result +where + R: io::Read, + F: for<'a> FnMut(CeoPost<&'a str>), +{ + fields.validate()?; + let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; + decode_ceo_posts_chunks(&mut chunk_reader, fields, unit, on_row) +} + /// Terminal error returned by [`decode_ceo_shorts_chunks`] and [`decode_ceo_shorts_stream`]. #[derive(Debug)] pub enum BsonCeoShortsStreamError { diff --git a/tools/curate-etl/src/bson_stream_tests.rs b/tools/curate-etl/src/bson_stream_tests.rs index 1ca61802..72ccad08 100644 --- a/tools/curate-etl/src/bson_stream_tests.rs +++ b/tools/curate-etl/src/bson_stream_tests.rs @@ -1731,6 +1731,268 @@ fn randomized_buffer_and_read_size_sweep_matches_buffer_decoder() { } } +#[test] +fn ceo_posts_chunks_match_buffer_across_small_chunks_and_respect_timestamp_unit() { + use super::{decode_ceo_posts_chunks, BsonStreamOptions, RawBsonChunkReader}; + use crate::bson_ceo_posts::{ + decode_ceo_posts_buffer, CeoPostsFieldNames, CeoPostsTimestampUnit, + }; + use crate::posts::CeoPost; + + let fields = CeoPostsFieldNames::default(); + + let mut fixture = Vec::new(); + for i in 0..40_i32 { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("ceoId"), format!("CEO{i}")); + doc.append(cstr!("spielId"), format!("sp-{i}")); + let ts_secs = 1_710_000_000_i64 + i64::from(i) * 60; + if i % 4 == 0 { + // BSON DateTime (always epoch milliseconds regardless of unit) + doc.append( + cstr!("timestamp"), + bson::DateTime::from_millis(ts_secs * 1_000), + ); + } else if i % 4 == 1 { + doc.append(cstr!("timestamp"), ts_secs); + } else if i % 4 == 2 { + doc.append(cstr!("timestamp"), ts_secs as f64); + } else { + doc.append(cstr!("timestamp"), ts_secs as i32); + } + + if i % 6 == 0 { + // Edited with numeric timestamp + doc.append(cstr!("edited"), ts_secs + 120); + } else if i % 6 == 1 { + // Edited with BSON DateTime + doc.append( + cstr!("edited"), + bson::DateTime::from_millis((ts_secs + 180) * 1_000), + ); + } else if i % 6 == 2 { + // Zero sentinel -> unedited + doc.append(cstr!("edited"), 0_i32); + } else if i % 6 == 3 { + // Semantic skip: invalid edited value (boolean true) + doc.append(cstr!("edited"), true); + } + + if i % 5 == 0 { + doc.append(cstr!("bot"), "1"); + } else if i % 5 == 1 { + doc.append(cstr!("bot"), false); + } + doc.append(cstr!("userId"), format!("user-{i}")); + if i % 9 == 0 { + // Semantic skip: wrong text type + doc.append(cstr!("spiel"), 123_i32); + } else { + doc.append(cstr!("spiel"), format!("post body #{i}")); + } + fixture.extend_from_slice(doc.as_bytes()); + } + + let to_owned = |p: CeoPost<&str>| CeoPost { + key: p.key.to_owned(), + spiel_id: p.spiel_id, + timestamp_ms: p.timestamp_ms, + edited_ms: p.edited_ms, + bot: p.bot, + user_id: p.user_id, + text: p.text, + }; + + for unit in [CeoPostsTimestampUnit::Seconds, CeoPostsTimestampUnit::Millis] { + let mut expected_rows = Vec::new(); + let expected_stats = decode_ceo_posts_buffer(&fixture, &fields, unit, |p| { + expected_rows.push(to_owned(p)); + }) + .expect("buffer decode"); + assert!(expected_stats.rows_out > 0); + assert!(expected_stats.skipped_total() > 0); + + // Tiny capacities and small read steps splitting reads within documents, plus single-chunk. + for (cap, step) in [(17, 7), (64, 19), (128, 37), (fixture.len() + 64, fixture.len())] { + let opts = BsonStreamOptions { + chunk_capacity_bytes: cap, + max_doc_bytes: 4096, + }; + let mut reader = + RawBsonChunkReader::with_options(FixedStepReader::new(&fixture, step), opts) + .unwrap(); + let mut got_rows = Vec::new(); + let got_stats = decode_ceo_posts_chunks(&mut reader, &fields, unit, |p| { + got_rows.push(to_owned(p)); + }) + .expect("chunk decode"); + + assert_eq!(got_stats, expected_stats, "unit={unit:?} cap={cap}"); + assert_eq!(got_rows, expected_rows, "unit={unit:?} cap={cap}"); + assert_eq!(reader.docs_framed() as usize, expected_stats.docs_in); + assert!( + reader.buffer_capacity() <= 4096.max(fixture.len() + 64), + "capacity {} exceeded expected bound", + reader.buffer_capacity() + ); + } + } + + // Explicitly verify 1,000x difference for numeric posting & edit timestamps and unit + // independence for BSON DateTime. + let mut unit_fixture = Vec::new(); + let numeric_ts = 1_710_000_123_i64; + let numeric_ed = 1_710_000_456_i64; + let dt_ts_ms = 1_710_000_789_000_i64; + let dt_ed_ms = 1_710_000_999_000_i64; + { + let mut d_num = RawDocumentBuf::new(); + d_num.append(cstr!("ceoId"), "NUM"); + d_num.append(cstr!("spielId"), "sp-num"); + d_num.append(cstr!("timestamp"), numeric_ts); + d_num.append(cstr!("edited"), numeric_ed); + d_num.append(cstr!("spiel"), "numeric"); + unit_fixture.extend_from_slice(d_num.as_bytes()); + + let mut d_dt = RawDocumentBuf::new(); + d_dt.append(cstr!("ceoId"), "DT"); + d_dt.append(cstr!("spielId"), "sp-dt"); + d_dt.append(cstr!("timestamp"), bson::DateTime::from_millis(dt_ts_ms)); + d_dt.append(cstr!("edited"), bson::DateTime::from_millis(dt_ed_ms)); + d_dt.append(cstr!("spiel"), "datetime"); + unit_fixture.extend_from_slice(d_dt.as_bytes()); + } + + let decode_unit = |unit: CeoPostsTimestampUnit| -> Vec> { + let mut rows = Vec::new(); + let mut reader = RawBsonChunkReader::with_options( + FixedStepReader::new(&unit_fixture, 11), + BsonStreamOptions { + chunk_capacity_bytes: 32, + max_doc_bytes: 4096, + }, + ) + .unwrap(); + decode_ceo_posts_chunks(&mut reader, &fields, unit, |p| rows.push(to_owned(p))) + .expect("decode unit fixture"); + rows + }; + + let rows_sec = decode_unit(CeoPostsTimestampUnit::Seconds); + let rows_ms = decode_unit(CeoPostsTimestampUnit::Millis); + assert_eq!(rows_sec.len(), 2); + assert_eq!(rows_ms.len(), 2); + + // Numeric doc: Seconds is 1,000x Millis for both timestamp and edited. + assert_eq!(rows_ms[0].timestamp_ms, numeric_ts); + assert_eq!(rows_sec[0].timestamp_ms, numeric_ts * 1_000); + assert_eq!(rows_ms[0].edited_ms, Some(numeric_ed)); + assert_eq!(rows_sec[0].edited_ms, Some(numeric_ed * 1_000)); + + // DateTime doc: identical under both Seconds and Millis. + assert_eq!(rows_ms[1].timestamp_ms, dt_ts_ms); + assert_eq!(rows_sec[1].timestamp_ms, dt_ts_ms); + assert_eq!(rows_ms[1].edited_ms, Some(dt_ed_ms)); + assert_eq!(rows_sec[1].edited_ms, Some(dt_ed_ms)); +} + +#[test] +fn ceo_posts_stream_rebases_corrupt_bson_offset_and_rejects_invalid_fields() { + use super::{ + decode_ceo_posts_chunks, decode_ceo_posts_stream, BsonCeoPostsStreamError, + BsonStreamError, BsonStreamOptions, RawBsonChunkReader, + }; + use crate::bson_ceo_posts::{BsonCeoPostsError, CeoPostsFieldNames, CeoPostsTimestampUnit}; + + // Duplicate field role rejected before reading. + let bad_fields = CeoPostsFieldNames { + key: "ceoId", + spiel_id: "ceoId", + ..CeoPostsFieldNames::default() + }; + assert!(matches!( + decode_ceo_posts_stream( + Cursor::new(Vec::::new()), + BsonStreamOptions::default(), + &bad_fields, + CeoPostsTimestampUnit::Millis, + |_| {}, + ), + Err(BsonCeoPostsStreamError::Decode( + BsonCeoPostsError::InvalidFieldNames { .. } + )) + )); + + let fields = CeoPostsFieldNames::default(); + let mut good = RawDocumentBuf::new(); + good.append(cstr!("ceoId"), "RY"); + good.append(cstr!("spielId"), "sp-1"); + good.append(cstr!("timestamp"), 1_710_460_800_000_i64); + good.append(cstr!("spiel"), "ok"); + let good_bytes = good.into_bytes(); + + let mut corrupt = RawDocumentBuf::new(); + corrupt.append(cstr!("ceoId"), "TD"); + corrupt.append(cstr!("z"), 1_i32); + let mut corrupt_bytes = corrupt.into_bytes(); + let z_pos = corrupt_bytes + .windows(3) + .position(|w| w == [0x10, b'z', 0x00]) + .expect("locate z"); + corrupt_bytes[z_pos] = 0x7e; + + let mut combined = Vec::new(); + combined.extend_from_slice(&good_bytes); + combined.extend_from_slice(&good_bytes); + let expected_offset = combined.len() as u64; + combined.extend_from_slice(&corrupt_bytes); + + // Chunk capacity == one doc forces the corrupt doc into a subsequent chunk. + let opts = BsonStreamOptions { + chunk_capacity_bytes: good_bytes.len(), + max_doc_bytes: 4096, + }; + let mut reader = RawBsonChunkReader::with_options(Cursor::new(combined), opts).unwrap(); + let err = decode_ceo_posts_chunks( + &mut reader, + &fields, + CeoPostsTimestampUnit::Millis, + |_| {}, + ) + .unwrap_err(); + assert!( + matches!( + err, + BsonCeoPostsStreamError::Decode(BsonCeoPostsError::CorruptBson { offset, .. }) + if offset == expected_offset + ), + "expected rebased CorruptBson at {expected_offset}, got {err:?}" + ); + + // Truncated trailing document preserves RawBsonChunkReader's absolute offset. + let mut truncated = Vec::new(); + truncated.extend_from_slice(&good_bytes); + let trunc_offset = truncated.len() as u64; + truncated.extend_from_slice(&64_i32.to_le_bytes()); + truncated.extend_from_slice(&[0x02, b'a', 0x00]); + let err = decode_ceo_posts_stream( + Cursor::new(truncated), + opts, + &fields, + CeoPostsTimestampUnit::Millis, + |_| {}, + ) + .unwrap_err(); + assert!( + matches!( + err, + BsonCeoPostsStreamError::Stream(BsonStreamError::TruncatedDocument { offset, .. }) + if offset == trunc_offset + ), + "expected TruncatedDocument at {trunc_offset}, got {err:?}" + ); +} + #[test] fn ceo_shorts_stream_matches_buffer_across_small_chunks_and_preserves_bounded_capacity() { use super::{decode_ceo_shorts_chunks, BsonStreamOptions, RawBsonChunkReader}; diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index bbcac68c..64296c92 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -87,13 +87,14 @@ pub use bson_qm_prices::{ BsonQmPriceError, RawQmPrice, FIELD_SHARE_VOLUME, }; pub use bson_stream::{ - decode_ceo_shorts_chunks, decode_ceo_shorts_stream, decode_eod_intraday_chunks, - decode_eod_intraday_stream, decode_eod_price_chunks, decode_eod_price_stream, - decode_qm_dividend_chunks, decode_qm_dividend_stream, decode_qm_earnings_chunks, - decode_qm_earnings_stream, decode_qm_filings_chunks, decode_qm_filings_stream, - decode_qm_intraday_chunks, decode_qm_intraday_stream, decode_qm_price_chunks, - decode_qm_price_stream, decode_qm_split_chunks, decode_qm_split_stream, - decode_te_market_data_chunks, decode_te_market_data_stream, BsonCeoShortsStreamError, + decode_ceo_posts_chunks, decode_ceo_posts_stream, decode_ceo_shorts_chunks, + decode_ceo_shorts_stream, decode_eod_intraday_chunks, decode_eod_intraday_stream, + decode_eod_price_chunks, decode_eod_price_stream, decode_qm_dividend_chunks, + decode_qm_dividend_stream, decode_qm_earnings_chunks, decode_qm_earnings_stream, + decode_qm_filings_chunks, decode_qm_filings_stream, decode_qm_intraday_chunks, + decode_qm_intraday_stream, decode_qm_price_chunks, decode_qm_price_stream, + decode_qm_split_chunks, decode_qm_split_stream, decode_te_market_data_chunks, + decode_te_market_data_stream, BsonCeoPostsStreamError, BsonCeoShortsStreamError, BsonQmEventsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunk, RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES, }; @@ -308,6 +309,12 @@ pub use run_curate_fx::{ ALLOWED_TE_SYMBOLS, DEFAULT_TE_SYMBOL, EOD_CAD_FOREX_CODE, }; +pub mod run_curate_posts; +pub use run_curate_posts::{ + format_curate_posts_report, run_curate_posts, run_curate_posts_with_reader, CuratePostsArgs, + CuratePostsRunReport, RunCuratePostsError, +}; + pub mod run_curate_shorts; pub use run_curate_shorts::{ format_curate_shorts_report, run_curate_shorts, run_curate_shorts_with_reader, diff --git a/tools/curate-etl/src/run_curate_posts.rs b/tools/curate-etl/src/run_curate_posts.rs new file mode 100644 index 00000000..2a1cd13e --- /dev/null +++ b/tools/curate-etl/src/run_curate_posts.rs @@ -0,0 +1,615 @@ +//! File-to-file `curate-posts` runner (`M2.2i`). +//! +//! Streams a concatenated raw BSON `ceoPosts` dump file alongside `provider_mapping.tsv` into an +//! atomically published `/events/year=YYYY/part.parquet` dataset via +//! [`curate_and_write_posts`]. +//! +//! # Dedicated Output Directory & Clobber Guard +//! `write_events_dataset` replaces whole `/events/year=YYYY/part.parquet` files, and +//! [`crate::run_curate_events`] (filings + earnings) publishes to the same `/events` +//! directory. To prevent silently clobbering another stage's partitions, this runner **requires a +//! dedicated output directory** and fails closed with [`RunCuratePostsError::EventsDatasetExists`] +//! before any write whenever `/events` already contains any `year=*` entry. Combining +//! filings, earnings, and posts into one `events` dataset is a separate follow-up. +//! +//! # Contract & Point-in-Time Rules +//! - Field names are supplied via [`CuratePostsArgs`] (validated via +//! [`CeoPostsFieldNames::validate`] before reading inputs). +//! - Numeric timestamp unit ([`CeoPostsTimestampUnit`]) has **no default** and must be chosen +//! explicitly by the caller because the live MongoDB `ceoPosts` numeric unit (`Seconds` vs. +//! `Millis`) is unverified in the repository. BSON `DateTime` values are always epoch +//! milliseconds regardless of unit. +//! - `provider_mapping.tsv` uses the strict headerless 5-column TSV format from +//! [`crate::run_curate_bars::load_provider_mapping_tsv`]. +//! - All decoded [`CeoPost`] rows are passed directly to [`curate_and_write_posts`] (which splits +//! `bot == "1"` newswire vs. retail, enforces the `edited` text `known_at` guard, resolves +//! `provider_mapping` on the Eastern local posting date of `posted_at`, and drops unmapped or +//! unsupported-date rows into stats). +//! - **In-memory accumulation:** [`RawBsonChunkReader`] bounds only the raw BSON chunk buffer +//! (`peak_chunk_bytes`); decoded posts and their text accumulate in memory before +//! [`curate_and_write_posts`] runs, as [`crate::curate_posts::curate_posts`] requires. +//! - **Empty / all-unmapped behavior:** returns `Ok` with `rows_written == 0` and +//! `files_written == 0` without creating `/events`. +//! - **Fail-closed safety:** invalid `out_dir`, pre-existing `/events/year=*` entries, +//! invalid field names, blank `mapping_source`, unreadable inputs, malformed/overlapping +//! `provider_mapping.tsv`, truncated/corrupt BSON framing or element bytes, and curation +//! timestamp overflow errors return a typed [`RunCuratePostsError`] before touching `out_dir`. +//! +//! # Counter Conservation Invariants +//! Every successful [`CuratePostsRunReport`] satisfies: +//! - `docs_framed as usize == decode.docs_in == decode.rows_out + decode.skipped_total()` +//! - `decode.rows_out == curate_stats.builder.input` +//! - `curate_stats.builder.input == curate_stats.builder.newswire + curate_stats.builder.retail + curate_stats.builder.duplicates_dropped + curate_stats.builder.rejected_invalid` +//! - `curate_stats.rows_in == curate_stats.builder.newswire + curate_stats.builder.retail == curate_stats.rows_out + curate_stats.dropped_unmapped + curate_stats.dropped_unsupported_date + curate_stats.listing_duplicate_collapsed` +//! - `write_stats.rows_written == curate_stats.rows_out` + +use std::collections::HashSet; +use std::error::Error; +use std::fmt; +use std::fs::{self, File}; +use std::io; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Instant; + +use crate::bson_ceo_posts::{ + BsonCeoPostsDecodeStats, BsonCeoPostsError, CeoPostsFieldNames, CeoPostsTimestampUnit, +}; +use crate::bson_stream::{ + decode_ceo_posts_chunks, BsonCeoPostsStreamError, BsonStreamError, BsonStreamOptions, + RawBsonChunkReader, +}; +use crate::curate_posts::{curate_and_write_posts, CuratePostsStats, CuratePostsWriteError}; +use crate::parquet_events::{EventsWriteOptions, EventsWriteStats}; +use crate::posts::CeoPost; +use crate::provider_mapping::{ProviderMappingError, ProviderMappingTable}; +use crate::run_curate_bars::{load_provider_mapping_tsv, RunCurateBarsError}; + +/// Default `mapping_source` passed to `provider_mapping` lookups for `ceoPosts`. +pub const DEFAULT_MAPPING_SOURCE: &str = "ceo"; + +/// Arguments for [`run_curate_posts`]. +/// +/// `timestamp_unit` intentionally has no default: callers must explicitly choose +/// [`CeoPostsTimestampUnit::Seconds`] or [`CeoPostsTimestampUnit::Millis`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CuratePostsArgs { + pub ceo_posts: PathBuf, + pub provider_mapping: PathBuf, + pub out_dir: PathBuf, + pub timestamp_unit: CeoPostsTimestampUnit, + pub key_field: String, + pub spiel_id_field: String, + pub timestamp_field: String, + pub edited_field: String, + pub bot_field: String, + pub user_id_field: String, + pub text_field: String, + pub mapping_source: String, +} + +impl CuratePostsArgs { + /// Borrows the configured BSON field names as [`CeoPostsFieldNames`]. + #[inline] + pub fn field_names(&self) -> CeoPostsFieldNames<'_> { + CeoPostsFieldNames { + key: self.key_field.as_str(), + spiel_id: self.spiel_id_field.as_str(), + timestamp: self.timestamp_field.as_str(), + edited: self.edited_field.as_str(), + bot: self.bot_field.as_str(), + user_id: self.user_id_field.as_str(), + text: self.text_field.as_str(), + } + } +} + +/// Full run report produced by [`run_curate_posts`] and [`run_curate_posts_with_reader`]. +#[derive(Debug, Clone, PartialEq)] +pub struct CuratePostsRunReport { + pub docs_framed: u64, + pub bytes_read: u64, + pub peak_chunk_bytes: usize, + pub decode: BsonCeoPostsDecodeStats, + pub curate_stats: CuratePostsStats, + pub write_stats: EventsWriteStats, + pub elapsed_secs: f64, +} + +/// Typed errors returned by [`run_curate_posts`] and [`run_curate_posts_with_reader`]. +/// +/// Every variant's `Display` output is a single line naming the offending path (and line number or +/// byte offset where applicable). +#[derive(Debug)] +pub enum RunCuratePostsError { + InvalidOutDir { + path: PathBuf, + detail: String, + }, + InspectOutDir { + path: PathBuf, + source: io::Error, + }, + EventsDatasetExists { + path: PathBuf, + }, + InvalidFieldNames { + source: BsonCeoPostsError, + }, + EmptyMappingSource, + OpenInput { + label: &'static str, + path: PathBuf, + source: io::Error, + }, + ReadInput { + label: &'static str, + path: PathBuf, + source: io::Error, + }, + TsvParse { + path: PathBuf, + line: usize, + detail: String, + }, + ProviderMapping { + path: PathBuf, + source: ProviderMappingError, + }, + BsonStream { + path: PathBuf, + source: BsonStreamError, + }, + CorruptBson { + path: PathBuf, + offset: u64, + source: BsonCeoPostsError, + }, + CurateWrite { + out_dir: PathBuf, + source: CuratePostsWriteError, + }, +} + +impl fmt::Display for RunCuratePostsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidOutDir { path, detail } => { + write!(f, "invalid --out '{}': {detail}", path.display()) + } + Self::InspectOutDir { path, source } => { + write!(f, "failed to inspect output path '{}': {source}", path.display()) + } + Self::EventsDatasetExists { path } => write!( + f, + "refusing to overwrite existing events partition '{}': use a dedicated --out directory for ceoPosts", + path.display() + ), + Self::InvalidFieldNames { source } => write!(f, "{source}"), + Self::EmptyMappingSource => { + write!(f, "invalid --mapping-source: must not be empty or blank") + } + Self::OpenInput { + label, + path, + source, + } => write!(f, "failed to open {label} '{}': {source}", path.display()), + Self::ReadInput { + label, + path, + source, + } => write!(f, "failed to read {label} '{}': {source}", path.display()), + Self::TsvParse { path, line, detail } => { + write!(f, "{}:{line}: {detail}", path.display()) + } + Self::ProviderMapping { path, source } => { + write!(f, "invalid provider_mapping '{}': {source}", path.display()) + } + Self::BsonStream { path, source } => { + write!(f, "failed reading ceo-posts '{}': {source}", path.display()) + } + Self::CorruptBson { + path, + offset, + source, + } => write!( + f, + "corrupt ceo-posts BSON '{}' at byte offset {offset}: {source}", + path.display() + ), + Self::CurateWrite { out_dir, source } => { + write!(f, "curate/write to '{}' failed: {source}", out_dir.display()) + } + } + } +} + +impl Error for RunCuratePostsError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::InspectOutDir { source, .. } => Some(source), + Self::InvalidFieldNames { source } => Some(source), + Self::OpenInput { source, .. } | Self::ReadInput { source, .. } => Some(source), + Self::ProviderMapping { source, .. } => Some(source), + Self::BsonStream { source, .. } => Some(source), + Self::CorruptBson { source, .. } => Some(source), + Self::CurateWrite { source, .. } => Some(source), + Self::InvalidOutDir { .. } + | Self::EventsDatasetExists { .. } + | Self::EmptyMappingSource + | Self::TsvParse { .. } => None, + } + } +} + +fn validate_out_dir_and_events_guard(out_dir: &Path) -> Result<(), RunCuratePostsError> { + if out_dir.as_os_str().is_empty() { + return Err(RunCuratePostsError::InvalidOutDir { + path: out_dir.to_path_buf(), + detail: "output directory path must not be empty".to_string(), + }); + } + + match fs::metadata(out_dir) { + Ok(meta) if !meta.is_dir() => { + return Err(RunCuratePostsError::InvalidOutDir { + path: out_dir.to_path_buf(), + detail: "path exists and is not a directory".to_string(), + }); + } + Ok(_) => {} + Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()), + Err(source) => { + return Err(RunCuratePostsError::InspectOutDir { + path: out_dir.to_path_buf(), + source, + }); + } + } + + let events_dir = out_dir.join("events"); + match fs::metadata(&events_dir) { + Ok(meta) if !meta.is_dir() => { + return Err(RunCuratePostsError::InvalidOutDir { + path: events_dir, + detail: "events output path exists and is not a directory".to_string(), + }); + } + Ok(_) => {} + Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()), + Err(source) => { + return Err(RunCuratePostsError::InspectOutDir { + path: events_dir, + source, + }); + } + } + + let entries = fs::read_dir(&events_dir).map_err(|source| RunCuratePostsError::InspectOutDir { + path: events_dir.clone(), + source, + })?; + + let mut existing_year_entry: Option = None; + for entry_res in entries { + let entry = entry_res.map_err(|source| RunCuratePostsError::InspectOutDir { + path: events_dir.clone(), + source, + })?; + let name = entry.file_name(); + if name.to_string_lossy().starts_with("year=") { + let candidate = entry.path(); + if existing_year_entry + .as_ref() + .is_none_or(|current| candidate < *current) + { + existing_year_entry = Some(candidate); + } + } + } + + if let Some(path) = existing_year_entry { + return Err(RunCuratePostsError::EventsDatasetExists { path }); + } + + Ok(()) +} + +fn map_tsv_error(path: &Path, err: RunCurateBarsError) -> RunCuratePostsError { + match err { + RunCurateBarsError::OpenInput { + label, + path, + source, + } => RunCuratePostsError::OpenInput { + label, + path, + source, + }, + RunCurateBarsError::ReadInput { + label, + path, + source, + } => RunCuratePostsError::ReadInput { + label, + path, + source, + }, + RunCurateBarsError::TsvParse { path, line, detail } => { + RunCuratePostsError::TsvParse { path, line, detail } + } + RunCurateBarsError::ProviderMapping { path, source } => { + RunCuratePostsError::ProviderMapping { path, source } + } + other => RunCuratePostsError::TsvParse { + path: path.to_path_buf(), + line: 0, + detail: other.to_string(), + }, + } +} + +fn bson_error_offset(err: &BsonCeoPostsError) -> u64 { + match err { + BsonCeoPostsError::TruncatedDocument { offset, .. } + | BsonCeoPostsError::CorruptDocumentLength { offset, .. } + | BsonCeoPostsError::CorruptBson { offset, .. } => *offset, + BsonCeoPostsError::InvalidFieldNames { .. } => 0, + } +} + +struct DecodedPostsInputs { + mapping: ProviderMappingTable, + posts: Vec>>, + docs_framed: u64, + bytes_read: u64, + peak_chunk_bytes: usize, + decode: BsonCeoPostsDecodeStats, +} + +fn decode_inputs_from_opener( + provider_mapping_path: &Path, + mapping_source: &str, + fields: &CeoPostsFieldNames<'_>, + timestamp_unit: CeoPostsTimestampUnit, + ceo_posts_path: &Path, + open_posts: F, +) -> Result +where + R: io::Read, + F: FnOnce() -> Result, +{ + fields + .validate() + .map_err(|source| RunCuratePostsError::InvalidFieldNames { source })?; + + if mapping_source.trim().is_empty() { + return Err(RunCuratePostsError::EmptyMappingSource); + } + + let mapping_rows = load_provider_mapping_tsv(provider_mapping_path) + .map_err(|err| map_tsv_error(provider_mapping_path, err))?; + let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| { + RunCuratePostsError::ProviderMapping { + path: provider_mapping_path.to_path_buf(), + source, + } + })?; + + let stream = open_posts()?; + let mut reader = RawBsonChunkReader::with_options(stream, BsonStreamOptions::default()) + .map_err(|source| RunCuratePostsError::BsonStream { + path: ceo_posts_path.to_path_buf(), + source, + })?; + + let mut key_interner: HashSet> = HashSet::new(); + let mut posts: Vec>> = Vec::new(); + + let decode = decode_ceo_posts_chunks(&mut reader, fields, timestamp_unit, |raw| { + let key = if let Some(existing) = key_interner.get(raw.key) { + Arc::clone(existing) + } else { + let arc: Arc = Arc::from(raw.key); + key_interner.insert(Arc::clone(&arc)); + arc + }; + posts.push(CeoPost { + key, + spiel_id: raw.spiel_id, + timestamp_ms: raw.timestamp_ms, + edited_ms: raw.edited_ms, + bot: raw.bot, + user_id: raw.user_id, + text: raw.text, + }); + }) + .map_err(|err| match err { + BsonCeoPostsStreamError::Stream(source) => RunCuratePostsError::BsonStream { + path: ceo_posts_path.to_path_buf(), + source, + }, + BsonCeoPostsStreamError::Decode(source) => match &source { + BsonCeoPostsError::InvalidFieldNames { .. } => { + RunCuratePostsError::InvalidFieldNames { source } + } + _ => { + let offset = bson_error_offset(&source); + RunCuratePostsError::CorruptBson { + path: ceo_posts_path.to_path_buf(), + offset, + source, + } + } + }, + })?; + + Ok(DecodedPostsInputs { + mapping, + posts, + docs_framed: reader.docs_framed(), + bytes_read: reader.bytes_read(), + peak_chunk_bytes: reader.buffer_capacity(), + decode, + }) +} + +fn run_curate_posts_from_opener( + provider_mapping_path: &Path, + mapping_source: &str, + fields: &CeoPostsFieldNames<'_>, + timestamp_unit: CeoPostsTimestampUnit, + ceo_posts_path: &Path, + open_posts: F, + out_dir: &Path, +) -> Result +where + R: io::Read, + F: FnOnce() -> Result, +{ + let start = Instant::now(); + validate_out_dir_and_events_guard(out_dir)?; + + let decoded = decode_inputs_from_opener( + provider_mapping_path, + mapping_source, + fields, + timestamp_unit, + ceo_posts_path, + open_posts, + )?; + + // Re-check output directory and clobber guard immediately before curating/writing. + validate_out_dir_and_events_guard(out_dir)?; + + let write_report = curate_and_write_posts( + out_dir, + decoded.posts, + mapping_source, + &decoded.mapping, + EventsWriteOptions::default(), + ) + .map_err(|source| RunCuratePostsError::CurateWrite { + out_dir: out_dir.to_path_buf(), + source, + })?; + + Ok(CuratePostsRunReport { + docs_framed: decoded.docs_framed, + bytes_read: decoded.bytes_read, + peak_chunk_bytes: decoded.peak_chunk_bytes, + decode: decoded.decode, + curate_stats: write_report.curate_stats, + write_stats: write_report.write_stats, + elapsed_secs: start.elapsed().as_secs_f64(), + }) +} + +/// Runs the end-to-end `curate-posts` file-to-Parquet pipeline via [`curate_and_write_posts`]. +/// +/// Any validation, clobber-guard, I/O, TSV, mapping, BSON framing/corruption, or curation error +/// returns before touching `args.out_dir`. +pub fn run_curate_posts( + args: &CuratePostsArgs, +) -> Result { + run_curate_posts_from_opener( + &args.provider_mapping, + &args.mapping_source, + &args.field_names(), + args.timestamp_unit, + &args.ceo_posts, + || { + File::open(&args.ceo_posts).map_err(|source| RunCuratePostsError::OpenInput { + label: "ceo-posts", + path: args.ceo_posts.clone(), + source, + }) + }, + &args.out_dir, + ) +} + +/// Runs `curate-posts` from an arbitrary raw-BSON [`io::Read`] stream. +pub fn run_curate_posts_with_reader( + provider_mapping_path: &Path, + mapping_source: &str, + fields: &CeoPostsFieldNames<'_>, + timestamp_unit: CeoPostsTimestampUnit, + ceo_posts_input: (&Path, R), + out_dir: &Path, +) -> Result { + let (ceo_path, stream) = ceo_posts_input; + run_curate_posts_from_opener( + provider_mapping_path, + mapping_source, + fields, + timestamp_unit, + ceo_path, + || Ok(stream), + out_dir, + ) +} + +/// Formats [`CuratePostsRunReport`] into a deterministic machine-readable `key=value` summary. +/// +/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`). +pub fn format_curate_posts_report(report: &CuratePostsRunReport) -> String { + let d = &report.decode; + let b = &report.curate_stats.builder; + let c = &report.curate_stats; + let w = &report.write_stats; + format!( + "curate-etl curate-posts\n\ + \x20 ceo_bson: docs_framed={} bytes_read={} peak_chunk_bytes={} docs_in={} rows_out={} skipped={} (missing_key={} wrong_key_type={} empty_key={} missing_spiel_id={} wrong_spiel_id_type={} empty_spiel_id={} missing_ts={} wrong_ts_type={} invalid_ts={} ts_oor={} invalid_edited={} wrong_text_type={}) emitted=(edited_zero_or_false={} nulled_bot={} nulled_user_id={} empty_text={})\n\ + \x20 builder: input={} newswire={} retail={} edited={} edited_before_posted={} dup_dropped={} rejected_invalid={}\n\ + \x20 curate: rows_in={} rows_out={} newswire_out={} retail_out={} listings_out={} dropped_unmapped={} dropped_unsupported_date={} listing_dup_collapsed={}\n\ + \x20 write: files={} row_groups={} rows_written={} bytes_written={}\n\ + \x20 timing: elapsed_secs={:.6}", + report.docs_framed, + report.bytes_read, + report.peak_chunk_bytes, + d.docs_in, + d.rows_out, + d.skipped_total(), + d.skipped_missing_key, + d.skipped_wrong_key_type, + d.skipped_empty_key, + d.skipped_missing_spiel_id, + d.skipped_wrong_spiel_id_type, + d.skipped_empty_spiel_id, + d.skipped_missing_timestamp, + d.skipped_wrong_timestamp_type, + d.skipped_invalid_timestamp, + d.skipped_timestamp_out_of_range, + d.skipped_invalid_edited, + d.skipped_wrong_text_type, + d.edited_zero_or_false, + d.nulled_wrong_type_bot, + d.nulled_wrong_type_user_id, + d.empty_text, + b.input, + b.newswire, + b.retail, + b.edited, + b.edited_before_posted, + b.duplicates_dropped, + b.rejected_invalid, + c.rows_in, + c.rows_out, + c.newswire_out, + c.retail_out, + c.listings_out, + c.dropped_unmapped, + c.dropped_unsupported_date, + c.listing_duplicate_collapsed, + w.files_written, + w.row_groups_written, + w.rows_written, + w.bytes_written, + report.elapsed_secs, + ) +} + +#[cfg(test)] +#[path = "run_curate_posts_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/run_curate_posts_tests.rs b/tools/curate-etl/src/run_curate_posts_tests.rs new file mode 100644 index 00000000..3115963e --- /dev/null +++ b/tools/curate-etl/src/run_curate_posts_tests.rs @@ -0,0 +1,1011 @@ +use std::borrow::Cow; +use std::fs::{self, File}; +use std::io::{self, Cursor, Read, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use bson::raw::{cstr, RawDocumentBuf}; +use parquet::basic::Compression; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::*; +use crate::bson_ceo_posts::{ + DEFAULT_BOT_FIELD, DEFAULT_EDITED_FIELD, DEFAULT_KEY_FIELD, DEFAULT_SPIEL_ID_FIELD, + DEFAULT_TEXT_FIELD, DEFAULT_TIMESTAMP_FIELD, DEFAULT_USER_ID_FIELD, +}; +use crate::curate_posts::{curate_posts, CuratePostsError, CuratePostsWriteError}; +use crate::parquet_events::EventsParquetRow; +use crate::parquet_posts::{ + EVENT_KIND_POST, KNOWN_AT_SOURCE_POST_EDITED, KNOWN_AT_SOURCE_POST_TIMESTAMP, + POST_SUBTYPE_NEWSWIRE, POST_SUBTYPE_RETAIL, +}; +use crate::posts::PostsError; +use crate::provider_mapping::ProviderMappingRow; +use crate::split::ymd_to_epoch_days; + +static TEMP_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDirGuard { + path: PathBuf, +} + +impl TempDirGuard { + fn new(label: &str) -> Self { + let seq = TEMP_SEQ.fetch_add(1, Ordering::Relaxed); + let pid = std::process::id(); + let path = + std::env::temp_dir().join(format!("curate-etl-run-posts-test-{label}-{pid}-{seq}")); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp dir"); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn utc_ms(year: i32, month: u32, day_num: u32, hour: u8, minute: u8, second: u8) -> i64 { + let epoch_day = day(year, month, day_num); + let secs = i64::from(epoch_day) * 86_400 + + i64::from(hour) * 3_600 + + i64::from(minute) * 60 + + i64::from(second); + secs * 1_000 +} + +fn write_bytes(path: &Path, bytes: &[u8]) { + let mut f = File::create(path).expect("create file"); + f.write_all(bytes).expect("write file"); +} + +fn default_args( + ceo_posts: PathBuf, + provider_mapping: PathBuf, + out_dir: PathBuf, + timestamp_unit: CeoPostsTimestampUnit, +) -> CuratePostsArgs { + CuratePostsArgs { + ceo_posts, + provider_mapping, + out_dir, + timestamp_unit, + key_field: DEFAULT_KEY_FIELD.to_string(), + spiel_id_field: DEFAULT_SPIEL_ID_FIELD.to_string(), + timestamp_field: DEFAULT_TIMESTAMP_FIELD.to_string(), + edited_field: DEFAULT_EDITED_FIELD.to_string(), + bot_field: DEFAULT_BOT_FIELD.to_string(), + user_id_field: DEFAULT_USER_ID_FIELD.to_string(), + text_field: DEFAULT_TEXT_FIELD.to_string(), + mapping_source: DEFAULT_MAPPING_SOURCE.to_string(), + } +} + +#[allow(clippy::too_many_arguments)] +fn make_post_doc( + fields: &CeoPostsFieldNames<'_>, + key: &str, + spiel_id: &str, + timestamp: i64, + edited: Option, + bot: Option<&str>, + user_id: Option<&str>, + text: &str, +) -> Vec { + let cstring = |s: &str| bson::raw::CString::try_from(s.to_owned()).expect("valid BSON key"); + let mut doc = RawDocumentBuf::new(); + doc.append(cstring(fields.key), key); + doc.append(cstring(fields.spiel_id), spiel_id); + doc.append(cstring(fields.timestamp), timestamp); + if let Some(ed) = edited { + doc.append(cstring(fields.edited), ed); + } + if let Some(b) = bot { + doc.append(cstring(fields.bot), b); + } + if let Some(u) = user_id { + doc.append(cstring(fields.user_id), u); + } + doc.append(cstring(fields.text), text); + doc.into_bytes() +} + +fn assert_report_invariants(report: &CuratePostsRunReport) { + assert_eq!(report.docs_framed as usize, report.decode.docs_in); + assert_eq!( + report.decode.docs_in, + report.decode.rows_out + report.decode.skipped_total() + ); + let b = &report.curate_stats.builder; + assert_eq!(report.decode.rows_out, b.input); + assert_eq!( + b.input, + b.newswire + b.retail + b.duplicates_dropped + b.rejected_invalid + ); + let c = &report.curate_stats; + assert_eq!(c.rows_in, b.newswire + b.retail); + assert_eq!( + c.rows_in, + c.rows_out + c.dropped_unmapped + c.dropped_unsupported_date + c.listing_duplicate_collapsed + ); + assert_eq!(c.rows_out, c.newswire_out + c.retail_out); + assert_eq!(report.write_stats.rows_written, c.rows_out); +} + +fn read_events_parquet_and_verify_zstd(path: &Path) -> Vec { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let meta = reader.metadata(); + let mut out = Vec::new(); + + for rg_idx in 0..meta.num_row_groups() { + let rg_meta = meta.row_group(rg_idx); + assert_eq!(rg_meta.num_columns(), 7, "expected 7 columns in events schema"); + for col_idx in 0..rg_meta.num_columns() { + let compression = rg_meta.column(col_idx).compression(); + assert!( + matches!(compression, Compression::ZSTD(_)), + "expected ZSTD compression for row_group={rg_idx} col={col_idx}, got {compression:?}" + ); + } + + let rg_rows = rg_meta.num_rows() as usize; + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + + let read_i32_col = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read i32 records"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected INT32 column at index {col_idx}"), + } + vals + }; + + let read_i64_col = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int64ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read i64 records"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected INT64 column at index {col_idx}"), + } + vals + }; + + let read_str_col = |col_idx: usize| -> Vec { + let mut raw = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut raw) + .expect("read byte_array records"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), + } + raw.iter() + .map(|b| std::str::from_utf8(b.data()).expect("valid utf8").to_string()) + .collect() + }; + + let listing_ids = read_i32_col(0); + let ts = read_i64_col(1); + let known_at = read_i64_col(2); + let known_at_source = read_str_col(3); + let kind = read_str_col(4); + let subtype = read_str_col(5); + let payload_json = read_str_col(6); + + for i in 0..rg_rows { + out.push(EventsParquetRow { + listing_id: listing_ids[i], + ts_micros: ts[i], + known_at_micros: known_at[i], + known_at_source: Cow::Owned(known_at_source[i].clone()), + kind: Cow::Owned(kind[i].clone()), + subtype: subtype[i].clone(), + payload_json: payload_json[i].clone(), + }); + } + } + + out +} + +fn read_all_event_partitions(out_dir: &Path) -> Vec { + let events_dir = out_dir.join("events"); + let mut year_dirs: Vec = fs::read_dir(&events_dir) + .expect("read events dir") + .map(|e| e.expect("dir entry").path()) + .filter(|p| { + p.file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n.starts_with("year=")) + }) + .collect(); + year_dirs.sort(); + + let mut all = Vec::new(); + for yd in year_dirs { + all.extend(read_events_parquet_and_verify_zstd(&yd.join("part.parquet"))); + } + all.sort_by(|a, b| { + a.listing_id + .cmp(&b.listing_id) + .then_with(|| a.ts_micros.cmp(&b.ts_micros)) + .then_with(|| a.kind.as_ref().cmp(b.kind.as_ref())) + .then_with(|| a.subtype.cmp(&b.subtype)) + .then_with(|| a.payload_json.cmp(&b.payload_json)) + .then_with(|| a.known_at_micros.cmp(&b.known_at_micros)) + .then_with(|| a.known_at_source.as_ref().cmp(b.known_at_source.as_ref())) + }); + all +} + +fn assert_single_line_err(err: &RunCuratePostsError) -> String { + let msg = err.to_string(); + assert!(!msg.is_empty(), "error message must not be empty"); + assert!( + !msg.contains('\n'), + "error message must be single-line, got: {msg:?}" + ); + msg +} + +struct FailingReader { + prefix: Vec, + pos: usize, +} + +impl Read for FailingReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if self.pos < self.prefix.len() { + let n = (self.prefix.len() - self.pos).min(buf.len()); + buf[..n].copy_from_slice(&self.prefix[self.pos..self.pos + n]); + self.pos += n; + return Ok(n); + } + Err(io::Error::new( + io::ErrorKind::BrokenPipe, + "injected read failure", + )) + } +} + +#[test] +fn happy_path_matches_curate_posts_verifies_zstd_edit_time_and_invariants() { + let dir = TempDirGuard::new("happy"); + let bson_path = dir.path().join("ceoPosts.bson"); + let map_path = dir.path().join("provider_mapping.tsv"); + let out_a = dir.path().join("out_a"); + let out_b = dir.path().join("out_b"); + + let mapping_tsv = concat!( + "ceo\tCEO_RY\t2020-01-01\t\t101\n", + "ceo\tCEO_SHOP\t2024-01-01\t\t202\n", + ); + write_bytes(&map_path, mapping_tsv.as_bytes()); + + let fields = CeoPostsFieldNames::default(); + let t_wire = utc_ms(2024, 6, 15, 14, 0, 0); + let t_retail = utc_ms(2024, 6, 15, 14, 5, 0); + let t_edited_post = utc_ms(2024, 6, 15, 15, 0, 0); + let t_edited_at = utc_ms(2024, 6, 15, 18, 30, 0); + let t_2025 = utc_ms(2025, 1, 10, 16, 0, 0); + + // Semantic skip doc: invalid edited (boolean true) + let mut skipped_doc = RawDocumentBuf::new(); + skipped_doc.append(cstr!("ceoId"), "CEO_RY"); + skipped_doc.append(cstr!("spielId"), "sp-skip"); + skipped_doc.append(cstr!("timestamp"), t_wire); + skipped_doc.append(cstr!("edited"), true); + skipped_doc.append(cstr!("spiel"), "should skip"); + + let docs = vec![ + // 1. Newswire (bot == "1") + make_post_doc( + &fields, + "CEO_RY", + "sp-wire-1", + t_wire, + None, + Some("1"), + Some("thenewswire"), + "Royal Bank quarterly release", + ), + // 2. Retail (bot == "0") + make_post_doc( + &fields, + "CEO_RY", + "sp-retail-1", + t_retail, + None, + Some("0"), + Some("trader42"), + "Looking strong today", + ), + // 3. Edited retail post: posted at t_edited_post, edited at t_edited_at + make_post_doc( + &fields, + "CEO_SHOP", + "sp-edited-1", + t_edited_post, + Some(t_edited_at), + None, + Some("analyst99"), + "Updated guidance notes", + ), + // 4. Duplicate spielId (earlier version of sp-edited-1 -> dropped by dedup) + make_post_doc( + &fields, + "CEO_SHOP", + "sp-edited-1", + t_edited_post, + None, + None, + Some("analyst99"), + "Initial draft", + ), + // 5. Unmapped key -> dropped_unmapped + make_post_doc( + &fields, + "UNKNOWN_CH", + "sp-unmapped-1", + t_retail, + None, + None, + Some("anon"), + "Unmapped channel post", + ), + // 6. Second partition year (2025) + make_post_doc( + &fields, + "CEO_SHOP", + "sp-2025-1", + t_2025, + None, + Some("1"), + Some("globenewswire"), + "2025 update", + ), + // 7. Semantic skip + skipped_doc.into_bytes(), + ]; + + let mut forward_bytes = Vec::new(); + for d in &docs { + forward_bytes.extend_from_slice(d); + } + write_bytes(&bson_path, &forward_bytes); + + let args_a = default_args( + bson_path.clone(), + map_path.clone(), + out_a.clone(), + CeoPostsTimestampUnit::Millis, + ); + let report_a = run_curate_posts(&args_a).expect("run forward"); + assert_report_invariants(&report_a); + assert_eq!(report_a.docs_framed, 7); + assert_eq!(report_a.decode.docs_in, 7); + assert_eq!(report_a.decode.rows_out, 6); + assert_eq!(report_a.decode.skipped_invalid_edited, 1); + assert_eq!(report_a.curate_stats.builder.input, 6); + assert_eq!(report_a.curate_stats.builder.duplicates_dropped, 1); + assert_eq!(report_a.curate_stats.dropped_unmapped, 1); + assert_eq!(report_a.curate_stats.rows_out, 4); + assert_eq!(report_a.curate_stats.newswire_out, 2); + assert_eq!(report_a.curate_stats.retail_out, 2); + assert_eq!(report_a.write_stats.files_written, 2); + assert_eq!(report_a.write_stats.rows_written, 4); + + // Baseline comparison against pure curate_posts on equivalent typed inputs. + let baseline_mapping = ProviderMappingTable::from_rows(vec![ + ProviderMappingRow { + source: "ceo".to_string(), + source_id: "CEO_RY".to_string(), + valid_from: day(2020, 1, 1), + valid_to: None, + listing_id: 101, + }, + ProviderMappingRow { + source: "ceo".to_string(), + source_id: "CEO_SHOP".to_string(), + valid_from: day(2024, 1, 1), + valid_to: None, + listing_id: 202, + }, + ]) + .expect("valid mapping"); + let baseline_posts = vec![ + CeoPost { + key: "CEO_RY".to_string(), + spiel_id: "sp-wire-1".to_string(), + timestamp_ms: t_wire, + edited_ms: None, + bot: Some("1".to_string()), + user_id: Some("thenewswire".to_string()), + text: "Royal Bank quarterly release".to_string(), + }, + CeoPost { + key: "CEO_RY".to_string(), + spiel_id: "sp-retail-1".to_string(), + timestamp_ms: t_retail, + edited_ms: None, + bot: Some("0".to_string()), + user_id: Some("trader42".to_string()), + text: "Looking strong today".to_string(), + }, + CeoPost { + key: "CEO_SHOP".to_string(), + spiel_id: "sp-edited-1".to_string(), + timestamp_ms: t_edited_post, + edited_ms: Some(t_edited_at), + bot: None, + user_id: Some("analyst99".to_string()), + text: "Updated guidance notes".to_string(), + }, + CeoPost { + key: "CEO_SHOP".to_string(), + spiel_id: "sp-edited-1".to_string(), + timestamp_ms: t_edited_post, + edited_ms: None, + bot: None, + user_id: Some("analyst99".to_string()), + text: "Initial draft".to_string(), + }, + CeoPost { + key: "UNKNOWN_CH".to_string(), + spiel_id: "sp-unmapped-1".to_string(), + timestamp_ms: t_retail, + edited_ms: None, + bot: None, + user_id: Some("anon".to_string()), + text: "Unmapped channel post".to_string(), + }, + CeoPost { + key: "CEO_SHOP".to_string(), + spiel_id: "sp-2025-1".to_string(), + timestamp_ms: t_2025, + edited_ms: None, + bot: Some("1".to_string()), + user_id: Some("globenewswire".to_string()), + text: "2025 update".to_string(), + }, + ]; + let baseline = curate_posts(baseline_posts, "ceo", &baseline_mapping).expect("baseline"); + let read_back = read_all_event_partitions(&out_a); + assert_eq!(read_back, baseline.rows); + assert_eq!(report_a.curate_stats, baseline.stats); + + // Independent checks on kind, subtype, and edited post's ts vs known_at. + assert!(read_back.iter().all(|r| r.kind.as_ref() == EVENT_KIND_POST)); + let wire_row = read_back + .iter() + .find(|r| r.payload_json.contains("sp-wire-1")) + .expect("newswire row"); + assert_eq!(wire_row.subtype, POST_SUBTYPE_NEWSWIRE); + assert_eq!(wire_row.known_at_source.as_ref(), KNOWN_AT_SOURCE_POST_TIMESTAMP); + assert_eq!(wire_row.ts_micros, t_wire * 1_000); + assert_eq!(wire_row.known_at_micros, t_wire * 1_000); + + let edited_row = read_back + .iter() + .find(|r| r.payload_json.contains("sp-edited-1")) + .expect("edited row"); + assert_eq!(edited_row.subtype, POST_SUBTYPE_RETAIL); + assert_eq!(edited_row.ts_micros, t_edited_post * 1_000); + assert_eq!(edited_row.known_at_micros, t_edited_at * 1_000); + assert_eq!(edited_row.known_at_source.as_ref(), KNOWN_AT_SOURCE_POST_EDITED); + + // Reversed input order must yield byte-identical Parquet files and deterministic report. + let bson_rev = dir.path().join("ceoPosts_rev.bson"); + let mut rev_bytes = Vec::new(); + for d in docs.iter().rev() { + rev_bytes.extend_from_slice(d); + } + write_bytes(&bson_rev, &rev_bytes); + + let args_b = CuratePostsArgs { + ceo_posts: bson_rev, + out_dir: out_b.clone(), + ..args_a + }; + let report_b = run_curate_posts(&args_b).expect("run reversed"); + assert_report_invariants(&report_b); + assert_eq!(report_a.curate_stats, report_b.curate_stats); + assert_eq!(report_a.write_stats, report_b.write_stats); + + for year in ["year=2024", "year=2025"] { + let a = fs::read(out_a.join("events").join(year).join("part.parquet")).expect("read a"); + let b = fs::read(out_b.join("events").join(year).join("part.parquet")).expect("read b"); + assert_eq!(a, b, "reversed input must produce byte-identical {year}/part.parquet"); + } + + let strip_timing = |s: &str| { + s.lines() + .filter(|l| !l.trim_start().starts_with("timing:")) + .collect::>() + .join("\n") + }; + assert_eq!( + strip_timing(&format_curate_posts_report(&report_a)), + strip_timing(&format_curate_posts_report(&report_b)) + ); +} + +#[test] +fn seconds_vs_millis_and_custom_fields_with_reader_work_end_to_end() { + let dir = TempDirGuard::new("units"); + let map_path = dir.path().join("mapping.tsv"); + write_bytes(&map_path, b"ceo_alt\tCH_1\t2020-01-01\t\t555\n"); + + let custom_fields = CeoPostsFieldNames { + key: "channel", + spiel_id: "id", + timestamp: "ts", + edited: "ed", + bot: "isBot", + user_id: "author", + text: "body", + }; + + let ts_sec = 1_718_460_000_i64; // 2024-06-15 14:00:00 UTC + let ed_sec = 1_718_463_600_i64; // 2024-06-15 15:00:00 UTC + let doc_sec = make_post_doc( + &custom_fields, + "CH_1", + "p-1", + ts_sec, + Some(ed_sec), + None, + Some("u1"), + "hello", + ); + let doc_ms = make_post_doc( + &custom_fields, + "CH_1", + "p-1", + ts_sec * 1_000, + Some(ed_sec * 1_000), + None, + Some("u1"), + "hello", + ); + + let out_sec = dir.path().join("out_sec"); + let out_ms = dir.path().join("out_ms"); + + let rep_sec = run_curate_posts_with_reader( + &map_path, + "ceo_alt", + &custom_fields, + CeoPostsTimestampUnit::Seconds, + (Path::new("in-mem-sec.bson"), Cursor::new(doc_sec)), + &out_sec, + ) + .expect("run seconds"); + let rep_ms = run_curate_posts_with_reader( + &map_path, + "ceo_alt", + &custom_fields, + CeoPostsTimestampUnit::Millis, + (Path::new("in-mem-ms.bson"), Cursor::new(doc_ms)), + &out_ms, + ) + .expect("run millis"); + + assert_report_invariants(&rep_sec); + assert_report_invariants(&rep_ms); + let rows_sec = read_all_event_partitions(&out_sec); + let rows_ms = read_all_event_partitions(&out_ms); + assert_eq!(rows_sec, rows_ms); + assert_eq!(rows_sec.len(), 1); + assert_eq!(rows_sec[0].ts_micros, ts_sec * 1_000_000); + assert_eq!(rows_sec[0].known_at_micros, ed_sec * 1_000_000); +} + +#[test] +fn clobber_guard_rejects_existing_year_partitions_and_preserves_bytes() { + let dir = TempDirGuard::new("clobber"); + let map_path = dir.path().join("mapping.tsv"); + write_bytes(&map_path, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); + + let fields = CeoPostsFieldNames::default(); + let bson_path = dir.path().join("posts.bson"); + write_bytes( + &bson_path, + &make_post_doc( + &fields, + "CEO_RY", + "sp-1", + utc_ms(2024, 6, 15, 14, 0, 0), + None, + None, + None, + "hi", + ), + ); + + // 1. Pre-existing events/year=2024/part.parquet with sentinel bytes + let out_a = dir.path().join("out_existing_parquet"); + let year_2024 = out_a.join("events/year=2024"); + fs::create_dir_all(&year_2024).unwrap(); + let sentinel_path = year_2024.join("part.parquet"); + let sentinel_bytes = b"SENTINEL-FILINGS-EARNINGS-EVENTS-PARQUET".to_vec(); + write_bytes(&sentinel_path, &sentinel_bytes); + + let args_a = default_args( + bson_path.clone(), + map_path.clone(), + out_a.clone(), + CeoPostsTimestampUnit::Millis, + ); + let err = run_curate_posts(&args_a).unwrap_err(); + assert!(matches!(err, RunCuratePostsError::EventsDatasetExists { .. })); + let msg = assert_single_line_err(&err); + assert!(msg.contains("year=2024"), "expected year=2024 in {msg}"); + assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes); + let entries: Vec<_> = fs::read_dir(out_a.join("events")) + .unwrap() + .map(|e| e.unwrap().file_name()) + .collect(); + assert_eq!(entries.len(), 1); + + // 2. Pre-existing year=* directory without a Parquet file must also fail closed + let out_b = dir.path().join("out_empty_year_dir"); + let year_2025 = out_b.join("events/year=2025"); + fs::create_dir_all(&year_2025).unwrap(); + let args_b = default_args(bson_path, map_path, out_b.clone(), CeoPostsTimestampUnit::Millis); + let err = run_curate_posts(&args_b).unwrap_err(); + assert!(matches!(err, RunCuratePostsError::EventsDatasetExists { .. })); + let msg = assert_single_line_err(&err); + assert!(msg.contains("year=2025"), "expected year=2025 in {msg}"); + assert_eq!(fs::read_dir(&year_2025).unwrap().count(), 0); +} + +#[test] +fn fail_closed_errors_are_typed_single_line_and_leave_out_dir_untouched() { + let dir = TempDirGuard::new("fail-closed"); + let out_dir = dir.path().join("out"); + fs::create_dir_all(&out_dir).unwrap(); + let marker = out_dir.join("keep.txt"); + let marker_bytes = b"DO-NOT-TOUCH".to_vec(); + write_bytes(&marker, &marker_bytes); + + let assert_out_untouched = || { + assert!(!out_dir.join("events").exists(), "events dir must not be created"); + assert_eq!(fs::read(&marker).unwrap(), marker_bytes); + let entries: Vec<_> = fs::read_dir(&out_dir) + .unwrap() + .map(|e| e.unwrap().file_name()) + .collect(); + assert_eq!(entries.len(), 1); + }; + + let valid_map = dir.path().join("valid_map.tsv"); + write_bytes(&valid_map, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); + + let fields = CeoPostsFieldNames::default(); + let valid_doc = make_post_doc( + &fields, + "CEO_RY", + "sp-valid", + utc_ms(2024, 6, 15, 14, 0, 0), + None, + None, + None, + "valid post", + ); + let valid_bson = dir.path().join("valid.bson"); + write_bytes(&valid_bson, &valid_doc); + + let base_args = default_args( + valid_bson.clone(), + valid_map.clone(), + out_dir.clone(), + CeoPostsTimestampUnit::Millis, + ); + + // 1. Invalid output paths: regular file as out_dir, empty out_dir, regular file as out/events + let file_as_out = dir.path().join("file_out"); + write_bytes(&file_as_out, b"not-a-dir"); + let err = run_curate_posts(&CuratePostsArgs { + out_dir: file_as_out.clone(), + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::InvalidOutDir { .. })); + assert_single_line_err(&err); + assert_eq!(fs::read(&file_as_out).unwrap(), b"not-a-dir"); + + let err = run_curate_posts(&CuratePostsArgs { + out_dir: PathBuf::new(), + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::InvalidOutDir { .. })); + assert_single_line_err(&err); + + let out_with_file_events = dir.path().join("out_file_events"); + fs::create_dir_all(&out_with_file_events).unwrap(); + write_bytes(&out_with_file_events.join("events"), b"file-not-dir"); + let err = run_curate_posts(&CuratePostsArgs { + out_dir: out_with_file_events.clone(), + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::InvalidOutDir { .. })); + assert_single_line_err(&err); + assert_eq!( + fs::read(out_with_file_events.join("events")).unwrap(), + b"file-not-dir" + ); + + // 2. Blank field name + let err = run_curate_posts(&CuratePostsArgs { + key_field: " ".to_string(), + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::InvalidFieldNames { .. })); + assert_single_line_err(&err); + assert_out_untouched(); + + // 3. Duplicate field names + let err = run_curate_posts(&CuratePostsArgs { + spiel_id_field: DEFAULT_KEY_FIELD.to_string(), + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::InvalidFieldNames { .. })); + assert_single_line_err(&err); + assert_out_untouched(); + + // 4. Blank mapping_source + let err = run_curate_posts(&CuratePostsArgs { + mapping_source: " \t ".to_string(), + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::EmptyMappingSource)); + assert_single_line_err(&err); + assert_out_untouched(); + + // 5. Missing input file + let err = run_curate_posts(&CuratePostsArgs { + ceo_posts: dir.path().join("missing.bson"), + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::OpenInput { .. })); + assert_single_line_err(&err); + assert_out_untouched(); + + // 6. Injected reader I/O error (valid doc followed by BrokenPipe) + let err = run_curate_posts_with_reader( + &valid_map, + DEFAULT_MAPPING_SOURCE, + &fields, + CeoPostsTimestampUnit::Millis, + ( + Path::new("failing.bson"), + FailingReader { + prefix: valid_doc.clone(), + pos: 0, + }, + ), + &out_dir, + ) + .unwrap_err(); + assert!(matches!( + err, + RunCuratePostsError::BsonStream { + source: BsonStreamError::Io { offset, .. }, + .. + } if offset == valid_doc.len() as u64 + )); + let msg = assert_single_line_err(&err); + assert!(msg.contains(&valid_doc.len().to_string())); + assert_out_untouched(); + + // 7. Malformed TSV (line 2) + let bad_tsv = dir.path().join("bad.tsv"); + write_bytes( + &bad_tsv, + b"ceo\tCEO_RY\t2020-01-01\t\t101\nceo\tCEO_SHOP\tnot-a-date\t\t202\n", + ); + let err = run_curate_posts(&CuratePostsArgs { + provider_mapping: bad_tsv, + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::TsvParse { line: 2, .. })); + let msg = assert_single_line_err(&err); + assert!(msg.contains(":2:"), "expected :2: in {msg}"); + assert_out_untouched(); + + // 8. Overlapping provider_mapping.tsv + let overlap_tsv = dir.path().join("overlap.tsv"); + write_bytes( + &overlap_tsv, + b"ceo\tCEO_RY\t2020-01-01\t2024-06-01\t101\nceo\tCEO_RY\t2024-06-01\t\t102\n", + ); + let err = run_curate_posts(&CuratePostsArgs { + provider_mapping: overlap_tsv, + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::ProviderMapping { .. })); + let msg = assert_single_line_err(&err); + assert!(msg.contains("CEO_RY"), "expected conflicting key in {msg}"); + assert_out_untouched(); + + // 9. Truncated BSON after valid doc + let trunc_bson = dir.path().join("trunc.bson"); + let mut trunc_bytes = valid_doc.clone(); + let trunc_offset = trunc_bytes.len() as u64; + trunc_bytes.extend_from_slice(&[30, 0, 0, 0, 0x02, b'a']); + write_bytes(&trunc_bson, &trunc_bytes); + let err = run_curate_posts(&CuratePostsArgs { + ceo_posts: trunc_bson, + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!( + err, + RunCuratePostsError::BsonStream { + source: BsonStreamError::TruncatedDocument { offset, .. }, + .. + } if offset == trunc_offset + )); + let msg = assert_single_line_err(&err); + assert!(msg.contains(&trunc_offset.to_string())); + assert_out_untouched(); + + // 10. Corrupt BSON element after valid doc + let corrupt_bson = dir.path().join("corrupt.bson"); + let mut corrupt_doc = RawDocumentBuf::new(); + corrupt_doc.append(cstr!("ceoId"), "CEO_RY"); + corrupt_doc.append(cstr!("z"), 1_i32); + let mut bad_doc_bytes = corrupt_doc.into_bytes(); + let z_pos = bad_doc_bytes + .windows(3) + .position(|w| w == [0x10, b'z', 0x00]) + .unwrap(); + bad_doc_bytes[z_pos] = 0x7e; + + let mut combined_corrupt = valid_doc.clone(); + let corrupt_offset = combined_corrupt.len() as u64; + combined_corrupt.extend_from_slice(&bad_doc_bytes); + write_bytes(&corrupt_bson, &combined_corrupt); + let err = run_curate_posts(&CuratePostsArgs { + ceo_posts: corrupt_bson, + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!( + err, + RunCuratePostsError::CorruptBson { offset, .. } if offset == corrupt_offset + )); + let msg = assert_single_line_err(&err); + assert!(msg.contains(&corrupt_offset.to_string())); + assert_out_untouched(); + + // 11. Curation timestamp overflow after valid doc -> late failure publishes nothing + let overflow_bson = dir.path().join("overflow.bson"); + let mut overflow_bytes = valid_doc; + overflow_bytes.extend_from_slice(&make_post_doc( + &fields, + "CEO_RY", + "sp-overflow", + i64::MAX, + None, + None, + None, + "overflow ts", + )); + write_bytes(&overflow_bson, &overflow_bytes); + let err = run_curate_posts(&CuratePostsArgs { + ceo_posts: overflow_bson, + ..base_args + }) + .unwrap_err(); + assert!(matches!( + err, + RunCuratePostsError::CurateWrite { + source: CuratePostsWriteError::Curate(CuratePostsError::Posts( + PostsError::TimestampOverflow { .. } + )), + .. + } + )); + assert_single_line_err(&err); + assert_out_untouched(); +} + +#[test] +fn empty_and_all_unmapped_inputs_return_zero_rows_without_creating_events_dir() { + let dir = TempDirGuard::new("zero-rows"); + let map_path = dir.path().join("mapping.tsv"); + write_bytes(&map_path, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); + + // 1. Empty BSON input + let empty_bson = dir.path().join("empty.bson"); + write_bytes(&empty_bson, &[]); + let out_empty = dir.path().join("out_empty"); + let rep_empty = run_curate_posts(&default_args( + empty_bson, + map_path.clone(), + out_empty.clone(), + CeoPostsTimestampUnit::Millis, + )) + .expect("empty succeeds"); + assert_report_invariants(&rep_empty); + assert_eq!(rep_empty.docs_framed, 0); + assert_eq!(rep_empty.write_stats.rows_written, 0); + assert_eq!(rep_empty.write_stats.files_written, 0); + assert!(!out_empty.join("events").exists()); + + // 2. All-unmapped BSON input + let fields = CeoPostsFieldNames::default(); + let unmapped_bson = dir.path().join("unmapped.bson"); + write_bytes( + &unmapped_bson, + &make_post_doc( + &fields, + "NO_MATCH", + "sp-unmapped", + utc_ms(2024, 6, 15, 14, 0, 0), + None, + None, + None, + "unmapped", + ), + ); + let out_unmapped = dir.path().join("out_unmapped"); + let rep_unmapped = run_curate_posts(&default_args( + unmapped_bson, + map_path, + out_unmapped.clone(), + CeoPostsTimestampUnit::Millis, + )) + .expect("all-unmapped succeeds"); + assert_report_invariants(&rep_unmapped); + assert_eq!(rep_unmapped.docs_framed, 1); + assert_eq!(rep_unmapped.curate_stats.dropped_unmapped, 1); + assert_eq!(rep_unmapped.write_stats.rows_written, 0); + assert_eq!(rep_unmapped.write_stats.files_written, 0); + assert!(!out_unmapped.join("events").exists()); +} From 3515ef487b3fc4991215b93ff6c7e8d36ce52afa Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 10:43:07 -0500 Subject: [PATCH 15/21] =?UTF-8?q?T-164:=20M2.2i=20=E2=80=94=20`tools/curat?= =?UTF-8?q?e-etl`:=20file-to-file=20`ceoPosts`=20runner=20(`decode=5Fceo?= =?UTF-8?q?=5Fposts=5Fchunks`=20in=20`bson=5Fstream.rs`=20+=20`run=5Fcurat?= =?UTF-8?q?e=5Fposts.rs`:=20raw=20BSON=20dump=20+=20`provider=5Fmapping.ts?= =?UTF-8?q?v`=20=E2=86=92=20`curate=5Fand=5Fwrite=5Fposts`=20=E2=86=92=20`?= =?UTF-8?q?events`=20Zstd=20Parquet)=20with=20tests=20(no=20new=20crates,?= =?UTF-8?q?=20no=20CLI/bench=20changes,=20no=20live=20Mongo)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/src/run_curate_posts.rs | 105 +++++++++++++-- .../curate-etl/src/run_curate_posts_tests.rs | 124 +++++++++++++++++- 2 files changed, 209 insertions(+), 20 deletions(-) diff --git a/tools/curate-etl/src/run_curate_posts.rs b/tools/curate-etl/src/run_curate_posts.rs index 2a1cd13e..9f7e6c2e 100644 --- a/tools/curate-etl/src/run_curate_posts.rs +++ b/tools/curate-etl/src/run_curate_posts.rs @@ -45,10 +45,10 @@ use std::collections::HashSet; use std::error::Error; -use std::fmt; +use std::fmt::{self, Write as _}; use std::fs::{self, File}; use std::io; -use std::path::{Path, PathBuf}; +use std::path::{Component, Path, PathBuf}; use std::sync::Arc; use std::time::Instant; @@ -171,54 +171,86 @@ pub enum RunCuratePostsError { }, } +struct SingleLineWriter<'a, 'b> { + f: &'a mut fmt::Formatter<'b>, +} + +impl fmt::Write for SingleLineWriter<'_, '_> { + fn write_str(&mut self, s: &str) -> fmt::Result { + let mut rest = s; + while let Some(idx) = rest.find(['\n', '\r']) { + let (head, tail) = rest.split_at(idx); + if !head.is_empty() { + self.f.write_str(head)?; + } + let mut chars = tail.chars(); + match chars.next() { + Some('\n') => self.f.write_str("\\n")?, + Some('\r') => self.f.write_str("\\r")?, + _ => unreachable!(), + } + rest = chars.as_str(); + } + if !rest.is_empty() { + self.f.write_str(rest)?; + } + Ok(()) + } +} + impl fmt::Display for RunCuratePostsError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut w = SingleLineWriter { f }; match self { Self::InvalidOutDir { path, detail } => { - write!(f, "invalid --out '{}': {detail}", path.display()) + write!(w, "invalid --out '{}': {detail}", path.display()) } Self::InspectOutDir { path, source } => { - write!(f, "failed to inspect output path '{}': {source}", path.display()) + write!( + w, + "failed to inspect output path '{}': {source}", + path.display() + ) } Self::EventsDatasetExists { path } => write!( - f, + w, "refusing to overwrite existing events partition '{}': use a dedicated --out directory for ceoPosts", path.display() ), - Self::InvalidFieldNames { source } => write!(f, "{source}"), + Self::InvalidFieldNames { source } => write!(w, "{source}"), Self::EmptyMappingSource => { - write!(f, "invalid --mapping-source: must not be empty or blank") + write!(w, "invalid --mapping-source: must not be empty or blank") } Self::OpenInput { label, path, source, - } => write!(f, "failed to open {label} '{}': {source}", path.display()), + } => write!(w, "failed to open {label} '{}': {source}", path.display()), Self::ReadInput { label, path, source, - } => write!(f, "failed to read {label} '{}': {source}", path.display()), + } => write!(w, "failed to read {label} '{}': {source}", path.display()), Self::TsvParse { path, line, detail } => { - write!(f, "{}:{line}: {detail}", path.display()) + write!(w, "{}:{line}: {detail}", path.display()) } Self::ProviderMapping { path, source } => { - write!(f, "invalid provider_mapping '{}': {source}", path.display()) + write!(w, "invalid provider_mapping '{}': {source}", path.display()) } Self::BsonStream { path, source } => { - write!(f, "failed reading ceo-posts '{}': {source}", path.display()) + write!(w, "failed reading ceo-posts '{}': {source}", path.display()) } Self::CorruptBson { path, offset, source, } => write!( - f, + w, "corrupt ceo-posts BSON '{}' at byte offset {offset}: {source}", path.display() ), Self::CurateWrite { out_dir, source } => { - write!(f, "curate/write to '{}' failed: {source}", out_dir.display()) + write!(w, "curate/write to '{}' failed: {source}", out_dir.display()) } } } @@ -250,6 +282,51 @@ fn validate_out_dir_and_events_guard(out_dir: &Path) -> Result<(), RunCuratePost }); } + // Reject `..` after a missing path component: `fs::metadata` reports `NotFound` for the + // unresolved path, but `create_dir_all` would create the missing component and then traverse + // `..` into an existing directory, bypassing the events clobber guard. + let mut prefix = PathBuf::new(); + let mut saw_missing = false; + for component in out_dir.components() { + match component { + Component::ParentDir => { + if saw_missing { + return Err(RunCuratePostsError::InvalidOutDir { + path: out_dir.to_path_buf(), + detail: "output path must not contain '..' after a missing component" + .to_string(), + }); + } + prefix.push(component); + } + Component::CurDir => { + if !saw_missing { + prefix.push(component); + } + } + Component::RootDir | Component::Prefix(_) => { + prefix.push(component); + } + Component::Normal(_) => { + prefix.push(component); + if !saw_missing { + match fs::metadata(&prefix) { + Ok(_) => {} + Err(err) if err.kind() == io::ErrorKind::NotFound => { + saw_missing = true; + } + Err(source) => { + return Err(RunCuratePostsError::InspectOutDir { + path: prefix, + source, + }); + } + } + } + } + } + } + match fs::metadata(out_dir) { Ok(meta) if !meta.is_dir() => { return Err(RunCuratePostsError::InvalidOutDir { diff --git a/tools/curate-etl/src/run_curate_posts_tests.rs b/tools/curate-etl/src/run_curate_posts_tests.rs index 3115963e..83122e21 100644 --- a/tools/curate-etl/src/run_curate_posts_tests.rs +++ b/tools/curate-etl/src/run_curate_posts_tests.rs @@ -277,7 +277,7 @@ fn assert_single_line_err(err: &RunCuratePostsError) -> String { let msg = err.to_string(); assert!(!msg.is_empty(), "error message must not be empty"); assert!( - !msg.contains('\n'), + !msg.contains('\n') && !msg.contains('\r'), "error message must be single-line, got: {msg:?}" ); msg @@ -286,6 +286,7 @@ fn assert_single_line_err(err: &RunCuratePostsError) -> String { struct FailingReader { prefix: Vec, pos: usize, + error_message: String, } impl Read for FailingReader { @@ -298,7 +299,7 @@ impl Read for FailingReader { } Err(io::Error::new( io::ErrorKind::BrokenPipe, - "injected read failure", + self.error_message.clone(), )) } } @@ -695,6 +696,70 @@ fn clobber_guard_rejects_existing_year_partitions_and_preserves_bytes() { assert_eq!(fs::read_dir(&year_2025).unwrap().count(), 0); } +#[test] +fn clobber_guard_rejects_parent_dir_after_missing_component_and_preserves_tree() { + let dir = TempDirGuard::new("clobber-parent-dir"); + let map_path = dir.path().join("mapping.tsv"); + write_bytes(&map_path, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); + + let fields = CeoPostsFieldNames::default(); + let bson_path = dir.path().join("posts.bson"); + write_bytes( + &bson_path, + &make_post_doc( + &fields, + "CEO_RY", + "sp-1", + utc_ms(2024, 6, 15, 14, 0, 0), + None, + None, + None, + "hi", + ), + ); + + // Seed exports/shared/events/year=2024/part.parquet while exports/scratch is absent. + let exports_dir = dir.path().join("exports"); + let shared_dir = exports_dir.join("shared"); + let year_2024 = shared_dir.join("events/year=2024"); + fs::create_dir_all(&year_2024).unwrap(); + let sentinel_path = year_2024.join("part.parquet"); + let sentinel_bytes = b"SENTINEL-FILINGS-EARNINGS-2024".to_vec(); + write_bytes(&sentinel_path, &sentinel_bytes); + + let bypass_out = exports_dir.join("scratch").join("..").join("shared"); + assert!(!exports_dir.join("scratch").exists()); + + let args = default_args( + bson_path, + map_path, + bypass_out, + CeoPostsTimestampUnit::Millis, + ); + let err = run_curate_posts(&args).unwrap_err(); + assert!(matches!(err, RunCuratePostsError::InvalidOutDir { .. })); + let msg = assert_single_line_err(&err); + assert!(msg.contains(".."), "expected '..' detail in {msg}"); + + // The missing scratch component must not have been created, and the target partition + // and surrounding directory tree must be completely unchanged. + assert!(!exports_dir.join("scratch").exists()); + assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes); + + let list_names = |p: &Path| -> Vec { + let mut names: Vec = fs::read_dir(p) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + names + }; + assert_eq!(list_names(&exports_dir), vec!["shared"]); + assert_eq!(list_names(&shared_dir), vec!["events"]); + assert_eq!(list_names(&shared_dir.join("events")), vec!["year=2024"]); + assert_eq!(list_names(&year_2024), vec!["part.parquet"]); +} + #[test] fn fail_closed_errors_are_typed_single_line_and_leave_out_dir_untouched() { let dir = TempDirGuard::new("fail-closed"); @@ -813,7 +878,8 @@ fn fail_closed_errors_are_typed_single_line_and_leave_out_dir_untouched() { assert_single_line_err(&err); assert_out_untouched(); - // 6. Injected reader I/O error (valid doc followed by BrokenPipe) + // 6. Injected reader I/O error (valid doc followed by multiline BrokenPipe) + let multiline_cause = "decompression failed\ncaused by: corrupt zstd frame\r\nstream aborted"; let err = run_curate_posts_with_reader( &valid_map, DEFAULT_MAPPING_SOURCE, @@ -824,6 +890,48 @@ fn fail_closed_errors_are_typed_single_line_and_leave_out_dir_untouched() { FailingReader { prefix: valid_doc.clone(), pos: 0, + error_message: multiline_cause.to_string(), + }, + ), + &out_dir, + ) + .unwrap_err(); + match &err { + RunCuratePostsError::BsonStream { + source: BsonStreamError::Io { offset, source }, + .. + } => { + assert_eq!(*offset, valid_doc.len() as u64); + // Typed cause is preserved intact. + assert_eq!(source.kind(), io::ErrorKind::BrokenPipe); + assert_eq!(source.to_string(), multiline_cause); + } + other => panic!("expected BsonStream::Io, got {other:?}"), + } + let msg = assert_single_line_err(&err); + assert!(msg.contains("failing.bson"), "expected path in {msg}"); + assert!( + msg.contains(&valid_doc.len().to_string()), + "expected byte offset in {msg}" + ); + assert!( + msg.contains("decompression failed\\ncaused by: corrupt zstd frame\\r\\nstream aborted"), + "expected escaped multiline cause in {msg}" + ); + assert_out_untouched(); + + // 6b. Path containing a newline is also escaped to a single line + let err = run_curate_posts_with_reader( + &valid_map, + DEFAULT_MAPPING_SOURCE, + &fields, + CeoPostsTimestampUnit::Millis, + ( + Path::new("dir/bad\nname.bson"), + FailingReader { + prefix: Vec::new(), + pos: 0, + error_message: "boom\nline2".to_string(), }, ), &out_dir, @@ -832,12 +940,16 @@ fn fail_closed_errors_are_typed_single_line_and_leave_out_dir_untouched() { assert!(matches!( err, RunCuratePostsError::BsonStream { - source: BsonStreamError::Io { offset, .. }, + source: BsonStreamError::Io { offset: 0, .. }, .. - } if offset == valid_doc.len() as u64 + } )); let msg = assert_single_line_err(&err); - assert!(msg.contains(&valid_doc.len().to_string())); + assert!( + msg.contains("dir/bad\\nname.bson"), + "expected escaped path in {msg}" + ); + assert!(msg.contains("boom\\nline2"), "expected escaped cause in {msg}"); assert_out_untouched(); // 7. Malformed TSV (line 2) From 2932f5640de1e1aa69deef053f89d94e59499fca Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 10:49:45 -0500 Subject: [PATCH 16/21] T-164: tests --- .../curate-etl/src/run_curate_posts_tests.rs | 351 +++++++++++++++++- 1 file changed, 339 insertions(+), 12 deletions(-) diff --git a/tools/curate-etl/src/run_curate_posts_tests.rs b/tools/curate-etl/src/run_curate_posts_tests.rs index 83122e21..7456672b 100644 --- a/tools/curate-etl/src/run_curate_posts_tests.rs +++ b/tools/curate-etl/src/run_curate_posts_tests.rs @@ -137,7 +137,10 @@ fn assert_report_invariants(report: &CuratePostsRunReport) { assert_eq!(c.rows_in, b.newswire + b.retail); assert_eq!( c.rows_in, - c.rows_out + c.dropped_unmapped + c.dropped_unsupported_date + c.listing_duplicate_collapsed + c.rows_out + + c.dropped_unmapped + + c.dropped_unsupported_date + + c.listing_duplicate_collapsed ); assert_eq!(c.rows_out, c.newswire_out + c.retail_out); assert_eq!(report.write_stats.rows_written, c.rows_out); @@ -151,7 +154,11 @@ fn read_events_parquet_and_verify_zstd(path: &Path) -> Vec { for rg_idx in 0..meta.num_row_groups() { let rg_meta = meta.row_group(rg_idx); - assert_eq!(rg_meta.num_columns(), 7, "expected 7 columns in events schema"); + assert_eq!( + rg_meta.num_columns(), + 7, + "expected 7 columns in events schema" + ); for col_idx in 0..rg_meta.num_columns() { let compression = rg_meta.column(col_idx).compression(); assert!( @@ -215,7 +222,11 @@ fn read_events_parquet_and_verify_zstd(path: &Path) -> Vec { _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), } raw.iter() - .map(|b| std::str::from_utf8(b.data()).expect("valid utf8").to_string()) + .map(|b| { + std::str::from_utf8(b.data()) + .expect("valid utf8") + .to_string() + }) .collect() }; @@ -258,7 +269,9 @@ fn read_all_event_partitions(out_dir: &Path) -> Vec { let mut all = Vec::new(); for yd in year_dirs { - all.extend(read_events_parquet_and_verify_zstd(&yd.join("part.parquet"))); + all.extend(read_events_parquet_and_verify_zstd( + &yd.join("part.parquet"), + )); } all.sort_by(|a, b| { a.listing_id @@ -517,7 +530,10 @@ fn happy_path_matches_curate_posts_verifies_zstd_edit_time_and_invariants() { .find(|r| r.payload_json.contains("sp-wire-1")) .expect("newswire row"); assert_eq!(wire_row.subtype, POST_SUBTYPE_NEWSWIRE); - assert_eq!(wire_row.known_at_source.as_ref(), KNOWN_AT_SOURCE_POST_TIMESTAMP); + assert_eq!( + wire_row.known_at_source.as_ref(), + KNOWN_AT_SOURCE_POST_TIMESTAMP + ); assert_eq!(wire_row.ts_micros, t_wire * 1_000); assert_eq!(wire_row.known_at_micros, t_wire * 1_000); @@ -528,7 +544,10 @@ fn happy_path_matches_curate_posts_verifies_zstd_edit_time_and_invariants() { assert_eq!(edited_row.subtype, POST_SUBTYPE_RETAIL); assert_eq!(edited_row.ts_micros, t_edited_post * 1_000); assert_eq!(edited_row.known_at_micros, t_edited_at * 1_000); - assert_eq!(edited_row.known_at_source.as_ref(), KNOWN_AT_SOURCE_POST_EDITED); + assert_eq!( + edited_row.known_at_source.as_ref(), + KNOWN_AT_SOURCE_POST_EDITED + ); // Reversed input order must yield byte-identical Parquet files and deterministic report. let bson_rev = dir.path().join("ceoPosts_rev.bson"); @@ -551,7 +570,10 @@ fn happy_path_matches_curate_posts_verifies_zstd_edit_time_and_invariants() { for year in ["year=2024", "year=2025"] { let a = fs::read(out_a.join("events").join(year).join("part.parquet")).expect("read a"); let b = fs::read(out_b.join("events").join(year).join("part.parquet")).expect("read b"); - assert_eq!(a, b, "reversed input must produce byte-identical {year}/part.parquet"); + assert_eq!( + a, b, + "reversed input must produce byte-identical {year}/part.parquet" + ); } let strip_timing = |s: &str| { @@ -674,7 +696,10 @@ fn clobber_guard_rejects_existing_year_partitions_and_preserves_bytes() { CeoPostsTimestampUnit::Millis, ); let err = run_curate_posts(&args_a).unwrap_err(); - assert!(matches!(err, RunCuratePostsError::EventsDatasetExists { .. })); + assert!(matches!( + err, + RunCuratePostsError::EventsDatasetExists { .. } + )); let msg = assert_single_line_err(&err); assert!(msg.contains("year=2024"), "expected year=2024 in {msg}"); assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes); @@ -688,9 +713,17 @@ fn clobber_guard_rejects_existing_year_partitions_and_preserves_bytes() { let out_b = dir.path().join("out_empty_year_dir"); let year_2025 = out_b.join("events/year=2025"); fs::create_dir_all(&year_2025).unwrap(); - let args_b = default_args(bson_path, map_path, out_b.clone(), CeoPostsTimestampUnit::Millis); + let args_b = default_args( + bson_path, + map_path, + out_b.clone(), + CeoPostsTimestampUnit::Millis, + ); let err = run_curate_posts(&args_b).unwrap_err(); - assert!(matches!(err, RunCuratePostsError::EventsDatasetExists { .. })); + assert!(matches!( + err, + RunCuratePostsError::EventsDatasetExists { .. } + )); let msg = assert_single_line_err(&err); assert!(msg.contains("year=2025"), "expected year=2025 in {msg}"); assert_eq!(fs::read_dir(&year_2025).unwrap().count(), 0); @@ -770,7 +803,10 @@ fn fail_closed_errors_are_typed_single_line_and_leave_out_dir_untouched() { write_bytes(&marker, &marker_bytes); let assert_out_untouched = || { - assert!(!out_dir.join("events").exists(), "events dir must not be created"); + assert!( + !out_dir.join("events").exists(), + "events dir must not be created" + ); assert_eq!(fs::read(&marker).unwrap(), marker_bytes); let entries: Vec<_> = fs::read_dir(&out_dir) .unwrap() @@ -949,7 +985,10 @@ fn fail_closed_errors_are_typed_single_line_and_leave_out_dir_untouched() { msg.contains("dir/bad\\nname.bson"), "expected escaped path in {msg}" ); - assert!(msg.contains("boom\\nline2"), "expected escaped cause in {msg}"); + assert!( + msg.contains("boom\\nline2"), + "expected escaped cause in {msg}" + ); assert_out_untouched(); // 7. Malformed TSV (line 2) @@ -1121,3 +1160,291 @@ fn empty_and_all_unmapped_inputs_return_zero_rows_without_creating_events_dir() assert_eq!(rep_unmapped.write_stats.files_written, 0); assert!(!out_unmapped.join("events").exists()); } + +/// Reader that serves `bytes` and, on the first EOF, runs `on_eof` once (used to simulate another +/// publisher creating an `events/year=*` partition while the dump is still being decoded). +struct EofHookReader { + bytes: Vec, + pos: usize, + on_eof: Option, +} + +impl Read for EofHookReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if self.pos < self.bytes.len() { + let n = (self.bytes.len() - self.pos).min(buf.len()); + buf[..n].copy_from_slice(&self.bytes[self.pos..self.pos + n]); + self.pos += n; + return Ok(n); + } + if let Some(mut hook) = self.on_eof.take() { + hook(); + } + Ok(0) + } +} + +fn sorted_names(p: &Path) -> Vec { + let mut names: Vec = fs::read_dir(p) + .expect("read dir") + .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + names +} + +#[test] +fn post_decode_guard_rejects_partition_created_during_decode_and_preserves_bytes() { + let dir = TempDirGuard::new("guard-recheck"); + let map_path = dir.path().join("mapping.tsv"); + write_bytes(&map_path, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); + let fields = CeoPostsFieldNames::default(); + let doc = make_post_doc( + &fields, + "CEO_RY", + "sp-1", + utc_ms(2024, 6, 15, 14, 0, 0), + None, + None, + None, + "hi", + ); + + let out_dir = dir.path().join("out"); + let partition = out_dir.join("events").join("year=2024"); + let sentinel_path = partition.join("part.parquet"); + let sentinel = b"SENTINEL-CONCURRENT-FILINGS".to_vec(); + assert!( + !out_dir.exists(), + "first guard must see a fresh output root" + ); + + let hook_partition = partition.clone(); + let hook_sentinel_path = sentinel_path.clone(); + let hook_sentinel = sentinel.clone(); + let err = run_curate_posts_with_reader( + &map_path, + DEFAULT_MAPPING_SOURCE, + &fields, + CeoPostsTimestampUnit::Millis, + ( + Path::new("hooked.bson"), + EofHookReader { + bytes: doc, + pos: 0, + on_eof: Some(move || { + fs::create_dir_all(&hook_partition).expect("create concurrent partition"); + write_bytes(&hook_sentinel_path, &hook_sentinel); + }), + }, + ), + &out_dir, + ) + .unwrap_err(); + + assert!( + matches!(&err, RunCuratePostsError::EventsDatasetExists { path } if path == &partition), + "expected EventsDatasetExists for {partition:?}, got {err:?}" + ); + assert_single_line_err(&err); + assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel); + assert_eq!(sorted_names(&out_dir.join("events")), vec!["year=2024"]); + assert_eq!(sorted_names(&partition), vec!["part.parquet"]); +} + +#[test] +fn events_dir_with_only_non_year_entries_is_published_and_non_year_entries_preserved() { + let dir = TempDirGuard::new("non-year-entries"); + let map_path = dir.path().join("mapping.tsv"); + write_bytes(&map_path, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); + let fields = CeoPostsFieldNames::default(); + let bson_path = dir.path().join("posts.bson"); + write_bytes( + &bson_path, + &make_post_doc( + &fields, + "CEO_RY", + "sp-1", + utc_ms(2024, 6, 15, 14, 0, 0), + None, + None, + None, + "hi", + ), + ); + + let out_dir = dir.path().join("out"); + let events_dir = out_dir.join("events"); + fs::create_dir_all(&events_dir).unwrap(); + let readme = events_dir.join("README.txt"); + write_bytes(&readme, b"not a partition"); + + let report = run_curate_posts(&default_args( + bson_path, + map_path, + out_dir.clone(), + CeoPostsTimestampUnit::Millis, + )) + .expect("non-year entries must not trip the clobber guard"); + + assert_report_invariants(&report); + assert_eq!(report.write_stats.rows_written, 1); + assert_eq!(fs::read(&readme).unwrap(), b"not a partition"); + assert_eq!(sorted_names(&events_dir), vec!["README.txt", "year=2024"]); +} + +#[test] +fn parent_dir_through_existing_components_still_hits_events_guard() { + let dir = TempDirGuard::new("parent-existing"); + let map_path = dir.path().join("mapping.tsv"); + write_bytes(&map_path, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); + let fields = CeoPostsFieldNames::default(); + let bson_path = dir.path().join("posts.bson"); + write_bytes( + &bson_path, + &make_post_doc( + &fields, + "CEO_RY", + "sp-1", + utc_ms(2024, 6, 15, 14, 0, 0), + None, + None, + None, + "hi", + ), + ); + + let exports = dir.path().join("exports"); + let shared_partition = exports.join("shared/events/year=2024"); + fs::create_dir_all(&shared_partition).unwrap(); + fs::create_dir_all(exports.join("scratch")).unwrap(); + let sentinel_path = shared_partition.join("part.parquet"); + write_bytes(&sentinel_path, b"SENTINEL"); + + // `scratch` exists, so `..` resolves consistently and the guard must inspect `shared`. + let out = exports.join("scratch").join("..").join("shared"); + let err = run_curate_posts(&default_args( + bson_path, + map_path, + out, + CeoPostsTimestampUnit::Millis, + )) + .unwrap_err(); + assert!( + matches!(err, RunCuratePostsError::EventsDatasetExists { .. }), + "got {err:?}" + ); + assert_single_line_err(&err); + assert_eq!(fs::read(&sentinel_path).unwrap(), b"SENTINEL"); + assert_eq!(sorted_names(&exports), vec!["scratch", "shared"]); + assert!(sorted_names(&exports.join("scratch")).is_empty()); +} + +#[test] +fn eastern_posting_date_mapping_and_edit_clamp_match_curate_posts_baseline() { + let dir = TempDirGuard::new("eastern-pit"); + let map_path = dir.path().join("mapping.tsv"); + // Listing switch at the Eastern calendar boundary 2023-12-31 -> 2024-01-01 (valid_to inclusive). + write_bytes( + &map_path, + b"ceo\tCEO_RY\t2020-01-01\t2023-12-31\t101\nceo\tCEO_RY\t2024-01-01\t\t102\n", + ); + let fields = CeoPostsFieldNames::default(); + + // 2024-01-01 03:00 UTC == 2023-12-31 22:00 EST -> listing 101 (UTC date would give 102). + let t_late_eve = utc_ms(2024, 1, 1, 3, 0, 0); + // 2024-01-01 06:00 UTC == 2024-01-01 01:00 EST -> listing 102. + let t_new_year = utc_ms(2024, 1, 1, 6, 0, 0); + // Posted 2023-12-31 23:30 EST, edited after the switch: mapping must follow posted date. + let t_edit_posted = utc_ms(2024, 1, 1, 4, 30, 0); + let t_edit_at = utc_ms(2024, 1, 2, 15, 0, 0); + // Edit earlier than posting (clock skew): known_at clamps to posted_at. + let t_skew_posted = utc_ms(2024, 3, 5, 15, 0, 0); + let t_skew_edit = utc_ms(2024, 3, 5, 14, 0, 0); + + let inputs: Vec<(&str, i64, Option, Option<&str>)> = vec![ + ("sp-eve", t_late_eve, None, Some("1")), + ("sp-ny", t_new_year, None, None), + ("sp-edit", t_edit_posted, Some(t_edit_at), None), + ("sp-skew", t_skew_posted, Some(t_skew_edit), Some("0")), + ]; + let mut bytes = Vec::new(); + let mut baseline_posts = Vec::new(); + for (spiel, ts, ed, bot) in &inputs { + bytes.extend_from_slice(&make_post_doc( + &fields, + "CEO_RY", + spiel, + *ts, + *ed, + *bot, + Some("u"), + spiel, + )); + baseline_posts.push(CeoPost { + key: "CEO_RY".to_string(), + spiel_id: spiel.to_string(), + timestamp_ms: *ts, + edited_ms: *ed, + bot: bot.map(str::to_string), + user_id: Some("u".to_string()), + text: spiel.to_string(), + }); + } + let bson_path = dir.path().join("posts.bson"); + write_bytes(&bson_path, &bytes); + let out_dir = dir.path().join("out"); + + let report = run_curate_posts(&default_args( + bson_path, + map_path.clone(), + out_dir.clone(), + CeoPostsTimestampUnit::Millis, + )) + .expect("run"); + assert_report_invariants(&report); + assert_eq!(report.curate_stats.builder.edited, 2); + assert_eq!(report.curate_stats.builder.edited_before_posted, 1); + assert_eq!(report.write_stats.rows_written, 4); + + let mapping = ProviderMappingTable::from_rows(vec![ + ProviderMappingRow { + source: "ceo".to_string(), + source_id: "CEO_RY".to_string(), + valid_from: day(2020, 1, 1), + valid_to: Some(day(2023, 12, 31)), + listing_id: 101, + }, + ProviderMappingRow { + source: "ceo".to_string(), + source_id: "CEO_RY".to_string(), + valid_from: day(2024, 1, 1), + valid_to: None, + listing_id: 102, + }, + ]) + .unwrap(); + let baseline = curate_posts(baseline_posts, "ceo", &mapping).expect("baseline"); + let rows = read_all_event_partitions(&out_dir); + assert_eq!(rows, baseline.rows); + assert_eq!(report.curate_stats, baseline.stats); + + let find = |spiel: &str| { + rows.iter() + .find(|r| r.payload_json.contains(spiel)) + .unwrap_or_else(|| panic!("row {spiel}")) + }; + assert_eq!(find("sp-eve").listing_id, 101); + assert_eq!(find("sp-ny").listing_id, 102); + let edit = find("sp-edit"); + assert_eq!(edit.listing_id, 101); + assert_eq!(edit.ts_micros, t_edit_posted * 1_000); + assert_eq!(edit.known_at_micros, t_edit_at * 1_000); + let skew = find("sp-skew"); + assert_eq!(skew.ts_micros, t_skew_posted * 1_000); + assert_eq!(skew.known_at_micros, t_skew_posted * 1_000); + // No row may become visible before it was posted. + assert!(rows.iter().all(|r| r.known_at_micros >= r.ts_micros)); + // All four posts land in the UTC-2024 partition only. + assert_eq!(sorted_names(&out_dir.join("events")), vec!["year=2024"]); +} From 272d3366030fe85467fcfe93cd5872e6376cb62a Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 11:05:08 -0500 Subject: [PATCH 17/21] =?UTF-8?q?T-165:=20M2.1l=20(re-queue)=20=E2=80=94?= =?UTF-8?q?=20PostgreSQL=20`trial=5Fledger`=20adapter=20for=20the=20MCP=20?= =?UTF-8?q?copilot=20`file=5Ffinding`=20tool:=20`TrialRefLookupPort`=20ove?= =?UTF-8?q?r=20an=20injected=20executor=20in=20`libs/research/src/mcp/adap?= =?UTF-8?q?ters/postgres-trial-ref.ts`=20(research-visible=20=3D=20`sample?= =?UTF-8?q?=5Fend`=20before=20the=20Vault=20cutoff=20date,=20parameterized?= =?UTF-8?q?=20SQL,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/mcp/adapters/postgres-trial-ref.ts | 165 ++++++++ libs/research/src/mcp/index.ts | 1 + .../test/mcp-postgres-trial-ref.test.ts | 361 ++++++++++++++++++ test/postgres/mcp-trial-ref-adapter.test.ts | 350 +++++++++++++++++ 4 files changed, 877 insertions(+) create mode 100644 libs/research/src/mcp/adapters/postgres-trial-ref.ts create mode 100644 libs/research/test/mcp-postgres-trial-ref.test.ts create mode 100644 test/postgres/mcp-trial-ref-adapter.test.ts diff --git a/libs/research/src/mcp/adapters/postgres-trial-ref.ts b/libs/research/src/mcp/adapters/postgres-trial-ref.ts new file mode 100644 index 00000000..adeb9825 --- /dev/null +++ b/libs/research/src/mcp/adapters/postgres-trial-ref.ts @@ -0,0 +1,165 @@ +/** + * Read-only PostgreSQL `trial_ledger` adapter implementing {@link TrialRefLookupPort} + * for the MCP copilot `file_finding` tool. + * + * Dependency-free (no `pg`, no `node:*`, no bare `process`): SQL execution is + * 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}$/; + +/** Error codes thrown by {@link PostgresTrialRefError}. */ +export type PostgresTrialRefErrorCode = 'INVALID_EXECUTOR' | 'INVALID_SCHEMA' | 'INVALID_ROW'; + +/** Typed validation error thrown by the PostgreSQL trial-ref lookup adapter. */ +export class PostgresTrialRefError extends RangeError { + readonly code: PostgresTrialRefErrorCode; + + constructor(code: PostgresTrialRefErrorCode, message: string) { + super(message); + this.name = 'PostgresTrialRefError'; + this.code = code; + Object.setPrototypeOf(this, new.target.prototype); + } +} + +/** + * Structural `pg.Pool` / `pg.PoolClient`-compatible query interface so this module + * has no runtime dependency on `pg` and is unit-testable with a fake executor. + */ +export interface TrialRefExecutor { + query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }>; +} + +/** Factory options for {@link createPostgresTrialRefPort}. */ +export interface PostgresTrialRefPortOptions { + readonly executor: TrialRefExecutor; + /** Server-injected Vault cutoff epoch-ms timestamp; trials with `sample_end < utcDate(vaultCutoffTs)` are visible. */ + readonly vaultCutoffTs: number; + /** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */ + readonly schema?: string; +} + +interface RawTrialRefVisibilityRow { + readonly visible: unknown; +} + +function isCanonicalPositiveBigInt(value: unknown): value is string { + if (typeof value !== 'string' || !CANONICAL_TRIAL_ID_RE.test(value)) { + return false; + } + if (value.length === MAX_PG_BIGINT_STR.length && value > MAX_PG_BIGINT_STR) { + return false; + } + return true; +} + +function buildTrialRefVisibilitySql(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): { + readonly executor: TrialRefExecutor; + readonly schemaPrefix: string; + readonly vaultCutoffDate: string; +} { + if (typeof options !== 'object' || options === null) { + throw new PostgresTrialRefError( + 'INVALID_EXECUTOR', + 'Invalid options: expected an object with a TrialRefExecutor.' + ); + } + + const { executor, vaultCutoffTs, schema } = options; + if (typeof executor !== 'object' || executor === null || typeof executor.query !== 'function') { + throw new PostgresTrialRefError( + 'INVALID_EXECUTOR', + 'Invalid executor: expected an object with a callable query(text, params?) method.' + ); + } + + let schemaPrefix = ''; + if (schema !== undefined) { + if (typeof schema !== 'string' || !SCHEMA_IDENT_RE.test(schema)) { + throw new PostgresTrialRefError( + 'INVALID_SCHEMA', + 'Invalid schema: expected an identifier matching ^[a-z_][a-z0-9_]*$.' + ); + } + 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' + ); + } + + return { executor, schemaPrefix, vaultCutoffDate }; +} + +/** + * 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. + */ +export function createPostgresTrialRefPort( + options: PostgresTrialRefPortOptions +): TrialRefLookupPort { + const { executor, schemaPrefix, vaultCutoffDate } = validateFactoryOptions(options); + const sql = buildTrialRefVisibilitySql(schemaPrefix); + + return { + async hasResearchVisibleTrial(trialRef: string): Promise { + if (!isCanonicalPositiveBigInt(trialRef)) { + return false; + } + + const result = await executor.query(sql, [ + trialRef, + vaultCutoffDate, + ]); + + if (typeof result !== 'object' || result === null || !Array.isArray(result.rows)) { + throw new PostgresTrialRefError( + 'INVALID_ROW', + 'Invalid executor response: expected an object with a rows array.' + ); + } + + if (result.rows.length === 0) { + return false; + } + + if (result.rows.length !== 1) { + throw new PostgresTrialRefError( + 'INVALID_ROW', + `Invalid executor response: expected at most 1 trial_ledger row, received ${result.rows.length}.` + ); + } + + const raw = result.rows[0]; + if (typeof raw !== 'object' || raw === null || raw.visible !== 1) { + throw new PostgresTrialRefError( + 'INVALID_ROW', + 'Invalid trial_ledger visibility row: expected an object with visible === 1.' + ); + } + + return true; + }, + }; +} diff --git a/libs/research/src/mcp/index.ts b/libs/research/src/mcp/index.ts index 2af06a5e..a6aab4ad 100644 --- a/libs/research/src/mcp/index.ts +++ b/libs/research/src/mcp/index.ts @@ -1,5 +1,6 @@ export * from './adapters/postgres-findings'; export * from './adapters/postgres-symbol-search'; +export * from './adapters/postgres-trial-ref'; export * from './copilot-server'; export * from './protocol'; export * from './server'; diff --git a/libs/research/test/mcp-postgres-trial-ref.test.ts b/libs/research/test/mcp-postgres-trial-ref.test.ts new file mode 100644 index 00000000..cffaf1a8 --- /dev/null +++ b/libs/research/test/mcp-postgres-trial-ref.test.ts @@ -0,0 +1,361 @@ +import { describe, expect, test } from 'bun:test'; +import { MarketDataStoreValidationError } from '../src/market-data-store'; +import { + PostgresTrialRefError, + type TrialRefExecutor, + createPostgresTrialRefPort, +} from '../src/mcp/index'; + +interface RecordedCall { + readonly text: string; + readonly params: readonly unknown[] | undefined; +} + +function createFakeExecutor(rows: readonly Record[] = []): { + readonly calls: RecordedCall[]; + readonly executor: TrialRefExecutor; +} { + const calls: RecordedCall[] = []; + const executor: TrialRefExecutor = { + async query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + calls.push({ text, params }); + return { rows: rows as readonly Row[] }; + }, + }; + 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'; + +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, + }); + + 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], + }, + ]); + }); + + 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', () => { + const invalidOptions: unknown[] = [ + null, + undefined, + {}, + { executor: null, vaultCutoffTs: CUTOFF_TS }, + { executor: {}, vaultCutoffTs: CUTOFF_TS }, + { executor: { query: 'not-a-fn' }, vaultCutoffTs: CUTOFF_TS }, + ]; + + for (const opts of invalidOptions) { + let caught: unknown; + try { + createPostgresTrialRefPort(opts as Parameters[0]); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresTrialRefError); + expect((caught as PostgresTrialRefError).code).toBe('INVALID_EXECUTOR'); + } + }); + + test('rejects invalid schema identifiers with INVALID_SCHEMA before any query', () => { + const fake = createFakeExecutor([]); + const badSchemas: unknown[] = [ + '', + 'Public', + '1schema', + 'bad-name', + 'bad.name', + 'public"; DROP TABLE trial_ledger; --', + 'space name', + 123, + null, + ]; + + for (const schema of badSchemas) { + let caught: unknown; + try { + createPostgresTrialRefPort({ + executor: fake.executor, + vaultCutoffTs: CUTOFF_TS, + schema: schema as string, + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresTrialRefError); + expect((caught as PostgresTrialRefError).code).toBe('INVALID_SCHEMA'); + } + + 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', () => { + 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', + Number.NaN, + Number.POSITIVE_INFINITY, + Number.NEGATIVE_INFINITY, + 1.5, + Number.MAX_SAFE_INTEGER + 1, + 8_640_000_000_000_000, + -8_640_000_000_000_000, + yearZeroTs, + negativeYearTs, + fiveDigitYearTs, + ]; + + for (const vaultCutoffTs of invalidCutoffs) { + let caught: unknown; + try { + createPostgresTrialRefPort({ + executor: fake.executor, + vaultCutoffTs: vaultCutoffTs as number, + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(MarketDataStoreValidationError); + expect((caught as MarketDataStoreValidationError).field).toBe('vaultCutoffTs'); + } + + expect(fake.calls).toHaveLength(0); + }); + + test('returns false with zero executor calls for every invalid, non-canonical, overflow, or injection-shaped ref', async () => { + const fake = createFakeExecutor([{ visible: 1 }]); + const port = createPostgresTrialRefPort({ + executor: fake.executor, + vaultCutoffTs: CUTOFF_TS, + }); + + const invalidRefs: unknown[] = [ + '', + ' ', + ' 1', + '1 ', + '\t1', + '1\n', + '0', + '-1', + '+1', + '01', + '0001', + '1.0', + '1e2', + '1E2', + '0x10', + '1_000', + 'abc', + '1; DROP TABLE trial_ledger', + '1 OR 1=1', + '9223372036854775808', + '9999999999999999999', + '10000000000000000000', + 1, + 0, + null, + undefined, + {}, + [], + 1n, + ]; + + for (const ref of invalidRefs) { + expect(await port.hasResearchVisibleTrial(ref as string)).toBe(false); + } + + expect(fake.calls).toHaveLength(0); + }); + + test('passes 9223372036854775807 as an exact string without Number coercion and skips 9223372036854775808', async () => { + const fake = createFakeExecutor([{ visible: 1 }]); + const port = createPostgresTrialRefPort({ + executor: fake.executor, + vaultCutoffTs: CUTOFF_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'); + + expect(await port.hasResearchVisibleTrial('9223372036854775808')).toBe(false); + expect(fake.calls).toHaveLength(1); + }); + + 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, + }); + expect(await emptyPort.hasResearchVisibleTrial('123')).toBe(false); + + const hitFake = createFakeExecutor([{ visible: 1 }]); + const hitPort = createPostgresTrialRefPort({ + executor: hitFake.executor, + vaultCutoffTs: CUTOFF_TS, + }); + expect(await hitPort.hasResearchVisibleTrial('123')).toBe(true); + }); + + test('throws INVALID_ROW for malformed envelopes, invalid singleton rows, and multiple rows (regression)', async () => { + const badResponses: unknown[] = [ + null, + undefined, + {}, + { rows: null }, + { rows: 'not-an-array' }, + { rows: {} }, + { rows: [null] }, + { rows: [undefined] }, + { rows: [1] }, + { rows: [{}] }, + { rows: [{ visible: '1' }] }, + { rows: [{ visible: true }] }, + { rows: [{ visible: 0 }] }, + { rows: [{ visible: 2 }] }, + { rows: [{ visible: null }] }, + // Regression: multiple rows must fail closed rather than returning true. + { rows: [{ visible: 1 }, { visible: 1 }] }, + ]; + + for (const response of badResponses) { + const executor: TrialRefExecutor = { + async query() { + return response as { readonly rows: readonly never[] }; + }, + }; + const port = createPostgresTrialRefPort({ + executor, + vaultCutoffTs: CUTOFF_TS, + }); + + let caught: unknown; + try { + await port.hasResearchVisibleTrial('101'); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresTrialRefError); + expect((caught as PostgresTrialRefError).code).toBe('INVALID_ROW'); + } + }); + + test('propagates rejected and synchronously thrown executor errors unchanged without retrying', async () => { + const asyncFailure = new Error('connection terminated'); + let asyncAttempts = 0; + const asyncExecutor: TrialRefExecutor = { + async query() { + asyncAttempts += 1; + throw asyncFailure; + }, + }; + const asyncPort = createPostgresTrialRefPort({ + executor: asyncExecutor, + vaultCutoffTs: CUTOFF_TS, + }); + + await expect(asyncPort.hasResearchVisibleTrial('101')).rejects.toBe(asyncFailure); + expect(asyncAttempts).toBe(1); + + const syncFailure = new Error('sync driver failure'); + let syncAttempts = 0; + const syncExecutor: TrialRefExecutor = { + query() { + syncAttempts += 1; + throw syncFailure; + }, + }; + const syncPort = createPostgresTrialRefPort({ + executor: syncExecutor, + vaultCutoffTs: CUTOFF_TS, + }); + + await expect(syncPort.hasResearchVisibleTrial('101')).rejects.toBe(syncFailure); + expect(syncAttempts).toBe(1); + }); +}); diff --git a/test/postgres/mcp-trial-ref-adapter.test.ts b/test/postgres/mcp-trial-ref-adapter.test.ts new file mode 100644 index 00000000..9fc8029b --- /dev/null +++ b/test/postgres/mcp-trial-ref-adapter.test.ts @@ -0,0 +1,350 @@ +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Client, Pool, type PoolClient, type PoolConfig } from 'pg'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; +import { + FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, + type FileFindingResultPayload, + type TrialRefExecutor, + createFileFindingTool, + createMcpServer, + createPostgresFindingWritePort, + createPostgresTrialRefPort, +} from '../../libs/research/src/mcp/index'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +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); +const FIXED_TS = '2026-01-15T12:34:56.789Z'; + +const cleanup: (() => Promise | void)[] = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); + +function assertSafetyDatabaseUrl(connectionString: string | undefined): string { + if (!connectionString) { + throw new Error('Dedicated stock_bot_safety database required'); + } + let parsed: URL; + try { + parsed = new URL(connectionString); + } catch { + throw new Error('Dedicated stock_bot_safety database required'); + } + if (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') { + throw new Error('Dedicated stock_bot_safety database required'); + } + const client = new Client({ connectionString }); + const effectiveDb = ( + client as unknown as { connectionParameters?: { database?: unknown } } + ).connectionParameters?.database; + if ( + typeof effectiveDb !== 'string' || + !effectiveDb.startsWith('stock_bot_safety') || + !parsed.pathname.startsWith('/stock_bot_safety') + ) { + throw new Error('Dedicated stock_bot_safety database required'); + } + return connectionString; +} + +function createPgExecutor( + queryable: Pick | Pick +): TrialRefExecutor { + return { + query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + return queryable.query( + text, + params === undefined ? undefined : [...params] + ) as unknown as Promise<{ readonly rows: readonly Row[] }>; + }, + }; +} + +function buildIsolatedPoolConfig(connectionString: string | undefined, schema: string): PoolConfig { + const safeUrl = assertSafetyDatabaseUrl(connectionString); + const parsed = new URL(safeUrl); + const existingOptions = parsed.searchParams + .getAll('options') + .map(value => value.trim()) + .filter(value => value.length > 0); + parsed.searchParams.delete('options'); + + const schemaOptions = `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`; + const options = [...existingOptions, schemaOptions].join(' '); + + return { + connectionString: parsed.toString(), + options, + }; +} + +async function createIsolatedFixture(connectionString: string | undefined = url) { + const safeUrl = assertSafetyDatabaseUrl(connectionString); + const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; + const admin = new Pool({ connectionString: safeUrl }); + await admin.query(`CREATE SCHEMA ${schema}`); + const pool = new Pool(buildIsolatedPoolConfig(safeUrl, schema)); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + + const { rows: schemaRows } = await pool.query<{ current_schema: string | null }>( + 'SELECT current_schema() AS current_schema' + ); + if (schemaRows[0]?.current_schema !== schema) { + throw new Error( + `Isolated fixture pool expected current_schema()=${schema}, got ${String(schemaRows[0]?.current_schema)}` + ); + } + + // Bootstrap pre-additive tables needed by the research migration track. + for (const filename of [ + '06-create-backtest-tables.sql', + '07-fix-execution-time-type.sql', + '08-create-runs-table.sql', + ]) { + await pool.query(readFileSync(`${initDir}${filename}`, 'utf8')); + } + + const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, + logger + ); + Object.defineProperty(postgres, 'connectionPool', { + get: () => ({ + connect: () => pool.connect(), + }), + }); + + await runPostgresMigrations(postgres, { track: 'research' }); + + return { admin, pool, schema }; +} + +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; +} + +describe('PostgreSQL trial-ref adapter safety guard', () => { + test('rejects unsafe database targets before connecting', () => { + expect(() => assertSafetyDatabaseUrl(undefined)).toThrow( + 'Dedicated stock_bot_safety database required' + ); + expect(() => + assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/trading_bot') + ).toThrow('Dedicated stock_bot_safety database required'); + expect(() => + assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5433/trading_bot_dev') + ).toThrow('Dedicated stock_bot_safety database required'); + expect(() => + assertSafetyDatabaseUrl('socket:/stock_bot_safety?db=trading_bot') + ).toThrow('Dedicated stock_bot_safety database required'); + expect(() => + assertSafetyDatabaseUrl('http://127.0.0.1:5432/stock_bot_safety_test') + ).toThrow('Dedicated stock_bot_safety database required'); + expect(() => assertSafetyDatabaseUrl('not-a-valid-url')).toThrow( + 'Dedicated stock_bot_safety database required' + ); + expect( + assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test') + ).toBe('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test'); + }); + + test('preserves isolated schema search_path precedence over URL startup options', () => { + const schema = 'stock_bot_safety_trial_ref_options'; + const urlWithOptions = + 'postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test?options=-c%20statement_timeout%3D30000%20-c%20search_path%3Dpublic'; + const poolConfig = buildIsolatedPoolConfig(urlWithOptions, schema); + + expect(new URL(poolConfig.connectionString!).searchParams.has('options')).toBe(false); + + const client = new Client(poolConfig); + const resolvedOptions = (client as unknown as { connectionParameters: { options?: string } }) + .connectionParameters.options; + expect(resolvedOptions).toBe( + `-c statement_timeout=30000 -c search_path=public -c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000` + ); + }); +}); + +describe.skipIf(!url)('PostgreSQL MCP trial-ref adapter', () => { + test('enforces strict sample_end < vaultCutoffDate across default search_path and explicit schema', 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({ + 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); + + // Explicit schema option against the admin pool (default search_path) + const scopedPort = createPostgresTrialRefPort({ + executor: createPgExecutor(f.admin), + 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); + }); + + 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({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + const writePort = createPostgresFindingWritePort({ executor }); + + let idSeq = 0; + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: writePort, + trialLookup, + newId: () => { + idSeq += 1; + return `finding-trial-ref-${idSeq}`; + }, + now: () => new Date(FIXED_TS), + }), + ], + }); + + const callFileFinding = async (args: Record) => { + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'req-file-finding', + method: 'tools/call', + params: { + name: 'file_finding', + arguments: args, + }, + }) + ); + expect(raw).not.toBeNull(); + const parsed = JSON.parse(raw!) as { + result: { isError?: boolean; content: Array<{ text: string }> }; + }; + return parsed.result; + }; + + // Visible trial (sample_end = 2025-06-29 < 2025-06-30) succeeds and persists pending_review row. + const okRes = await callFileFinding({ + kind: 'finding', + title: 'Pre-cutoff signal holds across US equities', + summary: 'Positive IC verified strictly before the Vault cutoff.', + trialRefs: [visibleTrialId], + evidenceRefs: ['snap:2025-06-29:ic'], + }); + expect(okRes.isError).toBeUndefined(); + const receipt = JSON.parse(okRes.content[0]!.text) as FileFindingResultPayload; + expect(receipt).toEqual({ + id: 'finding-trial-ref-1', + createdAt: FIXED_TS, + created: true, + }); + + const storedRows = ( + await f.pool.query<{ id: string; status: string; trial_refs: string[] }>( + 'SELECT id, status, trial_refs FROM findings ORDER BY id ASC' + ) + ).rows; + expect(storedRows).toEqual([ + { + id: 'finding-trial-ref-1', + status: 'pending_review', + trial_refs: [visibleTrialId], + }, + ]); + + // 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']) { + const deniedRes = await callFileFinding({ + kind: 'dead_end', + title: 'Should be rejected by Vault fence', + summary: 'References non-visible trial.', + trialRefs: [deniedRef], + }); + expect(deniedRes.isError).toBe(true); + expect(deniedRes.content[0]!.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); + } + + const totalFindings = ( + await f.pool.query<{ c: number }>('SELECT count(*)::int AS c FROM findings') + ).rows[0]?.c; + expect(totalFindings).toBe(1); + }); +}); From dbd3ca7480b98ef75cd3ed49ccce31c0acdb1037 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 11:11:27 -0500 Subject: [PATCH 18/21] T-165: tests --- .../test/mcp-postgres-trial-ref-qa.test.ts | 263 ++++++++++++++++++ test/postgres/mcp-trial-ref-adapter.test.ts | 26 +- 2 files changed, 283 insertions(+), 6 deletions(-) create mode 100644 libs/research/test/mcp-postgres-trial-ref-qa.test.ts diff --git a/libs/research/test/mcp-postgres-trial-ref-qa.test.ts b/libs/research/test/mcp-postgres-trial-ref-qa.test.ts new file mode 100644 index 00000000..f4cf1d66 --- /dev/null +++ b/libs/research/test/mcp-postgres-trial-ref-qa.test.ts @@ -0,0 +1,263 @@ +import { describe, expect, test } from 'bun:test'; +import { + createFileFindingTool, + createPostgresTrialRefPort, + FILE_FINDING_ERROR_FILING_FAILED, + FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, + PostgresTrialRefError, + type AppendFindingResult, + type FiledFindingRecord, + type FindingWritePort, + type PostgresTrialRefPortOptions, + type TrialRefExecutor, +} from '../src/mcp/index'; + +interface RecordedCall { + readonly text: string; + readonly params: readonly unknown[] | undefined; +} + +function scriptedExecutor(respond: (params: readonly unknown[] | undefined) => unknown): { + readonly calls: RecordedCall[]; + readonly executor: TrialRefExecutor; +} { + const calls: RecordedCall[] = []; + return { + calls, + executor: { + async query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + calls.push({ text, params }); + return respond(params) as { readonly rows: readonly Row[] }; + }, + }, + }; +} + +function recordingWritePort(): { + readonly appended: FiledFindingRecord[]; + readonly port: FindingWritePort; +} { + const appended: FiledFindingRecord[] = []; + return { + appended, + port: { + async appendFinding(record): Promise { + appended.push(record); + return { status: 'created', id: record.id, createdAt: record.createdAt }; + }, + }, + }; +} + +const CUTOFF_TS = Date.UTC(2025, 5, 30, 15, 45, 30, 500); // 2025-06-30T15:45:30.500Z +const CUTOFF_DATE = '2025-06-30'; +const FIXED_EPOCH_MS = Date.UTC(2026, 0, 15, 12, 0, 0); + +describe('createPostgresTrialRefPort QA edge cases', () => { + test('snapshots executor, schema and cutoff at construction so later option mutation has no effect', async () => { + const original = scriptedExecutor(() => ({ rows: [] })); + const replacement = scriptedExecutor(() => ({ rows: [{ visible: 1 }] })); + const options: { + -readonly [K in keyof PostgresTrialRefPortOptions]: PostgresTrialRefPortOptions[K]; + } = { + executor: original.executor, + vaultCutoffTs: CUTOFF_TS, + schema: 'research_a', + }; + const port = createPostgresTrialRefPort(options); + + options.executor = replacement.executor; + options.vaultCutoffTs = Date.UTC(2030, 0, 1); + options.schema = 'research_b'; + + expect(await port.hasResearchVisibleTrial('5')).toBe(false); + expect(replacement.calls).toHaveLength(0); + expect(original.calls).toEqual([ + { + text: 'SELECT 1 AS visible FROM "research_a".trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1', + params: ['5', CUTOFF_DATE], + }, + ]); + }); + + test('binds UTC dates for epoch, pre-1970 and four-digit-year extreme cutoffs', async () => { + const cases: [number, string][] = [ + [0, '1970-01-01'], + [-1, '1969-12-31'], + [Date.UTC(2025, 5, 30, 0, 0, 0, 0), '2025-06-30'], + [Date.UTC(2025, 5, 30, 23, 59, 59, 999), '2025-06-30'], + [new Date('0001-01-01T00:00:00.000Z').getTime(), '0001-01-01'], + [new Date('9999-12-31T23:59:59.999Z').getTime(), '9999-12-31'], + ]; + + for (const [vaultCutoffTs, expectedDate] of cases) { + const fake = scriptedExecutor(() => ({ rows: [] })); + const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs }); + expect(await port.hasResearchVisibleTrial('1')).toBe(false); + expect(fake.calls[0]?.params).toEqual(['1', expectedDate]); + } + }); + + test('reports INVALID_EXECUTOR before schema or cutoff errors when several options are invalid', () => { + let caught: unknown; + try { + createPostgresTrialRefPort({ + executor: {} as TrialRefExecutor, + vaultCutoffTs: Number.NaN, + schema: 'Bad-Schema', + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(PostgresTrialRefError); + expect(caught).toBeInstanceOf(RangeError); + expect((caught as PostgresTrialRefError).code).toBe('INVALID_EXECUTOR'); + expect((caught as PostgresTrialRefError).name).toBe('PostgresTrialRefError'); + }); + + test('queries every canonical id across the 1..19 digit range up to the PostgreSQL bigint max', async () => { + const fake = scriptedExecutor(() => ({ rows: [{ visible: 1 }] })); + const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_TS }); + const accepted = [ + '1', + '9', + '10', + '999999999999999999', + '1000000000000000000', + '9223372036854775799', + '9223372036854775806', + '9223372036854775807', + ]; + + for (const ref of accepted) { + expect(await port.hasResearchVisibleTrial(ref)).toBe(true); + } + expect(fake.calls.map(call => call.params?.[0])).toEqual(accepted); + }); + + test('returns false without querying for out-of-range, unicode-digit, control-char and boxed refs', async () => { + const fake = scriptedExecutor(() => ({ rows: [{ visible: 1 }] })); + const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_TS }); + const rejected: unknown[] = [ + '9223372036854775810', + '9300000000000000000', + '12345678901234567890', + '١', // Arabic-Indic digit one + '1', // full-width digit one + '1\u0000', + ' 1', + '1​', + new String('1'), + Number.MAX_SAFE_INTEGER, + ]; + + for (const ref of rejected) { + expect(await port.hasResearchVisibleTrial(ref as string)).toBe(false); + } + expect(fake.calls).toHaveLength(0); + }); + + test('concurrent lookups each issue their own query and keep their own answers', async () => { + const fake = scriptedExecutor(params => ({ + rows: params?.[0] === '2' ? [{ visible: 1 }] : [], + })); + const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_TS }); + + const results = await Promise.all( + ['1', '2', '3', '2'].map(ref => port.hasResearchVisibleTrial(ref)) + ); + + expect(results).toEqual([false, true, false, true]); + expect(fake.calls).toHaveLength(4); + for (const call of fake.calls) { + expect(call.text).toMatch(/^SELECT 1 AS visible FROM trial_ledger WHERE /); + expect(call.text).not.toMatch(/\b(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|TRUNCATE)\b/i); + expect(call.params?.[1]).toBe(CUTOFF_DATE); + } + }); + + test('exposes only the read-only hasResearchVisibleTrial method', () => { + const fake = scriptedExecutor(() => ({ rows: [] })); + const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_TS }); + expect(Object.keys(port)).toEqual(['hasResearchVisibleTrial']); + }); +}); + +describe('createPostgresTrialRefPort composed with file_finding (fake executor)', () => { + function composeTool(respond: (params: readonly unknown[] | undefined) => unknown) { + const fake = scriptedExecutor(respond); + const writes = recordingWritePort(); + const tool = createFileFindingTool({ + port: writes.port, + trialLookup: createPostgresTrialRefPort({ + executor: fake.executor, + vaultCutoffTs: CUTOFF_TS, + }), + newId: () => 'finding-qa-1', + now: () => FIXED_EPOCH_MS, + }); + return { fake, tool, writes }; + } + + const baseArgs = { kind: 'finding', title: 'QA filing', summary: 'Visible-only summary.' }; + + test('a visible ref files one finding with the original string ref', async () => { + const { fake, tool, writes } = composeTool(() => ({ rows: [{ visible: 1 }] })); + + const res = await tool.execute({ ...baseArgs, trialRefs: ['9223372036854775807'] }); + + expect(res.isError).toBeUndefined(); + expect(fake.calls).toHaveLength(1); + expect(writes.appended).toHaveLength(1); + expect(writes.appended[0]?.trialRefs).toEqual(['9223372036854775807']); + expect(writes.appended[0]?.status).toBe('pending_review'); + }); + + test('a non-canonical ref is reported unavailable without any query or append', async () => { + const { fake, tool, writes } = composeTool(() => ({ rows: [{ visible: 1 }] })); + + const res = await tool.execute({ ...baseArgs, trialRefs: ['1; DROP TABLE trial_ledger'] }); + + expect(res.isError).toBe(true); + expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); + expect(fake.calls).toHaveLength(0); + expect(writes.appended).toHaveLength(0); + }); + + test('one Vault-only ref among visible refs rejects the whole filing with zero appends', async () => { + const { tool, writes } = composeTool(params => ({ + rows: params?.[0] === '20' ? [] : [{ visible: 1 }], + })); + + const res = await tool.execute({ ...baseArgs, trialRefs: ['10', '20', '30'] }); + + expect(res.isError).toBe(true); + expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); + expect(writes.appended).toHaveLength(0); + }); + + test('a malformed multi-row response fails closed as filing_failed with zero appends', async () => { + const { tool, writes } = composeTool(() => ({ rows: [{ visible: 1 }, { visible: 1 }] })); + + const res = await tool.execute({ ...baseArgs, trialRefs: ['10'] }); + + expect(res.isError).toBe(true); + expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); + expect(writes.appended).toHaveLength(0); + }); + + test('an executor failure fails closed as filing_failed with zero appends', async () => { + const { tool, writes } = composeTool(() => { + throw new Error('connection terminated'); + }); + + const res = await tool.execute({ ...baseArgs, trialRefs: ['10'] }); + + expect(res.isError).toBe(true); + expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); + expect(writes.appended).toHaveLength(0); + }); +}); diff --git a/test/postgres/mcp-trial-ref-adapter.test.ts b/test/postgres/mcp-trial-ref-adapter.test.ts index 9fc8029b..371f583d 100644 --- a/test/postgres/mcp-trial-ref-adapter.test.ts +++ b/test/postgres/mcp-trial-ref-adapter.test.ts @@ -26,8 +26,17 @@ const FIXED_TS = '2026-01-15T12:34:56.789Z'; const cleanup: (() => Promise | void)[] = []; afterEach(async () => { + // Run every cleanup step even if an earlier one fails, then surface the first failure. + let firstError: unknown; for (const close of cleanup.splice(0).reverse()) { - await close(); + try { + await close(); + } catch (err) { + firstError ??= err; + } + } + if (firstError !== undefined) { + throw firstError; } }); @@ -96,13 +105,12 @@ async function createIsolatedFixture(connectionString: string | undefined = url) const safeUrl = assertSafetyDatabaseUrl(connectionString); const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; const admin = new Pool({ connectionString: safeUrl }); + // Registered before CREATE SCHEMA so the admin pool closes even if creation or teardown fails. + cleanup.push(() => admin.end()); await admin.query(`CREATE SCHEMA ${schema}`); + cleanup.push(() => admin.query(`DROP SCHEMA ${schema} CASCADE`).then(() => undefined)); const pool = new Pool(buildIsolatedPoolConfig(safeUrl, schema)); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); + cleanup.push(() => pool.end()); const { rows: schemaRows } = await pool.query<{ current_schema: string | null }>( 'SELECT current_schema() AS current_schema' @@ -237,6 +245,12 @@ describe.skipIf(!url)('PostgreSQL MCP trial-ref adapter', () => { 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); // Explicit schema option against the admin pool (default search_path) const scopedPort = createPostgresTrialRefPort({ From 8906f3ad343299c33e3f014602eb323d5b75f9a6 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 11:33:26 -0500 Subject: [PATCH 19/21] =?UTF-8?q?T-167:=20M2.2j=20(re-queue)=20=E2=80=94?= =?UTF-8?q?=20`tools/curate-etl`:=20`curate-posts`=20CLI=20command=20(file?= =?UTF-8?q?=20mode)=20wiring=20`run=5Fcurate=5Fposts`=20into=20`cli.rs`=20?= =?UTF-8?q?+=20`main.rs`=20with=20parser=20tests=20(no=20new=20crates,=20n?= =?UTF-8?q?o=20bench=20changes,=20no=20`--from-mongo`,=20no=20live=20Mongo?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/README.md | 43 ++- tools/curate-etl/src/cli.rs | 561 +++++++++++++++++++++++++++++++++-- tools/curate-etl/src/main.rs | 11 + 3 files changed, 591 insertions(+), 24 deletions(-) diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 599110d5..d7d6b6ac 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`) @@ -921,7 +921,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`) @@ -1539,6 +1539,45 @@ 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 \ + [--key-field ceoId] \ + [--spiel-id-field spielId] \ + [--timestamp-field timestamp] \ + [--edited-field edited] \ + [--bot-field bot] \ + [--user-id-field userId] \ + [--text-field spiel] \ + [--mapping-source ceo] +``` + +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. diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index 11a967b9..3483d0ed 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -26,6 +26,15 @@ use crate::bench::{ DEFAULT_PARQUET_FX_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS, DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, DEFAULT_SHORTS_BENCH_ROWS, }; +use crate::bson_ceo_posts::{ + CeoPostsTimestampUnit, DEFAULT_BOT_FIELD as DEFAULT_POSTS_BOT_FIELD, + DEFAULT_EDITED_FIELD as DEFAULT_POSTS_EDITED_FIELD, + DEFAULT_KEY_FIELD as DEFAULT_POSTS_KEY_FIELD, + DEFAULT_SPIEL_ID_FIELD as DEFAULT_POSTS_SPIEL_ID_FIELD, + DEFAULT_TEXT_FIELD as DEFAULT_POSTS_TEXT_FIELD, + DEFAULT_TIMESTAMP_FIELD as DEFAULT_POSTS_TIMESTAMP_FIELD, + DEFAULT_USER_ID_FIELD as DEFAULT_POSTS_USER_ID_FIELD, +}; use crate::bson_ceo_shorts::{DEFAULT_KEY_FIELD, DEFAULT_REPORT_DATE_FIELD}; use crate::bson_eod_prices::parse_ymd_strict_days; use crate::bson_qm_events::{ @@ -44,6 +53,9 @@ use crate::run_curate_bars::{ use crate::run_curate_corporate_actions::CurateCorporateActionsArgs; use crate::run_curate_events::{CurateEventsArgs, DEFAULT_EVENTS_MAPPING_SOURCE}; use crate::run_curate_fx::{is_supported_te_symbol, CurateFx1dArgs, DEFAULT_TE_SYMBOL}; +use crate::run_curate_posts::{ + CuratePostsArgs, DEFAULT_MAPPING_SOURCE as DEFAULT_POSTS_MAPPING_SOURCE, +}; use crate::run_curate_shorts::{CurateShortsArgs, DEFAULT_MAPPING_SOURCE}; use crate::run_mongo::{ CurateAdjFactorsMongoArgs, CurateBars1dMongoArgs, CurateCorporateActionsMongoArgs, @@ -68,6 +80,7 @@ pub enum CliAction { CurateShortsMongo(CurateShortsMongoArgs), CurateEvents(CurateEventsArgs), CurateEventsMongo(CurateEventsMongoArgs), + CuratePosts(CuratePostsArgs), BenchSplit(usize), BenchAdj(usize), BenchCorporateActions(usize), @@ -127,8 +140,11 @@ pub fn format_usage(name: &str, version: &str) -> String { {name} curate-shorts --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] --provider-mapping --out --shares-short-field [--key-field ] [--report-date-field ] [--net-change-field ] [--pct-float-field ] [--mapping-source ]\n\ Curate shorts from ceoShorts BSON or read-only MongoDB + provider_mapping TSV into shorts/part.parquet (defaults: --key-field {DEFAULT_KEY_FIELD}, --report-date-field {DEFAULT_REPORT_DATE_FIELD}, --mapping-source {DEFAULT_MAPPING_SOURCE})\n\ {name} curate-events --qm-filings --qm-earnings --provider-mapping --out --filings-form-type-field [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--earnings-key-field ] [--earnings-report-date-field ] [--earnings-announce-time-field ] [--earnings-fiscal-period-end-field ] [--earnings-actual-eps-field ] [--earnings-revenue-field ] [--mapping-source ]\n\ + {name} curate-posts --ceo-posts --provider-mapping --out --timestamp-unit [--key-field ] [--spiel-id-field ] [--timestamp-field ] [--edited-field ] [--bot-field ] [--user-id-field ] [--text-field ] [--mapping-source ]\n\ {name} curate-events --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] [--date-gte ] [--date-lt ] --provider-mapping --out --filings-form-type-field [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--earnings-key-field ] [--earnings-report-date-field ] [--earnings-announce-time-field ] [--earnings-fiscal-period-end-field ] [--earnings-actual-eps-field ] [--earnings-revenue-field ] [--mapping-source ]\n\ Curate events from qmFilings + qmEarnings BSON or read-only MongoDB + provider_mapping TSV into events/year=YYYY/part.parquet (defaults: --filings-key-field {DEFAULT_FILINGS_KEY_FIELD}, --filings-timefiled-field {DEFAULT_FILINGS_TIMEFILED_FIELD}, --earnings-key-field {DEFAULT_EARNINGS_KEY_FIELD}, --earnings-report-date-field {DEFAULT_EARNINGS_REPORT_DATE_FIELD}, --earnings-announce-time-field {DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD}, --mapping-source {DEFAULT_EVENTS_MAPPING_SOURCE})\n\ + {name} curate-posts --ceo-posts --provider-mapping --out --timestamp-unit [--key-field ] [--spiel-id-field ] [--timestamp-field ] [--edited-field ] [--bot-field ] [--user-id-field ] [--text-field ] [--mapping-source ]\n\ + Curate ceoPosts from BSON + provider_mapping TSV into /events/year=YYYY/part.parquet using a dedicated --out directory (--timestamp-unit has no default; defaults: --key-field {DEFAULT_POSTS_KEY_FIELD}, --spiel-id-field {DEFAULT_POSTS_SPIEL_ID_FIELD}, --timestamp-field {DEFAULT_POSTS_TIMESTAMP_FIELD}, --edited-field {DEFAULT_POSTS_EDITED_FIELD}, --bot-field {DEFAULT_POSTS_BOT_FIELD}, --user-id-field {DEFAULT_POSTS_USER_ID_FIELD}, --text-field {DEFAULT_POSTS_TEXT_FIELD}, --mapping-source {DEFAULT_POSTS_MAPPING_SOURCE})\n\ {name} bench-split [rows] Run fixed-seed split lookup + un-adjust benchmark (default: {DEFAULT_BENCH_ROWS})\n\ {name} bench-adj [events] Run fixed-seed adj_factors build benchmark (default: {DEFAULT_ADJ_BENCH_EVENTS})\n\ {name} bench-corporate-actions [events] Run fixed-seed corporate_actions build benchmark (default: {DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS})\n\ @@ -177,6 +193,7 @@ pub fn format_usage_stderr(name: &str) -> String { {name} curate-fx-1d --eod-prices --te-market-data [--te-symbol ] --out \n\ {name} curate-shorts --ceo-shorts --provider-mapping --out --shares-short-field [--key-field ] [--report-date-field ] [--net-change-field ] [--pct-float-field ] [--mapping-source ]\n\ {name} curate-events --qm-filings --qm-earnings --provider-mapping --out --filings-form-type-field [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--earnings-key-field ] [--earnings-report-date-field ] [--earnings-announce-time-field ] [--earnings-fiscal-period-end-field ] [--earnings-actual-eps-field ] [--earnings-revenue-field ] [--mapping-source ]\n\ + {name} curate-posts --ceo-posts --provider-mapping --out --timestamp-unit [--key-field ] [--spiel-id-field ] [--timestamp-field ] [--edited-field ] [--bot-field ] [--user-id-field ] [--text-field ] [--mapping-source ]\n\ {name} bench-split [rows]\n\ {name} bench-adj [events]\n\ {name} bench-corporate-actions [events]\n\ @@ -992,6 +1009,28 @@ fn parse_curate_fx_1d_args(args: &[&str]) -> Result { })) } +fn set_path(slot: &mut Option, flag_name: &str, raw: &str) -> Result<(), String> { + if slot.is_some() { + return Err(format!("duplicate flag '{flag_name}'")); + } + if raw.is_empty() { + return Err(format!("empty value for flag '{flag_name}'")); + } + *slot = Some(PathBuf::from(raw)); + Ok(()) +} + +fn set_name(slot: &mut Option, flag_name: &str, raw: &str) -> Result<(), String> { + if slot.is_some() { + return Err(format!("duplicate flag '{flag_name}'")); + } + if raw.trim().is_empty() { + return Err(format!("empty value for flag '{flag_name}'")); + } + *slot = Some(raw.to_string()); + Ok(()) +} + fn parse_curate_shorts_args(args: &[&str]) -> Result { let mut mongo = MongoFlagState::default(); let mut ceo_shorts: Option = None; @@ -1040,28 +1079,6 @@ fn parse_curate_shorts_args(args: &[&str]) -> Result { continue; } - let set_path = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(PathBuf::from(raw)); - Ok(()) - }; - - let set_name = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.trim().is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(raw.to_string()); - Ok(()) - }; - match flag { "--ceo-shorts" => set_path(&mut ceo_shorts, "--ceo-shorts", value)?, "--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?, @@ -1149,6 +1166,119 @@ fn parse_curate_shorts_args(args: &[&str]) -> Result { Ok(CliAction::CurateShorts(parsed)) } +fn parse_curate_posts_args(args: &[&str]) -> Result { + let mut ceo_posts: Option = None; + let mut provider_mapping: Option = None; + let mut out_dir: Option = None; + let mut timestamp_unit: Option = None; + let mut key_field: Option = None; + let mut spiel_id_field: Option = None; + let mut timestamp_field: Option = None; + let mut edited_field: Option = None; + let mut bot_field: Option = None; + let mut user_id_field: Option = None; + let mut text_field: Option = None; + let mut mapping_source: Option = None; + + let mut i = 0usize; + while i < args.len() { + let token = args[i]; + if !token.starts_with("--") { + return Err(format!( + "unexpected positional argument '{token}' for curate-posts" + )); + } + + let flag_name = token.split_once('=').map_or(token, |(k, _)| k); + if !matches!( + flag_name, + "--ceo-posts" + | "--provider-mapping" + | "--out" + | "--timestamp-unit" + | "--key-field" + | "--spiel-id-field" + | "--timestamp-field" + | "--edited-field" + | "--bot-field" + | "--user-id-field" + | "--text-field" + | "--mapping-source" + ) { + return Err(format!("unknown flag '{flag_name}' for curate-posts")); + } + + let (flag, value) = if let Some((k, v)) = token.split_once('=') { + i += 1; + (k, v) + } else { + let Some(&v) = args.get(i + 1) else { + return Err(format!("missing value for flag '{token}'")); + }; + if v.starts_with("--") { + return Err(format!("missing value for flag '{token}'")); + } + i += 2; + (token, v) + }; + + match flag { + "--ceo-posts" => set_path(&mut ceo_posts, "--ceo-posts", value)?, + "--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?, + "--out" => set_path(&mut out_dir, "--out", value)?, + "--timestamp-unit" => { + if timestamp_unit.is_some() { + return Err("duplicate flag '--timestamp-unit'".to_string()); + } + timestamp_unit = Some(match value { + "seconds" => CeoPostsTimestampUnit::Seconds, + "millis" => CeoPostsTimestampUnit::Millis, + _ => { + return Err(format!( + "invalid --timestamp-unit '{value}' (expected 'seconds' or 'millis')" + )); + } + }); + } + "--key-field" => set_name(&mut key_field, "--key-field", value)?, + "--spiel-id-field" => set_name(&mut spiel_id_field, "--spiel-id-field", value)?, + "--timestamp-field" => set_name(&mut timestamp_field, "--timestamp-field", value)?, + "--edited-field" => set_name(&mut edited_field, "--edited-field", value)?, + "--bot-field" => set_name(&mut bot_field, "--bot-field", value)?, + "--user-id-field" => set_name(&mut user_id_field, "--user-id-field", value)?, + "--text-field" => set_name(&mut text_field, "--text-field", value)?, + "--mapping-source" => set_name(&mut mapping_source, "--mapping-source", value)?, + other => return Err(format!("unknown flag '{other}' for curate-posts")), + } + } + + let ceo_posts = ceo_posts.ok_or_else(|| "missing required flag '--ceo-posts'".to_string())?; + let provider_mapping = + provider_mapping.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; + let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; + let timestamp_unit = + timestamp_unit.ok_or_else(|| "missing required flag '--timestamp-unit'".to_string())?; + + let parsed = CuratePostsArgs { + ceo_posts, + provider_mapping, + out_dir, + timestamp_unit, + key_field: key_field.unwrap_or_else(|| DEFAULT_POSTS_KEY_FIELD.to_string()), + spiel_id_field: spiel_id_field.unwrap_or_else(|| DEFAULT_POSTS_SPIEL_ID_FIELD.to_string()), + timestamp_field: timestamp_field + .unwrap_or_else(|| DEFAULT_POSTS_TIMESTAMP_FIELD.to_string()), + edited_field: edited_field.unwrap_or_else(|| DEFAULT_POSTS_EDITED_FIELD.to_string()), + bot_field: bot_field.unwrap_or_else(|| DEFAULT_POSTS_BOT_FIELD.to_string()), + user_id_field: user_id_field.unwrap_or_else(|| DEFAULT_POSTS_USER_ID_FIELD.to_string()), + text_field: text_field.unwrap_or_else(|| DEFAULT_POSTS_TEXT_FIELD.to_string()), + mapping_source: mapping_source.unwrap_or_else(|| DEFAULT_POSTS_MAPPING_SOURCE.to_string()), + }; + + parsed.field_names().validate().map_err(|e| e.to_string())?; + Ok(CliAction::CuratePosts(parsed)) +} + fn parse_curate_events_args(args: &[&str]) -> Result { let mut mongo = MongoFlagState::default(); let mut qm_filings: Option = None; @@ -1437,6 +1567,7 @@ pub fn parse_args(args: &[String]) -> Result { ["curate-fx-1d", rest @ ..] => parse_curate_fx_1d_args(rest), ["curate-shorts", rest @ ..] => parse_curate_shorts_args(rest), ["curate-events", rest @ ..] => parse_curate_events_args(rest), + ["curate-posts", rest @ ..] => parse_curate_posts_args(rest), ["bench-split"] => Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)), ["bench-split", raw] => match raw.parse::() { Ok(n) if n > 0 => Ok(CliAction::BenchSplit(n)), @@ -3459,4 +3590,390 @@ mod tests { assert!(parse_args(&to_args(&["bench-fundamentals", "abc"])).is_err()); assert!(parse_args(&to_args(&["bench-fundamentals", "1", "2"])).is_err()); } + + #[test] + fn curate_posts_parsing_validation_and_usage() { + let usage = format_usage("curate-etl", "0.1.0"); + let stderr_usage = format_usage_stderr("curate-etl"); + assert!(usage.contains("curate-posts --ceo-posts")); + assert!(stderr_usage.contains("curate-posts --ceo-posts")); + + // Minimal valid invocation with --timestamp-unit seconds fills all 8 defaults + assert_eq!( + parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "posts.bson", + "--provider-mapping", + "map.tsv", + "--out", + "posts_out", + "--timestamp-unit", + "seconds", + ])), + Ok(CliAction::CuratePosts(CuratePostsArgs { + ceo_posts: PathBuf::from("posts.bson"), + provider_mapping: PathBuf::from("map.tsv"), + out_dir: PathBuf::from("posts_out"), + timestamp_unit: CeoPostsTimestampUnit::Seconds, + key_field: "ceoId".to_string(), + spiel_id_field: "spielId".to_string(), + timestamp_field: "timestamp".to_string(), + edited_field: "edited".to_string(), + bot_field: "bot".to_string(), + user_id_field: "userId".to_string(), + text_field: "spiel".to_string(), + mapping_source: "ceo".to_string(), + })) + ); + + // Minimal valid invocation with --timestamp-unit millis + assert_eq!( + parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "posts.bson", + "--provider-mapping", + "map.tsv", + "--out", + "posts_out", + "--timestamp-unit", + "millis", + ])), + Ok(CliAction::CuratePosts(CuratePostsArgs { + ceo_posts: PathBuf::from("posts.bson"), + provider_mapping: PathBuf::from("map.tsv"), + out_dir: PathBuf::from("posts_out"), + timestamp_unit: CeoPostsTimestampUnit::Millis, + key_field: DEFAULT_POSTS_KEY_FIELD.to_string(), + spiel_id_field: DEFAULT_POSTS_SPIEL_ID_FIELD.to_string(), + timestamp_field: DEFAULT_POSTS_TIMESTAMP_FIELD.to_string(), + edited_field: DEFAULT_POSTS_EDITED_FIELD.to_string(), + bot_field: DEFAULT_POSTS_BOT_FIELD.to_string(), + user_id_field: DEFAULT_POSTS_USER_ID_FIELD.to_string(), + text_field: DEFAULT_POSTS_TEXT_FIELD.to_string(), + mapping_source: DEFAULT_POSTS_MAPPING_SOURCE.to_string(), + })) + ); + + // All 8 optional flags overridden using --flag=value syntax + assert_eq!( + parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts=p2.bson", + "--provider-mapping=m2.tsv", + "--out=o2", + "--timestamp-unit=millis", + "--key-field=channel", + "--spiel-id-field=postId", + "--timestamp-field=createdAt", + "--edited-field=updatedAt", + "--bot-field=isBot", + "--user-id-field=authorId", + "--text-field=body", + "--mapping-source=ceo_alt", + ])), + Ok(CliAction::CuratePosts(CuratePostsArgs { + ceo_posts: PathBuf::from("p2.bson"), + provider_mapping: PathBuf::from("m2.tsv"), + out_dir: PathBuf::from("o2"), + timestamp_unit: CeoPostsTimestampUnit::Millis, + key_field: "channel".to_string(), + spiel_id_field: "postId".to_string(), + timestamp_field: "createdAt".to_string(), + edited_field: "updatedAt".to_string(), + bot_field: "isBot".to_string(), + user_id_field: "authorId".to_string(), + text_field: "body".to_string(), + mapping_source: "ceo_alt".to_string(), + })) + ); + + // Each missing required flag errors + for (missing_flag, args) in [ + ( + "--ceo-posts", + &[ + "curate-posts", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + ][..], + ), + ( + "--provider-mapping", + &[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--out", + "o", + "--timestamp-unit", + "seconds", + ][..], + ), + ( + "--out", + &[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--timestamp-unit", + "seconds", + ][..], + ), + ( + "--timestamp-unit", + &[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + ][..], + ), + ] { + let err = parse_args(&to_args(args)).unwrap_err(); + assert!( + err.contains(&format!("missing required flag '{missing_flag}'")), + "expected missing {missing_flag}, got: {err}" + ); + } + + // Invalid --timestamp-unit values + for bad_unit in ["", " ", "ms", "sec", "SECONDS", "MILLIS", "micros"] { + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + bad_unit, + ])) + .unwrap_err(); + assert!( + err.contains("invalid --timestamp-unit"), + "expected invalid --timestamp-unit for '{bad_unit}', got: {err}" + ); + } + + // Missing flag value (at end and followed by --flag) + let err = parse_args(&to_args(&["curate-posts", "--ceo-posts"])).unwrap_err(); + assert!(err.contains("missing value for flag '--ceo-posts'"), "{err}"); + + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + ])) + .unwrap_err(); + assert!(err.contains("missing value for flag '--ceo-posts'"), "{err}"); + + // Duplicate flags including --timestamp-unit + for (dup_flag, args) in [ + ( + "--ceo-posts", + &[ + "curate-posts", + "--ceo-posts", + "a.bson", + "--ceo-posts=b.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + ][..], + ), + ( + "--timestamp-unit", + &[ + "curate-posts", + "--ceo-posts", + "a.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + "--timestamp-unit=millis", + ][..], + ), + ( + "--key-field", + &[ + "curate-posts", + "--ceo-posts", + "a.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + "--key-field", + "k1", + "--key-field=k2", + ][..], + ), + ] { + let err = parse_args(&to_args(args)).unwrap_err(); + assert!( + err.contains(&format!("duplicate flag '{dup_flag}'")), + "expected duplicate {dup_flag}, got: {err}" + ); + } + + // Unknown flags and --from-mongo (bare, followed by other flags, or with =) + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + "--bogus", + "1", + ])) + .unwrap_err(); + assert_eq!(err, "unknown flag '--bogus' for curate-posts"); + + for from_mongo_args in [ + &["curate-posts", "--from-mongo"][..], + &[ + "curate-posts", + "--from-mongo", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + ][..], + &["curate-posts", "--from-mongo=true"][..], + ] { + let err = parse_args(&to_args(from_mongo_args)).unwrap_err(); + assert_eq!(err, "unknown flag '--from-mongo' for curate-posts"); + } + + // Positional argument rejected + let err = parse_args(&to_args(&[ + "curate-posts", + "extra", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + ])) + .unwrap_err(); + assert_eq!(err, "unexpected positional argument 'extra' for curate-posts"); + + // Empty / blank field names and path values rejected + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts=", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + ])) + .unwrap_err(); + assert!(err.contains("empty value for flag '--ceo-posts'"), "{err}"); + + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + "--text-field", + " ", + ])) + .unwrap_err(); + assert!(err.contains("empty value for flag '--text-field'"), "{err}"); + + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + "--mapping-source", + " ", + ])) + .unwrap_err(); + assert!( + err.contains("empty value for flag '--mapping-source'"), + "{err}" + ); + + // Role collisions after defaults are applied + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + "--text-field", + "ceoId", + ])) + .unwrap_err(); + assert!(err.contains("cannot share BSON field 'ceoId'"), "{err}"); + + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + "--bot-field", + "shared", + "--user-id-field", + "shared", + ])) + .unwrap_err(); + assert!(err.contains("cannot share BSON field 'shared'"), "{err}"); + } } diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index 6f3be0c3..936c0d64 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -28,6 +28,7 @@ use curate_etl::run_curate_corporate_actions::{ }; use curate_etl::run_curate_events::{format_curate_events_report, run_curate_events}; use curate_etl::run_curate_fx::{format_curate_fx_report, run_curate_fx_1d}; +use curate_etl::run_curate_posts::{format_curate_posts_report, run_curate_posts}; use curate_etl::run_curate_shorts::{format_curate_shorts_report, run_curate_shorts}; use curate_etl::run_mongo::{ run_curate_adj_factors_mongo, run_curate_bars_1d_mongo, run_curate_corporate_actions_mongo, @@ -197,6 +198,16 @@ fn main() -> ExitCode { } } } + Ok(CliAction::CuratePosts(curate_args)) => match run_curate_posts(&curate_args) { + Ok(report) => { + println!("{}", format_curate_posts_report(&report)); + ExitCode::SUCCESS + } + Err(err) => { + eprintln!("error: {err}"); + ExitCode::FAILURE + } + }, Ok(CliAction::BenchSplit(rows)) => { let report = match run_split_benchmark(rows) { Ok(report) => report, From 5105ddf73cff74603b6235ce49f00ce755779cb7 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 11:38:15 -0500 Subject: [PATCH 20/21] =?UTF-8?q?T-167:=20M2.2j=20(re-queue)=20=E2=80=94?= =?UTF-8?q?=20`tools/curate-etl`:=20`curate-posts`=20CLI=20command=20(file?= =?UTF-8?q?=20mode)=20wiring=20`run=5Fcurate=5Fposts`=20into=20`cli.rs`=20?= =?UTF-8?q?+=20`main.rs`=20with=20parser=20tests=20(no=20new=20crates,=20n?= =?UTF-8?q?o=20bench=20changes,=20no=20`--from-mongo`,=20no=20live=20Mongo?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/README.md | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index d7d6b6ac..507ace3d 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1550,15 +1550,7 @@ curate-etl curate-posts \ --ceo-posts ceoPosts.bson \ --provider-mapping provider_mapping.tsv \ --out ./out-posts \ - --timestamp-unit \ - [--key-field ceoId] \ - [--spiel-id-field spielId] \ - [--timestamp-field timestamp] \ - [--edited-field edited] \ - [--bot-field bot] \ - [--user-id-field userId] \ - [--text-field spiel] \ - [--mapping-source ceo] + --timestamp-unit seconds ``` Inputs, defaults, and output rules: From 8168408df0838c1ec2acbbf7883274738d5a1db0 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 12:05:19 -0500 Subject: [PATCH 21/21] T-167: tests --- tools/curate-etl/tests/curate_posts.rs | 191 +++++++++++++++++++++++++ 1 file changed, 191 insertions(+) create mode 100644 tools/curate-etl/tests/curate_posts.rs 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}"); + } +}